Commit 3d47072028 for ffmpeg
commit 3d47072028c5f911488fd6a680b66b56633356b5
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date: Thu Dec 3 00:29:33 2026 -0600
avformat/mov: seek to a key sample that recovers by the target
A video key sample can be a recovery point whose pictures are whole only
some pictures later, so a seek lands before the target and the decoder
drops frames past it.
With AVSEEK_FLAG_PREROLL set, give the samples from each key sample to
the codec parser and land on the latest one whose first full picture is
presented between the lower bound of the seek and the target, within
300 samples and 64 MiB.
The ffmpeg CLI sets stream discards after its initial seek, so an
unselected video stream still moves that seek back a recovery period.
diff --git a/doc/APIchanges b/doc/APIchanges
index d25504d346..9413e51efd 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -2,6 +2,12 @@ The last version increases of all libraries were on 2026-06-23.
API changes, most recent first:
+2026-12-xx - xxxxxxxxxx - lavf 63.21.102 - avformat.h
+ With AVSEEK_FLAG_PREROLL set, a seek in MP4/MOV may land on an earlier
+ video key sample when the one before the target is a recovery point whose
+ codec parser reports a full picture only after the target, so that the
+ first full picture is presented by the target.
+
2026-11-xx - xxxxxxxxxx - lavu 61.21.102 - hwcontext_amf.h
AMF frames can be mapped to D3D11 frames with av_hwframe_map().
diff --git a/doc/formats.texi b/doc/formats.texi
index 36b8b9718b..52e259fead 100644
--- a/doc/formats.texi
+++ b/doc/formats.texi
@@ -86,6 +86,9 @@ Allow seeking to non-keyframes on demuxer level when supported.
@item preroll
Move the target of a seek back by the audio pre-roll, for a caller that
decodes. The seek can then land on an earlier video keyframe.
+In MP4 and MOV, it also lands on an earlier video key sample when the
+recovery point of the one before the target comes after it, as with intra
+refresh, for the codecs whose parser tracks recovery points.
@end table
@item seek2any @var{integer} (@emph{input})
diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index 6768627379..5d1cead403 100644
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -2557,7 +2557,8 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt);
* @param flags flags which select direction and seeking mode
*
* With AVSEEK_FLAG_PREROLL set, timestamp moves back by the audio pre-roll,
- * which is discarded after the seek, as with avformat_seek_file().
+ * which is discarded after the seek, and a demuxer may land on an earlier
+ * keyframe for video recovery, as with avformat_seek_file().
*
* @return >= 0 on success
*/
@@ -2590,6 +2591,13 @@ int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp,
* may be left. max_ts moves back as much, unless it is INT64_MAX. If that
* seek fails, the seek is done to ts.
*
+ * With AVSEEK_FLAG_PREROLL, a demuxer may also land on an earlier keyframe
+ * when the signalled recovery point of the one before ts comes after ts, as
+ * long as the recovery point is not before min_ts. The MP4/MOV demuxer does
+ * it for video key samples whose codec parser tracks recovery points, as
+ * with intra refresh, parsing at most 300 samples and 64 MiB per stream and
+ * in the fragments already read.
+ *
* The first packet read after a seek from an audio stream carries
* AV_PKT_DATA_SKIP_SAMPLES side data to discard the rest of the priming
* (AVCodecParameters.initial_padding) if the seek landed inside it. With
@@ -2750,7 +2758,7 @@ void avformat_close_input(AVFormatContext **s);
#define AVSEEK_FLAG_BYTE 2 ///< seeking based on position in bytes
#define AVSEEK_FLAG_ANY 4 ///< seek to any frame, even non-keyframes
#define AVSEEK_FLAG_FRAME 8 ///< seeking based on frame number
-#define AVSEEK_FLAG_PREROLL 16 ///< move the target back by the audio pre-roll, see avformat_seek_file()
+#define AVSEEK_FLAG_PREROLL 16 ///< move the target back by the audio pre-roll and land before the video recovery point, see avformat_seek_file()
/**
* @addtogroup lavf_encoding
diff --git a/libavformat/mov.c b/libavformat/mov.c
index 37ad0087f5..8257e980f1 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -61,6 +61,7 @@
#include "libavcodec/mpegaudiodata.h"
#include "libavcodec/mpegaudiodecheader.h"
#include "libavcodec/mlp_parse.h"
+#include "libavcodec/parser.h"
#include "avformat.h"
#include "internal.h"
#include "avio_internal.h"
@@ -13677,7 +13678,211 @@ static int can_seek_to_key_sample(AVStream *st, int sample, int64_t requested_pt
return 1;
}
-static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
+/* How many samples, and how many bytes of them, a seek with
+ * AVSEEK_FLAG_PREROLL parses to find a key sample from which the video is
+ * whole at the target. */
+#define MOV_RECOVERY_MAX_SAMPLES 300
+#define MOV_RECOVERY_MAX_BYTES (64 << 20)
+
+typedef struct MOVRecoveryProbe {
+ AVCodecContext *avctx;
+ AVCodecParserContext *parser;
+ uint8_t *buf;
+ unsigned buf_size;
+ int scanned;
+ int64_t bytes;
+} MOVRecoveryProbe;
+
+/**
+ * Give a sample to the codec parser.
+ *
+ * @param full_picture set to what avpriv_parser_full_picture() returns
+ */
+static int mov_parse_sample(AVStream *st, MOVRecoveryProbe *probe, int sample,
+ int *full_picture)
+{
+ MOVStreamContext *sc = st->priv_data;
+ const AVIndexEntry *e = &ffstream(st)->index_entries[sample];
+ uint8_t *out;
+ int out_size;
+
+ if (++probe->scanned > MOV_RECOVERY_MAX_SAMPLES ||
+ e->size > MOV_RECOVERY_MAX_BYTES - probe->bytes)
+ return AVERROR(ERANGE);
+ if (e->size <= 0 || e->pos < 0)
+ return AVERROR_INVALIDDATA;
+ probe->bytes += e->size;
+ if (avio_seek(sc->pb, e->pos, SEEK_SET) != e->pos)
+ return AVERROR(EIO);
+ av_fast_padded_malloc(&probe->buf, &probe->buf_size, e->size);
+ if (!probe->buf)
+ return AVERROR(ENOMEM);
+ if (avio_read(sc->pb, probe->buf, e->size) != e->size)
+ return AVERROR_INVALIDDATA;
+ av_parser_parse2(probe->parser, probe->avctx, &out, &out_size,
+ probe->buf, e->size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
+ *full_picture = avpriv_parser_full_picture(probe->parser);
+ return 0;
+}
+
+/** The pts of a sample, as mov_finalize_packet() sets it. */
+static int64_t mov_sample_pts(const MOVStreamContext *sc, const FFStream *sti,
+ int sample)
+{
+ int64_t dts = sti->index_entries[sample].timestamp;
+ int64_t time_sample = 0;
+
+ if (!sc->ctts_count)
+ return dts;
+ for (unsigned i = 0; i < sc->tts_count; i++) {
+ time_sample += sc->tts_data[i].count;
+ if (time_sample > sample)
+ return av_sat_add64(dts, av_sat_add64(sc->dts_shift,
+ sc->tts_data[i].offset));
+ }
+ return dts;
+}
+
+/**
+ * Whether the index holds every sample between two file positions. With a
+ * complete fragment index, a seek reads only the fragments it lands in.
+ */
+static int mov_index_is_contiguous(MOVContext *mov, int64_t start, int64_t end)
+{
+ MOVFragmentIndex *frag_index = &mov->frag_index;
+
+ if (!frag_index->complete)
+ return 1;
+ for (int i = FFMAX(search_frag_moof_offset(frag_index, start) - 1, 0);
+ i < frag_index->nb_items && frag_index->item[i].moof_offset < end; i++)
+ if (!frag_index->item[i].headers_read)
+ return 0;
+ return 1;
+}
+
+static int mov_recovery_before_min(const FFFormatContext *si,
+ const AVStream *st, int64_t pts)
+{
+ return si->seek_min_ts != INT64_MIN &&
+ av_compare_ts(pts, st->time_base,
+ si->seek_min_ts, si->seek_time_base) < 0;
+}
+
+/**
+ * Find the sample from which the pictures decoded from a key sample are
+ * whole, as the codec parser reports it. A key sample the parser knows
+ * nothing about is whole.
+ *
+ * @return 1 when that sample is set in recovered, 0 when it comes after the
+ * target or the recovery is unknown, < 0 to give up
+ */
+static int mov_recovered_sample(AVFormatContext *s, AVStream *st,
+ MOVRecoveryProbe *probe, int key,
+ int64_t target, int *recovered)
+{
+ MOVContext *mov = s->priv_data;
+ const FFStream *const sti = ffstream(st);
+ int i = key, state, ret;
+ int64_t end;
+
+ av_parser_close(probe->parser);
+ probe->parser = av_parser_init(st->codecpar->codec_id);
+ if (!probe->parser)
+ return AVERROR(ENOSYS);
+ probe->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
+
+ ret = mov_parse_sample(st, probe, key, &state);
+ if (ret < 0)
+ return ret;
+ while (!state) {
+ if (++i >= sti->nb_index_entries ||
+ sti->index_entries[i].timestamp > target)
+ break;
+ ret = mov_parse_sample(st, probe, i, &state);
+ if (ret < 0)
+ return ret;
+ }
+ end = i < sti->nb_index_entries ? sti->index_entries[i].pos : INT64_MAX;
+ if (!mov_index_is_contiguous(mov, sti->index_entries[key].pos, end))
+ return AVERROR(EAGAIN);
+ *recovered = i;
+ return i == key || state == 1;
+}
+
+/**
+ * A key sample may be a recovery point, as with the intra refresh of a low
+ * latency encoder. Look back for a key sample whose recovered picture is
+ * presented by the target, and not before the lower bound of the seek.
+ *
+ * @return that key sample, or the given one when there is none within
+ * MOV_RECOVERY_MAX_SAMPLES samples
+ */
+static int mov_recovery_seek(AVFormatContext *s, AVStream *st, int sample,
+ int64_t target)
+{
+ MOVContext *mov = s->priv_data;
+ const MOVStreamContext *sc = st->priv_data;
+ const FFStream *const sti = ffstream(st);
+ const FFFormatContext *si = ffformatcontext(s);
+ MOVRecoveryProbe probe = { 0 };
+ int ret = sample;
+
+ if (!sc->pb || sc->stsd_count != 1 ||
+ !(sc->pb->seekable & AVIO_SEEKABLE_NORMAL) ||
+ sc->cenc.aes_ctr || sc->cenc.encryption_index ||
+ sc->cenc.default_encrypted_sample)
+ return sample;
+
+ probe.avctx = avcodec_alloc_context3(NULL);
+ if (!probe.avctx ||
+ avcodec_parameters_to_context(probe.avctx, st->codecpar) < 0)
+ goto end;
+
+ for (int key = sample;;) {
+ int recovered, found;
+
+ found = mov_recovered_sample(s, st, &probe, key, target, &recovered);
+ // A key sample that is whole at once.
+ if (found < 0 || (found && key == sample && recovered == sample))
+ goto end;
+ if (found) {
+ int64_t pts = mov_sample_pts(sc, sti, recovered);
+
+ // Looking further back lands earlier.
+ if (mov_recovery_before_min(si, st, pts))
+ goto end;
+ if (pts <= target) {
+ if (key != sample)
+ av_log(s, AV_LOG_DEBUG, "stream %d, sample %d recovers "
+ "after the target, seeking to sample %d\n",
+ st->index, sample, key);
+ ret = key;
+ goto end;
+ }
+ }
+
+ do {
+ if (!key-- || sample - key > MOV_RECOVERY_MAX_SAMPLES)
+ goto end;
+ } while (!(sti->index_entries[key].flags & AVINDEX_KEYFRAME));
+ if (!mov_index_is_contiguous(mov, sti->index_entries[key].pos,
+ sti->index_entries[sample].pos))
+ goto end;
+ }
+
+end:
+ av_parser_close(probe.parser);
+ avcodec_free_context(&probe.avctx);
+ av_freep(&probe.buf);
+ return ret;
+}
+
+/**
+ * @param target the presentation time a recovery point must recover by, the
+ * requested one for every stream
+ */
+static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp,
+ int64_t target, int flags)
{
MOVStreamContext *sc = st->priv_data;
FFStream *const sti = ffstream(st);
@@ -13718,6 +13923,12 @@ static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp,
timestamp = next_ts;
}
+ if (ffformatcontext(s)->seek_has_preroll_flag && sample > 0 &&
+ (flags & AVSEEK_FLAG_BACKWARD) &&
+ st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
+ st->discard < AVDISCARD_ALL && !(flags & AVSEEK_FLAG_ANY))
+ sample = mov_recovery_seek(s, st, sample, target);
+
mov_current_sample_set(sc, sample);
av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
/* adjust time to sample index */
@@ -13771,6 +13982,8 @@ static int64_t mov_get_skip_samples(AVStream *st, int sample)
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
{
MOVContext *mc = s->priv_data;
+ const FFFormatContext *si = ffformatcontext(s);
+ int64_t recovery_target = sample_time;
AVStream *st;
FFStream *sti;
int sample;
@@ -13781,7 +13994,11 @@ static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
st = s->streams[stream_index];
sti = ffstream(st);
- sample = mov_seek_stream(s, st, sample_time, flags);
+ // The pre-roll moved sample_time back; recovery is due by the request.
+ if (si->seek_has_preroll_flag)
+ recovery_target = av_rescale_q(si->seek_ts, si->seek_time_base,
+ st->time_base);
+ sample = mov_seek_stream(s, st, sample_time, recovery_target, flags);
if (sample < 0)
return sample;
@@ -13795,14 +14012,15 @@ static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
AVStream *const st = s->streams[i];
FFStream *const sti = ffstream(st);
const MOVStreamContext *sc = st->priv_data;
- int64_t timestamp;
+ int64_t timestamp, target;
if (stream_index == i)
continue;
mc->next_root_atom = 0;
timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
- sample = mov_seek_stream(s, st, timestamp, flags);
+ target = av_rescale_q(recovery_target, s->streams[stream_index]->time_base, st->time_base);
+ sample = mov_seek_stream(s, st, timestamp, target, flags);
if (sample >= 0)
sti->skip_samples = mov_get_skip_samples(st, sample);
diff --git a/libavformat/version.h b/libavformat/version.h
index 2f54f57c02..227322c916 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -32,7 +32,7 @@
#include "version_major.h"
#define LIBAVFORMAT_VERSION_MINOR 21
-#define LIBAVFORMAT_VERSION_MICRO 101
+#define LIBAVFORMAT_VERSION_MICRO 102
#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
LIBAVFORMAT_VERSION_MINOR, \