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

Depends on https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26140; only the last 
commit is new.

The SBR delay held back the last 962 samples (481 downsampled) of HE-AAC 
streams. At EOF, the native decoder (float, fixed, LATM) now decodes one silent 
frame that repeats the last SBR and PS data, as libfdk does when flushing, and 
keeps the tail.

- The Nero HE files now reach their full length.
- Cutting a stream and comparing with the uncut decode: everything before the 
tail is bit-exact, and the drained tail is closer to the uncut decode than 
libfdk's flush.
- libfdk output and timestamps are unchanged.

Ref changes: audiomatch HE tests and mov-aac-sbr-edit-start gain the tail. The 
ISO conformance refs end at the last whole frame, so they get a size tolerance 
of exactly the tail. New test fate-aac-sbr-drain.

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



From 204a264854adf33fabd049d2abf9d7b031af425e Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 14 Nov 2026 00:46:09 -0800
Subject: [PATCH 1/6] 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                     | 50 ++++++++++++---------------
 tests/fate/mov.mak                    |  6 +++-
 tests/ref/fate/mov-aac-sbr-edit-start |  3 ++
 tests/ref/fate/mov-mp4-chapters       |  2 +-
 4 files changed, 31 insertions(+), 30 deletions(-)
 create mode 100644 tests/ref/fate/mov-aac-sbr-edit-start

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 9ad780cde9c..b487ce105dc 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -4670,8 +4670,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;
@@ -4717,6 +4716,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++;
@@ -4735,19 +4736,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.
@@ -4821,14 +4809,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
@@ -4840,7 +4827,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);
@@ -4853,11 +4840,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st)
                             break;
                         }
 
-                        // 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 {
@@ -4943,6 +4927,16 @@ 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) {
+        /* The output rate is unknown with several sample descriptions
+         * or implicit SBR, keep the skip in track ticks then. */
+        if (msc->stsd_count == 1 &&
+            (st->codecpar->codec_id != AV_CODEC_ID_AAC ||
+             st->codecpar->sample_rate >= msc->time_scale))
+            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/fate/mov.mak b/tests/fate/mov.mak
index e8972bc3eb6..db341680e1c 100644
--- a/tests/fate/mov.mak
+++ b/tests/fate/mov.mak
@@ -149,7 +149,7 @@ fate-mov-bbi-elst-starts-b: CMD = framemd5 -flags +bitexact 
-acodec aac_fixed -i
 fate-mov-neg-firstpts-discard: CMD = run ffprobe$(PROGSSUF)$(EXESUF) 
-show_entries stream=start_time -bitexact 
$(TARGET_SAMPLES)/mov/mov_neg_first_pts_discard.mov
 
 # Makes sure that the VORBIS audio stream start_time is not negative when the 
first few packets are DISCARD packets
-# with negative timestamps (skip_samples is not set for Vorbis, so ffmpeg 
computes start_time as negative if not specified by demuxer).
+# with negative timestamps.
 fate-mov-neg-firstpts-discard-vorbis: CMD = run ffprobe$(PROGSSUF)$(EXESUF) 
-show_entries stream=start_time -bitexact 
$(TARGET_SAMPLES)/mov/mov_neg_first_pts_discard_vorbis.mp4
 
 # Makes sure that expected frames are generated for 
mov_neg_first_pts_discard.mov with -fps_mode cfr
@@ -168,6 +168,10 @@ fate-mov-aac-2048-priming-preroll: CMD = run 
ffprobe$(PROGSSUF)$(EXESUF) -show_e
 FATE_MOV_FFPROBE-$(call DEMDEC, MOV, AAC) += 
fate-mov-aac-2048-priming-seek-landing
 fate-mov-aac-2048-priming-seek-landing: CMD = run ffprobe$(PROGSSUF)$(EXESUF) 
-seek_flags preroll -read_intervals 2.3%+\#3 -show_entries 
packet=pts,dts,duration -print_format compact 
$(TARGET_SAMPLES)/mov/aac-2048-priming.mov
 
+# With explicit SBR the edit priming, in core rate ticks, is skipped in output 
samples.
+FATE_MOV_FFPROBE-$(call DEMDEC, MOV, AAC) += fate-mov-aac-sbr-edit-start
+fate-mov-aac-sbr-edit-start: CMD = run ffprobe$(PROGSSUF)$(EXESUF) 
-read_intervals %+\#4 -show_entries stream=initial_padding:frame=pts,nb_samples 
-print_format compact $(TARGET_SAMPLES)/aac/sbr_edit_end.mp4
+
 # Seeking into the stream must not drop samples to the container's priming.
 FATE_MOV-$(call FRAMECRC, MOV, AAC, PCM_S16LE_ENCODER ARESAMPLE_FILTER 
VOLUME_FILTER) += fate-mov-aac-2048-priming-seek
 fate-mov-aac-2048-priming-seek: CMD = framecrc -ss 2.3 -t 0.15 -i 
$(TARGET_SAMPLES)/mov/aac-2048-priming.mov -af volume=0,aresample -c:a pcm_s16le
diff --git a/tests/ref/fate/mov-aac-sbr-edit-start 
b/tests/ref/fate/mov-aac-sbr-edit-start
new file mode 100644
index 00000000000..14eccff51ae
--- /dev/null
+++ b/tests/ref/fate/mov-aac-sbr-edit-start
@@ -0,0 +1,3 @@
+frame|pts=0|nb_samples=1920
+frame|pts=960|nb_samples=2048
+stream|initial_padding=4224
diff --git a/tests/ref/fate/mov-mp4-chapters b/tests/ref/fate/mov-mp4-chapters
index 7741770ec2e..e52ce0e3f24 100644
--- a/tests/ref/fate/mov-mp4-chapters
+++ b/tests/ref/fate/mov-mp4-chapters
@@ -6,7 +6,7 @@
 #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.1


From 5e1dccba8bd4e135d7dd5a784ac3c3a6b51ae3fd Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 14 Nov 2026 00:02:36 -0800
Subject: [PATCH 2/6] 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                        | 96 +++++++++++++++++++-----
 tests/fate/mov.mak                       | 23 ++++++
 tests/fate/qt.mak                        |  2 +-
 tests/ref/fate/adpcm-ima_wav-stereo      |  2 +-
 tests/ref/fate/adpcm_ms-stereo           |  2 +-
 tests/ref/fate/mov-aac-frag-short-trun   | 18 +++++
 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 +-
 14 files changed, 164 insertions(+), 25 deletions(-)
 create mode 100644 tests/ref/fate/mov-aac-frag-short-trun
 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 7ad42f52809..6adf6694aaa 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 b487ce105dc..13bc2629843 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -4322,7 +4322,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;
@@ -4331,12 +4331,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)
@@ -4641,7 +4641,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);
@@ -4682,8 +4682,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;
@@ -4714,8 +4714,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",
@@ -4770,14 +4773,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;
 
@@ -4808,7 +4817,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;
@@ -4869,20 +4879,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,
@@ -5153,6 +5167,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,
@@ -5395,7 +5418,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.
@@ -12936,10 +12959,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;
@@ -12979,6 +13004,38 @@ 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) {
+            /* Decoders taking one block at a time would trim every block of a 
grouped packet. */
+            if (sc->samples_per_frame <= 1 || sample->size <= 
sc->bytes_per_frame)
+                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++;
@@ -13027,6 +13084,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;
@@ -13076,6 +13134,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) {
@@ -13107,7 +13167,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;
@@ -13182,7 +13242,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 db341680e1c..c2fb9013691 100644
--- a/tests/fate/mov.mak
+++ b/tests/fate/mov.mak
@@ -445,6 +445,29 @@ fate-mov-dfpwm-last-packet: CMD = transcode lavfi 
"sine=r=48000,atrim=end_sample
 fate-mov-vfr: CMP = oneline
 fate-mov-vfr: REF = 54167f70fb0c2d164587b6af1aad9623
 
+# 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 decoder must drop the samples of the full last AAC frame beyond its 
short trun.
+FATE_MOV_FFMPEG_FFPROBE-$(call ALLYES, LAVFI_INDEV SINE_FILTER AAC_ENCODER 
AAC_DECODER \
+                                      MP4_MUXER MOV_DEMUXER FILE_PROTOCOL) += 
fate-mov-aac-frag-short-trun
+fate-mov-aac-frag-short-trun: CMD = run_with_temp \
+    "$(FFMPEG) -nostdin -v error -f lavfi -i sine=r=48000:d=0.15 -c:a aac \
+    -flags +bitexact -fflags +bitexact -movflags empty_moov+frag_keyframe -f 
mp4 -y" \
+    "ffprobe$(PROGSSUF)$(EXESUF) -v error -show_entries 
packet=pts,duration:frame=pts,nb_samples \
+    -print_format compact" mp4
+
 # 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..d9874b26ce2 100644
--- a/tests/fate/qt.mak
+++ b/tests/fate/qt.mak
@@ -4,7 +4,7 @@ fate-8bps: CMD = framecrc -i 
$(TARGET_SAMPLES)/8bps/full9iron-partial.mov -pix_f
 FATE_QT-$(call ENCDEC, PCM_S16LE QDM2, PCM_S16LE MOV, PIPE_PROTOCOL) += 
fate-qdm2
 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: REF = $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2-trimmed.pcm
 fate-qdm2: FUZZ = 2
 
 FATE_QT-$(call ENCDEC, PCM_S16LE PCM_ALAW, MOV PCM_S16LE) += fate-qt-alaw-mono
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-aac-frag-short-trun 
b/tests/ref/fate/mov-aac-frag-short-trun
new file mode 100644
index 00000000000..df209324098
--- /dev/null
+++ b/tests/ref/fate/mov-aac-frag-short-trun
@@ -0,0 +1,18 @@
+packet|pts=0|duration=1024
+frame|pts=0|nb_samples=1024
+packet|pts=1024|duration=1024
+frame|pts=1024|nb_samples=1024
+packet|pts=2048|duration=1024
+frame|pts=2048|nb_samples=1024
+packet|pts=3072|duration=1024
+frame|pts=3072|nb_samples=1024
+packet|pts=4096|duration=1024
+frame|pts=4096|nb_samples=1024
+packet|pts=5120|duration=1024
+frame|pts=5120|nb_samples=1024
+packet|pts=6144|duration=1024
+frame|pts=6144|nb_samples=1024
+packet|pts=7168|duration=1024
+frame|pts=7168|nb_samples=1024
+packet|pts=8192|duration=32
+frame|pts=8192|nb_samples=32
diff --git a/tests/ref/fate/mov-alaw-final-edit 
b/tests/ref/fate/mov-alaw-final-edit
new file mode 100644
index 00000000000..3d25f569d25
--- /dev/null
+++ b/tests/ref/fate/mov-alaw-final-edit
@@ -0,0 +1,12 @@
+d90ca4fdb61eda80cb52b872363b958c *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..1d6b00d06d6
--- /dev/null
+++ b/tests/ref/fate/mov-fractional-audio-edit
@@ -0,0 +1,12 @@
+1a6c8ed2b51989a00ce70594ae0dd1d7 *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..2180bbdd80a
--- /dev/null
+++ b/tests/ref/fate/mov-twos-final-edit
@@ -0,0 +1,12 @@
+1ba5452aa800fb149600ef7cdd730eb6 *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 b05d8890e07..cad64b9236e 100644
--- a/tests/ref/lavf-fate/qtrle_mace6.mov
+++ b/tests/ref/lavf-fate/qtrle_mace6.mov
@@ -1,3 +1,3 @@
-9ef5f70482cef2e9e8d51ba2816d6a86 *tests/data/lavf-fate/lavf.qtrle_mace6.mov
+3988251066e91b8db8ac894687ea8ea9 *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.1


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

SBR delays the decoder output, which needs it for the end of the edit,
as QuickTime does.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavformat/mov.c | 31 +++++++++++++++++++++++++++++--
 1 file changed, 29 insertions(+), 2 deletions(-)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 13bc2629843..3cd62035c9b 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -60,6 +60,7 @@
 #include "libavcodec/mpegaudiodata.h"
 #include "libavcodec/mpegaudiodecheader.h"
 #include "libavcodec/mlp_parse.h"
+#include "libavcodec/mpeg4audio.h"
 #include "avformat.h"
 #include "internal.h"
 #include "avio_internal.h"
@@ -4641,6 +4642,20 @@ 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.
  */
+/* SBR delays the decoder output (ISO/IEC 14496-3 Table 1.34); without
+ * explicit signaling, an AAC-LC core up to 24 kHz may carry it. */
+static int mov_audio_needs_post_roll(AVStream *st)
+{
+    MPEG4AudioConfig cfg;
+
+    if (st->codecpar->codec_id != AV_CODEC_ID_AAC || 
ffstream(st)->need_parsing ||
+        avpriv_mpeg4audio_get_config2(&cfg, st->codecpar->extradata,
+                                      st->codecpar->extradata_size, 1, NULL) < 
0)
+        return 0;
+    return cfg.sbr == 1 ||
+           (cfg.sbr < 0 && cfg.object_type == AOT_AAC_LC && cfg.sample_rate <= 
24000);
+}
+
 static void mov_fix_index(MOVContext *mov, AVStream *st, int64_t end_dts)
 {
     MOVStreamContext *msc = st->priv_data;
@@ -4674,6 +4689,8 @@ 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;
+    const int needs_post_roll = mov_audio_needs_post_roll(st);
+    int post_roll = 0;
 
     if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
         return;
@@ -4681,8 +4698,8 @@ static void mov_fix_index(MOVContext *mov, AVStream *st, 
int64_t end_dts)
 
     int64_t max_entries = nb_old * 16LL + (1 << 16);
 
-    // allocate the index ranges array
-    msc->index_ranges = av_calloc(msc->elst_count + 1,
+    // allocate the index ranges array: two per edit, with the post-roll 
sample, and the terminator
+    msc->index_ranges = av_calloc(2 * (size_t)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");
@@ -4732,6 +4749,7 @@ static void mov_fix_index(MOVContext *mov, AVStream *st, 
int64_t end_dts)
             break;
         }
         num_discarded_begin = 0;
+        post_roll = 0;
         if (edit_list_media_time == -1) {
             if (!found_non_empty_edit)
                 empty_edits_sum_duration += edit_list_duration;
@@ -4889,6 +4907,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) {
@@ -4898,6 +4918,13 @@ 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 edit, 
discarded,
+                // for decoders whose output lags their input. A parser would 
move
+                // the discard flag to the previous packet.
+                if (needs_post_roll && 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
-- 
2.54.1


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

Timestamps now move in pkt_timebase, the end of an edit comes out of the
discarded frame continuing it, and the start of a later edit is trimmed.

Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavcodec/decode.c        | 97 ++++++++++++++++++++++++++++++++++++++
 libavcodec/decode.h        | 30 ++++++++++++
 libavcodec/libfdk-aacdec.c | 78 +++++++-----------------------
 3 files changed, 144 insertions(+), 61 deletions(-)

diff --git a/libavcodec/decode.c b/libavcodec/decode.c
index 2696f8f916b..bb53342228b 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,102 @@ 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);
+    int64_t ts = frame->pts != AV_NOPTS_VALUE ? frame->pts : frame->pkt_dts;
+    int64_t diff = 0, duration = 0;
+    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);
+    }
+    if (d->delay && avctx->pkt_timebase.num && frame->sample_rate) {
+        AVRational tb = { 1, frame->sample_rate };
+        diff     = av_rescale_q(d->delay, tb, avctx->pkt_timebase);
+        duration = av_rescale_q(frame->nb_samples, tb, avctx->pkt_timebase);
+    }
+
+    if (skip)
+        skip += d->delay;
+    else if (d->start)
+        skip = d->start;
+    else if (d->dropped && !d->skip && !(frame->flags & AV_FRAME_FLAG_DISCARD))
+        skip = d->delay; // pushed out of a discarded frame
+    d->start = 0;
+
+    if (frame->flags & AV_FRAME_FLAG_DISCARD) {
+        /* Only the continuation of the last kept frame completes it. */
+        if (ts != AV_NOPTS_VALUE && d->tail_ts != AV_NOPTS_VALUE &&
+            FFABS(ts - d->tail_ts) > 1)
+            d->tail = 0;
+        if (d->tail) {
+            int keep = FFMIN(d->tail, frame->nb_samples);
+            skip     = 0;
+            discard  = frame->nb_samples - keep;
+            frame->flags &= ~AV_FRAME_FLAG_DISCARD;
+            d->tail -= keep;
+        }
+        d->dropped = 1;
+    } else {
+        d->tail    = d->delay - FFMIN(discard, d->delay);
+        discard    = discard > d->delay ? discard - d->delay : 0;
+        d->dropped = 0;
+    }
+    /* Follow the skip that decoding carries over to the next frames. */
+    d->skip    = FFMAX((int64_t)(skip ? skip : d->skip) - frame->nb_samples, 
0);
+    d->tail_ts = ts != AV_NOPTS_VALUE && duration ? av_sat_add64(ts, duration) 
: AV_NOPTS_VALUE;
+
+    if ((ret = set_skip_samples(frame, sd, skip, discard)) < 0)
+        return ret;
+
+    if (diff) {
+        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);
+    if (keep)
+        frame->flags &= ~AV_FRAME_FLAG_DISCARD;
+    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..309dc7ff12b 100644
--- a/libavcodec/decode.h
+++ b/libavcodec/decode.h
@@ -250,4 +250,34 @@ 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
+    int skip;  ///< samples left to skip in the next frames
+    int dropped;     ///< the last frame was discarded
+    int64_t tail_ts; ///< timestamp of the frame continuing the last one
+} 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 continuing a kept frame keeps the samples that the delay
+ * pushed out of the kept frame, and a kept frame following a discarded frame
+ * skips those of the discarded 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..3567745f281 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;
@@ -512,71 +509,32 @@ static int fdk_aac_decode_frame(AVCodecContext *avctx, 
AVFrame *frame,
 
     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
         goto end;
+    frame->pkt_dts = avpkt->dts;
 
 #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 +561,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;
@@ -638,6 +594,6 @@ const FFCodec ff_libfdk_aac_decoder = {
 #endif
     ,
     .p.priv_class   = &fdk_aac_dec_class,
-    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
+    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     .p.wrapper_name = "libfdk",
 };
-- 
2.54.1


From 28d2e39ab08d6d772c6c903c3a7f4c87881521b8 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Tue, 17 Nov 2026 11:54:43 -0800
Subject: [PATCH 5/6] 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                       | 13 ++++++--
 libavcodec/aac/aacdec.h                       |  3 ++
 libavcodec/aac/aacdec_latm.h                  |  2 +-
 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/mov-aac-sbr-edit-start         |  4 +--
 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 ++---
 24 files changed, 86 insertions(+), 35 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..57548281758 100644
--- a/libavcodec/aac/aacdec.c
+++ b/libavcodec/aac/aacdec.c
@@ -204,6 +204,7 @@ static int frame_configure_elements(AVCodecContext *avctx)
     ac->frame->nb_samples = 2048;
     if ((ret = ff_get_buffer(avctx, ac->frame, 0)) < 0)
         return ret;
+    ac->frame->pkt_dts = avctx->internal->last_pkt_props->dts;
 
     /* map output channel pointers to AVFrame data */
     for (ch = 0; ch < avctx->ch_layout.nb_channels; ch++) {
@@ -570,6 +571,7 @@ static av_cold void flush(AVCodecContext *avctx)
             }
         }
     }
+    ac->output_delay = (FFAudioOutputDelay){ 0 };
 
 #if CONFIG_AAC_DECODER
     ff_aac_usac_reset_state(ac, &ac->oc[1]);
@@ -2526,6 +2528,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);
@@ -2719,7 +2728,7 @@ const FFCodec ff_aac_decoder = {
     FF_CODEC_DECODE_CB(aac_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_FLTP),
     .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
-    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP,
+    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .flush = flush,
     .p.profiles      = NULL_IF_CONFIG_SMALL(ff_aac_profiles),
@@ -2739,7 +2748,7 @@ const FFCodec ff_aac_fixed_decoder = {
     FF_CODEC_DECODE_CB(aac_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_S32P),
     .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
-    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP,
+    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .p.profiles      = NULL_IF_CONFIG_SMALL(ff_aac_profiles),
     .flush = flush,
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/libavcodec/aac/aacdec_latm.h b/libavcodec/aac/aacdec_latm.h
index d9e836e949e..1055dcb6299 100644
--- a/libavcodec/aac/aacdec_latm.h
+++ b/libavcodec/aac/aacdec_latm.h
@@ -342,7 +342,7 @@ const FFCodec ff_aac_latm_decoder = {
     FF_CODEC_DECODE_CB(latm_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_FLTP),
     .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
-    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP,
+    .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .flush = flush,
     .p.profiles      = NULL_IF_CONFIG_SMALL(ff_aac_profiles),
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/mov-aac-sbr-edit-start 
b/tests/ref/fate/mov-aac-sbr-edit-start
index 14eccff51ae..e310fedafa5 100644
--- a/tests/ref/fate/mov-aac-sbr-edit-start
+++ b/tests/ref/fate/mov-aac-sbr-edit-start
@@ -1,3 +1,3 @@
-frame|pts=0|nb_samples=1920
-frame|pts=960|nb_samples=2048
+frame|pts=0|nb_samples=958
+frame|pts=479|nb_samples=2048
 stream|initial_padding=4224
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.1


From 8b374a8e38719ac9b13be890b0f746926f97ae79 Mon Sep 17 00:00:00 2001
From: Baptiste Coudurier <[email protected]>
Date: Sat, 21 Nov 2026 12:53:47 -0800
Subject: [PATCH 6/6] avcodec/aac/aacdec: drain the samples held back by the
 SBR delay

At the end, decode a silent frame repeating the last SBR data, so HE-AAC
streams keep their full length.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Baptiste Coudurier <[email protected]>
---
 libavcodec/aac/aacdec.c                       | 106 +++++++++++++++---
 libavcodec/aac/aacdec.h                       |   1 +
 libavcodec/aac/aacdec_latm.h                  |   5 +-
 libavcodec/aac/aacdec_proc_template.c         |   1 +
 libavcodec/aacsbr.h                           |   4 +
 libavcodec/aacsbr_template.c                  |  51 +++++++++
 libavcodec/decode.c                           |   8 ++
 libavcodec/decode.h                           |   1 +
 tests/fate/aac.mak                            |  15 +++
 tests/ref/fate/aac-sbr-drain                  |  49 ++++++++
 .../audiomatch-afconvert-16000-mono-he-adts   |   2 +-
 .../audiomatch-afconvert-16000-stereo-he-adts |   2 +-
 ...audiomatch-afconvert-16000-stereo-he2-adts |   2 +-
 .../audiomatch-afconvert-44100-mono-he-adts   |   2 +-
 .../audiomatch-afconvert-44100-stereo-he-adts |   2 +-
 ...audiomatch-afconvert-44100-stereo-he2-adts |   2 +-
 .../fate/audiomatch-dolby-44100-mono-he-mp4   |   2 +-
 .../fate/audiomatch-dolby-44100-stereo-he-mp4 |   2 +-
 .../audiomatch-dolby-44100-stereo-he2-mp4     |   2 +-
 .../fate/audiomatch-nero-16000-mono-he-m4a    |   2 +-
 .../fate/audiomatch-nero-16000-stereo-he-m4a  |   2 +-
 .../fate/audiomatch-nero-44100-stereo-he2-m4a |   2 +-
 tests/ref/fate/mov-aac-sbr-edit-start         |   1 +
 23 files changed, 240 insertions(+), 26 deletions(-)
 create mode 100644 tests/ref/fate/aac-sbr-drain

diff --git a/libavcodec/aac/aacdec.c b/libavcodec/aac/aacdec.c
index 57548281758..f515d79c1e6 100644
--- a/libavcodec/aac/aacdec.c
+++ b/libavcodec/aac/aacdec.c
@@ -2365,11 +2365,23 @@ static int aac_decode_er_frame(AVCodecContext *avctx, 
AVFrame *frame,
     return 0;
 }
 
+/* for dual-mono audio (SCE + SCE) */
+static void apply_dmono(AACDecContext *ac, AVFrame *frame, int sce_count)
+{
+    if (!ac->dmono_mode || sce_count != 2 ||
+        av_channel_layout_compare(&ac->oc[1].ch_layout,
+                                  &(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO))
+        return;
+    if (ac->dmono_mode == 1)
+        frame->data[1] = frame->data[0];
+    else if (ac->dmono_mode == 2)
+        frame->data[0] = frame->data[1];
+}
+
 static int decode_frame_ga(AVCodecContext *avctx, AACDecContext *ac,
                            GetBitContext *gb, int *got_frame_ptr)
 {
     int err;
-    int is_dmono;
     int elem_id;
     enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
     uint8_t che_presence[4][MAX_ELEM_ID] = {{0}};
@@ -2541,16 +2553,7 @@ static int decode_frame_ga(AVCodecContext *avctx, 
AACDecContext *ac,
         *got_frame_ptr = 0;
     }
 
-    /* for dual-mono audio (SCE + SCE) */
-    is_dmono = ac->dmono_mode && sce_count == 2 &&
-               !av_channel_layout_compare(&ac->oc[1].ch_layout,
-                                          
&(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO);
-    if (is_dmono) {
-        if (ac->dmono_mode == 1)
-            frame->data[1] = frame->data[0];
-        else if (ac->dmono_mode == 2)
-            frame->data[0] = frame->data[1];
-    }
+    apply_dmono(ac, frame, sce_count);
 
     return 0;
 }
@@ -2611,6 +2614,80 @@ fail:
     return err;
 }
 
+static void silence_ics(SingleChannelElement *sce)
+{
+    IndividualChannelStream *ics = &sce->ics;
+    enum WindowSequence prev = ics->window_sequence[0];
+
+    ics->window_sequence[1] = prev;
+    ics->window_sequence[0] = prev == LONG_START_SEQUENCE || prev == 
EIGHT_SHORT_SEQUENCE ?
+                              LONG_STOP_SEQUENCE : ONLY_LONG_SEQUENCE;
+    ics->use_kb_window[1]       = ics->use_kb_window[0];
+    ics->prev_num_window_groups = FFMAX(ics->num_window_groups, 1);
+    ics->num_window_groups      = 1;
+    ics->group_len[0]           = 1;
+    ics->num_windows            = 1;
+    ics->max_sfb                = 0;
+    ics->predictor_present      = 0;
+    ics->ltp.present            = 0;
+    sce->tns.present            = 0;
+    memset(&sce->coeffs, 0, sizeof(sce->coeffs));
+}
+
+/**
+ * Return the samples that the SBR delay holds back at the end of the stream,
+ * decoding a silent frame that repeats the last SBR data.
+ */
+static int aac_decode_drain(AVCodecContext *avctx, AVFrame *frame, int 
*got_frame_ptr)
+{
+    AACDecContext *ac = avctx->priv_data;
+    const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
+    int type, id, ret, samples, sce_count = 0;
+
+    *got_frame_ptr = 0;
+    if (m4ac->sbr != 1 || m4ac->object_type == AOT_USAC || 
!ac->output_delay.tail)
+        return 0;
+
+    ac->frame = frame;
+    ret = frame_configure_elements(avctx);
+    if (ret) {
+        ac->frame = NULL;
+        return FFMIN(ret, 0);
+    }
+
+    for (type = 0; type < 4; type++) {
+        for (id = 0; id < MAX_ELEM_ID; id++) {
+            ChannelElement *che = ac->che[type][id];
+            if (!che)
+                continue;
+            silence_ics(&che->ch[0]);
+            if (type == TYPE_CPE)
+                silence_ics(&che->ch[1]);
+            if (type != TYPE_CCE)
+                ac->proc.sbr_repeat(ac, che, type, m4ac->frame_length_short);
+            sce_count += type == TYPE_SCE;
+            che->present = 1;
+        }
+    }
+
+    samples = (m4ac->frame_length_short ? 960 : 1024) <<
+              (m4ac->ext_sample_rate > m4ac->sample_rate);
+    spectral_to_sample(ac, samples);
+    ac->frame = NULL;
+    apply_dmono(ac, frame, sce_count);
+
+    /* The drain packet carries no timestamps, the frame continues the last 
one. */
+    frame->pts         = AV_NOPTS_VALUE;
+    frame->pkt_dts     = AV_NOPTS_VALUE;
+    frame->nb_samples  = samples;
+    frame->sample_rate = avctx->sample_rate;
+    frame->flags      |= AV_FRAME_FLAG_KEY;
+    if ((ret = ff_decode_output_delay_drain(avctx, &ac->output_delay, frame)) 
< 0)
+        return ret;
+    *got_frame_ptr = 1;
+    return 0;
+}
+
 static int aac_decode_frame(AVCodecContext *avctx, AVFrame *frame,
                             int *got_frame_ptr, AVPacket *avpkt)
 {
@@ -2630,6 +2707,9 @@ static int aac_decode_frame(AVCodecContext *avctx, 
AVFrame *frame,
                                        AV_PKT_DATA_JP_DUALMONO,
                                        &jp_dualmono_size);
 
+    if (!avpkt->size)
+        return aac_decode_drain(avctx, frame, got_frame_ptr);
+
     if (new_extradata) {
         /* discard previous configuration */
         ac->oc[1].status = OC_NONE;
@@ -2727,7 +2807,7 @@ const FFCodec ff_aac_decoder = {
     .close           = decode_close,
     FF_CODEC_DECODE_CB(aac_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_FLTP),
-    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
+    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1 | 
AV_CODEC_CAP_DELAY,
     .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .flush = flush,
@@ -2747,7 +2827,7 @@ const FFCodec ff_aac_fixed_decoder = {
     .close           = decode_close,
     FF_CODEC_DECODE_CB(aac_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_S32P),
-    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
+    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1 | 
AV_CODEC_CAP_DELAY,
     .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .p.profiles      = NULL_IF_CONFIG_SMALL(ff_aac_profiles),
diff --git a/libavcodec/aac/aacdec.h b/libavcodec/aac/aacdec.h
index 3748ebb62b5..8bc8fe87c58 100644
--- a/libavcodec/aac/aacdec.h
+++ b/libavcodec/aac/aacdec.h
@@ -456,6 +456,7 @@ typedef struct AACDecProc {
     int (*sbr_ctx_alloc_init)(AACDecContext *ac, ChannelElement **che, int 
id_aac);
     int (*sbr_decode_extension)(AACDecContext *ac, ChannelElement *che,
                                 GetBitContext *gb, int crc, int cnt, int 
id_aac, int fl960);
+    void (*sbr_repeat)(AACDecContext *ac, ChannelElement *che, int id_aac, int 
fl960);
     void (*sbr_apply)(AACDecContext *ac, ChannelElement *che, int id_aac, int 
fl960,
                       void /* INTFLOAT */ *L, void /* INTFLOAT */ *R);
     void (*sbr_ctx_close)(ChannelElement *che);
diff --git a/libavcodec/aac/aacdec_latm.h b/libavcodec/aac/aacdec_latm.h
index 1055dcb6299..6470750f98a 100644
--- a/libavcodec/aac/aacdec_latm.h
+++ b/libavcodec/aac/aacdec_latm.h
@@ -260,6 +260,9 @@ static int latm_decode_frame(AVCodecContext *avctx, AVFrame 
*out,
     int                 muxlength, err;
     GetBitContext       gb;
 
+    if (!avpkt->size)
+        return aac_decode_drain(avctx, out, got_frame_ptr);
+
     if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)
         return err;
 
@@ -341,7 +344,7 @@ const FFCodec ff_aac_latm_decoder = {
     .close           = decode_close,
     FF_CODEC_DECODE_CB(latm_decode_frame),
     CODEC_SAMPLEFMTS(AV_SAMPLE_FMT_FLTP),
-    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
+    .p.capabilities  = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1 | 
AV_CODEC_CAP_DELAY,
     .caps_internal   = FF_CODEC_CAP_INIT_CLEANUP | FF_CODEC_CAP_SETS_PKT_DTS,
     CODEC_CH_LAYOUTS_ARRAY(ff_aac_ch_layout),
     .flush = flush,
diff --git a/libavcodec/aac/aacdec_proc_template.c 
b/libavcodec/aac/aacdec_proc_template.c
index b56302a93ff..9c853bfc075 100644
--- a/libavcodec/aac/aacdec_proc_template.c
+++ b/libavcodec/aac/aacdec_proc_template.c
@@ -442,6 +442,7 @@ static av_cold void AAC_RENAME(aac_proc_init)(AACDecProc 
*aac_proc)
 #define SET(member) aac_proc->member = AV_JOIN(ff_aac_, AAC_RENAME(member));
     SET(sbr_ctx_alloc_init);
     SET(sbr_decode_extension);
+    SET(sbr_repeat);
     SET(sbr_apply);
     SET(sbr_ctx_close);
     SET(sbr_ctx_reset);
diff --git a/libavcodec/aacsbr.h b/libavcodec/aacsbr.h
index c330a13183e..0731cd3f297 100644
--- a/libavcodec/aacsbr.h
+++ b/libavcodec/aacsbr.h
@@ -106,6 +106,10 @@ int ff_aac_sbr_decode_usac_data(AACDecContext *ac, 
ChannelElement *che,
                                 AACUsacElemConfig *ue, GetBitContext *gb,
                                 int sbr_ch, int indep_flag);
 
+/** Repeat the last SBR data of an element for a frame without it. */
+void ff_aac_sbr_repeat(AACDecContext *ac, ChannelElement *che, int id_aac, int 
fl960);
+void ff_aac_sbr_repeat_fixed(AACDecContext *ac, ChannelElement *che, int 
id_aac, int fl960);
+
 /** Apply one SBR element to one AAC element. */
 void ff_aac_sbr_apply(AACDecContext *ac, ChannelElement *che,
                       int id_aac, int fl960,
diff --git a/libavcodec/aacsbr_template.c b/libavcodec/aacsbr_template.c
index 78e2e2733f1..c6a921bc792 100644
--- a/libavcodec/aacsbr_template.c
+++ b/libavcodec/aacsbr_template.c
@@ -1717,6 +1717,57 @@ static void sbr_env_estimate(AAC_FLOAT (*e_curr)[48], 
INTFLOAT X_high[64][40][2]
     }
 }
 
+void AAC_RENAME(ff_aac_sbr_repeat)(AACDecContext *ac, ChannelElement *che,
+                                   int id_aac, int fl960)
+{
+    SpectralBandReplication *sbr = get_sbr(che);
+    PSCommonContext *ps = &sbr->ps.common;
+    int numTimeSlots = fl960 ? 15 : 16;
+    int ch;
+
+    if (!sbr->start || sbr->id_aac != id_aac)
+        return;
+
+    /* One envelope and noise floor with the last values, without transient. */
+    for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {
+        SBRData *d   = &sbr->data[ch];
+        unsigned old = d->bs_num_env;
+
+        memcpy(d->bs_invf_mode[1], d->bs_invf_mode[0], 
sizeof(d->bs_invf_mode[1]));
+        d->bs_freq_res[0]    = d->bs_freq_res[old];
+        d->bs_freq_res[1]    = d->bs_freq_res[old];
+        d->t_env_num_env_old = d->t_env[old];
+        if (old > 1)
+            memcpy(d->env_facs_q[1], d->env_facs_q[old], 
sizeof(d->env_facs_q[1]));
+        if (d->bs_num_noise > 1)
+            memcpy(d->noise_facs_q[1], d->noise_facs_q[d->bs_num_noise],
+                   sizeof(d->noise_facs_q[1]));
+        d->bs_num_env     = 1;
+        d->bs_num_noise   = 1;
+        d->bs_frame_class = FIXFIX;
+        d->t_env[0] = d->t_q[0] = FFMAX(d->t_env_num_env_old - numTimeSlots, 
0);
+        d->t_env[1] = d->t_q[1] = numTimeSlots;
+        d->e_a[0] = -(d->e_a[1] != old);
+        d->e_a[1] = -1;
+    }
+    sbr->ready_for_dequant = 1;
+
+    if (ac->oc[1].m4ac.ps == 1 && ps->start && ps->num_env > 0) {
+        int last = ps->num_env - 1;
+        if (last) {
+            memcpy(ps->iid_par[0], ps->iid_par[last], sizeof(ps->iid_par[0]));
+            memcpy(ps->icc_par[0], ps->icc_par[last], sizeof(ps->icc_par[0]));
+            memcpy(ps->ipd_par[0], ps->ipd_par[last], sizeof(ps->ipd_par[0]));
+            memcpy(ps->opd_par[0], ps->opd_par[last], sizeof(ps->opd_par[0]));
+        }
+        ps->num_env_old        = ps->num_env;
+        ps->is34bands_old      = ps->is34bands;
+        ps->num_env            = 1;
+        ps->border_position[0] = -1;
+        ps->border_position[1] = 2 * numTimeSlots - 1;
+    }
+}
+
 void AAC_RENAME(ff_aac_sbr_apply)(AACDecContext *ac, ChannelElement *che,
                                   int id_aac, int fl960, void *L_, void *R_)
 {
diff --git a/libavcodec/decode.c b/libavcodec/decode.c
index bb53342228b..e1c45027638 100644
--- a/libavcodec/decode.c
+++ b/libavcodec/decode.c
@@ -2497,6 +2497,14 @@ int ff_decode_output_delay_drain(AVCodecContext *avctx, 
FFAudioOutputDelay *d,
 
     if (sd && sd->size < 10)
         sd = NULL;
+    if (frame->pts == AV_NOPTS_VALUE && d->tail_ts != AV_NOPTS_VALUE) {
+        int64_t diff = avctx->pkt_timebase.num && frame->sample_rate ?
+                       av_rescale_q(d->delay, (AVRational){ 1, 
frame->sample_rate },
+                                    avctx->pkt_timebase) : 0;
+        frame->pts = av_sat_sub64(d->tail_ts, diff);
+        if (frame->pkt_dts == AV_NOPTS_VALUE)
+            frame->pkt_dts = frame->pts;
+    }
     ret = set_skip_samples(frame, sd, d->start, frame->nb_samples - keep);
     if (keep)
         frame->flags &= ~AV_FRAME_FLAG_DISCARD;
diff --git a/libavcodec/decode.h b/libavcodec/decode.h
index 309dc7ff12b..68f484bfc74 100644
--- a/libavcodec/decode.h
+++ b/libavcodec/decode.h
@@ -276,6 +276,7 @@ int ff_decode_output_delay(AVCodecContext *avctx, 
FFAudioOutputDelay *d,
 /**
  * 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.
+ * A frame without pts continues the last frame.
  */
 int ff_decode_output_delay_drain(AVCodecContext *avctx, FFAudioOutputDelay *d,
                                  AVFrame *frame);
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
index e5ebb13e650..382ea6024cb 100644
--- a/tests/fate/aac.mak
+++ b/tests/fate/aac.mak
@@ -58,6 +58,12 @@ FATE_AAC += fate-aac-al_sbr_ps_06_ur
 fate-aac-al_sbr_ps_06_ur: CMD = pcm -i 
$(TARGET_SAMPLES)/aac/al_sbr_ps_06_new.mp4
 fate-aac-al_sbr_ps_06_ur: REF = $(SAMPLES)/aac/al_sbr_ps_06_ur.s16
 
+# The references end with the last frame, without the samples that the SBR
+# delay holds back and draining returns.
+fate-aac-al_sbr_hq_cm_48_2 fate-aac-al_sbr_ps_04_ur fate-aac-al_sbr_ps_06_ur: 
SIZE_TOLERANCE = 3848
+fate-aac-al_sbr_hq_cm_48_5.1: SIZE_TOLERANCE = 11544
+fate-aac-al_sbr_hq_sr_48_2_fsaac48: SIZE_TOLERANCE = 1924
+
 FATE_AAC += fate-aac-ap05_48
 fate-aac-ap05_48: CMD = pcm -i $(TARGET_SAMPLES)/aac/ap05_48.mp4
 fate-aac-ap05_48: REF = $(SAMPLES)/aac/ap05_48.s16
@@ -166,6 +172,9 @@ fate-aac-fixed-al_sbr_hq_cm_48_5.1: REF = 
$(SAMPLES)/aac/al_sbr_hq_cm_48_5.1_reo
 FATE_AAC_FIXED += fate-aac-fixed-al_sbr_hq_sr_48_2_fsaac48
 fate-aac-fixed-al_sbr_hq_sr_48_2_fsaac48: CMD = pcm -c aac_fixed -i 
$(TARGET_SAMPLES)/aac/al_sbr_sr_48_2_fsaac48.mp4
 fate-aac-fixed-al_sbr_hq_sr_48_2_fsaac48: REF = 
$(SAMPLES)/aac/al_sbr_hq_sr_48_2_fsaac48.s16
+fate-aac-fixed-al_sbr_hq_cm_48_2: SIZE_TOLERANCE = 3848
+fate-aac-fixed-al_sbr_hq_cm_48_5.1: SIZE_TOLERANCE = 11544
+fate-aac-fixed-al_sbr_hq_sr_48_2_fsaac48: SIZE_TOLERANCE = 1924
 
 #FATE_AAC_FIXED += fate-aac-fixed-al_sbr_ps_06_ur
 #fate-aac-fixed-al_sbr_ps_06_ur: CMD = pcm -c aac_fixed-i 
$(TARGET_SAMPLES)/aac/al_sbr_ps_06_new.mp4
@@ -191,6 +200,7 @@ fate-aac-fixed-er_eld2000np_48_ep0: SIZE_TOLERANCE = 128
 
 fate-aac-ct%: CMD = pcm -i 
$(TARGET_SAMPLES)/aac/CT_DecoderCheck/$(@:fate-aac-ct-%=%)
 fate-aac-ct%: REF = $(SAMPLES)/aac/CT_DecoderCheck/aacPlusv2.wav
+fate-aac-ct%: SIZE_TOLERANCE = 3848
 
 FATE_AAC_CT_RAW = fate-aac-ct-sbr_i-ps_i.aac
 
@@ -315,6 +325,7 @@ fate-aac-encode-strict-rate: CMD = ffmpeg 
-auto_conversion_filters -f lavfi -i "
 FATE_AAC_LATM += fate-aac-latm_000000001180bc60
 fate-aac-latm_000000001180bc60: CMD = pcm -i 
$(TARGET_SAMPLES)/aac/latm_000000001180bc60.mpg
 fate-aac-latm_000000001180bc60: REF = $(SAMPLES)/aac/latm_000000001180bc60.s16
+fate-aac-latm_000000001180bc60: SIZE_TOLERANCE = 3848
 
 FATE_AAC_LATM += fate-aac-latm_stereo_to_51
 fate-aac-latm_stereo_to_51: CMD = pcm -i 
$(TARGET_SAMPLES)/aac/latm_stereo_to_51.ts -channel_layout 5.1
@@ -344,6 +355,10 @@ FATE_AAC_FRAMECRC-$(call FRAMECRC, MOV, AAC, 
ARESAMPLE_FILTER PAN_FILTER PCM_F32
 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
 
+# The samples the SBR delay holds back at the end come out when draining.
+FATE_AAC_FRAMECRC-$(call FRAMECRC, MOV, AAC, ARESAMPLE_FILTER VOLUME_FILTER 
PCM_S16LE_ENCODER) += fate-aac-sbr-drain
+fate-aac-sbr-drain: CMD = framecrc -i 
$(TARGET_SAMPLES)/audiomatch/tones_nero_44100_stereo_aac_he2.m4a -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-drain b/tests/ref/fate/aac-sbr-drain
new file mode 100644
index 00000000000..4308ea7ec9c
--- /dev/null
+++ b/tests/ref/fate/aac-sbr-drain
@@ -0,0 +1,49 @@
+#tb 0: 1/44100
+#media_type 0: audio
+#codec_id 0: pcm_s16le
+#sample_rate 0: 44100
+#channel_layout_name 0: stereo
+0,          0,          0,     1614,     6456, 0x00000000
+0,       1614,       1614,     2048,     8192, 0x00000000
+0,       3662,       3662,     2048,     8192, 0x00000000
+0,       5710,       5710,     2048,     8192, 0x00000000
+0,       7758,       7758,     2048,     8192, 0x00000000
+0,       9806,       9806,     2048,     8192, 0x00000000
+0,      11854,      11854,     2048,     8192, 0x00000000
+0,      13902,      13902,     2048,     8192, 0x00000000
+0,      15950,      15950,     2048,     8192, 0x00000000
+0,      17998,      17998,     2048,     8192, 0x00000000
+0,      20046,      20046,     2048,     8192, 0x00000000
+0,      22094,      22094,     2048,     8192, 0x00000000
+0,      24142,      24142,     2048,     8192, 0x00000000
+0,      26190,      26190,     2048,     8192, 0x00000000
+0,      28238,      28238,     2048,     8192, 0x00000000
+0,      30286,      30286,     2048,     8192, 0x00000000
+0,      32334,      32334,     2048,     8192, 0x00000000
+0,      34382,      34382,     2048,     8192, 0x00000000
+0,      36430,      36430,     2048,     8192, 0x00000000
+0,      38478,      38478,     2048,     8192, 0x00000000
+0,      40526,      40526,     2048,     8192, 0x00000000
+0,      42574,      42574,     2048,     8192, 0x00000000
+0,      44622,      44622,     2048,     8192, 0x00000000
+0,      46670,      46670,     2048,     8192, 0x00000000
+0,      48718,      48718,     2048,     8192, 0x00000000
+0,      50766,      50766,     2048,     8192, 0x00000000
+0,      52814,      52814,     2048,     8192, 0x00000000
+0,      54862,      54862,     2048,     8192, 0x00000000
+0,      56910,      56910,     2048,     8192, 0x00000000
+0,      58958,      58958,     2048,     8192, 0x00000000
+0,      61006,      61006,     2048,     8192, 0x00000000
+0,      63054,      63054,     2048,     8192, 0x00000000
+0,      65102,      65102,     2048,     8192, 0x00000000
+0,      67150,      67150,     2048,     8192, 0x00000000
+0,      69198,      69198,     2048,     8192, 0x00000000
+0,      71246,      71246,     2048,     8192, 0x00000000
+0,      73294,      73294,     2048,     8192, 0x00000000
+0,      75342,      75342,     2048,     8192, 0x00000000
+0,      77390,      77390,     2048,     8192, 0x00000000
+0,      79438,      79438,     2048,     8192, 0x00000000
+0,      81486,      81486,     2048,     8192, 0x00000000
+0,      83534,      83534,     2048,     8192, 0x00000000
+0,      85582,      85582,     2048,     8192, 0x00000000
+0,      87630,      87630,      570,     2280, 0x00000000
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-mono-he-adts 
b/tests/ref/fate/audiomatch-afconvert-16000-mono-he-adts
index d0c421a8a65..deaeae9ee93 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-mono-he-adts
+++ b/tests/ref/fate/audiomatch-afconvert-16000-mono-he-adts
@@ -1 +1 @@
-presig: 2593 postsig:223 lenerr:2816
+presig: 2593 postsig:704 lenerr:3297
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-adts 
b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-adts
index e1616f33e92..a9cc00ea7ff 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-adts
+++ b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he-adts
@@ -1 +1 @@
-presig: 5186 postsig:446 lenerr:5632
+presig: 5186 postsig:1408 lenerr:6594
diff --git a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-adts 
b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-adts
index e1616f33e92..a9cc00ea7ff 100644
--- a/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-adts
+++ b/tests/ref/fate/audiomatch-afconvert-16000-stereo-he2-adts
@@ -1 +1 @@
-presig: 5186 postsig:446 lenerr:5632
+presig: 5186 postsig:1408 lenerr:6594
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-mono-he-adts 
b/tests/ref/fate/audiomatch-afconvert-44100-mono-he-adts
index 401a99dd80b..9c4bc0a51c1 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-mono-he-adts
+++ b/tests/ref/fate/audiomatch-afconvert-44100-mono-he-adts
@@ -1 +1 @@
-presig: 5186 postsig:822 lenerr:6008
+presig: 5186 postsig:1784 lenerr:6970
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-adts 
b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-adts
index 5a552e2f84c..ab232ca1e6a 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-adts
+++ b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he-adts
@@ -1 +1 @@
-presig: 10372 postsig:1644 lenerr:12016
+presig: 10372 postsig:3568 lenerr:13940
diff --git a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-adts 
b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-adts
index 5a552e2f84c..ab232ca1e6a 100644
--- a/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-adts
+++ b/tests/ref/fate/audiomatch-afconvert-44100-stereo-he2-adts
@@ -1 +1 @@
-presig: 10372 postsig:1644 lenerr:12016
+presig: 10372 postsig:3568 lenerr:13940
diff --git a/tests/ref/fate/audiomatch-dolby-44100-mono-he-mp4 
b/tests/ref/fate/audiomatch-dolby-44100-mono-he-mp4
index ac8cfdc5788..12a68ade2c9 100644
--- a/tests/ref/fate/audiomatch-dolby-44100-mono-he-mp4
+++ b/tests/ref/fate/audiomatch-dolby-44100-mono-he-mp4
@@ -1 +1 @@
-presig: 5569 postsig:-1609 lenerr:3960
+presig: 5569 postsig:-647 lenerr:4922
diff --git a/tests/ref/fate/audiomatch-dolby-44100-stereo-he-mp4 
b/tests/ref/fate/audiomatch-dolby-44100-stereo-he-mp4
index b6b3027b18a..75875636699 100644
--- a/tests/ref/fate/audiomatch-dolby-44100-stereo-he-mp4
+++ b/tests/ref/fate/audiomatch-dolby-44100-stereo-he-mp4
@@ -1 +1 @@
-presig: 11160 postsig:-3240 lenerr:7920
+presig: 11160 postsig:-1316 lenerr:9844
diff --git a/tests/ref/fate/audiomatch-dolby-44100-stereo-he2-mp4 
b/tests/ref/fate/audiomatch-dolby-44100-stereo-he2-mp4
index 244721dfa41..bf1bf182006 100644
--- a/tests/ref/fate/audiomatch-dolby-44100-stereo-he2-mp4
+++ b/tests/ref/fate/audiomatch-dolby-44100-stereo-he2-mp4
@@ -1 +1 @@
-presig: 15884 postsig:228 lenerr:16112
+presig: 15884 postsig:2152 lenerr:18036
diff --git a/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a 
b/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
index 52824b73396..313bedd40bb 100644
--- a/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-16000-mono-he-m4a
@@ -1 +1 @@
-presig: -966 postsig:196 lenerr:-770
+presig: -966 postsig:966 lenerr:0
diff --git a/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a 
b/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
index a8557c0a8a8..cf3cf84fdea 100644
--- a/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
+++ b/tests/ref/fate/audiomatch-nero-16000-stereo-he-m4a
@@ -1 +1 @@
-presig: -1932 postsig:392 lenerr:-1540
+presig: -1932 postsig:1932 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 178d0373cef..85862988c81 100644
--- a/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a
+++ b/tests/ref/fate/audiomatch-nero-44100-stereo-he2-m4a
@@ -1 +1 @@
-presig: -1922 postsig:782 lenerr:-1140
+presig: -1922 postsig:1922 lenerr:0
diff --git a/tests/ref/fate/mov-aac-sbr-edit-start 
b/tests/ref/fate/mov-aac-sbr-edit-start
index e310fedafa5..c94cdac3e03 100644
--- a/tests/ref/fate/mov-aac-sbr-edit-start
+++ b/tests/ref/fate/mov-aac-sbr-edit-start
@@ -1,3 +1,4 @@
 frame|pts=0|nb_samples=958
 frame|pts=479|nb_samples=2048
+frame|pts=1503|nb_samples=962
 stream|initial_padding=4224
-- 
2.54.1

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

Reply via email to