Newest 'ffmpeg' Questions - Stack Overflow

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

Les articles publiés sur le site

  • 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?.

  • SEI type 63 truncated ? Best way to convert non-mp4 to web optimized mp4 ?

    28 mars 2017, par Chris Palmer Breuer

    I am trying to convert any video file to a web optimized mp4 format and I tried this sample mkv file to make some tests.

    The following is a message I keep getting for multiple minutes over and over again:

    [NULL @ 0x7f979c00a600] SEI type 63 size 4208 truncated at 88
    [h264 @ 0x7f979b06a000] SEI type 63 size 4208 truncated at 80
    [NULL @ 0x7f979c00a600] SEI type 63 size 4208 truncated at 88
    [h264 @ 0x7f979b002c00] SEI type 63 size 4208 truncated at 80
    [NULL @ 0x7f979c00a600] SEI type 63 size 4208 truncated at 528
    [h264 @ 0x7f979b027400] SEI type 63 size 4208 truncated at 520
    

    The code that I use the convert the mkv file is:

    ffmpeg -i test.mkv -movflags faststart -vcodec h264 -acodec aac -strict -2 test-ffmpeg.mp4
    

    Now, my question is, am I doing anything wrong? Should I just ignore those messages as the file gets created? Is there a more efficient way to create a web optimized mp4 file from a non mp4 file?

    Thanks so much for the help.

  • Traverse folder to convert all contained files

    28 mars 2017, par E.Owen

    I've recently started using ffmpeg with the intention of converting my video library to h265 due to its compression benefits. I would like to run one command and have ffmpeg traverse the folder converting each file, one-by-one into h265. I've checked the documentation Here but I can't get my head around it. Does anybody have a template loop script for me to use?

    I have ffmpeg installed on a Linux box and have successfully converted single files but I have around 400 files to convert, hence the looping question.

    Thanks in advance.

    EDIT: The files I'm waiting to convert are videos with varying containers. I have bee using the python script below, which I have tweaked to suit my needs but isn't working. I will include the error I'm getting and a link to the original below my code.

    import os
    import sys
    import re
    import shutil
    import subprocess
    
    
    __author__ = 'Nikhil'
    
    # Edit options here ##################################################
    outmode = 'mp4'                          #Extension of file
    remover = True                           # Delete original file after conversion complete
    accept_ext = 'mp4 mkv avi divx m4v mpeg mpg wmv'   #Extensions of video files to convert
    
    ffmpeg_exe = "ffmpeg"                    #Path to ffmpeg executable
    ffprobe_exe = "ffprobe"                  #Path to ffprobe executable
    mkvextract_exe = "mkvextract"            #Path to mkvextract executable
    video_codec = 'libx265'                  #Video codec to use
    video_type = 'h265'                      #Name of video codec to check for remux
    audio_codec = 'aac'                      #Audio codec to use
    audio_type = 'aac'                       #Name of audio codec to check for remux
    crf = "28"                               #Video quality for libx264
    vbr = ''                                 #Audio quality
    extract_subtitle = True                  #Extract subtitles?
    subtitle_languages = "en eng english"    #Codes for languages to extract
    threads = 0                              #Number of threads to use in ffmpeg, 0 defaults to all
    additional_ffmpeg = '-preset slow -movflags +faststart'     #Additional flags for ffmpeg, preset sets speed and compression, movflags to make file web optimized
    
    ## END OPTIONS - DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING ##
    
    outformat = 'mp4'
    if outmode == 'mp4':
    outformat = 'mp4'
    elif outmode == 'mkv':
    outformat = 'matroska'
    
    
    def ffmpeg(*args, **kwargs):
    largs = [ffmpeg_exe, ]
    largs.extend(args)
    try:
    return subprocess.check_output(largs, **kwargs).decode('utf-8')
    except:
    return None
    
    def getoutput(cmd):
    if sys.version < '3':
    try:
    return subprocess.check_output(cmd.split(' '))
    except:
    return None
    else:
    return subprocess.getoutput(cmd)
    
    formats = ""
    if getoutput(ffmpeg_exe + ' -formats'):
    formats = getoutput(ffmpeg_exe + ' -formats 2')
    else:
    exit(1)
    
    if ('E mp4' in formats) and ('E matroska' in formats):
    print("You have the suitable formats")
    else:
    print("You do not have both the mkv and mp4 formats...Exiting!")
    exit(1)
    
    codecs = getoutput(ffmpeg_exe + ' -codecs 2')
    
    if video_codec in codecs:
    print("Check " + video_codec + " Audio Encoder ... OK")
    else:
    print("Check " + video_codec + " Audio Encoder ... NOK")
    exit(1)
    
    if audio_codec in codecs:
    print("Check " + audio_codec + " Audio Encoder ... OK")
    else:
    print("Check " + audio_codec + " Audio Encoder ... NOK")
    exit(1)
    
    print("Your FFMpeg is OK\nEntering File Processing\n")
    
    subtitle_languages = subtitle_languages.lower()
    
    def process_file(path, file):
    extension = os.path.splitext(file)[1].replace(".", "")
    filename = os.path.splitext(file)[0]
    
    if extension in accept_ext:
    print(file + " is an acceptable extension. Checking file...")
    else:
    print(file + " is not an acceptable extension. Skipping...")
    return
    
    if ffprobe_exe:
    file_info = getoutput('"' + ffprobe_exe + '"' + " " + '"' + os.path.join(path, file) + '"')
    else:
    file_info = ffmpeg("-i", os.path.join(path, file))
    
    if 'Invalid data found' in file_info:
    print("File " + file + " is NOT A VIDEO FILE cannot be converted!")
    return
    
    encode_crf = []
    if file_info.find("Video: " + video_type) != -1:
    vcodec = 'copy'
    print("Video is " + video_type + ", remuxing....")
    else:
    vcodec = video_codec
    if crf:
    encode_crf = ["-crf", "" + crf]
    print("Video is not " + video_type + ", converting...")
    
    encode_vbr = []
    if "Audio: " + audio_type in file_info:
    acodec = 'copy'
    print("Audio is " + audio_type + ", remuxing....")
    else:
    acodec = audio_codec
    if vbr:
    encode_vbr = ["-vbr", "" + vbr]
    print("Audio is not " + audio_type + ", converting...")
    
    if extension == outmode and vcodec == 'copy' and acodec == 'copy':
    print(file + " is already " + outmode + " and no conversion needed. Skipping...")
    return
    
    print(
    "Using video codec: " + vcodec + " audio codec: " + acodec + " and Container format " + outformat + " for\nFile: " + file + "\nStarting Conversion...\n")
    
    filename = filename.replace("XVID", video_type)
    filename = filename.replace("xvid", video_type)
    
    try:
    args = ['-i', os.path.join(path, file), '-y', '-f', outformat, '-acodec', acodec]
    if encode_vbr:
    args.extend(encode_vbr)
    args.extend(['-vcodec', vcodec])
    if encode_crf:
    args.extend(encode_crf)
    if additional_ffmpeg:
    args.extend(additional_ffmpeg.split(" "))
    if threads:
    args.extend(['-threads', str(threads)])
    args.append(os.path.join(path, filename + '.temp'))
    ffmpeg(*args)
    print("")
    except Exception as e:
    print("Error: %s" % e)
    print("Removing temp file and skipping file")
    if os.path.isfile(os.path.join(path, filename + '.temp')):
    os.remove(os.path.join(path, filename + '.temp'))
    return
    
    if extract_subtitle and (file_info.find("Subtitle:") != -1):
    print("Extracting Subtitles")
    matches = re.finditer("Stream #(\d+):(\d+)\((\w+)\): Subtitle: (.*)", file_info)
    for m in matches:
    if m.group(3).lower() not in subtitle_languages.split(" "):
    continue
    try:
    if 'subrip' in m.group(4):
    sub_format = 'copy'
    sub_ext = '.srt'
    elif mkvextract_exe and 'hdmv_pgs' in m.group(4):
    subprocess.check_output([mkvextract_exe, 'tracks', os.path.join(path, file),
    m.group(2) + ':' + os.path.join(path, filename + '.' + m.group(
    3) + '.' + m.group(2) + '.sup')])
    continue
    else:
    sub_format = 'srt'
    sub_ext = '.srt'
    ffmpeg("-i", os.path.join(path, file), '-y', '-map', m.group(1) + ':' + m.group(2), '-c:s:0',
    sub_format,
    os.path.join(path, filename + '.' + m.group(3) + '.' + m.group(2) + sub_ext))
    print("")
    except Exception as e:
    print("Error: %s" % e)
    print("Deleting subtitle.")
    if os.path.isfile(os.path.join(path, filename + '.' + m.group(3) + '.' + m.group(2) + sub_ext)):
    os.remove(os.path.join(path, filename + '.' + m.group(3) + '.' + m.group(2) + sub_ext))
    
    if remover:
    print("Deleting original file: " + file)
    os.remove(os.path.join(path, file))
    
    if outmode == extension:
    shutil.move(os.path.join(path, filename + ".temp"), os.path.join(path, filename + ".enc." + outmode))
    filename += ".enc"
    else:
    shutil.move(os.path.join(path, filename + ".temp"), os.path.join(path, filename + "." + outmode))
    
    
    def process_directory(path):
    if os.path.isfile(os.path.join(path, ".noconvert")):
    return
    for file in os.listdir(path):
    filepath = os.path.join(path, file)
    if os.path.isdir(filepath):
    process_directory(filepath)
    elif os.path.isfile(filepath):
    process_file(path, file)
    
    
    for arg in sys.argv[1:]:
    if os.path.isdir(arg):
    process_directory(arg)
    elif os.path.isfile(arg):
    process_file(os.path.dirname(arg), os.path.basename(arg))
    

    The error I am getting is this:

    Traceback (most recent call last):
    File "/media/569f/ethan1878/bin/convert.py", line 209, in 
    process_file(os.path.dirname(arg), os.path.basename(arg))
    File "/media/569f/ethan1878/bin/convert.py", line 100, in process_file
    if 'Invalid data found' in file_info:
    TypeError: argument of type 'NoneType' is not iterable
    

    and the original file is hosted Here (as a .txt file)