Newest 'ffmpeg' Questions - Stack Overflow

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

Les articles publiés sur le site

  • FFMPEG Corrupt output remuxing MP4 (Using API in C) -First file OK, 2nd file onwards is not

    25 janvier, par RichardP

    I have a simple application written in C - it takes the video from a RTSP camera and just writes to disk in 1 minute segments. The first file created works fine, plays on anlmost anything. The Second file does not play. Programatically, The trace shows they are the same code flows, but I cant seem to find where the problem is to allow the 2nd file to be play exactly the same as the first.

    There are frames in the 2nd file but they are random. The second file is created EXACTLY the same way as the first.

    Any help from a guru would be greatly appreciated.

    EDIT: FIX - The output duration needs to be set before the trailer is written.

    int actual_duration = (int)difftime(time(NULL), start_time);
    
    for (int i = 0; i < output_ctx->nb_streams; i++) {
        output_ctx->streams[i]->duration = actual_duration * AV_TIME_BASE;
    }
    
    output_ctx->duration = actual_duration * AV_TIME_BASE;
    printf("DURATION = %d\r\n",output_ctx->duration);
    
    // Set the start_time for the output context
    output_ctx->start_time = 0;
    
    av_write_trailer(output_ctx);
    

    Code flow

       Open RTSP Stream 
    A: Create File n context 
       Remux to file n 
       Wait for minute to change 
       Close File n context  
       increment n Goto A
    

    Makefile

    CC = gcc
    CFLAGS = -Wall -g
    LIBS = -lavformat -lavcodec -lavutil -lavdevice -lswscale -lavfilter -lavutil -lm -lz -lpthread
    
    TARGET = rtsp_remux
    
    all: $(TARGET)
    
    $(TARGET): rtsp_remux.o
            $(CC) -o $(TARGET) rtsp_remux.o $(LIBS)
    
    rtsp_remux.o: rtsp_remux.c
            $(CC) $(CFLAGS) -c rtsp_remux.c
    
    clean:
            rm -f $(TARGET) rtsp_remux.o
    
    .PHONY: all clean
    

    rtsp_remux.c

    #include avformat.h>
    #include time.h>
    #include 
    #include 
    
    #define OUTPUT_PREFIX "output"
    #define OUTPUT_EXTENSION ".mp4"
    #define MAX_FILES 4
    
    int main(int argc, char *argv[]) {
        if (argc < 2) {
            fprintf(stderr, "Usage: %s \n", argv[0]);
            return -1;
        }
    
        const char *rtsp_url = argv[1];
        AVFormatContext *input_ctx = NULL, *output_ctx = NULL;
        AVOutputFormat *output_fmt = NULL;
        AVPacket pkt;
        int ret, file_count = 0;
        char output_filename[1024];
        time_t current_time;
        struct tm *timeinfo;
        int rename_lock = 0;
    
        avformat_network_init();
    
        if ((ret = avformat_open_input(&input_ctx, rtsp_url, NULL, NULL)) < 0) {
            fprintf(stderr, "Could not open input file '%s'\n", rtsp_url);
            return -1;
        }
    
        if ((ret = avformat_find_stream_info(input_ctx, NULL)) < 0) {
            fprintf(stderr, "Failed to retrieve input stream information\n");
            return -1;
        }
    
        av_dump_format(input_ctx, 0, rtsp_url, 0);
    
        while (file_count < MAX_FILES) {
            snprintf(output_filename, sizeof(output_filename), "%s_%03d%s", OUTPUT_PREFIX, file_count, OUTPUT_EXTENSION);
    
            if ((ret = avformat_alloc_output_context2(&output_ctx, NULL, NULL, output_filename)) < 0) {
                fprintf(stderr, "Could not create output context\n");
                return -1;
            }
    
            output_fmt = output_ctx->oformat;
    
            for (int i = 0; i < input_ctx->nb_streams; i++) {
                AVStream *in_stream = input_ctx->streams[i];
                AVStream *out_stream = avformat_new_stream(output_ctx, NULL);
                if (!out_stream) {
                    fprintf(stderr, "Failed allocating output stream\n");
                    return -1;
                }
    
                if ((ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar)) < 0) {
                    fprintf(stderr, "Failed to copy codec parameters\n");
                    return -1;
                }
                out_stream->codecpar->codec_tag = 0;
            }
    
            if (!(output_fmt->flags & AVFMT_NOFILE)) {
                if ((ret = avio_open(&output_ctx->pb, output_filename, AVIO_FLAG_WRITE)) < 0) {
                    fprintf(stderr, "Could not open output file '%s'\n", output_filename);
                    return -1;
                }
            }
    
            if ((ret = avformat_write_header(output_ctx, NULL)) < 0) {
                fprintf(stderr, "Error occurred when opening output file\n");
                return -1;
            }
    
            while (1) {
                current_time = time(NULL);
                timeinfo = localtime(&current_time);
    
                if (timeinfo->tm_sec == 0 && !rename_lock) {
                    rename_lock = 1;
                    break;
                } else if (timeinfo->tm_sec != 0) {
                    rename_lock = 0;
                }
    
                if ((ret = av_read_frame(input_ctx, &pkt)) < 0)
                    break;
    
                AVStream *in_stream = input_ctx->streams[pkt.stream_index];
                AVStream *out_stream = output_ctx->streams[pkt.stream_index];
    
                pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
                pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
                pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
                pkt.pos = -1;
    
                if ((ret = av_interleaved_write_frame(output_ctx, &pkt)) < 0) {
                    fprintf(stderr, "Error muxing packet\n");
                    break;
                }
    
                av_packet_unref(&pkt);
            }
    
            av_write_trailer(output_ctx);
    
            if (!(output_fmt->flags & AVFMT_NOFILE))
                avio_closep(&output_ctx->pb);
    
            avformat_free_context(output_ctx);
    
            file_count++;
        }
    
        avformat_close_input(&input_ctx);
        avformat_network_deinit();
    
        return 0;
    }
    

    I have tried changing to pointers, freeing and different things. I was expecting the 2nd file created to behave identically to the first.

  • FFMPEG Video Multiplexer [closed]

    24 janvier, par Nader

    I am a DirectShow developer, I used to build multiplexers that take 2 video inputs and generate one output, I would then use a video encoder mux to feed it the output + anothrr audio stream to generate the final video output. The multiplexer (DirectShow framework) allows me to process the input video from two sources (for example, adding effects using the two frames).

    How can this can be done using FFMPEG?

  • How to create thumbnail of a video using FFMpegCore ?

    24 janvier, par l.diazborg

    I have a web application, where I need to create thumbnails or images taking the first frame of a video. There are already many examples of this, but I can't find anything that solves my problem. I am using this, but I'm finding it challenging, because I need to read the video and write the result using streams directly. This is my code:

    var videoStream = file.OpenReadStream();
    var outputStream = new MemoryStream();
    FFMpegArguments
        .FromPipeInput(new StreamPipeSource(videoStream))
        .OutputToPipe(new StreamPipeSink(outputStream), options => options
        .WithFrameOutputCount(1)
        .ForceFormat("jpeg")
        )
        .ProcessSynchronously();
    

    Which leads me to the error: Pipe is broken. According to here, the error is related to the fact that the output format cannot be known. Only by adding the .ForceFormat("opus") option does the error disappear, but I understand that the opus format is for audio. Could any expert help me find the solution or tell me how I should do it? Thank you very much in advance.

    UPDATE

    I found this answer where it explains how to correctly use ffmpeg pipes. I modified my code and now it is:

    var videoStream = file.OpenReadStream();
    var outputStream = new MemoryStream();
    FFMpegArguments
        .FromPipeInput(new StreamPipeSource(videoStream))
        .OutputToPipe(new StreamPipeSink(outputStream), opt => opt
        .Seek(TimeSpan.Zero)
        .Resize(650, 390)
        .WithFrameOutputCount(1)
        .WithVideoCodec(VideoCodec.Png)
        .ForceFormat("image2pipe")
        )
        .ProcessSynchronously();
    

    The arguments indicated in the answer ffmpeg -i - -ss 00:00:3 -s 650x390 -vframes 1 -c:v png -f image2pipe - are very similar to those generated by my code -i "\\.\pipe\FFMpegCore_9dd64" -ss 00:00:00.000 -s 650x390 -vframes 1 -c:v png -f image2pipe "\\.\pipe\FFMpegCore_997f4" -y, and even so, errors persists. ​

  • ffmpeg "Time code of first frame" not making sense [closed]

    23 janvier, par Kevin Vasko

    I can't seem to make sense of where ffmpeg is coming up with the "Time code of first frame" value.

    My original file that I am using.

    This video has the general timestamps of the original encoding date (aka the start time of the video the way I understanding it) and a duration of 8 min and 52s

    $ mediainfo GL0100002_output.mp4 
    General
    Complete name                            : GL0100002_output.mp4
    Format                                   : MPEG-4
    Format profile                           : Base Media
    Codec ID                                 : isom (isom/iso2/avc1/mp41)
    File size                                : 93.7 MiB
    Duration                                 : 8 min 52 s
    Overall bit rate                         : 1 476 kb/s
    Encoded date                             : UTC 2022-02-23 15:18:42
    Tagged date                              : UTC 2022-02-23 15:18:42
    Writing application                      : Lavf58.29.100
    
    Video
    ID                                       : 1
    Format                                   : AVC
    Format/Info                              : Advanced Video Codec
    Format profile                           : High@L3
    Format settings                          : CABAC / 4 Ref Frames
    Format settings, CABAC                   : Yes
    Format settings, Reference frames        : 4 frames
    Codec ID                                 : avc1
    Codec ID/Info                            : Advanced Video Coding
    Duration                                 : 8 min 52 s
    Bit rate                                 : 1 342 kb/s
    Width                                    : 848 pixels
    Height                                   : 480 pixels
    Display aspect ratio                     : 16:9
    Frame rate mode                          : Constant
    Frame rate                               : 23.976 (24000/1001) FPS
    Color space                              : YUV
    Chroma subsampling                       : 4:2:0
    Bit depth                                : 8 bits
    Scan type                                : Progressive
    Bits/(Pixel*Frame)                       : 0.138
    Stream size                              : 85.2 MiB (91%)
    Title                                    : GoPro AVC  
    Writing library                          : x264 core 155 r2917 0a84d98
    Encoding settings                        : cabac=1 / ref=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_pskip=1 / chroma_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=23 / 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
    Language                                 : English
    Encoded date                             : UTC 2022-02-23 15:18:42
    Tagged date                              : UTC 2022-02-23 15:18:42
    Color range                              : Full
    Codec configuration box                  : avcC
    
    Audio
    ID                                       : 2
    Format                                   : AAC LC
    Format/Info                              : Advanced Audio Codec Low Complexity
    Codec ID                                 : mp4a-40-2
    Duration                                 : 8 min 52 s
    Bit rate mode                            : Constant
    Bit rate                                 : 129 kb/s
    Channel(s)                               : 2 channels
    Channel layout                           : L R
    Sampling rate                            : 48.0 kHz
    Frame rate                               : 46.875 FPS (1024 SPF)
    Compression mode                         : Lossy
    Stream size                              : 8.16 MiB (9%)
    Title                                    : GoPro AAC  
    Language                                 : English
    Default                                  : Yes
    Alternate group                          : 1
    Encoded date                             : UTC 2022-02-23 15:18:42
    Tagged date                              : UTC 2022-02-23 15:18:42
    
    Other
    ID                                       : 3
    Type                                     : Time code
    Format                                   : QuickTime TC
    Duration                                 : 8 min 52 s
    Frame rate                               : 23.976 (24000/1001) FPS
    Time code of first frame                 : 15:57:41:15
    Time code, striped                       : Yes
    Title                                    : GoPro AVC  
    Language                                 : English
    Default                                  : No
    Encoded date                             : UTC 2022-02-23 15:18:42
    Tagged date                              : UTC 2022-02-23 15:18:42
    

    Now if I run

    ffmpeg -y -nostdin -v error -ss 00:00:00.042 -i GL0100002_output.mp4 -t 00:00:25.192 -map 0 -map -0:d -c:v libx264 -preset fast -crf 21 -c:a aac -sn GL0100002_test.DSME_0001.mp4

    I get the following mediainfo

    $ mediainfo GL0100002_test.DSME_0001.mp4 
    General
    Complete name                            : GL0100002_test.DSME_0001.mp4
    Format                                   : MPEG-4
    Format profile                           : Base Media
    Codec ID                                 : isom (isom/iso2/avc1/mp41)
    File size                                : 4.54 MiB
    Duration                                 : 25 s 234 ms
    Overall bit rate                         : 1 510 kb/s
    Writing application                      : Lavf58.29.100
    
    Video
    ID                                       : 1
    Format                                   : AVC
    Format/Info                              : Advanced Video Codec
    Format profile                           : High@L3
    Format settings                          : CABAC / 4 Ref Frames
    Format settings, CABAC                   : Yes
    Format settings, Reference frames        : 4 frames
    Codec ID                                 : avc1
    Codec ID/Info                            : Advanced Video Coding
    Duration                                 : 25 s 234 ms
    Bit rate                                 : 1 376 kb/s
    Width                                    : 848 pixels
    Height                                   : 480 pixels
    Display aspect ratio                     : 16:9
    Frame rate mode                          : Constant
    Frame rate                               : 23.976 (24000/1001) FPS
    Color space                              : YUV
    Chroma subsampling                       : 4:2:0
    Bit depth                                : 8 bits
    Scan type                                : Progressive
    Bits/(Pixel*Frame)                       : 0.141
    Stream size                              : 4.14 MiB (91%)
    Title                                    : GoPro AVC  
    Writing library                          : x264 core 155 r2917 0a84d98
    Encoding settings                        : cabac=1 / ref=2 / deblock=1:0:0 / analyse=0x3:0x113 / me=hex / subme=6 / 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 / chroma_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=1 / keyint=250 / keyint_min=23 / scenecut=40 / intra_refresh=0 / rc_lookahead=30 / rc=crf / mbtree=1 / crf=21.0 / qcomp=0.60 / qpmin=0 / qpmax=69 / qpstep=4 / ip_ratio=1.40 / aq=1:1.00
    Language                                 : English
    Color range                              : Full
    Codec configuration box                  : avcC
    
    Audio
    ID                                       : 2
    Format                                   : AAC LC
    Format/Info                              : Advanced Audio Codec Low Complexity
    Codec ID                                 : mp4a-40-2
    Duration                                 : 25 s 214 ms
    Duration_LastFrame                       : -3 ms
    Bit rate mode                            : Constant
    Bit rate                                 : 129 kb/s
    Channel(s)                               : 2 channels
    Channel layout                           : L R
    Sampling rate                            : 48.0 kHz
    Frame rate                               : 46.875 FPS (1024 SPF)
    Compression mode                         : Lossy
    Stream size                              : 398 KiB (9%)
    Title                                    : GoPro AAC  
    Language                                 : English
    Default                                  : Yes
    Alternate group                          : 1
    
    Other
    ID                                       : 3
    Type                                     : Time code
    Format                                   : QuickTime TC
    Duration                                 : 25 s 234 ms
    Frame rate                               : 23.976 (24000/1001) FPS
    Time code of first frame                 : 15:57:41:15
    Time code, striped                       : Yes
    Title                                    : GoPro AVC  
    Language                                 : English
    Default                                  : No
    

    But what I don't understand is where Time code of first frame is coming from. I would expect it would be 00:00:00.042 or even UTC 2022-02-23 15:18:42 + .042 but appear to be.

    Time code of first frame                 : 15:57:41:15
    

    Is this potentially clobbering together something to get this time that isn't obvious?

  • reduce compression artifacts (using madVR as filter for ffmpeg ?) [closed]

    23 janvier, par artifact4727

    madVR has a filter called 'reduce compression artifacts' which produces a very good quality output image on 'live playback'. I would like to permanently apply this filter to a video. Is it possible to use madVR as a filter for ffmpeg to generate a permanent output file? Thanks! madVR filter settings