Newest 'ffmpeg' Questions - Stack Overflow

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

Les articles publiés sur le site

  • I am trying to trim a Video, I can perform trimming Operation.I am not able to get response from node js.

    28 mars 2017, par Sumit Sarkar

    This is my block of code from index.js

    router.get('/trimVideo', function(req, res, next){ res.set({ "Content-Type":"text/json" });

     try{
     var inputDirectory = opts.videoDir+'/'+req.query.videoName;
     var outputDirectory = opts.videoDir+'/trim/'+'Trimmed_'+req.query.videoName;
     ffmpeg()
        .input(inputDirectory)
        .format('mp4')
        .seekInput(req.query.StartTrimTime)
        .duration(req.query.EndTrimTime)
        .on('start', function(cmd){
            console.log('Started' + cmd)
        })
        .on('error', function(err){
            console.log('An error occured: ' + err.message)
        })
        .output(outputDirectory)
        .on('end',function(){
            fs.createReadStream(outputDirectory).pipe(fs.createWriteStream(opts.videoDir+'/'+req.query.videoName));
            console.log('Finished Encoding');
    
            res.write(JSON.stringify({ OK: 1 }));
            res.end();
        })
        .run();
    }
    
     catch(error){
        res.write(JSON.stringify({ OK: 0 }));
        res.end();
    }
    

    });

    This is my block of code for ajax call

    $.ajax({ type: "GET", url: "/trimVideo", data: { StartTrimTime : startTime, EndTrimTime : endTime, videoName : name }, dataJson: 'json', success: function(data) { console.log('success'); console.log(JSON.stringify(data)); } })

  • FFMpeg : ffmpeg failed to execute command error

    28 mars 2017, par Richard McFriend Oluwamuyiwa

    I am trying to transcode a video file of 1.2mb file uploaded to my website server via php/html upload, but I keep getting the error:

    PHP Fatal error: Uncaught exception 'Alchemy\BinaryDriver\Exception\ExecutionFailureException' with message 'ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/home/user/public_html/contents/videos/1490719990_MP4_360p_Short_video_clip_nature_mp4.mp4' '-async' '1' '-metadata:s:v:0' 'start_time=0' '-r' '16' '-b_strategy' '1' '-bf' '3' '-g' '9' '-vcodec' 'libx264' '-acodec' 'libmp3lame' '-b:v' '128k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '8k' '-ac' '1' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes58dab05a323b6eknk4/pass-58dab05a32465' '/home/user/public_html/contents/videos/1490719990_MP4_360p_Short_video_clip_nature_mp4_22995.mp4'' in /home/user/public_html/app/ffmpeg/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/ProcessRunner.php:100 Stack trace:

    0 /home/user/public_html/app/ffmpeg/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/ProcessRunner.php(72): Alch in /home/user/public_html/app/ffmpeg/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Media/Video.php on line 168

    Funny thing is that the same server is extracting frames and getting duration of the same file using ffprobe and ffmpeg.

    Here is the code I am using to transcode:

    $ffmpeg = $ffmpeg = FFMpeg\FFMpeg::create(['timeout'=>3600, 'ffmpeg.thread'=>12, 'ffmpeg.binaries'  => '/usr/local/bin/ffmpeg',
        'ffprobe.binaries' => '/usr/local/bin/ffprobe']);
    
                $ffprobe_prep = FFMpeg\FFProbe::create(['ffmpeg.binaries'  => '/usr/local/bin/ffmpeg',
        'ffprobe.binaries' => '/usr/local/bin/ffprobe']);
                $ffprobe = $ffprobe_prep->format($video_file);
    
                $video = $ffmpeg->open($video_file);
    
                // Get video duration to ensure our videos are never longer than our video limit.
                $duration = $ffprobe->get('duration');
    
                // Use mp4 format and set the audio bitrate to 56Kbit and Mono channel.
                // TODO: Try stereo later...
                $format = new FFMpeg\Format\Video\X264('libmp3lame', 'libx264');
                $format
                    -> setKiloBitrate(128)
                    -> setAudioChannels(1)
                    -> setAudioKiloBitrate(8);
    
                $first = $ffprobe_prep
                            ->streams($video_file)
                            ->videos()
                            ->first();
    
                $width = $first->get('width');
    
                if($width > VIDEO_WIDTH){
                    // Resize to 558 x 314 and resize to fit width.
                    $video
                        ->filters()
                        ->resize(new FFMpeg\Coordinate\Dimension(VIDEO_WIDTH, ceil(VIDEO_WIDTH / 16 * 9)));
                }
    
                // Trim to videos longer than three minutes to 3 minutes.
                if($duration > MAX_VIDEO_PLAYTIME){
    
                    $video
                        ->filters()
                        ->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(0), FFMpeg\Coordinate\TimeCode::fromSeconds(MAX_VIDEO_PLAYTIME));
                }
    
                // Change the framerate to 16fps and GOP as 9.
                $video
                    ->filters()
                    ->framerate(new FFMpeg\Coordinate\FrameRate(16), 9);
    
                // Synchronize audio and video
                $video->filters()->synchronize();
    
                $video->save($format, $video_file_new_2);
    

    I have contacted my host to no vital assistance. The only useful information they can provide me is that ffmpeg was compiled on the server with libmp3lame support.

    This code works perfect on localhost

    Any help as to why I may be getting the error and how to correct it is appreciated.

  • matplotlib ArtistAnimation returns a blank video

    28 mars 2017, par Mpaull

    I'm trying to produce an animation of a networkx graph changing over time. I'm using the networkx_draw utilities to create matplotlib figures of the graph, and matplotlib's ArtistAnimation module to create an animation from the artists networkx produces. I've made a minimum reproduction of what I'm doing here:

    import numpy as np
    import networkx as nx
    import matplotlib.animation as animation
    import matplotlib.pyplot as plt
    
    # Instantiate the graph model
    G = nx.Graph()
    G.add_edge(1, 2)
    
    # Keep track of highest node ID
    G.maxNode = 2
    
    fig = plt.figure()
    nx.draw(G)
    ims = []
    
    for timeStep in xrange(10):
    
        G.add_edge(G.maxNode,G.maxNode+1)
        G.maxNode += 1
    
        pos = nx.drawing.spring_layout(G)
        nodes = nx.drawing.draw_networkx_nodes(G, pos)
        lines = nx.drawing.draw_networkx_edges(G, pos)
    
        ims.append((nodes,lines,))
        plt.pause(.2)
        plt.cla()
    
    im_ani = animation.ArtistAnimation(fig, ims, interval=200,            repeat_delay=3000,blit=True)
    im_ani.save('im.mp4', metadata={'artist':'Guido'})
    

    The process works fine while displaying the figures live, it produces exactly the animation I want. And it even produces a looping animation in a figure at the end of the script, again what I want, which would suggest that the animation process worked. However when I open the "im.mp4" file saved to disk, it is a blank white image which runs for the expected period of time, never showing any of the graph images which were showed live.

    I'm using networkx version 1.11, and matplotlib version 2.0. I'm using ffmpeg for the animation, and am running on a Mac, OSX 10.12.3.

    What am I doing incorrectly?

  • Copying audio stream via ffmpeg c api

    28 mars 2017, par David Barishev

    I'm trying to replicate ffmpeg command ffmpeg -i -vn -acodec copy ,using the C api, in my c++ android project.

    There isn't too much documentations on the subject, and some of the methods in the example are deprecated and i don't know how to fix them.

    Here is the code i have worked on, and understood,i have highlited some parts in with the comments:

     extern "C"
    int extract_audio(const char *in_filename,const char *out_filename){
    
        // Library init
        SSL_load_error_strings();
        SSL_library_init();
    
        av_register_all ();
        avformat_network_init ();
    
        //Logging init
        av_log_set_callback(log_callback_android);
    
    
        //Variable init
        AVOutputFormat *ofmt = NULL;
        AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
        AVPacket pkt;
        int ret, i;
    
        int stream_index = 0;
    
        //Open input file
        if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
            av_log(NULL,AV_LOG_FATAL, "Could not open input file '%s'", in_filename);
            goto end;
        }
        if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
            av_log(NULL,AV_LOG_FATAL, "Failed to retrieve input stream information");
            goto end;
        }
    
        //Print input file stream info
        av_dump_format(ifmt_ctx, 0, in_filename, 0);
    
        //Allocate new context for output file
        avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
        if (!ofmt_ctx) {
            av_log(NULL,AV_LOG_FATAL, "Could not create output context");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
    
        ofmt = ofmt_ctx->oformat;
    
        // Iterate over all streams in input file
        for (i = 0; i < ifmt_ctx->nb_streams; i++) {
            //Stream input
            AVStream *in_stream = ifmt_ctx->streams[i];
    
            //Filter non audio streams
            if(in_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO){
                __android_log_print(ANDROID_LOG_INFO,APPNAME,"Audio stream found");
    
                AVStream *out_stream = avformat_new_stream(ofmt_ctx, NULL);
                if (!out_stream) {
                    __android_log_print(ANDROID_LOG_ERROR, APPNAME, "Failed allocating output stream\n");
                    ret = AVERROR_UNKNOWN;
                    goto end;
                }
    
    
                if ((ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar)) < 0) {
                    av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
                    return ret;
                }
    
                out_stream->time_base = in_stream->time_base;
    
    
            }
    
        }
    
        //Dump output format
        av_dump_format(ofmt_ctx, 0, out_filename, 1);
    
        //Open output file
        if (!(ofmt->flags & AVFMT_NOFILE)) {
            ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", out_filename);
                goto end;
            }
        }
    
        //Writing output header
        if ((ret = avformat_write_header(ofmt_ctx, NULL)) < 0) {
            av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file");
            goto end;
        }
    
        while (1) {
            AVStream *in_stream, *out_stream;
    
            if ((ret = av_read_frame(ifmt_ctx, &pkt)) < 0)
                break;
    
            stream_index = pkt.stream_index;
    
            /* remux this frame without reencoding */
            av_packet_rescale_ts(&pkt,
                                 ifmt_ctx->streams[stream_index]->time_base,
                                 ofmt_ctx->streams[stream_index]->time_base);
    
            if ((ret = ret = av_interleaved_write_frame(ofmt_ctx, &pkt)) < 0){
                av_log(NULL,AV_LOG_FATAL,"Error muxing packet");
                goto end;
            }
    
    
            av_packet_unref(&pkt);
        }
    
        av_write_trailer(ofmt_ctx);
    
        end:
        avformat_close_input(&ifmt_ctx);
    
        /* close output */
        if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
            avio_closep(&ofmt_ctx->pb);
        avformat_free_context(ofmt_ctx);
    
    
        if (ret < 0 && ret != AVERROR_EOF) {
            av_log(NULL,AV_LOG_FATAL, "Error: %s", av_err2str(ret));
        }
    
    }
    

    This code produces the following output:

    ===Input Information===
    
    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '':
      Metadata:
        major_brand     : 
            isom
        minor_version   : 
            512
        compatible_brands: 
            isomiso2avc1mp41
        encoder         : 
            Lavf57.25.100
        Duration: 
            00:00:58.82
            , start: 
            0.000000
            , bitrate: 
        7369 kb/s
            Stream #0:0
                (eng)
                    Audio: aac (mp4a / 0x6134706D), 44100 Hz, 2 channels, 160 kb/s
                (default)
            Metadata:
            handler_name    : 
                SoundHandler
            Stream #0:1
                (eng)
                    Video: h264 (avc1 / 0x31637661), none, 640x640, 7213 kb/s
    
                30 fps, 
                30 tbr, 
                15360 tbn, 
                15360 tbc
                (default)
            Metadata:
            handler_name    : 
            VideoHandler
    
    ===Ouput Information===
    
    Audio stream found
    Output #0, adts, to 'out.aac':
        Stream #0:0
    Audio: aac (mp4a / 0x6134706D), 44100 Hz, 2 channels, 160 kb/s
    
    ==Packet Logging==
    
    in: pts:-2048 pts_time:-0.0464399 dts:-2048 dts_time:-0.0464399 duration:1024 duration_time:0.02322 stream_index:0
    out: pts:-2048 pts_time:-0.0464399 dts:-2048 dts_time:-0.0464399 duration:1024 duration_time:0.02322 stream_index:0
    in: pts:-1024 pts_time:-0.02322 dts:-1024 dts_time:-0.02322 duration:1024 duration_time:0.02322 stream_index:0
    out: pts:-1024 pts_time:-0.02322 dts:-1024 dts_time:-0.02322 duration:1024 duration_time:0.02322 stream_index:0
    in: pts:0 pts_time:0 dts:0 dts_time:0 duration:1024 duration_time:0.02322 stream_index:0
    out: pts:0 pts_time:0 dts:0 dts_time:0 duration:1024 duration_time:0.02322 stream_index:0
    in: pts:0 pts_time:0 dts:0 dts_time:0 duration:512 duration_time:0.0333333 stream_index:1
    

    The snippit handlers file opening, context creation, stream codec copying fine, but crashes after a few loops in the packet muxing part, with signal error :

    Signal: SIGSEGV (signal SIGSEGV: invalid address (fault address: 0x28))
    

    What did i do wrong ? I wrote this code using some examples and got the code to the current state, but i'm lost now, any help would be greatly appreciated !

  • Convert TS with closed captions into MKV/MP4 with sub title

    28 mars 2017, par Sudheesh

    I am trying to convert a TS file ( with US closed captions ) into MKV ( or MP4 ). Currently I am doing using a three step approach.

    Step-1 : Extract the subtitle in srt format.

    ffmpeg -f lavfi -i "movie=test.ts[out0+subcc]" -map s output.srt

    Step-2 : Transcode the TS into MKV

    ffmpeg i test.ts -vcodec libx264 -acodec copy out.mkv

    Step-3 : Add subtitle back to out.mkv

    ffmpeg -i out.mkv -i output.srt -acodec copy -vcodec copy -scodec copy final.mkv.

    I believe all these three steps can be combined in a single ffmeg command. Is there any way to do this?.