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

Depends on https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26057; only the last 
three commits are new.

HE-AAC decoded 962 samples late: edit lists and iTunSMPB priming apply to the 
core AAC output, which the SBR tool delays (ISO/IEC 14496-3 Table 1.34, ISO/IEC 
TR 14496-24 clause 2). The decoder now compensates the delay the way 
libfdk-aacdec already does for its output delay, with that logic shared in 
decode.c:

- avformat/mov: keep the audio sample after the last edit, discarded, so a 
delayed decoder can return the end of the edit, as QuickTime does
- avcodec/decode: factor the output delay handling out of libfdk-aacdec (its 
timestamps now move in pkt_timebase, and it also returns the end of an edit 
from the following discarded frame)
- avcodec/aac/aacdec: compensate the SBR delay (962 samples, 481 with 
downsampled SBR)

Afconvert and fdkaac HE-AAC files now line up with the source (audiomatch); 
Nero files, whose edits already include the delay, end up 962 samples early. 
Against QuickTime's decoder, every HE-AAC file in my edit cross-check now 
starts at lag 0, and an edit ending mid-stream matches it sample for sample.

New test fate-aac-sbr-edit-end needs aac/sbr_edit_end.mp4 (13.7 KB) in the 
samples suite.

🤖 Generated with [Claude Code](https://claude.com/claude-code)



From 546171b8bd81ec06bf44843079285c86e44c4835 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 14 Nov 2026 00:46:09 -0800
Subject: [PATCH 1/5] avformat/mov: express audio edit priming in output
 samples

Accumulate the skipped duration of the first nonempty audio edit in
64-bit track ticks and convert it once to output samples.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/mov.c               | 45 +++++++++++++--------------------
 tests/ref/fate/mov-mp4-chapters |  2 +-
 2 files changed, 18 insertions(+), 29 deletions(-)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index ca33cb2285b..1410cbea58a 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -4562,8 +4562,7 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
     int64_t search_timestamp = 0;
     int64_t* frame_duration_buffer = NULL;
     int num_discarded_begin = 0;
-    int first_non_zero_audio_edit = -1;
-    int packet_skip_samples = 0;
+    int64_t skip_duration = 0;
     MOVIndexRange *current_index_range = NULL;
     int found_keyframe_after_edit = 0;
     int found_non_empty_edit = 0;
@@ -4609,6 +4608,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
 
     while (get_edit_list_entry(mov, msc, edit_list_index, 
&edit_list_media_time,
                                &edit_list_duration, mov->time_scale)) {
+        const int trim_start = !found_non_empty_edit && 
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
+
         av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" 
- media time: %"PRId64", duration: %"PRId64"\n",
                st->index, edit_list_index, edit_list_media_time, 
edit_list_duration);
         edit_list_index++;
@@ -4627,19 +4628,6 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
         }
         found_non_empty_edit = 1;
 
-        // If we encounter a non-negative edit list reset the 
skip_samples/initial_padding fields and set them
-        // according to the edit list below.
-        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
-            if (first_non_zero_audio_edit < 0) {
-                first_non_zero_audio_edit = 1;
-            } else {
-                first_non_zero_audio_edit = 0;
-            }
-
-            if (first_non_zero_audio_edit > 0)
-                sti->skip_samples = st->codecpar->initial_padding = 0;
-        }
-
         // While reordering frame index according to edit list we must handle 
properly
         // the scenario when edit list entry starts from none key frame.
         // We find closest previous key frame and preserve it and consequent 
frames in index.
@@ -4713,14 +4701,13 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
             }
 
             if (curr_cts < edit_list_media_time || curr_cts >= 
(edit_list_duration + edit_list_media_time)) {
-                if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && 
st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
-                    curr_cts < edit_list_media_time && curr_cts + 
frame_duration > edit_list_media_time &&
-                    first_non_zero_audio_edit > 0) {
-                    packet_skip_samples = edit_list_media_time - curr_cts;
-                    sti->skip_samples += packet_skip_samples;
+                if (trim_start && curr_cts < edit_list_media_time &&
+                    av_sat_add64(curr_cts, frame_duration) > 
edit_list_media_time) {
+                    int64_t packet_skip_duration = edit_list_media_time - 
curr_cts;
+                    skip_duration = av_sat_add64(skip_duration, 
packet_skip_duration);
 
-                    // Shift the index entry timestamp by packet_skip_samples 
to be correct.
-                    edit_list_dts_counter -= packet_skip_samples;
+                    // Shift the index entry timestamp by the skipped media 
duration.
+                    edit_list_dts_counter -= packet_skip_duration;
                     if (edit_list_start_encountered == 0)  {
                         edit_list_start_encountered = 1;
                         // Make timestamps strictly monotonically increasing 
for audio, by rewriting timestamps for
@@ -4732,7 +4719,7 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
                         }
                     }
 
-                    av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from 
curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
+                    av_log(mov->fc, AV_LOG_DEBUG, "skip %"PRId64" ticks from 
curr_cts: %"PRId64"\n", packet_skip_duration, curr_cts);
                 } else {
                     flags |= AVINDEX_DISCARD_FRAME;
                     av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: 
%"PRId64" @ %"PRId64"\n", curr_cts, index);
@@ -4746,11 +4733,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
                         }
                         frame_duration_buffer[num_discarded_begin - 1] = 
frame_duration;
 
-                        // Increment skip_samples for the first non-zero audio 
edit list
-                        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
-                            first_non_zero_audio_edit > 0 && 
st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
-                            sti->skip_samples += frame_duration;
-                        }
+                        if (trim_start)
+                            skip_duration = av_sat_add64(skip_duration, 
frame_duration);
                     }
                 }
             } else {
@@ -4836,6 +4820,11 @@ truncated:
 
     // Update av stream length, if it ends up shorter than the track's media 
duration
     st->duration = FFMIN(st->duration, edit_list_dts_entry_end - start_dts);
+    if (found_non_empty_edit && st->codecpar->codec_type == 
AVMEDIA_TYPE_AUDIO) {
+        skip_duration = av_rescale_q(skip_duration, st->time_base,
+                                     (AVRational){ 1, 
st->codecpar->sample_rate });
+        sti->skip_samples = av_clip64(skip_duration, 0, INT_MAX);
+    }
     st->codecpar->initial_padding = sti->skip_samples;
 
     // Free the old index and the old CTTS structures
diff --git a/tests/ref/fate/mov-mp4-chapters b/tests/ref/fate/mov-mp4-chapters
index 02f267a0fb2..6fc02970ae6 100644
--- a/tests/ref/fate/mov-mp4-chapters
+++ b/tests/ref/fate/mov-mp4-chapters
@@ -6,7 +6,7 @@ f0289770c1fb126b195755ba7ccc1f50 
*tests/data/fate/mov-mp4-chapters.mp4
 #codec_id 0: vorbis
 #sample_rate 0: 44100
 #channel_layout_name 0: mono
-0,       -256,       -256,      256,       28, 0xefcf103e, F=0x5
+0,       -256,       -256,      256,       28, 0xefcf103e, F=0x5, S=1, Skip 
Samples,       10, 0x00090001
 0,          0,          0,     1152,      198, 0xfbbe5eb5
 0,       1152,       1152,     2048,      198, 0xabd95c6c
 0,       3200,       3200,     1152,       41, 0x954b12a5
-- 
2.54.0


From b7a49e83668257c27d66ef6a5fb5c473f5b944b8 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 14 Nov 2026 00:02:36 -0800
Subject: [PATCH 2/5] avformat/mov: account for audio samples ending at edit
 boundaries

Signal trailing padding for audio ending inside an edit or a short trun,
and keep a sample partially covered by the last edit, as QuickTime does.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/isom.h                       |  2 +
 libavformat/mov.c                        | 94 +++++++++++++++++++-----
 tests/fate/mov.mak                       | 14 ++++
 tests/fate/qt.mak                        |  2 +
 tests/ref/fate/adpcm-ima_wav-stereo      |  2 +-
 tests/ref/fate/adpcm_ms-stereo           |  2 +-
 tests/ref/fate/mov-alaw-final-edit       | 12 +++
 tests/ref/fate/mov-fractional-audio-edit | 12 +++
 tests/ref/fate/mov-twos-final-edit       | 12 +++
 tests/ref/fate/pcm_s16be-stereo          |  2 +-
 tests/ref/fate/qt-ima4-mono              |  2 +-
 tests/ref/fate/qt-ima4-stereo            |  2 +-
 tests/ref/lavf-fate/qtrle_mace6.mov      |  2 +-
 13 files changed, 136 insertions(+), 24 deletions(-)
 create mode 100644 tests/ref/fate/mov-alaw-final-edit
 create mode 100644 tests/ref/fate/mov-fractional-audio-edit
 create mode 100644 tests/ref/fate/mov-twos-final-edit

diff --git a/libavformat/isom.h b/libavformat/isom.h
index 6230218e37f..dd9901b6987 100644
--- a/libavformat/isom.h
+++ b/libavformat/isom.h
@@ -175,6 +175,7 @@ typedef struct MOVFragmentIndex {
 typedef struct MOVIndexRange {
     int64_t start;
     int64_t end;
+    unsigned int end_padding; ///< media ticks trimmed from the last sample
 } MOVIndexRange;
 
 typedef struct MOVStreamContext {
@@ -215,6 +216,7 @@ typedef struct MOVStreamContext {
     unsigned int keyframe_count;
     int *keyframes;
     int time_scale;
+    int64_t fragment_edit_end; ///< finite edit end on the presentation 
timeline
     int64_t time_offset;  ///< time offset of the edit list entries
     int64_t min_corrected_pts;  ///< minimum Composition time shown by the 
edits excluding empty edits.
     int current_sample;
diff --git a/libavformat/mov.c b/libavformat/mov.c
index 1410cbea58a..112068f4acb 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -4214,7 +4214,7 @@ static int get_edit_list_entry(MOVContext *mov,
                                unsigned int edit_list_index,
                                int64_t *edit_list_media_time,
                                int64_t *edit_list_duration,
-                               int64_t global_timescale)
+                               int round_up)
 {
     if (edit_list_index == msc->elst_count) {
         return 0;
@@ -4223,12 +4223,12 @@ static int get_edit_list_entry(MOVContext *mov,
     *edit_list_duration = msc->elst_data[edit_list_index].duration;
 
     /* duration is in global timescale units;convert to msc timescale */
-    if (global_timescale == 0) {
+    if (mov->time_scale == 0) {
       avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with 
editlists");
       return 0;
     }
-    *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
-                                     global_timescale);
+    *edit_list_duration = av_rescale_rnd(*edit_list_duration, msc->time_scale, 
mov->time_scale,
+                                         round_up ? AV_ROUND_UP : 
AV_ROUND_NEAR_INF);
 
     if (*edit_list_duration < 0 ||
         *edit_list_media_time > INT64_MAX - *edit_list_duration)
@@ -4533,7 +4533,7 @@ static void mov_current_sample_set(MOVStreamContext *sc, 
int current_sample)
  * Also fixes the timestamps of the index entries to match the timeline
  * specified the edit lists.
  */
-static void mov_fix_index(MOVContext *mov, AVStream *st)
+static void mov_fix_index(MOVContext *mov, AVStream *st, int64_t end_dts)
 {
     MOVStreamContext *msc = st->priv_data;
     FFStream *const sti = ffstream(st);
@@ -4574,8 +4574,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
     int64_t max_entries = nb_old * 16LL + (1 << 16);
 
     // allocate the index ranges array
-    msc->index_ranges = av_malloc_array(msc->elst_count + 1,
-                                        sizeof(msc->index_ranges[0]));
+    msc->index_ranges = av_calloc(msc->elst_count + 1,
+                                  sizeof(msc->index_ranges[0]));
     if (!msc->index_ranges) {
         av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
         return;
@@ -4606,8 +4606,11 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
 
     start_dts = edit_list_dts_entry_end;
 
-    while (get_edit_list_entry(mov, msc, edit_list_index, 
&edit_list_media_time,
-                               &edit_list_duration, mov->time_scale)) {
+    /* Like QuickTime, keep the audio samples starting before the last edit 
ends. */
+    while (get_edit_list_entry(mov, msc, edit_list_index, 
&edit_list_media_time, &edit_list_duration,
+                               st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO 
&&
+                               edit_list_index + 1 == msc->elst_count)) {
+        const int64_t edit_end = edit_list_media_time + edit_list_duration;
         const int trim_start = !found_non_empty_edit && 
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
 
         av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" 
- media time: %"PRId64", duration: %"PRId64"\n",
@@ -4662,14 +4665,20 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
         edit_list_start_encountered = 0;
         found_keyframe_after_edit = 0;
         for (; current < e_old_end; current++, index++) {
+            int64_t remaining;
+
             if (sti->nb_index_entries >= max_entries) {
                 av_log(mov->fc, AV_LOG_ERROR, "Edit list expands the sample 
index beyond %"PRId64" entries\n",
                        max_entries);
                 goto truncated;
             }
             // check  if frame outside edit list mark it for discard
-            frame_duration = (current + 1 <  e_old_end) ?
-                             ((current + 1)->timestamp - current->timestamp) : 
edit_list_duration;
+            if (current + 1 < e_old_end)
+                frame_duration = current[1].timestamp - current->timestamp;
+            else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
+                frame_duration = end_dts - current->timestamp;
+            else
+                frame_duration = edit_list_duration;
 
             flags = current->flags;
 
@@ -4700,7 +4709,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
                 }
             }
 
-            if (curr_cts < edit_list_media_time || curr_cts >= 
(edit_list_duration + edit_list_media_time)) {
+            remaining = av_sat_sub64(edit_end, curr_cts);
+            if (curr_cts < edit_list_media_time || remaining <= 0) {
                 if (trim_start && curr_cts < edit_list_media_time &&
                     av_sat_add64(curr_cts, frame_duration) > 
edit_list_media_time) {
                     int64_t packet_skip_duration = edit_list_media_time - 
curr_cts;
@@ -4762,20 +4772,24 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
             }
 
             // Update the index ranges array
-            if (!current_index_range || index != current_index_range->end) {
+            if (!current_index_range || current_index_range->end_padding || 
index != current_index_range->end) {
                 current_index_range = current_index_range ? 
current_index_range + 1
                                                           : msc->index_ranges;
                 current_index_range->start = index;
             }
             current_index_range->end = index + 1;
 
+            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
+                !(flags & AVINDEX_DISCARD_FRAME) && remaining > 0 && remaining 
< frame_duration)
+                current_index_range->end_padding = frame_duration - remaining;
+
             // Only start incrementing DTS in frame_duration amounts, when we 
encounter a frame in edit list.
             if (edit_list_start_encountered > 0) {
                 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
             }
 
             // Break when found first key frame after edit entry completion
-            if ((curr_cts + frame_duration >= (edit_list_duration + 
edit_list_media_time)) &&
+            if (frame_duration >= remaining &&
                 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == 
AVMEDIA_TYPE_AUDIO)))) {
                 if (msc->ctts_count) {
                     // If we have CTTS and this is the first keyframe after 
edit elist,
@@ -5041,6 +5055,15 @@ static void mov_build_index(MOVContext *mov, AVStream 
*st)
                 current_dts = -av_clip64(sc->time_offset, -INT64_MAX, 
INT64_MAX);
         }
 
+        if (!multiple_edits && edit_start_index < sc->elst_count &&
+            sc->elst_data[edit_start_index].rate == 1 && mov->time_scale > 0) {
+            int64_t media_time, duration;
+            if (get_edit_list_entry(mov, sc, edit_start_index, &media_time, 
&duration,
+                                    st->codecpar->codec_type == 
AVMEDIA_TYPE_AUDIO) &&
+                duration > 0)
+                sc->fragment_edit_end = av_sat_add64(empty_duration, duration);
+        }
+
         if (!multiple_edits && !mov->advanced_editlist &&
             st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
             st->codecpar->initial_padding = av_rescale_q(start_time, 
st->time_base,
@@ -5283,7 +5306,7 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
 
     if (!mov->ignore_editlist && mov->advanced_editlist) {
         // Fix index according to edit lists.
-        mov_fix_index(mov, st);
+        mov_fix_index(mov, st, current_dts);
     }
 
     // Update start time of the stream.
@@ -12771,10 +12794,12 @@ static int get_eia608_packet(AVIOContext *pb, 
AVPacket *pkt, int src_size)
 }
 
 static int mov_finalize_packet(AVFormatContext *s, AVStream *st, AVIndexEntry 
*sample,
-                                int64_t current_index, AVPacket *pkt)
+                                unsigned edit_padding, AVPacket *pkt)
 {
     MOVContext *mov = s->priv_data;
     MOVStreamContext *sc = st->priv_data;
+    int64_t end_padding = 0;
+    AVRational sample_time = { 1, st->codecpar->sample_rate };
 
     pkt->stream_index = sc->ffindex;
     pkt->dts = sample->timestamp;
@@ -12814,6 +12839,36 @@ static int mov_finalize_packet(AVFormatContext *s, 
AVStream *st, AVIndexEntry *s
             ffstream(st)->last_discard_sample  = total;
     }
 
+    /* A full parser delays and retimes packets, so the padding would land on 
the wrong frame. */
+    if (ffstream(st)->need_parsing != AVSTREAM_PARSE_FULL) {
+        if (edit_padding) {
+            end_padding = av_rescale_q(edit_padding, st->time_base, 
sample_time);
+        } else if (mov->fragment.found_tfhd && st->codecpar->codec_type == 
AVMEDIA_TYPE_AUDIO &&
+                   pkt->duration > 0) {
+            if (sc->fragment_edit_end && pkt->pts >= sc->fragment_edit_end) {
+                pkt->flags |= AV_PKT_FLAG_DISCARD;
+            } else {
+                int frame_samples = av_get_audio_frame_duration2(st->codecpar, 
sample->size);
+                int64_t coded = av_rescale_q(pkt->duration, st->time_base, 
sample_time);
+                int64_t end = pkt->duration;
+
+                /* A run shorter than its frame by a whole tick still codes 
the full frame. */
+                if (pkt->duration < av_rescale_q_rnd(frame_samples, 
sample_time, st->time_base, AV_ROUND_DOWN))
+                    coded = frame_samples;
+                if (sc->fragment_edit_end)
+                    end = FFMIN(end, sc->fragment_edit_end - pkt->pts);
+                end_padding = coded - av_rescale_q(end, st->time_base, 
sample_time);
+            }
+        }
+    }
+    if (end_padding > 0) {
+        uint8_t *sd = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 
10);
+        if (!sd)
+            return AVERROR(ENOMEM);
+        memset(sd, 0, 10);
+        AV_WL32(sd + 4, end_padding);
+    }
+
     if (sc->tts_data && sc->tts_index < sc->tts_count) {
         /* update tts context */
         sc->tts_sample++;
@@ -12862,6 +12917,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket 
*pkt)
     AVStream *st = NULL;
     FFStream *avsti = NULL;
     int64_t current_index;
+    unsigned edit_padding;
     int ret;
     int i;
     mov->fc = s;
@@ -12911,6 +12967,8 @@ static int mov_read_packet(AVFormatContext *s, AVPacket 
*pkt)
     sc = st->priv_data;
     /* must be done just before reading, to avoid infinite loop on sample */
     current_index = sc->current_index;
+    edit_padding = sc->current_index_range && current_index + 1 == 
sc->current_index_range->end ?
+                   sc->current_index_range->end_padding : 0;
     mov_current_sample_inc(sc);
 
     if (mov->next_root_atom) {
@@ -12942,7 +13000,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket 
*pkt)
         else if (sc->iamf) {
             int64_t pts, dts, pos, duration;
             int flags, size = sample->size;
-            ret = mov_finalize_packet(s, st, sample, current_index, pkt);
+            ret = mov_finalize_packet(s, st, sample, edit_padding, pkt);
             pts = pkt->pts; dts = pkt->dts;
             pos = pkt->pos; flags = pkt->flags;
             duration = pkt->duration;
@@ -13017,7 +13075,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket 
*pkt)
         }
     }
 
-    ret = mov_finalize_packet(s, st, sample, current_index, pkt);
+    ret = mov_finalize_packet(s, st, sample, edit_padding, pkt);
     if (ret < 0)
         return ret;
 
diff --git a/tests/fate/mov.mak b/tests/fate/mov.mak
index bb94f66f67d..55540a49174 100644
--- a/tests/fate/mov.mak
+++ b/tests/fate/mov.mak
@@ -420,6 +420,20 @@ fate-mov-dfpwm-last-packet: CMD = transcode lavfi 
"sine=r=48000,atrim=end_sample
 fate-mov-vfr: CMP = oneline
 fate-mov-vfr: REF = 1558b4a9398d8635783c93f84eb5a60d
 
+# Shorten the final packet's declared duration while retaining all 4800 coded 
samples.
+MOV_PCM_EDIT_DEPS = LAVFI_INDEV SINE_FILTER PCM_S16LE_DECODER 
PCM_S16LE_ENCODER SETTS_BSF
+FATE_MOV_FFMPEG-$(call TRANSCODE, PCM_S16BE, MOV, $(MOV_PCM_EDIT_DEPS)) += 
fate-mov-twos-final-edit
+FATE_MOV_FFMPEG-$(call TRANSCODE, PCM_ALAW, MOV, $(MOV_PCM_EDIT_DEPS)) += 
fate-mov-alaw-final-edit
+fate-mov-twos-final-edit: CODEC = pcm_s16be
+fate-mov-alaw-final-edit: CODEC = pcm_alaw
+fate-mov-twos-final-edit fate-mov-alaw-final-edit: CMD = transcode lavfi 
sine=r=48000:d=0.1 mov \
+    "-c:a $(CODEC) -movie_timescale 48000 -bsf:a 
setts=duration=DURATION-300*trunc(PTS/4096)" "-c:a pcm_s16le"
+
+# 337 movie ticks at 600 Hz retain 4494 samples at 8 kHz.
+FATE_MOV_FFMPEG-$(call TRANSCODE, PCM_S16BE, MOV, $(MOV_PCM_EDIT_DEPS)) += 
fate-mov-fractional-audio-edit
+fate-mov-fractional-audio-edit: CMD = transcode lavfi sine=r=8000:d=0.6 mov \
+    "-c:a pcm_s16be -movie_timescale 600 -bsf:a 
setts=duration=DURATION-308*trunc(PTS/4096)" "-c:a pcm_s16le"
+
 # The QuickTime user data list has to carry the composer atom the demuxer
 # already reads: without it a mov to mov remux dropped the tag.
 FATE_MOV_FFMPEG_FFPROBE-$(call TRANSCODE, PCM_S16LE, MOV, WAV_DEMUXER 
ARESAMPLE_FILTER) += fate-mov-composer-metadata
diff --git a/tests/fate/qt.mak b/tests/fate/qt.mak
index 436da172f1a..89a0597cbb3 100644
--- a/tests/fate/qt.mak
+++ b/tests/fate/qt.mak
@@ -6,6 +6,8 @@ fate-qdm2: CMD = pcm -i 
$(TARGET_SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.mov
 fate-qdm2: CMP = oneoff
 fate-qdm2: REF = $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.pcm
 fate-qdm2: FUZZ = 2
+# the reference is not trimmed to the edit list, 33 frames longer
+fate-qdm2: SIZE_TOLERANCE = 132
 
 FATE_QT-$(call ENCDEC, PCM_S16LE PCM_ALAW, MOV PCM_S16LE) += fate-qt-alaw-mono
 fate-qt-alaw-mono: CMD = md5 -i 
$(TARGET_SAMPLES)/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le
diff --git a/tests/ref/fate/adpcm-ima_wav-stereo 
b/tests/ref/fate/adpcm-ima_wav-stereo
index 2a368009519..0e8cb11a9df 100644
--- a/tests/ref/fate/adpcm-ima_wav-stereo
+++ b/tests/ref/fate/adpcm-ima_wav-stereo
@@ -1 +1 @@
-b4697f4f64c12afb37acfebd5f7a756c
+b6eae33bb512951d3d62dfe1046d644d
diff --git a/tests/ref/fate/adpcm_ms-stereo b/tests/ref/fate/adpcm_ms-stereo
index 6b131c1f970..fca7cf34d46 100644
--- a/tests/ref/fate/adpcm_ms-stereo
+++ b/tests/ref/fate/adpcm_ms-stereo
@@ -1 +1 @@
-3b7554e9a186c30adfd2a86bae950f4a
+92671d0fc31c2995f480ae5a097deb08
diff --git a/tests/ref/fate/mov-alaw-final-edit 
b/tests/ref/fate/mov-alaw-final-edit
new file mode 100644
index 00000000000..586421f6cd8
--- /dev/null
+++ b/tests/ref/fate/mov-alaw-final-edit
@@ -0,0 +1,12 @@
+6620f10fefcf7dd3511692e054d1745a *tests/data/fate/mov-alaw-final-edit.mov
+5453 tests/data/fate/mov-alaw-final-edit.mov
+#tb 0: 1/48000
+#media_type 0: audio
+#codec_id 0: pcm_s16le
+#sample_rate 0: 48000
+#channel_layout_name 0: mono
+0,          0,          0,     1024,     2048, 0x02aaef8e
+0,       1024,       1024,     1024,     2048, 0xffe80683
+0,       2048,       2048,     1024,     2048, 0x3eec030b
+0,       3072,       3072,     1024,     2048, 0x587df461
+0,       4096,       4096,      404,      808, 0x7b599b66
diff --git a/tests/ref/fate/mov-fractional-audio-edit 
b/tests/ref/fate/mov-fractional-audio-edit
new file mode 100644
index 00000000000..0c840069de9
--- /dev/null
+++ b/tests/ref/fate/mov-fractional-audio-edit
@@ -0,0 +1,12 @@
+f6ff3e26c2a263a39e2a1a9fbfc3c499 *tests/data/fate/mov-fractional-audio-edit.mov
+10253 tests/data/fate/mov-fractional-audio-edit.mov
+#tb 0: 1/8000
+#media_type 0: audio
+#codec_id 0: pcm_s16le
+#sample_rate 0: 8000
+#channel_layout_name 0: mono
+0,          0,          0,     1024,     2048, 0x2561e692
+0,       1024,       1024,     1024,     2048, 0x6b4be872
+0,       2048,       2048,     1024,     2048, 0x5bf9ee24
+0,       3072,       3072,     1024,     2048, 0x445de786
+0,       4096,       4096,      398,      796, 0xa1c6865f
diff --git a/tests/ref/fate/mov-twos-final-edit 
b/tests/ref/fate/mov-twos-final-edit
new file mode 100644
index 00000000000..6b242937940
--- /dev/null
+++ b/tests/ref/fate/mov-twos-final-edit
@@ -0,0 +1,12 @@
+fecf96a66b22ec671cde4b669733f669 *tests/data/fate/mov-twos-final-edit.mov
+10253 tests/data/fate/mov-twos-final-edit.mov
+#tb 0: 1/48000
+#media_type 0: audio
+#codec_id 0: pcm_s16le
+#sample_rate 0: 48000
+#channel_layout_name 0: mono
+0,          0,          0,     1024,     2048, 0x0ae4e6ab
+0,       1024,       1024,     1024,     2048, 0xbcaffeb7
+0,       2048,       2048,     1024,     2048, 0xa1e8fbc9
+0,       3072,       3072,     1024,     2048, 0xe75fee83
+0,       4096,       4096,      404,      808, 0x98319a0c
diff --git a/tests/ref/fate/pcm_s16be-stereo b/tests/ref/fate/pcm_s16be-stereo
index 6d29a67e2ba..f0837d1206b 100644
--- a/tests/ref/fate/pcm_s16be-stereo
+++ b/tests/ref/fate/pcm_s16be-stereo
@@ -1 +1 @@
-759cf5d12a4b2fb653e61f5219331f14
+0262b20b728f5bb95594e64e2173b2f2
diff --git a/tests/ref/fate/qt-ima4-mono b/tests/ref/fate/qt-ima4-mono
index b8fc5f99de9..83f2958203f 100644
--- a/tests/ref/fate/qt-ima4-mono
+++ b/tests/ref/fate/qt-ima4-mono
@@ -1 +1 @@
-e178ed520edf2f46492ae740d88f5815
+dd6ba393d7aee90d71ab35c72095d166
diff --git a/tests/ref/fate/qt-ima4-stereo b/tests/ref/fate/qt-ima4-stereo
index 84c9f46d023..c847af6ebed 100644
--- a/tests/ref/fate/qt-ima4-stereo
+++ b/tests/ref/fate/qt-ima4-stereo
@@ -1 +1 @@
-d22be0e193dcbba1068a1ca6ab04cf77
+5f2a3bedc62ea1ce63726e0eff29e741
diff --git a/tests/ref/lavf-fate/qtrle_mace6.mov 
b/tests/ref/lavf-fate/qtrle_mace6.mov
index daa36934295..52a02fe6d4d 100644
--- a/tests/ref/lavf-fate/qtrle_mace6.mov
+++ b/tests/ref/lavf-fate/qtrle_mace6.mov
@@ -1,3 +1,3 @@
-5cd71c735dae1c72a0f912002cc0c48f *tests/data/lavf-fate/lavf.qtrle_mace6.mov
+24fa4f7b8fa082996f626e6532c9fd68 *tests/data/lavf-fate/lavf.qtrle_mace6.mov
 1270415 tests/data/lavf-fate/lavf.qtrle_mace6.mov
 tests/data/lavf-fate/lavf.qtrle_mace6.mov CRC=0x9320cd26
-- 
2.54.0


From 6aa7c7539b2de867b021680dd211493c8e37dc4c Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Tue, 17 Nov 2026 11:15:50 -0800
Subject: [PATCH 3/5] avformat/mov: keep the audio sample after the last edit,
 discarded

Decoders whose output lags their input, like SBR, need it for the end
of the edit, as QuickTime does.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/mov.c                          | 11 +++++++++++
 tests/ref/fate/enhanced-flv-hevc           |  5 +++--
 tests/ref/fate/matroska-dovi-write-config8 |  4 ++--
 3 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 112068f4acb..2f9086b8b03 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -4566,6 +4566,7 @@ static void mov_fix_index(MOVContext *mov, AVStream *st, 
int64_t end_dts)
     MOVIndexRange *current_index_range = NULL;
     int found_keyframe_after_edit = 0;
     int found_non_empty_edit = 0;
+    int post_roll = 0;
 
     if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
         return;
@@ -4782,6 +4783,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st, 
int64_t end_dts)
             if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
                 !(flags & AVINDEX_DISCARD_FRAME) && remaining > 0 && remaining 
< frame_duration)
                 current_index_range->end_padding = frame_duration - remaining;
+            else if (post_roll)
+                current_index_range->end_padding = frame_duration;
 
             // Only start incrementing DTS in frame_duration amounts, when we 
encounter a frame in edit list.
             if (edit_list_start_encountered > 0) {
@@ -4791,6 +4794,14 @@ static void mov_fix_index(MOVContext *mov, AVStream *st, 
int64_t end_dts)
             // Break when found first key frame after edit entry completion
             if (frame_duration >= remaining &&
                 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == 
AVMEDIA_TYPE_AUDIO)))) {
+                // Like QuickTime, decode the audio sample after the last 
edit, discarded,
+                // for decoders whose output lags their input (e.g. SBR). A 
parser
+                // would move the discard flag to the previous packet.
+                if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && 
!sti->need_parsing &&
+                    edit_list_index == msc->elst_count && remaining > 0) {
+                    post_roll = 1;
+                    continue;
+                }
                 if (msc->ctts_count) {
                     // If we have CTTS and this is the first keyframe after 
edit elist,
                     // wait for one more, because there might be trailing 
B-frames after this I-frame
diff --git a/tests/ref/fate/enhanced-flv-hevc b/tests/ref/fate/enhanced-flv-hevc
index 80cedbcff3b..5b426d7ba48 100644
--- a/tests/ref/fate/enhanced-flv-hevc
+++ b/tests/ref/fate/enhanced-flv-hevc
@@ -1,5 +1,5 @@
-6d8f2f8590bbcf9bd998b4420155412b *tests/data/fate/enhanced-flv-hevc.flv
-3602973 tests/data/fate/enhanced-flv-hevc.flv
+807fbf592d7311a8057034104cadeeab *tests/data/fate/enhanced-flv-hevc.flv
+3603438 tests/data/fate/enhanced-flv-hevc.flv
 #extradata 0:      551, 0xb1ddcd66
 #extradata 1:        2, 0x00340022
 #tb 0: 1/1000
@@ -256,3 +256,4 @@
 1,       3274,       3274,       23,      397, 0xcf2bc6d6
 1,       3297,       3297,       23,      411, 0xecf7bf70
 1,       3320,       3320,       23,      403, 0x4a35c58a
+1,       3344,       3344,       23,      448, 0x10f5e53d
diff --git a/tests/ref/fate/matroska-dovi-write-config8 
b/tests/ref/fate/matroska-dovi-write-config8
index 6b38ad88062..0913f6488ba 100644
--- a/tests/ref/fate/matroska-dovi-write-config8
+++ b/tests/ref/fate/matroska-dovi-write-config8
@@ -1,5 +1,5 @@
-c10db6bfab4b9b2344c7e7f92e8998de 
*tests/data/fate/matroska-dovi-write-config8.matroska
-3600558 tests/data/fate/matroska-dovi-write-config8.matroska
+0b512530675a198a04d64cf840220d19 
*tests/data/fate/matroska-dovi-write-config8.matroska
+3601023 tests/data/fate/matroska-dovi-write-config8.matroska
 #extradata 0:      551, 0xb1ddcd66
 #extradata 1:        2, 0x00340022
 #tb 0: 1/1000
-- 
2.54.0


From a57cae2fb05a0ce8928f9a635470dcfdcee1f969 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Tue, 17 Nov 2026 11:54:42 -0800
Subject: [PATCH 4/5] avcodec/decode: factor the output delay handling out of
 libfdk-aacdec

Timestamps now move in pkt_timebase, and the end of an edit comes out
of the following discarded frame.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavcodec/decode.c        | 73 +++++++++++++++++++++++++++++++++++++
 libavcodec/decode.h        | 26 +++++++++++++
 libavcodec/libfdk-aacdec.c | 75 ++++++++------------------------------
 3 files changed, 114 insertions(+), 60 deletions(-)

diff --git a/libavcodec/decode.c b/libavcodec/decode.c
index 2696f8f916b..2d9290f2b03 100644
--- a/libavcodec/decode.c
+++ b/libavcodec/decode.c
@@ -37,6 +37,7 @@
 #include "libavutil/hwcontext.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/internal.h"
+#include "libavutil/intreadwrite.h"
 #include "libavutil/mastering_display_metadata.h"
 #include "libavutil/mem.h"
 #include "libavutil/stereo3d.h"
@@ -2408,6 +2409,78 @@ int ff_hwaccel_frame_priv_alloc(AVCodecContext *avctx, 
void **hwaccel_picture_pr
     return 0;
 }
 
+static int set_skip_samples(AVFrame *frame, AVFrameSideData *sd,
+                            uint32_t skip, uint32_t discard)
+{
+    if (!sd) {
+        if (!skip && !discard)
+            return 0;
+        sd = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
+        if (!sd)
+            return AVERROR(ENOMEM);
+        memset(sd->data, 0, 10);
+    }
+    AV_WL32(sd->data,     skip);
+    AV_WL32(sd->data + 4, discard);
+    return 0;
+}
+
+int ff_decode_output_delay(AVCodecContext *avctx, FFAudioOutputDelay *d,
+                           AVFrame *frame)
+{
+    AVFrameSideData *sd = av_frame_get_side_data(frame, 
AV_FRAME_DATA_SKIP_SAMPLES);
+    uint32_t skip = 0, discard = 0;
+    int ret;
+
+    if (sd && sd->size < 10)
+        sd = NULL;
+    if (sd) {
+        skip    = AV_RL32(sd->data);
+        discard = AV_RL32(sd->data + 4);
+    }
+    skip     = skip ? skip + d->delay : d->start;
+    d->start = 0;
+
+    if (frame->flags & AV_FRAME_FLAG_DISCARD) {
+        if (d->tail) {
+            discard = frame->nb_samples - FFMIN(d->tail, frame->nb_samples);
+            frame->flags &= ~AV_FRAME_FLAG_DISCARD;
+        }
+        d->tail = 0;
+    } else {
+        d->tail = d->delay - FFMIN(discard, d->delay);
+        discard = discard > d->delay ? discard - d->delay : 0;
+    }
+
+    if ((ret = set_skip_samples(frame, sd, skip, discard)) < 0)
+        return ret;
+
+    if (d->delay && avctx->pkt_timebase.num && frame->sample_rate) {
+        int64_t diff = av_rescale_q(d->delay, (AVRational){ 1, 
frame->sample_rate },
+                                    avctx->pkt_timebase);
+        if (frame->pts != AV_NOPTS_VALUE)
+            frame->pts = av_sat_sub64(frame->pts, diff);
+        if (frame->pkt_dts != AV_NOPTS_VALUE)
+            frame->pkt_dts = av_sat_sub64(frame->pkt_dts, diff);
+    }
+    return 0;
+}
+
+int ff_decode_output_delay_drain(AVCodecContext *avctx, FFAudioOutputDelay *d,
+                                 AVFrame *frame)
+{
+    AVFrameSideData *sd = av_frame_get_side_data(frame, 
AV_FRAME_DATA_SKIP_SAMPLES);
+    int keep = FFMIN(d->tail, frame->nb_samples);
+    int ret;
+
+    if (sd && sd->size < 10)
+        sd = NULL;
+    ret = set_skip_samples(frame, sd, d->start, frame->nb_samples - keep);
+    d->start = 0;
+    d->tail -= keep;
+    return ret;
+}
+
 av_cold void ff_decode_flush_buffers(AVCodecContext *avctx)
 {
     AVCodecInternal *avci = avctx->internal;
diff --git a/libavcodec/decode.h b/libavcodec/decode.h
index cfe0a11ce57..fec02aae332 100644
--- a/libavcodec/decode.h
+++ b/libavcodec/decode.h
@@ -250,4 +250,30 @@ int ff_decode_content_light_new_ext(const AVCodecContext 
*avctx,
  */
 const char *ff_decode_subtitle_text(AVCodecContext *avctx, const AVPacket 
*avpkt);
 
+/**
+ * State to compensate the output delay of an audio decoder, the samples by
+ * which its output lags the timestamps, priming and padding of its input.
+ */
+typedef struct FFAudioOutputDelay {
+    int delay; ///< samples the output lags its input
+    int start; ///< samples to skip at the start when the input signals no 
priming
+    int tail;  ///< samples of the last kept frame that the delay pushed out
+} FFAudioOutputDelay;
+
+/**
+ * Compensate the output delay for a decoded audio frame: move its timestamps
+ * and the priming and padding from its skip samples side data by the delay.
+ * A discarded frame directly following a kept frame keeps the samples that
+ * the delay pushed out of the kept frame.
+ */
+int ff_decode_output_delay(AVCodecContext *avctx, FFAudioOutputDelay *d,
+                           AVFrame *frame);
+
+/**
+ * Compensate the output delay for a frame of delayed samples returned while
+ * draining: keep the samples that the delay pushed out of the last kept frame.
+ */
+int ff_decode_output_delay_drain(AVCodecContext *avctx, FFAudioOutputDelay *d,
+                                 AVFrame *frame);
+
 #endif /* AVCODEC_DECODE_H */
diff --git a/libavcodec/libfdk-aacdec.c b/libavcodec/libfdk-aacdec.c
index a2b6c6d0c97..ecc8da23b64 100644
--- a/libavcodec/libfdk-aacdec.c
+++ b/libavcodec/libfdk-aacdec.c
@@ -21,7 +21,6 @@
 
 #include "libavutil/channel_layout.h"
 #include "libavutil/common.h"
-#include "libavutil/intreadwrite.h"
 #include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "avcodec.h"
@@ -64,9 +63,7 @@ typedef struct FDKAACDecContext {
 #if FDKDEC_VER_AT_LEAST(2, 5) // 2.5.10
     int output_delay_set;
     int flush_samples;
-    int skip_samples;
-    int output_delay;
-    int discard_padding;
+    FFAudioOutputDelay output_delay;
     int64_t last_pts;
     int64_t last_dts;
 #endif
@@ -142,8 +139,8 @@ static int get_stream_info(AVCodecContext *avctx, AVFrame 
*frame)
     if (!s->output_delay_set && info->outputDelay) {
         // Set this only once.
         s->flush_samples    = info->outputDelay;
-        s->skip_samples     = info->outputDelay;
-        s->output_delay     = info->outputDelay;
+        s->output_delay     = (FFAudioOutputDelay){ .delay = info->outputDelay,
+                                                    .start = info->outputDelay 
};
         s->last_pts         = AV_NOPTS_VALUE;
         s->last_dts         = AV_NOPTS_VALUE;
         s->output_delay_set = 1;
@@ -515,68 +512,28 @@ static int fdk_aac_decode_frame(AVCodecContext *avctx, 
AVFrame *frame,
 
 #if FDKDEC_VER_AT_LEAST(2, 5) // 2.5.10
     if (flags & AACDEC_FLUSH) {
+        int64_t duration = avctx->pkt_timebase.num ?
+                           av_rescale_q(frame->nb_samples, (AVRational){ 1, 
avctx->sample_rate },
+                                        avctx->pkt_timebase) : 0;
         if (s->last_pts != AV_NOPTS_VALUE)
-            frame->pts = av_sat_add64(s->last_pts,
-                                      av_rescale_q(frame->nb_samples, 
avctx->time_base,
-                                                   (AVRational){ 1, 
avctx->sample_rate }));
+            frame->pts = av_sat_add64(s->last_pts, duration);
         if (s->last_dts != AV_NOPTS_VALUE)
-            frame->pkt_dts = av_sat_add64(s->last_dts,
-                                          av_rescale_q(frame->nb_samples, 
avctx->time_base,
-                                                       (AVRational){ 1, 
avctx->sample_rate }));
+            frame->pkt_dts = av_sat_add64(s->last_dts, duration);
 
         // Only return the right amount of samples at the end; if calling the
         // decoder with AACDEC_FLUSH, it will keep returning frames 
indefinitely.
         frame->nb_samples = FFMIN(s->flush_samples, frame->nb_samples);
         av_log(s, AV_LOG_DEBUG, "Returning %d/%d delayed samples.\n",
                                 frame->nb_samples, s->flush_samples);
-        if (s->skip_samples || s->discard_padding) {
-            AVFrameSideData *sd = av_frame_get_side_data(frame, 
AV_FRAME_DATA_SKIP_SAMPLES);
-            if (!sd) {
-                sd = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 
10);
-                if (sd)
-                    memset(sd->data, 0, 10);
-            }
-            if (sd && sd->size >= 10) {
-                AV_WL32(sd->data,     s->skip_samples);
-                AV_WL32(sd->data + 4, s->discard_padding);
-            }
-            s->skip_samples = 0;
-            s->discard_padding = 0;
-        }
+        if ((ret = ff_decode_output_delay_drain(avctx, &s->output_delay, 
frame)) < 0)
+            goto end;
         s->flush_samples -= frame->nb_samples;
-        s->last_pts = frame->pts;
-        s->last_dts = frame->pkt_dts;
     } else {
-        AVFrameSideData *sd = av_frame_get_side_data(frame, 
AV_FRAME_DATA_SKIP_SAMPLES);
-        if (!sd && s->skip_samples) {
-            sd = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
-            if (sd)
-                memset(sd->data, 0, 10);
-        }
-        if (sd && sd->size >= 10) {
-            int skip_samples = AV_RL32(sd->data);
-            s->discard_padding = AV_RL32(sd->data + 4);
-            if (s->discard_padding >= s->output_delay) {
-                AV_WL32(sd->data + 4, s->discard_padding - s->output_delay);
-                s->discard_padding = s->output_delay;
-            } else
-                AV_WL32(sd->data + 4, 0);
-            AV_WL32(sd->data, skip_samples + s->skip_samples);
-            s->skip_samples = 0;
-        }
-        if (frame->pts != AV_NOPTS_VALUE && s->output_delay)
-            frame->pts = av_sat_sub64(frame->pts,
-                                      av_rescale_q(s->output_delay,
-                                                   (AVRational){ 1, 
avctx->sample_rate },
-                                                   avctx->time_base));
-        if (frame->pkt_dts != AV_NOPTS_VALUE && s->output_delay)
-            frame->pkt_dts = av_sat_sub64(frame->pkt_dts,
-                                          av_rescale_q(s->output_delay,
-                                                       (AVRational){ 1, 
avctx->sample_rate },
-                                                       avctx->time_base));
-        s->last_pts = frame->pts;
-        s->last_dts = frame->pkt_dts;
+        if ((ret = ff_decode_output_delay(avctx, &s->output_delay, frame)) < 0)
+            goto end;
     }
+    s->last_pts = frame->pts;
+    s->last_dts = frame->pkt_dts;
 #endif
 
     memcpy(frame->extended_data[0], s->decoder_buffer,
@@ -603,10 +560,8 @@ static av_cold void fdk_aac_decode_flush(AVCodecContext 
*avctx)
         av_log(avctx, AV_LOG_WARNING, "failed to clear buffer when 
flushing\n");
 
 #if FDKDEC_VER_AT_LEAST(2, 5) // 2.5.10
-    s->skip_samples = 0;
-    s->discard_padding = 0;
     s->flush_samples = 0;
-    s->output_delay = 0;
+    s->output_delay = (FFAudioOutputDelay){ 0 };
     s->last_pts = AV_NOPTS_VALUE;
     s->last_dts = AV_NOPTS_VALUE;
     s->output_delay_set = 0;
-- 
2.54.0


From e4a538b6bbc1cdebb824603131c3b796aa81cb30 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Tue, 17 Nov 2026 11:54:43 -0800
Subject: [PATCH 5/5] avcodec/aac/aacdec: compensate the SBR delay

Timestamps, edits and trimming apply to the core AAC output, which the
SBR tool delays (ISO/IEC 14496-3 Table 1.34).

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavcodec/aac/aacdec.c                       |  8 +++++
 libavcodec/aac/aacdec.h                       |  3 ++
 tests/fate/aac.mak                            |  6 ++++
 tests/ref/fate/aac-sbr-edit-end               | 31 +++++++++++++++++++
 .../audiomatch-afconvert-16000-mono-he-m4a    |  2 +-
 .../audiomatch-afconvert-16000-stereo-he-m4a  |  2 +-
 .../audiomatch-afconvert-16000-stereo-he2-m4a |  2 +-
 .../audiomatch-afconvert-44100-mono-he-m4a    |  2 +-
 .../audiomatch-afconvert-44100-stereo-he-m4a  |  2 +-
 .../audiomatch-afconvert-44100-stereo-he2-m4a |  2 +-
 .../audiomatch-fdkaac-44100-stereo-he-m4a     |  2 +-
 .../audiomatch-fdkaac-44100-stereo-he2-m4a    |  2 +-
 .../fate/audiomatch-nero-16000-mono-he-m4a    |  2 +-
 .../fate/audiomatch-nero-16000-stereo-he-m4a  |  2 +-
 .../fate/audiomatch-nero-16000-stereo-he2-m4a |  2 +-
 .../fate/audiomatch-nero-44100-mono-he-m4a    |  2 +-
 .../fate/audiomatch-nero-44100-stereo-he-m4a  |  2 +-
 .../fate/audiomatch-nero-44100-stereo-he2-m4a |  2 +-
 tests/ref/fate/preroll-aac-he-adts-decode     |  9 +++---
 .../preroll-aac-he-adts-decode-noaccurate     |  8 ++---
 .../fate/preroll-aac-he-implicit-mov-decode   |  9 +++---
 ...roll-aac-he-implicit-mov-decode-noaccurate |  8 ++---
 22 files changed, 80 insertions(+), 30 deletions(-)
 create mode 100644 tests/ref/fate/aac-sbr-edit-end

diff --git a/libavcodec/aac/aacdec.c b/libavcodec/aac/aacdec.c
index 4ac16844bed..10578fe3bf7 100644
--- a/libavcodec/aac/aacdec.c
+++ b/libavcodec/aac/aacdec.c
@@ -570,6 +570,7 @@ static av_cold void flush(AVCodecContext *avctx)
             }
         }
     }
+    ac->output_delay.tail = 0;
 
 #if CONFIG_AAC_DECODER
     ff_aac_usac_reset_state(ac, &ac->oc[1]);
@@ -2526,6 +2527,13 @@ static int decode_frame_ga(AVCodecContext *avctx, 
AACDecContext *ac,
         ac->frame->nb_samples = samples;
         ac->frame->sample_rate = avctx->sample_rate;
         ac->frame->flags |= AV_FRAME_FLAG_KEY;
+        if (ac->oc[1].m4ac.sbr == 1) {
+            /* ISO/IEC 14496-3 Table 1.34: timestamps apply to the core AAC 
output. */
+            int ret;
+            ac->output_delay.delay = multiplier ? 962 : 481;
+            if ((ret = ff_decode_output_delay(avctx, &ac->output_delay, 
ac->frame)) < 0)
+                return ret;
+        }
         *got_frame_ptr = 1;
     } else {
         av_frame_unref(ac->frame);
diff --git a/libavcodec/aac/aacdec.h b/libavcodec/aac/aacdec.h
index 1fb89ace613..3748ebb62b5 100644
--- a/libavcodec/aac/aacdec.h
+++ b/libavcodec/aac/aacdec.h
@@ -40,6 +40,7 @@
 
 #include "libavcodec/aac.h"
 #include "libavcodec/avcodec.h"
+#include "libavcodec/decode.h"
 #include "libavcodec/mpeg4audio.h"
 
 #include "aacdec_ac.h"
@@ -575,6 +576,8 @@ struct AACDecContext {
     int dmono_mode;      ///< 0->not dmono, 1->use first channel, 2->use 
second channel
     /** @} */
 
+    FFAudioOutputDelay output_delay; ///< SBR delay
+
     enum AACOutputChannelOrder output_channel_order;
 
     /**
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
index be0420d9519..e5ebb13e650 100644
--- a/tests/fate/aac.mak
+++ b/tests/fate/aac.mak
@@ -338,6 +338,12 @@ fate-aac-sce-in-stereo: CMD = framecrc -i 
$(TARGET_SAMPLES)/aac/aac-sce-in-stere
 
 FATE_AAC_FRAMECRC-$(call FRAMECRC, MOV, AAC, ARESAMPLE_FILTER PAN_FILTER 
PCM_F32LE_ENCODER) += $(FATE_AAC_FRAMECRC)
 
+# An edit ending less than the SBR delay before the end of its last sample:
+# the rest comes out of the next sample. The output is silenced, as only its
+# timing is compared.
+FATE_AAC_FRAMECRC-$(call FRAMECRC, MOV, AAC, ARESAMPLE_FILTER VOLUME_FILTER 
PCM_S16LE_ENCODER) += fate-aac-sbr-edit-end
+fate-aac-sbr-edit-end: CMD = framecrc -i 
$(TARGET_SAMPLES)/aac/sbr_edit_end.mp4 -af volume=0,aresample -c:a pcm_s16le
+
 FATE_AAC_ENCODE-$(call TRANSCODE, AAC, MP4 MOV, WAV_MUXER WAV_DEMUXER 
PCM_S16LE_DECODER ARESAMPLE_FILTER) += $(FATE_AAC_ENCODE)
 FATE_AAC_ENCODE_FFPROBE-$(call TRANSCODE, AAC, ADTS AAC, WAV_DEMUXER 
PCM_S16LE_DECODER ARESAMPLE_FILTER) += $(FATE_AAC_ENCODE_FFPROBE)
 FATE_AAC_ENCODE_LAVFI-$(call TRANSCODE, AAC, ADTS AAC, LAVFI_INDEV 
AEVALSRC_FILTER ARESAMPLE_FILTER PCM_F64LE_DECODER PCM_F64BE_DECODER) += 
$(FATE_AAC_ENCODE_LAVFI)
diff --git a/tests/ref/fate/aac-sbr-edit-end b/tests/ref/fate/aac-sbr-edit-end
new file mode 100644
index 00000000000..d218030ff79
--- /dev/null
+++ b/tests/ref/fate/aac-sbr-edit-end
@@ -0,0 +1,31 @@
+#tb 0: 1/48000
+#media_type 0: audio
+#codec_id 0: pcm_s16le
+#sample_rate 0: 48000
+#channel_layout_name 0: stereo
+0,          0,          0,      958,     3832, 0x00000000
+0,        958,        958,     2048,     8192, 0x00000000
+0,       3006,       3006,     2048,     8192, 0x00000000
+0,       5054,       5054,     2048,     8192, 0x00000000
+0,       7102,       7102,     2048,     8192, 0x00000000
+0,       9150,       9150,     2048,     8192, 0x00000000
+0,      11198,      11198,     2048,     8192, 0x00000000
+0,      13246,      13246,     2048,     8192, 0x00000000
+0,      15294,      15294,     2048,     8192, 0x00000000
+0,      17342,      17342,     2048,     8192, 0x00000000
+0,      19390,      19390,     2048,     8192, 0x00000000
+0,      21438,      21438,     2048,     8192, 0x00000000
+0,      23486,      23486,     2048,     8192, 0x00000000
+0,      25534,      25534,     2048,     8192, 0x00000000
+0,      27582,      27582,     2048,     8192, 0x00000000
+0,      29630,      29630,     2048,     8192, 0x00000000
+0,      31678,      31678,     2048,     8192, 0x00000000
+0,      33726,      33726,     2048,     8192, 0x00000000
+0,      35774,      35774,     2048,     8192, 0x00000000
+0,      37822,      37822,     2048,     8192, 0x00000000
+0,      39870,      39870,     2048,     8192, 0x00000000
+0,      41918,      41918,     2048,     8192, 0x00000000
+0,      43966,      43966,     2048,     8192, 0x00000000
+0,      46014,      46014,     2048,     8192, 0x00000000
+0,      48062,      48062,     2048,     8192, 0x00000000
+0,      50110,      50110,      524,     2096, 0x00000000
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-mono-he-m4a 
b/tests/ref/fate/audiomatch-afconvert-16000-mono-he-m4a
index edd4b475bd9..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-mono-he-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-16000-mono-he-m4a
@@ -1 +1 @@
-presig: 481 postsig:-481 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-m4a 
b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-m4a
index 9849bffda63..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-m4a
@@ -1 +1 @@
-presig: 962 postsig:-962 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-m4a 
b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-m4a
index 9849bffda63..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-m4a
@@ -1 +1 @@
-presig: 962 postsig:-962 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-mono-he-m4a 
b/tests/ref/fate/audiomatch-afconvert-44100-mono-he-m4a
index 9849bffda63..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-mono-he-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-44100-mono-he-m4a
@@ -1 +1 @@
-presig: 962 postsig:-962 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-m4a 
b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-m4a
index 5ea95e4507c..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-m4a
@@ -1 +1 @@
-presig: 1924 postsig:-1924 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-m4a 
b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-m4a
index 5ea95e4507c..1d29bafedac 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-m4a
@@ -1 +1 @@
-presig: 1924 postsig:-1924 lenerr:0
+presig: 0 postsig:0 lenerr:0
diff --git a/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he-m4a 
b/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he-m4a
index f4a40156614..a3a4f4d179a 100644
--- a/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he-m4a
@@ -1 +1 @@
-presig: 1922 postsig:-1922 lenerr:0
+presig: -2 postsig:2 lenerr:0
diff --git a/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he2-m4a 
b/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he2-m4a
index f4a40156614..a3a4f4d179a 100644
--- a/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-fdkaac-44100-stereo-he2-m4a
@@ -1 +1 @@
-presig: 1922 postsig:-1922 lenerr:0
+presig: -2 postsig:2 lenerr:0
diff --git a/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a 
b/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
index 0c8a568738f..52824b73396 100644
--- a/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
@@ -1 +1 @@
-presig: -4 postsig:4 lenerr:0
+presig: -966 postsig:196 lenerr:-770
diff --git a/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a 
b/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
index 88dbfbb8ef7..a8557c0a8a8 100644
--- a/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
@@ -1 +1 @@
-presig: -8 postsig:8 lenerr:0
+presig: -1932 postsig:392 lenerr:-1540
diff --git a/tests/ref/fate/audiomatch-nero-16000-stereo-he2-m4a 
b/tests/ref/fate/audiomatch-nero-16000-stereo-he2-m4a
index eee301f6e13..85862988c81 100644
--- a/tests/ref/fate/audiomatch-nero-16000-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-nero-16000-stereo-he2-m4a
@@ -1 +1 @@
-presig: 2 postsig:-2 lenerr:0
+presig: -1922 postsig:1922 lenerr:0
diff --git a/tests/ref/fate/audiomatch-nero-44100-mono-he-m4a 
b/tests/ref/fate/audiomatch-nero-44100-mono-he-m4a
index 1d29bafedac..72866860690 100644
--- a/tests/ref/fate/audiomatch-nero-44100-mono-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-44100-mono-he-m4a
@@ -1 +1 @@
-presig: 0 postsig:0 lenerr:0
+presig: -962 postsig:962 lenerr:0
diff --git a/tests/ref/fate/audiomatch-nero-44100-stereo-he-m4a 
b/tests/ref/fate/audiomatch-nero-44100-stereo-he-m4a
index a3a4f4d179a..3a8f510a2c1 100644
--- a/tests/ref/fate/audiomatch-nero-44100-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-44100-stereo-he-m4a
@@ -1 +1 @@
-presig: -2 postsig:2 lenerr:0
+presig: -1926 postsig:1926 lenerr:0
diff --git a/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a 
b/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a
index eee301f6e13..178d0373cef 100644
--- a/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a
@@ -1 +1 @@
-presig: 2 postsig:-2 lenerr:0
+presig: -1922 postsig:782 lenerr:-1140
diff --git a/tests/ref/fate/preroll-aac-he-adts-decode 
b/tests/ref/fate/preroll-aac-he-adts-decode
index a6552ba4e9a..4a9b4bfb3b9 100644
--- a/tests/ref/fate/preroll-aac-he-adts-decode
+++ b/tests/ref/fate/preroll-aac-he-adts-decode
@@ -3,7 +3,8 @@
 #codec_id 0: pcm_s16le
 #sample_rate 0: 44100
 #channel_layout_name 0: stereo
-0,          0,          0,     1203,     4812, 0x00000000
-0,       1203,       1203,     2048,     8192, 0x00000000
-0,       3251,       3251,     2048,     8192, 0x00000000
-0,       5299,       5299,     1316,     5264, 0x00000000
+0,          0,          0,      241,      964, 0x00000000
+0,        241,        241,     2048,     8192, 0x00000000
+0,       2289,       2289,     2048,     8192, 0x00000000
+0,       4337,       4337,     2048,     8192, 0x00000000
+0,       6385,       6385,      230,      920, 0x00000000
diff --git a/tests/ref/fate/preroll-aac-he-adts-decode-noaccurate 
b/tests/ref/fate/preroll-aac-he-adts-decode-noaccurate
index 7499e24eb41..f085b4b3438 100644
--- a/tests/ref/fate/preroll-aac-he-adts-decode-noaccurate
+++ b/tests/ref/fate/preroll-aac-he-adts-decode-noaccurate
@@ -3,7 +3,7 @@
 #codec_id 0: pcm_s16le
 #sample_rate 0: 44100
 #channel_layout_name 0: stereo
-0,       -845,       -845,     2048,     8192, 0x00000000
-0,       1203,       1203,     2048,     8192, 0x00000000
-0,       3251,       3251,     2048,     8192, 0x00000000
-0,       5299,       5299,      471,     1884, 0x00000000
+0,       -845,       -845,     1086,     4344, 0x00000000
+0,        241,        241,     2048,     8192, 0x00000000
+0,       2289,       2289,     2048,     8192, 0x00000000
+0,       4337,       4337,     1433,     5732, 0x00000000
diff --git a/tests/ref/fate/preroll-aac-he-implicit-mov-decode 
b/tests/ref/fate/preroll-aac-he-implicit-mov-decode
index fe7cbac7316..02fc22e43b1 100644
--- a/tests/ref/fate/preroll-aac-he-implicit-mov-decode
+++ b/tests/ref/fate/preroll-aac-he-implicit-mov-decode
@@ -3,7 +3,8 @@
 #codec_id 0: pcm_s16le
 #sample_rate 0: 44100
 #channel_layout_name 0: stereo
-0,          0,          0,     1202,     4808, 0x00000000
-0,       1202,       1202,     2048,     8192, 0x00000000
-0,       3250,       3250,     2048,     8192, 0x00000000
-0,       5298,       5298,     1317,     5268, 0x00000000
+0,          0,          0,      240,      960, 0x00000000
+0,        240,        240,     2048,     8192, 0x00000000
+0,       2288,       2288,     2048,     8192, 0x00000000
+0,       4336,       4336,     2048,     8192, 0x00000000
+0,       6384,       6384,      231,      924, 0x00000000
diff --git a/tests/ref/fate/preroll-aac-he-implicit-mov-decode-noaccurate 
b/tests/ref/fate/preroll-aac-he-implicit-mov-decode-noaccurate
index 35c4c19cf01..62807811b4b 100644
--- a/tests/ref/fate/preroll-aac-he-implicit-mov-decode-noaccurate
+++ b/tests/ref/fate/preroll-aac-he-implicit-mov-decode-noaccurate
@@ -3,7 +3,7 @@
 #codec_id 0: pcm_s16le
 #sample_rate 0: 44100
 #channel_layout_name 0: stereo
-0,       -846,       -846,     2048,     8192, 0x00000000
-0,       1202,       1202,     2048,     8192, 0x00000000
-0,       3250,       3250,     2048,     8192, 0x00000000
-0,       5298,       5298,      471,     1884, 0x00000000
+0,       -846,       -846,     1086,     4344, 0x00000000
+0,        240,        240,     2048,     8192, 0x00000000
+0,       2288,       2288,     2048,     8192, 0x00000000
+0,       4336,       4336,     1433,     5732, 0x00000000
-- 
2.54.0

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

Reply via email to