Commit 445cc9905f for ffmpeg

commit 445cc9905f379c81cc5a895debc96a4e53a1f420
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Tue Nov 24 17:02:57 2026 -0800

    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.
    This applies to fragmented MP4 output that uses tfdt and negative CTS
    offsets. ISMV keeps its tfxd timing.

    Signed-off-by: Baptiste Coudurier <baptiste.coudurier@gmail.com>
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index f832ae712a..726f36ab4f 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -4534,6 +4534,7 @@ static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
         avio_wb32(pb, start_ct);
     }
     avio_wb32(pb, 0x00010000);
+    track->has_editlist = 1;
     return size;
 }

@@ -6194,6 +6195,13 @@ static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
             info->duration += info->time;
             info->time = 0;
         }
+        info->tfra_time = info->time;
+        if (mov->mode != MODE_ISM && !track->has_editlist &&
+            mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
+            /* Match the sample's presentation time in tfdt and trun. */
+            info->tfra_time = FFMAX(0, track->cluster[0].dts - track->start_dts +
+                                      track->cluster[0].cts);
+        }
         info->tfrf_offset = 0;
         mov_write_tfrf_tags(pb, mov, track);
     }
@@ -6490,7 +6498,7 @@ static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
     avio_wb32(pb, 0); /* length of traf/trun/sample num */
     avio_wb32(pb, track->nb_frag_info);
     for (i = 0; i < track->nb_frag_info; i++) {
-        avio_wb64(pb, track->frag_info[i].time);
+        avio_wb64(pb, track->frag_info[i].tfra_time);
         avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
         avio_w8(pb, 1); /* traf number */
         avio_w8(pb, 1); /* trun number */
@@ -7051,6 +7059,54 @@ static int mov_finish_fragment(MOVMuxContext *mov, MOVTrack *track,
     return 0;
 }

+/**
+ * With negative CTS offsets, lower dts_shift so that the earliest presented
+ * sample of the first fragment, such as a leading picture after an open GOP
+ * key frame, is composed at tfdt. Packets written later keep the lowered
+ * dts_shift, so their composition offsets have that much less range.
+ */
+static void mov_shift_leading_pictures(MOVTrack *track)
+{
+    int64_t shift = 0, max_cts, offset;
+
+    /* ISMV carries the fragment timestamp in tfxd. */
+    if (track->mode == MODE_ISM || track->dts_shift == AV_NOPTS_VALUE ||
+        track->dts_shift_final || !track->entry)
+        return;
+    track->dts_shift_final = 1;
+
+    max_cts = track->cluster[0].cts;
+    for (int i = 1; i < track->entry; i++) {
+        shift   = FFMIN(shift, track->cluster[i].dts + track->cluster[i].cts -
+                               track->cluster[0].dts);
+        max_cts = FFMAX(max_cts, track->cluster[i].cts);
+    }
+    /* The next sample starts at the track end and is presented at end_pts. */
+    if (track->end_pts != AV_NOPTS_VALUE)
+        max_cts = FFMAX(max_cts, av_sat_sub64(track->end_pts, track->start_dts +
+                                                              track->track_duration));
+    if (!shift || max_cts > INT32_MAX + shift)
+        return;
+
+    /* Keep an origin set by frag_discont if tfdt can absorb the shift. */
+    offset = track->cluster[0].dts - track->start_dts;
+    if (offset || track->start_dts_explicit) {
+        if (offset < -shift)
+            return;
+        track->track_duration += shift;
+    } else {
+        track->start_dts += shift;
+        if (track->start_cts != AV_NOPTS_VALUE)
+            track->start_cts -= shift;
+    }
+    for (int i = 0; i < track->entry; i++) {
+        track->cluster[i].dts += shift;
+        track->cluster[i].cts -= shift;
+    }
+    track->dts_shift += shift;
+    track->flags |= MOV_TRACK_CTTS;
+}
+
 static int mov_flush_fragment(AVFormatContext *s, int force)
 {
     MOVMuxContext *mov = s->priv_data;
@@ -7133,6 +7189,12 @@ static int mov_flush_fragment(AVFormatContext *s, int force)
         if (i < mov->nb_tracks && !force)
             return 0;

+        /* A delayed moov is written alone, and more leading pictures can
+         * still join the first fragment, unless its edit list needs them. */
+        if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV) || mov->use_editlist)
+            for (i = 0; i < mov->nb_tracks; i++)
+                mov_shift_leading_pictures(&mov->tracks[i]);
+
         moov_size = get_moov_size(s);
         for (i = 0; i < mov->nb_tracks; i++)
             mov->tracks[i].data_offset = pos + moov_size + 8;
@@ -7172,6 +7234,9 @@ static int mov_flush_fragment(AVFormatContext *s, int force)
         return 0;
     }

+    for (i = 0; i < mov->nb_tracks; i++)
+        mov_shift_leading_pictures(&mov->tracks[i]);
+
     if (mov->frag_interleave) {
         for (i = 0; i < mov->nb_tracks; i++) {
             MOVTrack *track = &mov->tracks[i];
@@ -7778,6 +7843,7 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
     if (trk->start_dts == AV_NOPTS_VALUE) {
         trk->start_dts = pkt->dts;
         if (trk->frag_discont) {
+            trk->start_dts_explicit = 1;
             if (mov->use_editlist) {
                 /* Pretend the whole stream started at pts=0, with earlier fragments
                  * already written. If the stream started at pts=0, the duration sum
@@ -8022,10 +8088,15 @@ static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
     if (!pkt->size) {
         if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
             trk->start_dts = pkt->dts;
-            if (pkt->pts != AV_NOPTS_VALUE)
+            trk->start_dts_explicit = 1;
+            if (pkt->pts != AV_NOPTS_VALUE) {
+                /* The caller supplied the shift for the original timeline.
+                 * Keep it even if a delayed header will write an edit. */
+                trk->dts_shift_final = 1;
                 trk->start_cts = pkt->pts - pkt->dts;
-            else
+            } else {
                 trk->start_cts = 0;
+            }
         }

         return 0;             /* Discard 0 sized packets */
@@ -8043,6 +8114,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
@@ -8061,6 +8133,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 576c98320b..9ec27cec99 100644
--- a/libavformat/movenc.h
+++ b/libavformat/movenc.h
@@ -78,6 +78,7 @@ typedef struct HintSampleQueue {
 } HintSampleQueue;

 typedef struct MOVFragmentInfo {
+    int64_t tfra_time;   ///< presentation time of the indexed sample
     int64_t offset;
     int64_t time;
     int64_t duration;
@@ -135,12 +136,15 @@ typedef struct MOVTrack {
     int         nb_tref_tags;
     MovTag      *tref_tags;
     int64_t     start_dts;
+    int         start_dts_explicit; ///< initial origin was set by frag_discont
     int64_t     start_cts;
     int64_t     end_pts;
     int64_t     elst_end_pts;
     int         end_reliable;
     int64_t     dts_shift;
     int64_t     start_delay; ///< presentation delay kept in the composition offsets
+    int         dts_shift_final; ///< dts_shift covers the leading pictures
+    int         has_editlist; ///< track carries an edit list in the moov

     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 f4a78313f5..53bcb2f8b3 100644
--- a/tests/api/api-movenc-test.c
+++ b/tests/api/api-movenc-test.c
@@ -883,6 +883,37 @@ int main(int argc, char **argv)
     finish();
     close_out();

+    // The first GOP had an earliest PTS of 60 ms and a first DTS of zero.
+    // In the resumed GOP, deriving the shift again would move tfdt from 80
+    // to 60 ms, even though the two samples' composition times would agree.
+    for (int delayed = 0; delayed <= 1; delayed++) {
+        uint8_t data[8] = { 0 };
+
+        init_out(delayed ? "delay-moov-open-gop-restart" : "empty-moov-open-gop-restart");
+        av_dict_set(&opts, "movflags", delayed ? "+delay_moov" : "+empty_moov", 0);
+        av_dict_set(&opts, "movflags", "+negative_cts_offsets+frag_keyframe+frag_discont",
+                    AV_DICT_APPEND);
+        av_dict_set(&opts, "video_track_timescale", "1000", 0);
+        av_dict_set(&opts, "avoid_negative_ts", "disabled", 0);
+        av_dict_set(&opts, "use_editlist", "1", 0);
+        init(1, 0);
+        av_packet_unref(pkt);
+        pkt->dts = 0;
+        pkt->pts = 60;
+        check(av_write_frame(ctx, pkt) >= 0, "Failed to signal restart timestamps");
+        for (int i = 0; i < 2; i++) {
+            pkt->data = data;
+            pkt->size = sizeof(data);
+            pkt->dts = 80 + 40 * i;
+            pkt->pts = 160 - 40 * i;
+            pkt->duration = 40;
+            pkt->flags = i ? 0 : AV_PKT_FLAG_KEY;
+            check(av_write_frame(ctx, pkt) >= 0, "Failed to write open GOP packet");
+        }
+        finish();
+        close_out();
+    }
+
 end:
     av_free(md5);
     av_packet_free(&pkt);
diff --git a/tests/fate/mov.mak b/tests/fate/mov.mak
index 056e3e5ed7..c96eb2d8e4 100644
--- a/tests/fate/mov.mak
+++ b/tests/fate/mov.mak
@@ -739,6 +739,18 @@ fate-mov-mp4-noelst-frag-delay: CMD = run_with_temp \
     "ffprobe$(PROGSSUF)$(EXESUF) -select_streams v -show_entries stream=start_time:packet=pts,dts \
     -print_format compact -v 0" mp4

+FATE_MOV_FFMPEG_FFPROBE_SAMPLES-$(call ALLYES, FILE_PROTOCOL MOV_DEMUXER MP4_MUXER) += fate-mov-frag-open-gop-tfra-empty-moov
+# An eager moov cannot write an edit, even when edits are enabled.
+fate-mov-frag-open-gop-tfra-empty-moov: CMD = run_with_temp \
+    "$(FFMPEG) -nostdin -v error -fflags +bitexact -copyts -i $(TARGET_SAMPLES)/h264/twofields_packet.mp4 -map 0:v -c copy \
+    -output_ts_offset -0.066733 -avoid_negative_ts disabled -use_editlist 1 -movflags empty_moov+negative_cts_offsets+frag_keyframe -f mp4 -y" \
+    "ffprobe$(PROGSSUF)$(EXESUF) -v error -bitexact -use_mfra_for pts -read_intervals %+\#1 -show_entries packet=pts,dts,flags -of compact -select_streams v" mp4
+
+FATE_MOV_FFMPEG_SAMPLES-$(call REMUX, MP4 MXF, MOV_DEMUXER H264_DECODER H264_PARSER) += fate-mov-mp4-frag-open-gop-wait
+# The first fragment waits for audio, so its leading picture is composed at tfdt.
+fate-mov-mp4-frag-open-gop-wait: CMD = transcode mxf $(TARGET_SAMPLES)/h264/SonyXAVC_LongGOP_green_pixelation_early_Frames.MXF mp4 \
+    "-map 0:v -map 0:a:0 -c copy -movflags +negative_cts_offsets+delay_moov -use_editlist 0 -frag_size 1 -write_btrt 0" "-c copy"
+
 FATE_MOV_FFMPEG_FFPROBE-$(call ALLYES, LAVFI_INDEV ANULLSRC_FILTER AFORMAT_FILTER \
                                       PCM_S16$(if $(filter yes,$(HAVE_BIGENDIAN)),BE,LE)_DECODER \
                                       PCM_S16BE_ENCODER                          \
diff --git a/tests/ref/fate/api-movenc b/tests/ref/fate/api-movenc
index f2947818ce..0e41fcf69e 100644
--- a/tests/ref/fate/api-movenc
+++ b/tests/ref/fate/api-movenc
@@ -163,3 +163,12 @@ 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 36, time nopts, type header atom ftyp
+write_data len 1123, time nopts, type header atom -
+write_data len 144, time 140000, type sync atom moof
+write_data len 67, time nopts, type trailer atom -
+1880f24f5284fff22f97f3dd29161b80 1370 empty-moov-open-gop-restart
+write_data len 1207, time nopts, type header atom ftyp
+write_data len 144, time 140000, type sync atom moof
+write_data len 67, time nopts, type trailer atom -
+2a2c73294a5a08833dd3c0549f6ab9b2 1418 delay-moov-open-gop-restart
diff --git a/tests/ref/fate/mov-frag-open-gop-tfra-empty-moov b/tests/ref/fate/mov-frag-open-gop-tfra-empty-moov
new file mode 100644
index 0000000000..0651659fe6
--- /dev/null
+++ b/tests/ref/fate/mov-frag-open-gop-tfra-empty-moov
@@ -0,0 +1 @@
+packet|pts=9009|dts=0|flags=K__
diff --git a/tests/ref/fate/mov-mp4-frag-open-gop-wait b/tests/ref/fate/mov-mp4-frag-open-gop-wait
new file mode 100644
index 0000000000..2625809b49
--- /dev/null
+++ b/tests/ref/fate/mov-mp4-frag-open-gop-wait
@@ -0,0 +1,26 @@
+9c90a174a45129b3c17e84e97dcae923 *tests/data/fate/mov-mp4-frag-open-gop-wait.mp4
+1390616 tests/data/fate/mov-mp4-frag-open-gop-wait.mp4
+#extradata 0:      256, 0xeb4d5fe0
+#tb 0: 1/12800
+#media_type 0: video
+#codec_id 0: h264
+#dimensions 0: 1920x1080
+#sar 0: 1/1
+#tb 1: 1/48000
+#media_type 1: audio
+#codec_id 1: pcm_s24le
+#sample_rate 1: 48000
+#channel_layout_name 1: mono
+0,          0,       1536,      512,   553248, 0x29d326d2
+1,          0,          0,     1920,     5760, 0xd5894ac8
+0,        512,        512,      512,   119985, 0xf8f959be, F=0x0
+0,       1024,       1024,      512,    98815, 0xa428674b, F=0x0
+1,       3840,       3840,     1920,     5760, 0x9f71829c
+0,       1536,       3072,      512,   257022, 0x2ef179de, F=0x0
+1,       5760,       5760,     1920,     5760, 0xf7245421
+0,       2048,       2048,      512,   123833, 0x604636b6, F=0x0
+1,       7680,       7680,     1920,     5760, 0x3cef69d8
+0,       2560,       2560,      512,   117099, 0xa8c0af46, F=0x0
+1,       9600,       9600,     1920,     5760, 0x6b647758
+1,       9600,       9600,     1920,     5760, 0x0958976a, F=0x5
+0,       3072,       4608,      512,    82412, 0x27cd2a30, F=0x0