Skip to content

Effort free video editing!

15.0 KB
Raw Blame
diff --git a/configure b/configure
index f5e1fbb..fb4ca4c 100755
--- a/configure
+++ b/configure
@@ -2011,8 +2011,6 @@ EXTERNAL_LIBRARY_GPL_LIST="
     libdvdread
     librubberband
     libvidstab
-    libx264
-    libx265
     libxavs
     libxavs2
     libxvid
@@ -2026,6 +2024,8 @@ EXTERNAL_LIBRARY_NONFREE_LIST="
 "
 
 EXTERNAL_LIBRARY_VERSION3_LIST="
+    libx264
+    libx265
     gmp
     libaribb24
     libastcenc
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -724,6 +724,9 @@ static int X264_frame(AVCodecContext *ctx, AVPacket *pkt, const AVFrame *frame,
         return AVERROR_EXTERNAL;
     }
 
+    if (pic_out.i_type == X264_TYPE_B)
+        pkt->flags |= AV_PKT_FLAG_DISPOSABLE;
+
     pkt->flags |= AV_PKT_FLAG_KEY*pic_out.b_keyframe;
     if (ret) {
         int error_count = 0;
diff --git a/libavcodec/mpegaudiodec_template.c b/libavcodec/mpegaudiodec_template.c
--- a/libavcodec/mpegaudiodec_template.c
+++ b/libavcodec/mpegaudiodec_template.c
@@ -41,6 +41,7 @@
 #include "decode.h"
 #include "get_bits.h"
 #include "mathops.h"
+#include "mpegaudiodata.h"
 #include "mpegaudiodsp.h"
 
 /*
@@ -1558,6 +1559,35 @@
     return nb_frames * 32 * sizeof(OUT_INT) * s->hdr.nb_channels;
 }
 
+/**
+ * Samples a decoder started inside the stream outputs before its output is
+ * exact: the synthesis history, then for layer III the IMDCT overlap and
+ * the granules whose main data begins before the first frame decoded. The
+ * bit reservoir reach is bounded for the smallest frames this stream format
+ * allows, as an encoder may use all of it.
+ */
+static int seek_preroll(const MPADecodeHeader2 *hdr)
+{
+    const int synth_history = 512 - 32;
+    const int imdct_overlap = 576;
+
+    if (hdr->layer != 3)
+        return synth_history;
+
+    const int samples_per_frame   = hdr->lsf ? 576 : 1152;
+    const int max_main_data_begin = hdr->lsf ? 255 : 511;
+    const int side_info_size      = hdr->lsf ? (hdr->nb_channels == 1 ?  9 : 17)
+                                             : (hdr->nb_channels == 1 ? 17 : 32);
+    const int min_frame_size      = ff_mpa_bitrate_tab[hdr->lsf][2][1] * 144000 /
+                                    (hdr->sample_rate << hdr->lsf);
+    /* header and CRC */
+    const int min_main_data       = min_frame_size - 4 - 2 - side_info_size;
+
+    return synth_history + imdct_overlap +
+           (max_main_data_begin + min_main_data - 1) / min_main_data *
+           samples_per_frame;
+}
+
 static int decode_frame(AVCodecContext *avctx, AVFrame *frame,
                         int *got_frame_ptr, AVPacket *avpkt)
 {
@@ -1597,6 +1627,7 @@
                                              (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO;
     if (!avctx->bit_rate)
         avctx->bit_rate = s->hdr.bit_rate;
+    avctx->seek_preroll = FFMAX(avctx->seek_preroll, seek_preroll(&s->hdr));
 
     if (s->hdr.frame_size <= 0) {
         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
diff --git a/libavdevice/avfoundation.m b/libavdevice/avfoundation.m
index 8b7e728..c10ab93 100644
--- a/libavdevice/avfoundation.m
+++ b/libavdevice/avfoundation.m
@@ -57,6 +57,9 @@
 
 static const int avf_time_base = 1000000;
 
+// ~10 minutes of 10ms buffers
+#define AVF_AUDIO_QUEUE_MAX 65536
+
 static const AVRational avf_time_base_q = {
     .num = 1,
     .den = avf_time_base
@@ -149,7 +152,10 @@ typedef struct
     AVCaptureVideoDataOutput *video_output;
     AVCaptureAudioDataOutput *audio_output;
     CMSampleBufferRef         current_frame;
-    CMSampleBufferRef         current_audio_frame;
+    // Audio buffers queue up (FIFO, retained by the array) until read_packet
+    // takes them, so a reader that stalls for longer than one ~10ms buffer
+    // loses nothing. A microphone can't resend, so this is the place to buffer.
+    CFMutableArrayRef         audio_frames;
 
     AVCaptureDevice          *observed_device;
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
@@ -302,16 +308,17 @@ static void unlock_frames(AVFContext* ctx)
 {
     lock_frames(_context);
 
-    while ((_context->current_audio_frame != nil) && !_context->is_stopping) {
-        pthread_cond_wait(&_context->frame_wait_cond, &_context->frame_lock);
-    }
-
     if (_context->is_stopping) {
         unlock_frames(_context);
         return;
     }
 
-    _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
+    // Only a reader that has died can let the queue run away; cap it rather
+    // than eat all memory, and let the pts jump expose the loss.
+    if (CFArrayGetCount(_context->audio_frames) >= AVF_AUDIO_QUEUE_MAX) {
+        CFArrayRemoveValueAtIndex(_context->audio_frames, 0);
+    }
+    CFArrayAppendValue(_context->audio_frames, audioFrame);
 
     unlock_frames(_context);
 
@@ -353,9 +360,8 @@ static void destroy_context(AVFContext* ctx)
         ctx->current_frame = nil;
     }
 
-    if (ctx->current_audio_frame) {
-        CFRelease(ctx->current_audio_frame);
-        ctx->current_audio_frame = nil;
+    if (ctx->audio_frames) {
+        CFRelease(ctx->audio_frames);
     }
 }
 
@@ -745,7 +751,8 @@ static int get_audio_config(AVFormatContext *s)
 
     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
 
-    format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
+    CMSampleBufferRef first_frame = (CMSampleBufferRef)CFArrayGetValueAtIndex(ctx->audio_frames, 0);
+    format_desc = CMSampleBufferGetFormatDescription(first_frame);
     const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
 
     if (!basic_desc) {
@@ -793,7 +800,7 @@ static int get_audio_config(AVFormatContext *s)
     }
 
     if (ctx->audio_non_interleaved) {
-        CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
+        CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(first_frame);
         ctx->audio_buffer_size        = CMBlockBufferGetDataLength(block_buffer);
         ctx->audio_buffer             = av_malloc(ctx->audio_buffer_size);
         if (!ctx->audio_buffer) {
@@ -803,9 +810,6 @@ static int get_audio_config(AVFormatContext *s)
         }
     }
 
-    CFRelease(ctx->current_audio_frame);
-    ctx->current_audio_frame = nil;
-
     unlock_frames(ctx);
 
     return 0;
@@ -1099,6 +1103,11 @@ static int avf_read_header(AVFormatContext *s)
     pthread_mutex_init(&ctx->frame_lock, NULL);
     pthread_cond_init(&ctx->frame_wait_cond, NULL);
     ctx->is_stopping = 0;
+    ctx->audio_frames = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
+    if (!ctx->audio_frames) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
 
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
     CGGetActiveDisplayList(0, NULL, &num_screens);
@@ -1437,16 +1446,19 @@ static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
                 unlock_frames(ctx);
                 return status;
             }
-        } else if (ctx->current_audio_frame != nil) {
-            CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
+        } else if (CFArrayGetCount(ctx->audio_frames) > 0) {
+            CMSampleBufferRef audio_frame = (CMSampleBufferRef)CFArrayGetValueAtIndex(ctx->audio_frames, 0);
+            CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(audio_frame);
             int block_buffer_size         = CMBlockBufferGetDataLength(block_buffer);
 
             if (!block_buffer || !block_buffer_size) {
+                CFArrayRemoveValueAtIndex(ctx->audio_frames, 0);
                 unlock_frames(ctx);
                 return AVERROR(EIO);
             }
 
             if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
+                CFArrayRemoveValueAtIndex(ctx->audio_frames, 0);
                 unlock_frames(ctx);
                 return AVERROR_BUFFER_TOO_SMALL;
             }
@@ -1459,7 +1471,7 @@ static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
             CMItemCount count;
             CMSampleTimingInfo timing_info;
 
-            if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
+            if (CMSampleBufferGetOutputSampleTimingInfoArray(audio_frame, 1, &timing_info, &count) == noErr) {
                 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
                 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
             }
@@ -1472,6 +1484,7 @@ static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
 
                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
                 if (ret != kCMBlockBufferNoErr) {
+                    CFArrayRemoveValueAtIndex(ctx->audio_frames, 0);
                     unlock_frames(ctx);
                     return AVERROR(EIO);
                 }
@@ -1508,13 +1521,13 @@ static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
             } else {
                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
                 if (ret != kCMBlockBufferNoErr) {
+                    CFArrayRemoveValueAtIndex(ctx->audio_frames, 0);
                     unlock_frames(ctx);
                     return AVERROR(EIO);
                 }
             }
 
-            CFRelease(ctx->current_audio_frame);
-            ctx->current_audio_frame = nil;
+            CFArrayRemoveValueAtIndex(ctx->audio_frames, 0);
         } else {
             pkt->data = NULL;
             if (ctx->observed_quit) {
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index 1f6cb96..e0163c1 100644
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -1107,6 +1107,60 @@ static int ebml_read_binary(AVIOContext *pb, int length,
     return 0;
 }
 
+/*
+ * Read a block as ebml_read_binary does, unless its track's stream is
+ * discarded: then nothing would use the data, so only the track number is
+ * read and 1 is returned with *length the bytes left to skip.
+ */
+static int matroska_read_block(MatroskaDemuxContext *matroska, AVIOContext *pb,
+                               uint64_t *length, int64_t pos, EbmlBin *bin)
+{
+    MatroskaTrack *tracks = matroska->tracks.elem;
+    uint8_t head[8];
+    int size = *length, n = FFMIN(size, sizeof(head)), bytes, ret, i;
+
+    if (!n)
+        return ebml_read_binary(pb, size, pos, bin);
+    if ((ret = avio_read(pb, head, n)) != n)
+        return ret < 0 ? ret : NEEDS_CHECKING;
+
+    /* The track number is a variable-length integer, as ebml_read_num reads. */
+    bytes = head[0] ? 8 - ff_log2_tab[head[0]] : n + 1;
+    if (bytes <= n) {
+        uint64_t num = head[0] ^ (1 << ff_log2_tab[head[0]]);
+
+        for (i = 1; i < bytes; i++)
+            num = num << 8 | head[i];
+        for (i = 0; i < matroska->tracks.nb_elem; i++)
+            if (tracks[i].num == num) {
+                if (tracks[i].stream &&
+                    tracks[i].stream->discard >= AVDISCARD_ALL) {
+                    *length = size - n;
+                    return 1;
+                }
+                break;
+            }
+    }
+
+    ret = av_buffer_realloc(&bin->buf, size + AV_INPUT_BUFFER_PADDING_SIZE);
+    if (ret < 0)
+        return ret;
+    memset(bin->buf->data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
+    memcpy(bin->buf->data, head, n);
+
+    bin->data = bin->buf->data;
+    bin->size = size;
+    bin->pos  = pos;
+    if ((ret = avio_read(pb, bin->data + n, size - n)) != size - n) {
+        av_buffer_unref(&bin->buf);
+        bin->data = NULL;
+        bin->size = 0;
+        return ret < 0 ? ret : NEEDS_CHECKING;
+    }
+
+    return 0;
+}
+
 /*
  * Read the next element, but only the header. The contents
  * are supposed to be sub-elements which can be read separately.
@@ -1493,7 +1547,12 @@ static int ebml_parse(MatroskaDemuxContext *matroska,
         res = ebml_read_ascii(pb, length, syntax->def.s, data);
         break;
     case EBML_BIN:
-        res = ebml_read_binary(pb, length, pos_alt, data);
+        if (id == MATROSKA_ID_SIMPLEBLOCK || id == MATROSKA_ID_BLOCK) {
+            res = matroska_read_block(matroska, pb, &length, pos_alt, data);
+            if (res == 1)
+                goto skip;
+        } else
+            res = ebml_read_binary(pb, length, pos_alt, data);
         break;
     case EBML_LEVEL1:
     case EBML_NEST:
diff --git a/libavformat/mp3enc.c b/libavformat/mp3enc.c
index 4ea54f7..11bdf7b 100644
--- a/libavformat/mp3enc.c
+++ b/libavformat/mp3enc.c
@@ -131,6 +131,8 @@ typedef struct MP3Context {
     MPADecodeHeader2 *first_frame;
     int delay;
     int64_t padding;
+    int64_t skip;   /* start delay as packets report it, summed */
+    int skip_done;  /* a packet without any has been seen */
 
     /* index of the audio stream */
     int audio_stream_idx;
@@ -390,12 +392,20 @@ static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
                                                 &side_data_size);
             if (side_data && side_data_size >= 10) {
                 uint32_t discard_padding = AV_RL32(side_data + 4);
+                uint32_t skip_samples    = AV_RL32(side_data);
                 /* Padding longer than a frame is spread over several packets. */
                 mp3->padding = discard_padding ? mp3->padding + discard_padding : 0;
-                if (!mp3->delay)
-                    mp3->delay =  FFMAX((int64_t)AV_RL32(side_data) - 528 - 1, 0);
+                /* So is a start delay longer than a frame, as LAME's is at
+                 * 24 kHz and below, where a frame is 576 samples. */
+                if (!mp3->skip_done) {
+                    if (skip_samples)
+                        mp3->skip += skip_samples;
+                    else
+                        mp3->skip_done = 1;
+                }
             } else {
                 mp3->padding = 0;
+                mp3->skip_done = 1;
             }
         }
     }
@@ -509,6 +519,7 @@ static void mp3_update_xing(AVFormatContext *s)
     }
 
     /* write encoder delay/padding */
+    mp3->delay = FFMIN(FFMAX(mp3->skip - 528 - 1, 0), INT_MAX);
     if (mp3->padding)
         mp3->padding += 528 + 1;
     if (mp3->delay >= 1 << 12) {
diff --git a/libavformat/webp_anim_dec.c b/libavformat/webp_anim_dec.c
index 14abb61..1bf7a1a 100644
--- a/libavformat/webp_anim_dec.c
+++ b/libavformat/webp_anim_dec.c
@@ -272,7 +272,12 @@ static int webp_anim_read_packet(AVFormatContext *s, AVPacket *pkt)
             ret = av_get_packet(pb, pkt, size);
             if (ret < 0)
                 return ret;
-            if (!ctx->cur_frame++)
+            /* The chunk's start: the generic index seeks back to pkt->pos, and
+             * from the payload this would read the frame's data as a chunk. */
+            pkt->pos = offset;
+            /* Keyed by offset so a seek back to the start still marks the
+             * first frame key, which resets the decoder's canvas. */
+            if (offset == ctx->first_anmf_offset)
                 pkt->flags |= AV_PKT_FLAG_KEY;
             pkt->pts = AV_NOPTS_VALUE;
             pkt->dts = AV_NOPTS_VALUE;