PR #26313 opened by fengchenguang
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26313
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26313.patch

MPEG-TS does not provide a keyframe index, and mpegts_get_dts() marks
every probed timestamp as a keyframe. A timestamp seek can therefore
land in the middle of a GOP and force decoders to start from unavailable
references.

Add keyframe-aware seek callbacks that scan a bounded window around the
binary-search landing, honor the requested timestamp range, and move to
the nearest real AV_PKT_FLAG_KEY packet. Preserve existing fallback
behavior for non-video streams, byte seeks, network inputs, and streams
without usable keyframe information.

Update the MPEG-TS seek FATE reference to reflect the corrected landing
positions.

Signed-off-by: fengchenguang <[email protected]>

# Summary of changes

Briefly describe what this PR does and why.

<!--
If this PR requires new FATE test samples, attach them to the PR and
list their target paths below (relative to the fate-suite root).

Attached filenames must match the sample's filename:

```fate-samples
# e.g. vorbis/new-sample.ogg
```
-->



>From aa54df143c24b1f1bfc2ee9b8e7ed213bdb443f4 Mon Sep 17 00:00:00 2001
From: fengchenguang <[email protected]>
Date: Tue, 24 Nov 2026 15:31:45 +0800
Subject: [PATCH] avformat/mpegts: seek to keyframes for timestamp-based seeks

MPEG-TS does not provide a keyframe index, and mpegts_get_dts() marks
every probed timestamp as a keyframe. A timestamp seek can therefore
land in the middle of a GOP and force decoders to start from unavailable
references.

Add keyframe-aware seek callbacks that scan a bounded window around the
binary-search landing, honor the requested timestamp range, and move to
the nearest real AV_PKT_FLAG_KEY packet. Preserve existing fallback
behavior for non-video streams, byte seeks, network inputs, and streams
without usable keyframe information.

Update the MPEG-TS seek FATE reference to reflect the corrected landing
positions.

Signed-off-by: fengchenguang <[email protected]>
---
 libavformat/mpegts.c   | 286 +++++++++++++++++++++++++++++++++++++++++
 tests/ref/seek/lavf-ts |   6 +-
 2 files changed, 289 insertions(+), 3 deletions(-)

diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 8e6d175e9a6..f83af706cac 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -3848,6 +3848,290 @@ static int64_t mpegts_get_dts(AVFormatContext *s, int 
stream_index,
     return AV_NOPTS_VALUE;
 }
 
+/* Align pos to the TS packet boundary used by mpegts_get_dts(). */
+static int64_t mpegts_align_packet_pos(MpegTSContext *ts, int64_t pos)
+{
+    int pos47 = ts->pos47_full % ts->raw_packet_size;
+
+    return ((pos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
+           ts->raw_packet_size + pos47;
+}
+
+/* Start with roughly one second of stream and grow the scan if necessary. */
+static int64_t mpegts_seek_scan_size(AVFormatContext *s, AVStream *st)
+{
+    int64_t bit_rate = s->bit_rate > 0 ? s->bit_rate : st->codecpar->bit_rate;
+    int64_t size     = bit_rate > 0 ? av_rescale(bit_rate, 1, 8)
+                                    : 8 * 1024 * 1024;
+
+    return av_clip64(size, 2 * 1024 * 1024, 16 * 1024 * 1024);
+}
+
+/*
+ * Find a random access point in the scan window. Without an index, the
+ * timestamp seek can land in the middle of a GOP.
+ */
+static int64_t mpegts_find_keyframe(AVFormatContext *s, int stream_index,
+                                    int64_t min_ts, int64_t target_ts,
+                                    int64_t max_ts, int64_t scan_start,
+                                    int64_t scan_end, int preference,
+                                    int64_t *ts, int *found_key)
+{
+    AVPacket *pkt = av_packet_alloc();
+    int64_t pos = scan_start;
+    int64_t prev_pos = -1, prev_ts = AV_NOPTS_VALUE;
+    int64_t next_pos = -1, next_ts = AV_NOPTS_VALUE;
+    int seen_after_target = 0;
+
+    if (!pkt)
+        return -1;
+    ff_read_frame_flush(s);
+    if (avio_seek(s->pb, scan_start, SEEK_SET) < 0) {
+        av_packet_free(&pkt);
+        return -1;
+    }
+
+    while (pos < scan_end) {
+        int ret = av_read_frame(s, pkt);
+        int done;
+
+        if (ret < 0)
+            break;
+        if (pkt->pos >= 0)
+            pos = pkt->pos;
+        if (pkt->stream_index == stream_index &&
+            pkt->flags & AV_PKT_FLAG_KEY)
+            *found_key = 1;
+        if (pkt->stream_index == stream_index && pkt->dts != AV_NOPTS_VALUE) {
+            if (pkt->dts > target_ts) {
+                seen_after_target = 1;
+                if ((pkt->flags & AV_PKT_FLAG_KEY) &&
+                    pkt->dts <= max_ts && next_pos < 0) {
+                    next_pos = pkt->pos;
+                    next_ts  = pkt->dts;
+                }
+            } else if ((pkt->flags & AV_PKT_FLAG_KEY) &&
+                       pkt->dts >= min_ts) {
+                prev_pos = pkt->pos;
+                prev_ts  = pkt->dts;
+            }
+
+            if (pkt->dts > max_ts ||
+                (preference > 0 && seen_after_target) ||
+                (preference <= 0 && next_pos >= 0))
+                done = 1;
+            else
+                done = 0;
+        } else {
+            done = 0;
+        }
+        av_packet_unref(pkt);
+
+        if (done)
+            break;
+    }
+    av_packet_free(&pkt);
+
+    if (prev_pos >= 0 && prev_ts == target_ts) {
+        *ts = prev_ts;
+        return prev_pos;
+    }
+    if (prev_pos >= 0 && next_pos >= 0) {
+        if (preference > 0 ||
+            (preference < 0 && target_ts - prev_ts <= next_ts - target_ts)) {
+            *ts = prev_ts;
+            return prev_pos;
+        }
+        *ts = next_ts;
+        return next_pos;
+    }
+    if (prev_pos >= 0) {
+        *ts = prev_ts;
+        return prev_pos;
+    }
+    if (next_pos >= 0) {
+        *ts = next_ts;
+        return next_pos;
+    }
+    return -1;
+}
+
+static int mpegts_read_seek_common(AVFormatContext *s, int stream_index,
+                                   int64_t min_ts, int64_t target_ts,
+                                   int64_t max_ts, int flags, int preference,
+                                   int fallback)
+{
+    MpegTSContext *ts = s->priv_data;
+    AVStream *st;
+    int64_t seek_back, landing, scan_start, scan_end;
+    int64_t scan_size, max_scan, kf_pos;
+    int64_t kf_ts = AV_NOPTS_VALUE;
+    int found_key = 0;
+
+    if (stream_index < 0 || stream_index >= (int)s->nb_streams)
+        return AVERROR(EINVAL);
+    st = s->streams[stream_index];
+
+    if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
+        (flags & AVSEEK_FLAG_ANY))
+        return AVERROR(ENOSYS);
+    if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
+        return AVERROR(ENOSYS);
+
+    seek_back = avio_tell(s->pb);
+
+    /* Locate an approximate position first, then snap it to a real keyframe. 
*/
+    if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0) {
+        if (seek_back >= 0)
+            avio_seek(s->pb, seek_back, SEEK_SET);
+        return -1;
+    }
+    landing = avio_tell(s->pb);
+
+    scan_size = FFMIN(mpegts_seek_scan_size(s, st) * 2,
+                      64 * 1024 * 1024);
+    max_scan  = 64 * 1024 * 1024;
+    for (;;) {
+        int64_t half_scan = scan_size / 2;
+
+        scan_start = mpegts_align_packet_pos(ts,
+                                             FFMAX(landing - half_scan, 0));
+        scan_end   = landing + scan_size - half_scan;
+        if (avio_size(s->pb) > 0)
+            scan_end = FFMIN(scan_end, avio_size(s->pb));
+
+        kf_pos = mpegts_find_keyframe(s, stream_index, min_ts, target_ts,
+                                      max_ts, scan_start, scan_end,
+                                      preference, &kf_ts, &found_key);
+        if (kf_pos >= 0)
+            break;
+        if (scan_size >= max_scan)
+            break;
+        scan_size = FFMIN(scan_size * 2, max_scan);
+    }
+    if (kf_pos < 0) {
+        if (!fallback && found_key &&
+            (st->start_time == AV_NOPTS_VALUE ||
+             target_ts >= st->start_time)) {
+            if (seek_back >= 0) {
+                avio_seek(s->pb, seek_back, SEEK_SET);
+                ff_read_frame_flush(s);
+            }
+            return AVERROR(ERANGE);
+        }
+
+        /* Keep the landing when the codec provides no keyframe information. */
+        av_log(s, AV_LOG_DEBUG,
+               "mpegts: no usable keyframe information near ts %"PRId64
+               ", keeping pos %"PRId64"\n", target_ts, landing);
+        if (avio_seek(s->pb, landing, SEEK_SET) < 0)
+            return -1;
+        ff_read_frame_flush(s);
+        avpriv_update_cur_dts(s, st, target_ts);
+        return 0;
+    }
+
+    av_log(s, AV_LOG_DEBUG,
+           "mpegts: seeking to keyframe at pos %"PRId64" ts %"PRId64
+           " (target ts %"PRId64", range %"PRId64"..%"PRId64
+           ", landed at %"PRId64", scanned %"PRId64" from %"PRId64")\n",
+           kf_pos, kf_ts, target_ts, min_ts, max_ts,
+           landing, scan_size, scan_start);
+
+    if (avio_seek(s->pb, kf_pos, SEEK_SET) < 0)
+        return -1;
+    ff_read_frame_flush(s);
+    avpriv_update_cur_dts(s, st, kf_ts);
+    return 0;
+}
+
+static int mpegts_read_seek(AVFormatContext *s, int stream_index,
+                            int64_t target_ts, int flags)
+{
+    int preference = !!(flags & AVSEEK_FLAG_BACKWARD);
+
+    if (flags & AVSEEK_FLAG_FRAME)
+        return AVERROR(ENOSYS);
+    return mpegts_read_seek_common(s, stream_index, INT64_MIN, target_ts,
+                                   INT64_MAX, flags, preference, 1);
+}
+
+static int mpegts_read_seek_binary(AVFormatContext *s, int stream_index,
+                                   int64_t min_ts, int64_t target_ts,
+                                   int64_t max_ts, int flags)
+{
+    int dir = (target_ts - (uint64_t)min_ts >
+               (uint64_t)max_ts - target_ts)
+                  ? AVSEEK_FLAG_BACKWARD : 0;
+    int ret = ff_seek_frame_binary(s, stream_index, target_ts, flags | dir);
+
+    if (ret < 0 && target_ts != min_ts && max_ts != target_ts) {
+        ret = ff_seek_frame_binary(s, stream_index,
+                                   dir ? max_ts : min_ts, flags | dir);
+        if (ret >= 0)
+            ret = ff_seek_frame_binary(s, stream_index, target_ts,
+                                       flags | (dir ^ AVSEEK_FLAG_BACKWARD));
+    }
+    return ret;
+}
+
+static int mpegts_read_seek2(AVFormatContext *s, int stream_index,
+                             int64_t min_ts, int64_t target_ts,
+                             int64_t max_ts, int flags)
+{
+    AVStream *st;
+    const char *protocol;
+    int64_t pos;
+    int preference;
+
+    if (min_ts > target_ts || max_ts < target_ts)
+        return AVERROR(EINVAL);
+
+    if (flags & AVSEEK_FLAG_BYTE) {
+        int64_t size = avio_size(s->pb);
+        int64_t pos_min, pos_max;
+        int ret;
+
+        if (size <= 0)
+            return AVERROR(ENOSYS);
+        pos_min = FFMAX(min_ts, 0);
+        pos_max = FFMIN(max_ts, size - 1);
+        if (pos_min > pos_max)
+            return AVERROR(ERANGE);
+        pos = av_clip64(target_ts, pos_min, pos_max);
+        if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
+            return ret;
+        s->io_repositioned = 1;
+        return 0;
+    }
+    if (flags & AVSEEK_FLAG_FRAME)
+        return AVERROR(ENOSYS);
+
+    if (stream_index < 0) {
+        stream_index = av_find_default_stream_index(s);
+        if (stream_index < 0)
+            return AVERROR(EINVAL);
+        ff_rescale_interval(AV_TIME_BASE_Q, 
s->streams[stream_index]->time_base,
+                            &min_ts, &target_ts, &max_ts);
+    }
+    if (stream_index >= (int)s->nb_streams)
+        return AVERROR(EINVAL);
+
+    st = s->streams[stream_index];
+    protocol = s->url ? avio_find_protocol_name(s->url) : NULL;
+    if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
+        (flags & AVSEEK_FLAG_ANY) ||
+        !protocol || strcmp(protocol, "file") ||
+        (s->flags & AVFMT_FLAG_CUSTOM_IO))
+        return mpegts_read_seek_binary(s, stream_index, min_ts, target_ts,
+                                       max_ts, flags);
+
+    preference = max_ts <= target_ts ? 1 :
+                 min_ts >= target_ts ? 0 : -1;
+    return mpegts_read_seek_common(s, stream_index, min_ts, target_ts,
+                                   max_ts, flags, preference, 0);
+}
+
 /**************************************************************/
 /* parsing functions - called from other demuxers such as RTP */
 
@@ -3914,6 +4198,8 @@ const FFInputFormat ff_mpegts_demuxer = {
     .read_header    = mpegts_read_header,
     .read_packet    = mpegts_read_packet,
     .read_close     = mpegts_read_close,
+    .read_seek      = mpegts_read_seek,
+    .read_seek2     = mpegts_read_seek2,
     .read_timestamp = mpegts_get_dts,
     .flags_internal  = FF_INFMT_FLAG_PREFER_CODEC_FRAMERATE,
 };
diff --git a/tests/ref/seek/lavf-ts b/tests/ref/seek/lavf-ts
index 3347b7ead50..0fddf3aac7b 100644
--- a/tests/ref/seek/lavf-ts
+++ b/tests/ref/seek/lavf-ts
@@ -16,7 +16,7 @@ ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos: 
   564 size: 24801
 ret: 0         st:-1 flags:1  ts:-0.740831
 ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos:    564 size: 
24801
 ret: 0         st: 0 flags:0  ts: 2.153333
-ret: 0         st: 1 flags:1 dts: 1.794811 pts: 1.794811 pos: 308508 size:   
209
+ret: 0         st: 1 flags:1 dts: 2.160522 pts: 2.160522 pos: 386716 size:   
209
 ret: 0         st: 0 flags:1  ts: 1.047500
 ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos:    564 size: 
24801
 ret: 0         st: 1 flags:0  ts:-0.058333
@@ -24,7 +24,7 @@ ret: 0         st: 1 flags:1 dts: 1.429089 pts: 1.429089 pos: 
152844 size:   208
 ret: 0         st: 1 flags:1  ts: 2.835833
 ret: 0         st: 1 flags:1 dts: 2.160522 pts: 2.160522 pos: 386716 size:   
209
 ret: 0         st:-1 flags:0  ts: 1.730004
-ret: 0         st: 1 flags:1 dts: 1.429089 pts: 1.429089 pos: 152844 size:   
208
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.920000 pos: 181420 size: 
24786
 ret: 0         st:-1 flags:1  ts: 0.624171
 ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos:    564 size: 
24801
 ret: 0         st: 0 flags:0  ts:-0.481667
@@ -38,7 +38,7 @@ ret: 0         st: 1 flags:1 dts: 1.429089 pts: 1.429089 pos: 
152844 size:   208
 ret: 0         st:-1 flags:0  ts:-0.904994
 ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos:    564 size: 
24801
 ret: 0         st:-1 flags:1  ts: 1.989173
-ret: 0         st: 0 flags:0 dts: 1.960000 pts: 2.000000 pos: 224848 size: 
15019
+ret: 0         st: 0 flags:1 dts: 1.880000 pts: 1.920000 pos: 181420 size: 
24786
 ret: 0         st: 0 flags:0  ts: 0.883344
 ret: 0         st: 0 flags:1 dts: 1.400000 pts: 1.440000 pos:    564 size: 
24801
 ret: 0         st: 0 flags:1  ts:-0.222489
-- 
2.54.1

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to