Commit b0b86104e1 for ffmpeg
commit b0b86104e1cfa2fd6c186027cea67e1dfb65f10b
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date: Thu Nov 19 08:16:06 2026 -0600
avformat/mp3enc: sum encoder delay spread over several packets
Since c31a781412 the audio frame queue spreads the encoder delay over the
skip samples of the leading packets. Only the first one was read, so a
libmp3lame encode at 22050 Hz wrote a delay of 47 instead of 576.
Sum them and subtract the decoder delay when writing the Xing header.
diff --git a/libavformat/mp3enc.c b/libavformat/mp3enc.c
index 6a60e325c4..98b47ace95 100644
--- a/libavformat/mp3enc.c
+++ b/libavformat/mp3enc.c
@@ -129,7 +129,8 @@ typedef struct MP3Context {
MPADecodeHeader2 *hdr;
MPADecodeHeader2 *xing_header;
MPADecodeHeader2 *first_frame;
- int delay;
+ int64_t delay;
+ int delay_done;
int64_t padding;
/* index of the audio stream */
@@ -319,6 +320,13 @@ static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
}
}
+static int mp3_frame_samples(const MPADecodeHeader2 *hdr)
+{
+ if (hdr->layer == 1)
+ return 384;
+ return hdr->layer == 3 && hdr->lsf ? 576 : 1152;
+}
+
static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
{
MP3Context *mp3 = s->priv_data;
@@ -389,12 +397,17 @@ static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
AV_PKT_DATA_SKIP_SAMPLES,
&side_data_size);
if (side_data && side_data_size >= 10) {
+ uint32_t skip_samples = AV_RL32(side_data);
uint32_t discard_padding = AV_RL32(side_data + 4);
- /* Padding longer than a frame is spread over several packets. */
+ /* Delay and padding longer than a frame are spread over
+ * several packets. */
+ if (!mp3->delay_done)
+ mp3->delay += skip_samples;
+ /* Only fully skipped frames carry the delay over. */
+ mp3->delay_done |= skip_samples != mp3_frame_samples(mp3->xing_header);
mp3->padding = discard_padding ? mp3->padding + discard_padding : 0;
- if (!mp3->delay)
- mp3->delay = FFMAX((int64_t)AV_RL32(side_data) - MP3_DECODER_DELAY, 0);
} else {
+ mp3->delay_done = 1;
mp3->padding = 0;
}
}
@@ -508,7 +521,9 @@ static void mp3_update_xing(AVFormatContext *s)
}
}
- /* write encoder delay/padding */
+ /* The LAME tag stores the encoder delay only: remove the decoder delay
+ * included in the leading skip. */
+ mp3->delay = FFMAX(mp3->delay - MP3_DECODER_DELAY, 0);
if (mp3->padding)
mp3->padding += MP3_DECODER_DELAY;
if (mp3->delay >= 1 << 12) {
diff --git a/tests/ref/fate/gapless-mp3-split-delay-remux b/tests/ref/fate/gapless-mp3-split-delay-remux
index 35fcf92dfb..8400c99d4b 100644
--- a/tests/ref/fate/gapless-mp3-split-delay-remux
+++ b/tests/ref/fate/gapless-mp3-split-delay-remux
@@ -1,3 +1,3 @@
-36dc8ba5708648784f951045e9b76c4c *tests/data/fate/gapless-mp3-split-delay-remux.mp3
+3765088ef73f39b647914c10d2ede355 *tests/data/fate/gapless-mp3-split-delay-remux.mp3
725 tests/data/fate/gapless-mp3-split-delay-remux.mp3
-stream|start_pts=368640|duration_ts=3160960
+stream|start_pts=707200|duration_ts=2822400