Newest 'ffmpeg' Questions - Stack Overflow

http://stackoverflow.com/questions/tagged/ffmpeg

Les articles publiés sur le site

  • How to decode audiostream to play with AudioUnits ?

    4 décembre 2015, par sadhi

    I have a PCM ulaw stream that I receive and I want to play this on iOS. To play audio in my app I made an AudioUnit implementation, but since it requires linear PCM I must decode it first. For this I use ffmpeg with the following code:

            AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_PCM_MULAW);
    
            self.audio_codec_context = avcodec_alloc_context3(codec);
            self.audio_codec_context->codec_type = AVMEDIA_TYPE_AUDIO;
            self.audio_codec_context->sample_fmt = *codec->sample_fmts;
            self.audio_codec_context->sample_rate = 48000;
            self.audio_codec_context->channels    = 1;
            //open codec
            int result = avcodec_open2(self.audio_codec_context, codec,NULL);            
    
            //this should hold the raw data
            AVFrame * audioFrm = av_frame_alloc();
    
            AVPacket pkt;
            av_init_packet(&pkt);
            pkt.data = (unsigned char*)buf;
            pkt.size = ret;
            pkt.flags = AV_PKT_FLAG_KEY;
    
            int got_packet;
            result = avcodec_decode_audio4(self.audio_codec_context, audioFrm, &got_packet, &pkt);
    
            AVPacket encodedPkt;
            av_init_packet(&encodedPkt);
            encodedPkt.size = 0;
            encodedPkt.data = NULL;
    
            if (audioFrm != NULL) {
                self.audio_codec_context = NULL;
                AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE);
    
                self.audio_codec_context = avcodec_alloc_context3(codec);
                self.audio_codec_context->codec_type = AVMEDIA_TYPE_AUDIO;
                self.audio_codec_context->sample_fmt = *codec->sample_fmts;
                self.audio_codec_context->bit_rate = 64000;
                self.audio_codec_context->sample_rate = 48000;
                self.audio_codec_context->channels    = 1;
    
    
                int result = avcodec_open2(self.audio_codec_context, codec,NULL);
                if (result < 0) {
                    NSLog(@"avcodec_open2 returned %i", result);
                }
    
    
                result = avcodec_encode_audio2(self.audio_codec_context, &encodedPkt, audioFrm, &got_packet);
    
                if (result < 0) {
                    NSLog(@"avcodec_encode_audio2 returned %s", av_err2str (result));
                    continue;
                }
            }
    

    For some reason no matter what I do the audio that comes out at the end is all noise. So my question is: How should I decode my audiostrean to play it with AudioUnits?

  • Combine 2 .FLV videos

    4 décembre 2015, par Rune

    For the last 4 hours I've been trying to combine 2 .flv files into one using ffmpeg (or well, just C# in general).

    Here's what I got so far: I've converted both the videos to .mp4 videos:

    "-i " + videoFileLocation + " -c copy -copyts " + newConvertedFileLocation
    

    I have then combined the two .mp4 files into a single one using: (txtPath is the text file with the two mp4 file locations)

    "-f concat -i " + txtPath + " -c copy " + saveLocation
    

    This ends up with an mp4 file which contains the combination of both the videos BUT with the following fault:

    The length of the first video is 0:05

    The length of the second video is 6:11

    However the length of the combined video is for some reason 07:51 - thus the video runs at a slower pace than it should.

    Furthermore the audio is async with the video.

    What am I doing wrong here?

    I haven't used ffmpeg before and I just wanna get this working.

    Any help is greatly appreciated!

    As requested here is the output from running 'ffmpeg -i input1.flv -i input2.flv':

    ffmpeg version 2.7 Copyright (c) 2000-2015 the FFmpeg developers   built with gcc 4.9.2 (GCC)...
    
    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'filepath\input1.flv':   Metadata:
        major_brand     : isom
        minor_version   : 512
        compatible_brands: isomiso2avc1mp41
        creation_time   : 1970-01-01 00:00:00
        encoder         : Lavf53.24.2   Duration: 00:00:05.31, start: 0.000000, bitrate: 1589 kb/s
        Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 1205 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : VideoHandler
        Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, 5.1, fltp, 384 kb/s (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : SoundHandler Input #1, flv, from 'filepath\input2.flv':   Metadata:
        audiosize       : 4476626
        canSeekToEnd    : true
        datasize        : 23876671
        videosize       : 19004263
        hasAudio        : true
        hasCuePoints    : false
        hasKeyframes    : true
        hasMetadata     : true
        hasVideo        : true
        lasttimestamp   : 372
        metadatacreator : flvtool++ (Facebook, Motion project, dweatherford)
        totalframes     : 9298
        encoder         : Lavf56.36.100   Duration: 00:06:11.92, start: 0.080000, bitrate: 513 kb/s
        Stream #1:0: Video: h264 (High), yuv420p, 646x364 [SAR 1:1 DAR 323:182], 400 kb/s, 25 fps, 25 tbr, 1k tbn, 50 tbc
        Stream #1:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 96 kb/s At least one output file must be specified
    
  • FFmpeg4Android : How to select videos from gallery ?

    4 décembre 2015, par marian

    I have created an app using FFmpeg4Android library. I would like to add watermark into videos using ffmpeg. Command for adding watermark is working fine but the coding has pre-fixed video name in the command. I would like to choose videos from gallery folder and then add watermark to the videos. I do not know how to add intent for choosing videos with FFmpeg. I have tried to add the intent like this replacing the in.mp4 with PICK_FROM_GALLERY intent:

     private void runTranscodingUsingLoader() {
        Log.i(Prefs.TAG, "runTranscodingUsingLoader started...");
    
        PowerManager powerManager = (PowerManager)ProgressBarExample.this.getSystemService(Activity.POWER_SERVICE);
        WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VK_LOCK");
        Log.d(Prefs.TAG, "Acquire wake lock");
        wakeLock.acquire();
    
        Intent intent = new Intent();
    
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
    
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
    
    
        String[] complexCommand = {"ffmpeg","-y" ,"-i", String.valueOf(PICK_FROM_GALLERY),"-strict","experimental",
                "-vf", "movie=/sdcard/videokit/watermark.png [watermark];" +
                " [in][watermark] overlay=main_w-overlay_w-10:10 [out]","-s",
                "320x240","-r", "30", "-b", "15496k", "-vcodec", "mpeg4","-ab",
                "48000", "-ac", "2", "-ar", "22050", "/sdcard/videokit/out1.mp4"};
    

    It opens the gallery but the watermarking command doesnt get executed in the selected video. Can someone help me to resolve this issue. I could not find proper references/examples regarding this. My full coding is as follows.

    public class ProgressBarExample extends Activity  {
    
    public ProgressDialog progressBar;
    
    String workFolder = null;
    String demoVideoFolder = null;
    String demoVideoPath = null;
    String vkLogPath = null;
    LoadJNI vk;
    private final int STOP_TRANSCODING_MSG = -1;
    private final int FINISHED_TRANSCODING_MSG = 0;
    private boolean commandValidationFailedFlag = false;
    private static final int PICK_FROM_GALLERY = 1;
    
    private void runTranscodingUsingLoader() {
        Log.i(Prefs.TAG, "runTranscodingUsingLoader started...");
    
        PowerManager powerManager = (PowerManager)ProgressBarExample.this.getSystemService(Activity.POWER_SERVICE);
        WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VK_LOCK");
        Log.d(Prefs.TAG, "Acquire wake lock");
        wakeLock.acquire();
    
    
    
    
        String[] complexCommand = {"ffmpeg","-y" ,"-i", "/sdcard/videokit/in.mp4","-strict","experimental",
                "-vf", "movie=/sdcard/videokit/watermark.png [watermark];" +
                " [in][watermark] overlay=main_w-overlay_w-10:10 [out]","-s",
                "320x240","-r", "30", "-b", "15496k", "-vcodec", "mpeg4","-ab",
                "48000", "-ac", "2", "-ar", "22050", "/sdcard/videokit/out1.mp4"};
        ///////////////////////////////////////////////////////////////////////
    
    
        vk = new LoadJNI();
        try {
            // running complex command with validation
            vk.run(complexCommand, workFolder, getApplicationContext());
    
            // running without command validation
            //vk.run(complexCommand, workFolder, getApplicationContext(), false);
    
            // running regular command with validation
            //vk.run(GeneralUtils.utilConvertToComplex(commandStr), workFolder, getApplicationContext());
    
            Log.i(Prefs.TAG, "vk.run finished.");
            // copying vk.log (internal native log) to the videokit folder
            GeneralUtils.copyFileToFolder(vkLogPath, demoVideoFolder);
    
        } catch (CommandValidationException e) {
            Log.e(Prefs.TAG, "vk run exeption.", e);
            commandValidationFailedFlag = true;
    
        } catch (Throwable e) {
            Log.e(Prefs.TAG, "vk run exeption.", e);
        }
        finally {
            if (wakeLock.isHeld()) {
                wakeLock.release();
                Log.i(Prefs.TAG, "Wake lock released");
            }
            else{
                Log.i(Prefs.TAG, "Wake lock is already released, doing nothing");
            }
        }
    
        // finished Toast
        String rc = null;
        if (commandValidationFailedFlag) {
            rc = "Command Vaidation Failed";
        }
        else {
            rc = GeneralUtils.getReturnCodeFromLog(vkLogPath);
        }
        final String status = rc;
        ProgressBarExample.this.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(ProgressBarExample.this, status, Toast.LENGTH_LONG).show();
                if (status.equals("Transcoding Status: Failed")) {
                    Toast.makeText(ProgressBarExample.this, "Check: " + vkLogPath + " for more information.", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(Prefs.TAG, "onCreate ffmpeg4android ProgressBarExample");
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ffmpeg_demo_client_2);
    
        demoVideoFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videokit/";
        demoVideoPath = demoVideoFolder + "in.mp4";
    
        Log.i(Prefs.TAG, getString(R.string.app_name) + " version: " + GeneralUtils.getVersionName(getApplicationContext()) );
    
        Button invoke =  (Button)findViewById(R.id.invokeButton);
        invoke.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                Log.i(Prefs.TAG, "run clicked.");
                runTranscoding();
            }
        });
    
        workFolder = getApplicationContext().getFilesDir() + "/";
        Log.i(Prefs.TAG, "workFolder (license and logs location) path: " + workFolder);
        vkLogPath = workFolder + "vk.log";
        Log.i(Prefs.TAG, "vk log (native log) path: " + vkLogPath);
        GeneralUtils.copyLicenseFromAssetsToSDIfNeeded(this, workFolder);
        GeneralUtils.copyDemoVideoFromAssetsToSDIfNeeded(this, demoVideoFolder);
        int rc = GeneralUtils.isLicenseValid(getApplicationContext(), workFolder);
        Log.i(Prefs.TAG, "License check RC: " + rc);
    }
    
    
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(Prefs.TAG, "Handler got message");
            if (progressBar != null) {
                progressBar.dismiss();
    
                // stopping the transcoding native
                if (msg.what == STOP_TRANSCODING_MSG) {
                    Log.i(Prefs.TAG, "Got cancel message, calling fexit");
                    vk.fExit(getApplicationContext());
    
    
                }
            }
        }
    };
    
    public void runTranscoding() {
        progressBar = new ProgressDialog(ProgressBarExample.this);
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setTitle("FFmpeg4Android Direct JNI");
        progressBar.setMessage("Press the cancel button to end the operation");
        progressBar.setMax(100);
        progressBar.setProgress(0);
    
        progressBar.setCancelable(false);
        progressBar.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                handler.sendEmptyMessage(STOP_TRANSCODING_MSG);
            }
        });
    
        progressBar.show();
    
        new Thread() {
            public void run() {
                Log.d(Prefs.TAG,"Worker started");
                try {
                    //sleep(5000);
                    runTranscodingUsingLoader();
                    handler.sendEmptyMessage(FINISHED_TRANSCODING_MSG);
    
                } catch(Exception e) {
                    Log.e("threadmessage",e.getMessage());
                }
            }
        }.start();
    
        // Progress update thread
        new Thread() {
            ProgressCalculator pc = new ProgressCalculator(vkLogPath);
            public void run() {
                Log.d(Prefs.TAG,"Progress update started");
                int progress = -1;
                try {
                    while (true) {
                        sleep(300);
                        progress = pc.calcProgress();
                        if (progress != 0 && progress < 100) {
                            progressBar.setProgress(progress);
                        }
                        else if (progress == 100) {
                            Log.i(Prefs.TAG, "==== progress is 100, exiting Progress update thread");
                            pc.initCalcParamsForNextInter();
                            break;
                        }
                    }
    
                } catch(Exception e) {
                    Log.e("threadmessage",e.getMessage());
                }
            }
        }.start();
    }
    
    }
    

    Any help/guidance would be really helpful. Thank you.

  • FFmpeg : Error occurred while encoding audio stream from ac3 to aac

    4 décembre 2015, par akki_2891

    I am using following command to encode my video to h264 and aac audio codec :

    ffmpeg -i sample.mp4 -codec:v libx264 -profile:v high -level:v 4.0 -codec:a libvo_aacenc -b:a 128k output_file.mp4
    

    Following is a trace of the error i am getting at the console.

    Input #0, mpegts, from 'sample.mp4':
      Duration: 00:00:58.08, start: 1.000033, bitrate: 17290 kb/s
      Program 1
        Stream #0:0[0x1011]: Video: h264 (High) (HDMV / 0x564D4448), yuv420p, 1920x1
    080 [SAR 1:1 DAR 16:9], 29.97 fps, 59.94 tbr, 90k tbn, 59.94 tbc
        Stream #0:1[0x1100]: Audio: ac3 (AC-3 / 0x332D4341), 48000 Hz, 5.1(side), fl
    tp, 448 kb/s
        Stream #0:2[0x1200]: Subtitle: hdmv_pgs_subtitle ([144][0][0][0] / 0x0090)
    [libx264 @ 003dc660] using SAR=1/1
    [libx264 @ 003dc660] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
    [libx264 @ 003dc660] profile High, level 4.0
    [libx264 @ 003dc660] 264 - core 130 r2274 c832fe9 - H.264/MPEG-4 AVC codec - Cop
    yright 2003-2013 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 de
    block=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1
    me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chr
    oma_qp_offset=-2 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1
     interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=
    1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scen
    ecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmi
    n=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
    [libvo_aacenc @ 03c3c640] Unable to set encoding parameters
    Output #0, mp4, to 'output_file.mp4':
        Stream #0:0: Video: h264, yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], q=-1--1, 90
    k tbn, 29.97 tbc
        Stream #0:1: Audio: aac, 48000 Hz, 5.1(side), s16, 128 kb/s
    Stream mapping:
      Stream #0:0 -> #0:0 (h264 -> libx264)
      Stream #0:1 -> #0:1 (ac3 -> libvo_aacenc)
    Error while opening encoder for output stream #0:1 - maybe incorrect parameters
    such as bit_rate, rate, width or height
    

    I am really not able to find what possibly could be wrong. I dont want to copy audio codec , i wish to encode it from ac3 to aac

    Also any suggestion to make it lossless

  • ffmpeg Error while opening enconder for output stream [duplicate]

    4 décembre 2015, par user650922

    This question already has an answer here:

    As a testing purpose I am converting .mp4 video to .mp4.

    The error message is "Error while opening encoder for output stream #0:1 - maybe incorrect parameters such as bit_rate, rate, width or height".

    Could someone please help me in finding the reason behind below error.

    Below is my terminal log.

    C:\Users\work\Downloads\ffmpeg-20151130-git-7b11eea-win64-static\ffmpeg-20151130
    -git-7b11eea-win64-static\bin
    >ffmpeg -i C:\Users\work\Desktop\Esocializ\Sample.mp4 C:\Users\work\Desktop\Esoc
    ializ\Sample1.mp4
    ffmpeg version N-76957-g7b11eea Copyright (c) 2000-2015 the FFmpeg developers
      built with gcc 5.2.0 (GCC)
      configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
    isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
    le-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --
    enable-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-l
    ibilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enab
    le-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --en
    able-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --ena
    ble-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc
     --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enabl
    e-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzimg --
    enable-lzma --enable-decklink --enable-zlib
      libavutil      55.  9.100 / 55.  9.100
      libavcodec     57. 16.101 / 57. 16.101
      libavformat    57. 19.100 / 57. 19.100
      libavdevice    57.  0.100 / 57.  0.100
      libavfilter     6. 17.100 /  6. 17.100
      libswscale      4.  0.100 /  4.  0.100
      libswresample   2.  0.101 /  2.  0.101
      libpostproc    54.  0.100 / 54.  0.100
    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'C:\Users\work\Desktop\Esocializ\Sample.
    mp4':
      Metadata:
        major_brand     : isom
        minor_version   : 512
        compatible_brands: isomiso2avc1mp41
        creation_time   : 1970-01-01 00:00:00
        encoder         : Lavf53.24.2
      Duration: 00:00:05.31, start: 0.000000, bitrate: 1589 kb/s
        Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p, 1280x720
    [SAR 1:1 DAR 16:9], 1205 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : VideoHandler
        Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, 5.1, fltp,
    384 kb/s (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : SoundHandler
    [libx264 @ 000000c07583dde0] using SAR=1/1
    [libx264 @ 000000c07583dde0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2
    [libx264 @ 000000c07583dde0] profile High, level 3.1
    [libx264 @ 000000c07583dde0] 264 - core 148 r2638 7599210 - H.264/MPEG-4 AVC cod
    ec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options: cabac=1 r
    ef=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed
    _ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pski
    p=1 chroma_qp_offset=-2 threads=12 lookahead_threads=2 sliced_threads=0 nr=0 dec
    imate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b
    _adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=
    25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.
    60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
    [libvo_aacenc @ 000000c0758d6da0] Unable to set encoding parameters
    Output #0, mp4, to 'C:\Users\work\Desktop\Esocializ\Sample1.mp4':
      Metadata:
        major_brand     : isom
        minor_version   : 512
        compatible_brands: isomiso2avc1mp41
        encoder         : Lavf53.24.2
        Stream #0:0(und): Video: h264 (libx264), yuv420p, 1280x720 [SAR 1:1 DAR 16:9
    ], q=-1--1, 25 fps, 25 tbn, 25 tbc (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : VideoHandler
          encoder         : Lavc57.16.101 libx264
        Stream #0:1(und): Audio: aac, 0 channels, 128 kb/s (default)
        Metadata:
          creation_time   : 1970-01-01 00:00:00
          handler_name    : SoundHandler
          encoder         : Lavc57.16.101 libvo_aacenc
    Stream mapping:
      Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
      Stream #0:1 -> #0:1 (aac (native) -> aac (libvo_aacenc))
    Error while opening encoder for output stream #0:1 - maybe incorrect parameters
    such as bit_rate, rate, width or height
    
    C:\Users\work\Downloads\ffmpeg-20151130-git-7b11eea-win64-static\ffmpeg-20151130
    -git-7b11eea-win64-static\bin
    >