PR #26262 opened by Baptiste Coudurier (bcoudurier)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26262
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26262.patch

Two CMAF timing fixes reported as pre-existing on 
https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25931.

- Open GOP start: with negative CTS offsets, leading pictures were presented 
before tfdt (ISO/IEC 23000-19 7.5.17). `h264/twofields_packet.mp4` remuxed with 
`-movflags cmaf+frag_keyframe` had every fragment start 2 frames early.
- Delayed tracks with edit lists: an empty edit was written, which CMAF forbids 
(7.5.13). The delay now goes in tfdt with a single offset edit. HLS fMP4 with 
`+cmaf` used this path, so its init segment loses 12 bytes; read-back 
timestamps are unchanged.

api-movenc covers both cases and prints tfdt, composition times and edit lists.



>From cf0163ec3ee4e30c2aaacab911a3421d145168c7 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 21 Nov 2026 12:14:33 -0800
Subject: [PATCH 1/2] avformat/movenc: compose leading pictures at tfdt with
 negative CTS offsets

A track starting on an open GOP key frame had its leading pictures
presented before tfdt, against ISO/IEC 23000-19 7.5.17.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/movenc.c        |  39 +++++++++++
 libavformat/movenc.h        |   1 +
 tests/api/api-movenc-test.c | 126 ++++++++++++++++++++++++++++++++++++
 tests/ref/fate/api-movenc   |  10 +++
 4 files changed, 176 insertions(+)

diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index f302a366129..b9bede77129 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -6945,6 +6945,38 @@ static int mov_finish_fragment(MOVMuxContext *mov, 
MOVTrack *track,
     return 0;
 }
 
+/**
+ * With negative CTS offsets, dts_shift composes the first sample at its
+ * decode time. A track starting on an open GOP key frame has leading
+ * pictures presented before it, so lower the shift to compose the earliest
+ * presented sample of the first fragment at that time instead.
+ */
+static void mov_shift_leading_pictures(MOVTrack *track)
+{
+    int64_t shift = 0;
+
+    if (track->dts_shift == AV_NOPTS_VALUE || track->dts_shift_final ||
+        !track->entry)
+        return;
+    track->dts_shift_final = 1;
+
+    for (int i = 1; i < track->entry; i++)
+        shift = FFMIN(shift, track->cluster[i].dts + track->cluster[i].cts -
+                             track->cluster[0].dts);
+    if (!shift || shift < INT_MIN / 2)
+        return;
+
+    for (int i = 0; i < track->entry; i++) {
+        track->cluster[i].dts += shift;
+        track->cluster[i].cts -= shift;
+    }
+    track->start_dts += shift;
+    track->dts_shift += shift;
+    if (track->start_cts != AV_NOPTS_VALUE)
+        track->start_cts -= shift;
+    track->flags |= MOV_TRACK_CTTS;
+}
+
 static int mov_flush_fragment(AVFormatContext *s, int force)
 {
     MOVMuxContext *mov = s->priv_data;
@@ -7015,6 +7047,9 @@ static int mov_flush_fragment(AVFormatContext *s, int 
force)
         }
     }
 
+    for (i = 0; i < mov->nb_tracks; i++)
+        mov_shift_leading_pictures(&mov->tracks[i]);
+
     if (!mov->moov_written) {
         int64_t pos = avio_tell(s->pb);
         uint8_t *buf;
@@ -7778,6 +7813,7 @@ static int mov_write_single_packet(AVFormatContext *s, 
AVPacket *pkt)
              trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
             (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
         if (frag_duration >= mov->min_fragment_duration) {
+            int64_t dts_shift = trk->dts_shift;
             if (trk->entry) {
                 // Set the duration of this track to line up with the next
                 // sample in this track. This avoids relying on AVPacket
@@ -7796,6 +7832,9 @@ static int mov_write_single_packet(AVFormatContext *s, 
AVPacket *pkt)
                 trk->end_reliable = 1;
             }
             mov_auto_flush_fragment(s, 0);
+            /* The flush may have lowered the shift for leading pictures. */
+            if (dts_shift != AV_NOPTS_VALUE)
+                pkt->dts += trk->dts_shift - dts_shift;
         }
     }
 
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index ce5f928015c..074ec83ca60 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -140,6 +140,7 @@ typedef struct MOVTrack {
     int64_t     elst_end_pts;
     int         end_reliable;
     int64_t     dts_shift;
+    int         dts_shift_final; ///< dts_shift covers the leading pictures
 
     int         hint_track;   ///< the track that hints this track, -1 if no 
hint track is set
     int         nb_src_track;
diff --git a/tests/api/api-movenc-test.c b/tests/api/api-movenc-test.c
index f4a78313f5b..1bbb6fb3246 100644
--- a/tests/api/api-movenc-test.c
+++ b/tests/api/api-movenc-test.c
@@ -75,6 +75,10 @@ static int clear_duration;
 static int force_iobuf_size;
 static int do_interleave;
 static int fake_pkt_duration;
+static int open_gop;
+static int dump;
+static uint8_t *dump_buf;
+static int dump_size;
 
 static int num_warnings;
 
@@ -100,6 +104,14 @@ static void reset_count_warnings(void)
 
 static int io_write(void *opaque, const uint8_t *buf, int size)
 {
+    if (dump) {
+        uint8_t *tmp = av_realloc(dump_buf, dump_size + size);
+        if (!tmp)
+            exit(1);
+        dump_buf = tmp;
+        memcpy(dump_buf + dump_size, buf, size);
+        dump_size += size;
+    }
     out_size += size;
     av_md5_update(md5, buf, size);
     if (out)
@@ -152,9 +164,104 @@ static void init_out(const char *name)
     out_size = 0;
 }
 
+typedef struct BoxDump {
+    int track_id;
+    uint32_t default_duration;
+    int64_t tfdt, dts, first, earliest;
+} BoxDump;
+
+// Print the edit lists and, for each traf, tfdt and the composition times
+// of its first and earliest samples.
+static void dump_boxes(const uint8_t *p, const uint8_t *end, BoxDump *d)
+{
+    while (end - p >= 8) {
+        uint32_t size = AV_RB32(p), type = AV_RL32(p + 4);
+        const uint8_t *b = p + 8, *q;
+        BoxDump traf = { .first = INT64_MAX, .earliest = INT64_MAX };
+        unsigned flags, count;
+        int version;
+
+        if (size < 8 || size > end - p)
+            return;
+        if (size < 16) {
+            p += size;
+            continue;
+        }
+        version = b[0];
+        flags   = AV_RB24(b + 1);
+        q       = b + 8;
+        switch (type) {
+        case MKTAG('m','o','o','v'):
+        case MKTAG('t','r','a','k'):
+        case MKTAG('e','d','t','s'):
+        case MKTAG('m','o','o','f'):
+            dump_boxes(b, p + size, d);
+            break;
+        case MKTAG('t','r','a','f'):
+            dump_boxes(b, p + size, &traf);
+            printf("track %d tfdt %"PRId64" first %"PRId64" earliest 
%"PRId64"\n",
+                   traf.track_id, traf.tfdt, traf.first, traf.earliest);
+            break;
+        case MKTAG('t','k','h','d'):
+            d->track_id = AV_RB32(b + (version ? 20 : 12));
+            break;
+        case MKTAG('e','l','s','t'):
+            count = AV_RB32(b + 4);
+            printf("track %d elst", d->track_id);
+            for (unsigned i = 0; i < count && q + (version ? 20 : 12) <= p + 
size; i++) {
+                printf(" %"PRId64"/%"PRId64,
+                       version ? (int64_t)AV_RB64(q) : AV_RB32(q),
+                       version ? (int64_t)AV_RB64(q + 8) : (int32_t)AV_RB32(q 
+ 4));
+                q += version ? 20 : 12;
+            }
+            printf("\n");
+            break;
+        case MKTAG('t','f','h','d'):
+            d->track_id = AV_RB32(b + 4);
+            q = b + 8 + (flags & 0x01 ? 8 : 0) + (flags & 0x02 ? 4 : 0);
+            if (flags & 0x08)
+                d->default_duration = AV_RB32(q);
+            break;
+        case MKTAG('t','f','d','t'):
+            d->tfdt = d->dts = version ? AV_RB64(b + 4) : AV_RB32(b + 4);
+            break;
+        case MKTAG('t','r','u','n'):
+            count = AV_RB32(b + 4);
+            q += (flags & 0x01 ? 4 : 0) + (flags & 0x04 ? 4 : 0);
+            for (unsigned i = 0; i < count; i++) {
+                uint32_t dur = d->default_duration;
+                int64_t cts = 0;
+                if (flags & 0x100) {
+                    dur = AV_RB32(q);
+                    q += 4;
+                }
+                q += (flags & 0x200 ? 4 : 0) + (flags & 0x400 ? 4 : 0);
+                if (flags & 0x800) {
+                    cts = version ? (int32_t)AV_RB32(q) : (int64_t)AV_RB32(q);
+                    q += 4;
+                }
+                if (q > p + size)
+                    break;
+                if (d->first == INT64_MAX)
+                    d->first = d->dts + cts;
+                d->earliest = FFMIN(d->earliest, d->dts + cts);
+                d->dts += dur;
+            }
+            break;
+        }
+        p += size;
+    }
+}
+
 static void close_out(void)
 {
     int i;
+    if (dump) {
+        BoxDump d = { 0 };
+        dump_boxes(dump_buf, dump_buf + dump_size, &d);
+        av_freep(&dump_buf);
+        dump_size = 0;
+    }
     av_md5_final(md5, hash);
     for (i = 0; i < HASH_SIZE; i++)
         printf("%02x", hash[i]);
@@ -286,6 +393,12 @@ static void mux_frames(int n, int c)
                 last_picture = AV_PICTURE_TYPE_I;
                 pkt->pts = pkt->dts + duration;
                 video_dts = pkt->pts;
+                if (open_gop) {
+                    // Followed by a leading picture presented before it.
+                    last_picture = AV_PICTURE_TYPE_P;
+                    next_p_pts = pkt->pts = pkt->dts + 2 * duration;
+                    video_dts = pkt->dts + duration;
+                }
             } else {
                 if (last_picture == AV_PICTURE_TYPE_P) {
                     last_picture = AV_PICTURE_TYPE_B;
@@ -883,6 +996,19 @@ int main(int argc, char **argv)
     finish();
     close_out();
 
+    // CMAF fragments starting on open GOP key frames, followed by leading
+    // pictures: the earliest presented sample shall be composed at tfdt.
+    dump = 1;
+    open_gop = 1;
+    init_out("cmaf-open-gop");
+    av_dict_set(&opts, "movflags", "+frag_keyframe+cmaf", 0);
+    init(1, 0);
+    mux_gops(2);
+    finish();
+    close_out();
+    open_gop = 0;
+    dump = 0;
+
 end:
     av_free(md5);
     av_packet_free(&pkt);
diff --git a/tests/ref/fate/api-movenc b/tests/ref/fate/api-movenc
index f2947818ceb..2fd2942c1a1 100644
--- a/tests/ref/fate/api-movenc
+++ b/tests/ref/fate/api-movenc
@@ -163,3 +163,13 @@ write_data len 70, time 2000000, type boundary atom emsg
 write_data len 1840, time 2000000, type sync atom moof
 write_data len 148, time nopts, type trailer atom -
 f4cb225a8db4d38080587d0a949099af 5111 emsg
+write_data len 28, time nopts, type header atom ftyp
+write_data len 1123, time nopts, type header atom -
+write_data len 892, time 0, type sync atom moof
+write_data len 900, time 1000000, type sync atom moof
+write_data len 148, time nopts, type trailer atom -
+track 1 tfdt 0 first 512 earliest 0
+track 2 tfdt 0 first 0 earliest 0
+track 1 tfdt 15360 first 15872 earliest 15360
+track 2 tfdt 43008 first 43008 earliest 43008
+1a349c32f310c12407d15356bb561f42 3091 cmaf-open-gop
-- 
2.54.1


>From e2554885a7df6844aed45d3ff2f196f8ec7cd58d Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 21 Nov 2026 12:14:53 -0800
Subject: [PATCH 2/2] avformat/movenc: write a single offset edit for delayed
 CMAF tracks

ISO/IEC 23000-19 7.5.13 allows no empty edit; signal the delay in tfdt.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/movenc.c                        | 13 ++++++++++++-
 libavformat/movenc.h                        |  1 +
 tests/api/api-movenc-test.c                 | 13 +++++++++++++
 tests/ref/fate/api-movenc                   |  8 ++++++++
 tests/ref/fate/hls-fmp4-frag-keyframe       |  6 +++---
 tests/ref/fate/hls-fmp4-frag-keyframe-short |  4 ++--
 6 files changed, 39 insertions(+), 6 deletions(-)

diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index b9bede77129..3b97e591c7a 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -4417,6 +4417,17 @@ static int mov_write_edts_tag(AVIOContext *pb, 
MOVMuxContext *mov,
     }
 #endif
 
+    if (mov->flags & FF_MOV_FLAG_CMAF &&
+        !(mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED) &&
+        start_dts + start_ct > 0) {
+        /* CMAF only allows a single offset edit (ISO/IEC 23000-19, 7.5.13):
+         * signal the later start in tfdt instead of an empty edit, and only
+         * remove the composition offset. */
+        track->edit_delay = start_dts + start_ct;
+        start_dts = -start_ct;
+        delay     = 0;
+    }
+
     version |= delay < INT32_MAX ? 0 : 1;
 
     entry_size = (version == 1) ? 20 : 12;
@@ -6118,7 +6129,7 @@ static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack 
*track)
     ffio_wfourcc(pb, "tfdt");
     avio_w8(pb, 1); /* version */
     avio_wb24(pb, 0);
-    avio_wb64(pb, track->cluster[0].dts - track->start_dts);
+    avio_wb64(pb, track->cluster[0].dts - track->start_dts + 
track->edit_delay);
     return update_size(pb, pos);
 }
 
diff --git a/libavformat/movenc.h b/libavformat/movenc.h
index 074ec83ca60..db85fcffe40 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -141,6 +141,7 @@ typedef struct MOVTrack {
     int         end_reliable;
     int64_t     dts_shift;
     int         dts_shift_final; ///< dts_shift covers the leading pictures
+    int64_t     edit_delay;      ///< start delay moved from the edit list to 
tfdt
 
     int         hint_track;   ///< the track that hints this track, -1 if no 
hint track is set
     int         nb_src_track;
diff --git a/tests/api/api-movenc-test.c b/tests/api/api-movenc-test.c
index 1bbb6fb3246..01bb2f279b4 100644
--- a/tests/api/api-movenc-test.c
+++ b/tests/api/api-movenc-test.c
@@ -1007,6 +1007,19 @@ int main(int argc, char **argv)
     finish();
     close_out();
     open_gop = 0;
+
+    // CMAF with edit lists, video starting after audio: a single offset
+    // edit per track, the start delay in tfdt.
+    init_out("cmaf-elst-delayed-video");
+    av_dict_set(&opts, "movflags", "+frag_custom+cmaf+delay_moov", 0);
+    av_dict_set(&opts, "use_editlist", "1", 0);
+    init(1, 0);
+    video_dts += 8 * duration;
+    mux_gops(1);
+    av_write_frame(ctx, NULL); // Flush fragment.
+    mux_gops(1);
+    finish();
+    close_out();
     dump = 0;
 
 end:
diff --git a/tests/ref/fate/api-movenc b/tests/ref/fate/api-movenc
index 2fd2942c1a1..dedd5a07811 100644
--- a/tests/ref/fate/api-movenc
+++ b/tests/ref/fate/api-movenc
@@ -173,3 +173,11 @@ track 2 tfdt 0 first 0 earliest 0
 track 1 tfdt 15360 first 15872 earliest 15360
 track 2 tfdt 43008 first 43008 earliest 43008
 1a349c32f310c12407d15356bb561f42 3091 cmaf-open-gop
+write_data len 1227, time nopts, type header atom ftyp
+write_data len 1928, time 233333, type sync atom moof
+write_data len 110, time nopts, type trailer atom -
+track 1 elst 0/512
+track 2 elst 0/0
+track 1 tfdt 4096 first 4608 earliest 4608
+track 2 tfdt 0 first 0 earliest 0
+dafa7439963ea28b23658530ea08f563 3265 cmaf-elst-delayed-video
diff --git a/tests/ref/fate/hls-fmp4-frag-keyframe 
b/tests/ref/fate/hls-fmp4-frag-keyframe
index de0719118c2..d1322faa34f 100644
--- a/tests/ref/fate/hls-fmp4-frag-keyframe
+++ b/tests/ref/fate/hls-fmp4-frag-keyframe
@@ -1,3 +1,3 @@
-#EXT-X-MAP:URI="hls_fmp4_frag_keyframe.mp4",BYTERANGE="814@0"
-#EXT-X-BYTERANGE:20959@814
-#EXT-X-BYTERANGE:11213@21773
+#EXT-X-MAP:URI="hls_fmp4_frag_keyframe.mp4",BYTERANGE="802@0"
+#EXT-X-BYTERANGE:20959@802
+#EXT-X-BYTERANGE:11213@21761
diff --git a/tests/ref/fate/hls-fmp4-frag-keyframe-short 
b/tests/ref/fate/hls-fmp4-frag-keyframe-short
index db63e27456d..78c6cdb07e4 100644
--- a/tests/ref/fate/hls-fmp4-frag-keyframe-short
+++ b/tests/ref/fate/hls-fmp4-frag-keyframe-short
@@ -1,2 +1,2 @@
-#EXT-X-MAP:URI="hls_fmp4_frag_keyframe_short.mp4",BYTERANGE="814@0"
-#EXT-X-BYTERANGE:32172@814
+#EXT-X-MAP:URI="hls_fmp4_frag_keyframe_short.mp4",BYTERANGE="802@0"
+#EXT-X-BYTERANGE:32172@802
-- 
2.54.1

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

Reply via email to