Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a video in React Native

Tried using react-native-video-processing by Shahen:

Below is the code:

compressVideo(source) {
    const options = {
        width: 800,
        height: 800,
        bitrateMultiplier: 3,
        saveToCameraRoll: true, 
        saveWithCurrentDate: true, 
        removeAudio: true 
    };

    ProcessingManager.compress(source, options)
        .then(data => {
            console.log(data);
            this.setState({ base64String: data });
        })
        .catch(console.warn);
}

but it gives error in Android device.

{ [Error: compress error: failed. ffmpeg version 3.3.5 Copyright (c) 2000-2017 the FFmpeg developers built with gcc 4.8 (GCC) configuration: --target-os=linux --cross-prefix=/Users/kesha/Projects/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/Users/kesha/Projects/ffmpeg-android/toolchain-android/sysroot --enable-libx264 --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-yasm --disable-doc --disable-shared --enable-static --enable-nonfree --disable-network --enable-gpl --enable-ffmpeg --enable-small --disable-filters --enable-filter=copy --enable-filter=trim --enable-filter=crop --enable-filter=scale --enable-filter=format --pkg-config=/Users/kesha/Projects/ffmpeg-android/ffmpeg-3.3-pkg-config --prefix=/Users/kesha/Projects/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/Users/kesha/Projects/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/Users/kesha/Projects/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-cxxflags= --extra-libs='-lx264 -lm' libavutil 55. 58.100 / 55. 58.100 libavcodec 57. 89.100 / 57. 89.100 libavformat 57. 71.100 / 57. 71.100 libavdevice 57. 6.100 / 57. 6.100 libavfilter 6. 82.100 / 6. 82.100 libswscale 4. 6.100 / 4. 6.100 libswresample 2.7.100 / 2. 7.100 libpostproc 54. 5.100 / 54. 5.100Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'file:///storage/emulated/0/DCIM/Camera/20180301_141708.mp4': Metadata: major_brand : mp42 minor_version : 0
compatible_brands: isommp42 creation_time : 2018-03-01T08:47:13.000000Z com.android.version: 7.0 Duration: 00:00:04.07, start: 0.000000, bitrate: 3366 kb/s Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuv420p(tv, smpte170m/smpte170m/bt709), 640x480, 3091 kb/s, SAR 1:1 DAR 4:3, 29.88 fps, 30 tbr, 90k tbn, 180k tbc (default) Metadata: rotate
: 90 creation_time : 2018-03-01T08:47:13.000000Z
handler_name : VideoHandle Side data: displaymatrix: rotation of -90.00 degrees Stream #0:1(eng): Audio:aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 256 kb/s (default) Metadata:
creation_time : 2018-03-01T08:47:13.000000Z handler_name : SoundHandleStream mapping: Stream #0:0-> #0:0 (h264 (native) -> h264 (libx264))Press [q] to stop, [?] for helpError reinitializing filters!Failed to inject frame into filter network: Out of memoryError while processing the decoded data for stream #0:0Conversion failed!] framesToPop: 1, code: 'EUNSPECIFIED' } 03-01 15:40:05.658 29497 29772 I ReactNativeJS: 4, { height: 640, width: 480 } 03-01 15:40:05.757 29497 29772 W ReactNativeJS: { [Error: compress error: failed. ffmpeg version 3.3.5 Copyright (c) 2000-2017 the FFmpeg developers built with gcc 4.8 (GCC) configuration: --target-os=linux --cross-prefix=/Users/kesha/Projects/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/Users/kesha/Projects/ffmpeg-android/toolchain-android/sysroot --enable-libx264 --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-yasm --disable-doc --disable-shared --enable-static --enable-nonfree --disable-network --enable-gpl --enable-ffmpeg --enable-small --disable-filters --enable-filter=copy --enable-filter=trim --enable-filter=crop --enable-filter=scale --enable-filter=format --pkg-config=/Users/kesha/Projects/ffmpeg-android/ffmpeg-3.3-pkg-config --prefix=/Users/kesha/Projects/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/Users/kesha/Projects/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/Users/kesha/Projects/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-cxxflags= --extra-libs='-lx264 -lm' libavutil 55. 58.100 / 55. 58.100 libavcodec 57. 89.100 / 57. 89.100 libavformat 57. 71.100 / 57. 71.100 libavdevice 57. 6.100 / 57. 6.100 libavfilter 6. 82.100 / 6. 82.100 libswscale 4. 6.100 / 4. 6.100 libswresample 2.7.100 / 2. 7.100 libpostproc 54. 5.100 / 54. 5.100Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'file:///storage/emulated/0/DCIM/Camera/20180301_141708.mp4': Metadata: major_brand : mp42 minor_version : 0
compatible_brands: isommp42 creation_time : 2018-03-01T08:47:13.000000Z com.android.version: 7.0 Duration: 00:00:04.07, start: 0.000000, bitrate: 3366 kb/s Stream #0:0(eng): Video: h264 (avc1 / 0x31637661), yuv420p(tv, smpte170m/smpte170m/bt709), 640x480, 3091 kb/s, SAR 1:1 DAR 4:3, 29.88 fps, 30 tbr, 90k tbn, 180k tbc (default) Metadata: rotate
: 90 creation_time : 2018-03-01T08:47:13.000000Z
handler_name : VideoHandle Side data: displaymatrix: rotation of -90.00 degrees Stream #0:1(eng): Audio:aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 256 kb/s (default) Metadata:
creation_time : 2018-03-01T08:47:13.000000Z handler_name : SoundHandleStream mapping: Stream #0:0-> #0:0 (h264 (native) -> h264 (libx264))Press [q] to stop, [?] for helpError reinitializing filters!Failed to inject frame into filter network: Out of memoryError while processing the decoded data for stream #0:0Conversion failed!] framesToPop: 1, code: 'EUNSPECIFIED' }

Any solution for this issue or any other method to compress the video before uploading.

like image 905
Niveditha Avatar asked Mar 01 '18 12:03

Niveditha


2 Answers

Have a try on the following code to successfully compress videos in react-native. My compressing result => 7.5mb into 1.48mb. This command require full-gpl package

import { Platform } from 'react-native';
import {RNFFmpeg} from "react-native-ffmpeg"
import RNFS from 'react-native-fs';

function processVideo(videoUrl, callback) {
  const finalVideo = `${RNFS.CachesDirectoryPath}/audioVideoFinal.mp4`;

  cacheResourcePath(videoUrl).then((rVideoUrl) => {
   const str_cmd = `-y -i ${rVideoUrl} -c:v libx264 -crf 28 -preset ultrafast  ${finalVideo}`;
   
    RNFFmpeg.execute(
      str_cmd,
    ).then((result) => {
      if (result === 0) {
        RNFS.unlink(rVideoUrl);

        callback({
          videoPath:
            Platform.OS === 'android' ? 'file://' + finalVideo : finalVideo,
        });
      }
    });
  });
};

async function cacheResourcePath(sourcePath) {
  const uriComponents = sourcePath.split('/');
  const fileNameAndExtension = uriComponents[uriComponents.length - 1].replaceAll(' ','');

  const destPath = `${RNFS.CachesDirectoryPath}/${fileNameAndExtension}`;

  await RNFS.copyFile(sourcePath, destPath);
  return destPath;
}
like image 71
Utonium Avatar answered Oct 28 '22 07:10

Utonium


Use rn-fetch-blob for android to convert the path first as the URI you get is temporary in the case of android and can't be found in the directory,

const res = await RNFetchBlob.fs.stat(SOURCE_URI);
src = "file://" + res.path;

ProcessingManager.compress(src, options)
    .then(data => {
        console.log(data);
        this.setState({ base64String: data });
    })
    .catch(console.warn);

This will resolve the path issue.

like image 32
Rohit Khandelwal Avatar answered Oct 28 '22 06:10

Rohit Khandelwal