PR #25981 opened by Romain Beauxis (toots)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25981
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25981.patch

The MPEG audio decoder sets `avctx->sample_rate` only after `mp_decode_frame()` 
has allocated the output frame, so each frame carries the sample rate of the 
previous one. After a mid-stream rate change, as in MP3 files concatenated 
without re-encoding, the first frame at the new rate is stamped with the old 
one.

This PR sets the sample rate together with the channel layout, from the parsed 
header, before decoding, as `decode_frame_adu()` already does.

The first commit adds `fate-mpegaudiodec-sample-rate-change`, which encodes MP2 
frames at 44.1 kHz then 48 kHz and prints each decoded frame's rate next to its 
header's. The fix commit updates its reference: the first 48 kHz frame goes 
from 44100 Hz to 48000 Hz.


>From 540f3cef4e33ecaeed3786e1574d785bf11e72fb Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 12 Nov 2026 11:53:28 -0600
Subject: [PATCH 1/2] tests/fate/libavcodec: add a test for MPEG audio sample
 rate changes

The test encodes MP2 frames at 44.1 kHz then 48 kHz and decodes them in order, 
as concatenated MPEG audio files play.

It prints the sample rate of each frame next to the rate of its header.
---
 libavcodec/Makefile                           |   1 +
 libavcodec/tests/.gitignore                   |   1 +
 libavcodec/tests/mpegaudiodec.c               | 143 ++++++++++++++++++
 tests/fate/libavcodec.mak                     |   4 +
 .../ref/fate/mpegaudiodec-sample-rate-change  |   6 +
 5 files changed, 155 insertions(+)
 create mode 100644 libavcodec/tests/mpegaudiodec.c
 create mode 100644 tests/ref/fate/mpegaudiodec-sample-rate-change

diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index f12ad9c8e8d..f44d8cbe83d 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -1405,6 +1405,7 @@ TESTPROGS-$(CONFIG_IDCTDSP)               += dct
 TESTPROGS-$(CONFIG_DXV_ENCODER)           += hashtable
 TESTPROGS-$(CONFIG_MJPEG_ENCODER)         += mjpegenc_huffman
 TESTPROGS-$(CONFIG_MPEGAUDIOHEADER)       += mpegaudiodecheader
+TESTPROGS-$(CONFIG_MP2_DECODER)           += mpegaudiodec
 TESTPROGS-$(CONFIG_MPEGVIDEO)             += mpeg12framerate
 TESTPROGS-$(CONFIG_H264_METADATA_BSF)     += h264_levels
 TESTPROGS-$(CONFIG_HEVC_METADATA_BSF)     += h265_levels
diff --git a/libavcodec/tests/.gitignore b/libavcodec/tests/.gitignore
index 436476bc785..b64d0881d0b 100644
--- a/libavcodec/tests/.gitignore
+++ b/libavcodec/tests/.gitignore
@@ -19,6 +19,7 @@
 /mathops
 /mjpegenc_huffman
 /mpeg12framerate
+/mpegaudiodec
 /mpegaudiodecheader
 /packet_side_data_handle
 /rangecoder
diff --git a/libavcodec/tests/mpegaudiodec.c b/libavcodec/tests/mpegaudiodec.c
new file mode 100644
index 00000000000..151a9f3c0bd
--- /dev/null
+++ b/libavcodec/tests/mpegaudiodec.c
@@ -0,0 +1,143 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * Decodes MP2 frames whose sample rate changes mid-stream, as MPEG audio
+ * files concatenated without re-encoding do, and checks that every decoded
+ * frame carries the sample rate of its own header.
+ */
+
+#include <stdio.h>
+
+#include "libavcodec/avcodec.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/frame.h"
+#include "libavutil/samplefmt.h"
+
+#define FRAMES_PER_RATE 3
+#define MAX_PACKETS     16
+
+typedef struct Encoded {
+    AVPacket *pkt[MAX_PACKETS];
+    int sample_rate[MAX_PACKETS];
+    int nb;
+} Encoded;
+
+static int store(AVCodecContext *enc, Encoded *out)
+{
+    int ret;
+
+    for (;;) {
+        AVPacket *pkt = av_packet_alloc();
+        if (!pkt)
+            return AVERROR(ENOMEM);
+        ret = avcodec_receive_packet(enc, pkt);
+        if (ret < 0) {
+            av_packet_free(&pkt);
+            return ret == AVERROR(EAGAIN) || ret == AVERROR_EOF ? 0 : ret;
+        }
+        if (out->nb == MAX_PACKETS) {
+            av_packet_free(&pkt);
+            return AVERROR_BUG;
+        }
+        out->sample_rate[out->nb] = enc->sample_rate;
+        out->pkt[out->nb++]       = pkt;
+    }
+}
+
+static int encode(int sample_rate, Encoded *out)
+{
+    const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
+    AVCodecContext *enc  = avcodec_alloc_context3(codec);
+    AVFrame *frame       = av_frame_alloc();
+    int ret;
+
+    if (!codec || !enc || !frame) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+    enc->sample_rate = sample_rate;
+    enc->sample_fmt  = AV_SAMPLE_FMT_S16;
+    enc->bit_rate    = 128000;
+    av_channel_layout_default(&enc->ch_layout, 2);
+    if ((ret = avcodec_open2(enc, codec, NULL)) < 0)
+        goto end;
+
+    frame->nb_samples  = enc->frame_size;
+    frame->format      = enc->sample_fmt;
+    frame->sample_rate = sample_rate;
+    if ((ret = av_channel_layout_copy(&frame->ch_layout, &enc->ch_layout)) < 0 
||
+        (ret = av_frame_get_buffer(frame, 0)) < 0)
+        goto end;
+    av_samples_set_silence(frame->extended_data, 0, frame->nb_samples, 2, 
enc->sample_fmt);
+
+    for (int i = 0; i < FRAMES_PER_RATE; i++) {
+        frame->pts = (int64_t)i * frame->nb_samples;
+        if ((ret = avcodec_send_frame(enc, frame)) < 0 || (ret = store(enc, 
out)) < 0)
+            goto end;
+    }
+    if ((ret = avcodec_send_frame(enc, NULL)) < 0)
+        goto end;
+    ret = store(enc, out);
+
+end:
+    av_frame_free(&frame);
+    avcodec_free_context(&enc);
+    return ret;
+}
+
+int main(void)
+{
+    const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
+    AVCodecContext *dec  = NULL;
+    AVFrame *frame       = av_frame_alloc();
+    Encoded encoded      = { 0 };
+    int ret = 1;
+
+    if (!codec || !frame)
+        goto end;
+    if (encode(44100, &encoded) < 0 || encode(48000, &encoded) < 0) {
+        fprintf(stderr, "could not encode the test stream\n");
+        goto end;
+    }
+
+    dec = avcodec_alloc_context3(codec);
+    if (!dec || avcodec_open2(dec, codec, NULL) < 0)
+        goto end;
+
+    for (int i = 0; i < encoded.nb; i++) {
+        int err = avcodec_send_packet(dec, encoded.pkt[i]);
+        if (err < 0) {
+            fprintf(stderr, "packet %d: send failed: %d\n", i, err);
+            goto end;
+        }
+        while (avcodec_receive_frame(dec, frame) >= 0) {
+            printf("packet %d: header %d Hz, frame %d Hz\n",
+                   i, encoded.sample_rate[i], frame->sample_rate);
+            av_frame_unref(frame);
+        }
+    }
+    ret = 0;
+
+end:
+    for (int i = 0; i < encoded.nb; i++)
+        av_packet_free(&encoded.pkt[i]);
+    av_frame_free(&frame);
+    avcodec_free_context(&dec);
+    return ret;
+}
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 2e2dabcd148..1c9eaeb7659 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -51,6 +51,10 @@ fate-codec_desc: libavcodec/tests/codec_desc$(EXESUF)
 fate-codec_desc: CMD = run libavcodec/tests/codec_desc$(EXESUF)
 fate-codec_desc: CMP = null
 
+FATE_LIBAVCODEC-$(call ALLYES, MP2_ENCODER MP2_DECODER) += 
fate-mpegaudiodec-sample-rate-change
+fate-mpegaudiodec-sample-rate-change: libavcodec/tests/mpegaudiodec$(EXESUF)
+fate-mpegaudiodec-sample-rate-change: CMD = run 
libavcodec/tests/mpegaudiodec$(EXESUF)
+
 FATE_LIBAVCODEC-$(CONFIG_GOLOMB) += fate-golomb
 fate-golomb: libavcodec/tests/golomb$(EXESUF)
 fate-golomb: CMD = run libavcodec/tests/golomb$(EXESUF)
diff --git a/tests/ref/fate/mpegaudiodec-sample-rate-change 
b/tests/ref/fate/mpegaudiodec-sample-rate-change
new file mode 100644
index 00000000000..fab60c33d87
--- /dev/null
+++ b/tests/ref/fate/mpegaudiodec-sample-rate-change
@@ -0,0 +1,6 @@
+packet 0: header 44100 Hz, frame 44100 Hz
+packet 1: header 44100 Hz, frame 44100 Hz
+packet 2: header 44100 Hz, frame 44100 Hz
+packet 3: header 48000 Hz, frame 44100 Hz
+packet 4: header 48000 Hz, frame 48000 Hz
+packet 5: header 48000 Hz, frame 48000 Hz
-- 
2.54.0


>From 1fed4975b8eb9e63aeea43343dcf8818532c4615 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 12 Nov 2026 11:53:39 -0600
Subject: [PATCH 2/2] avcodec/mpegaudiodec: set the sample rate before
 allocating the frame

decode_frame() sets the sample rate from the parsed header along with the 
channel layout, before mp_decode_frame() allocates the output frame, as 
decode_frame_adu() does.

The first frame after a mid-stream sample rate change carries its own rate, as 
the updated mpegaudiodec-sample-rate-change reference shows.
---
 libavcodec/mpegaudiodec_template.c             | 5 ++---
 tests/ref/fate/mpegaudiodec-sample-rate-change | 2 +-
 2 files changed, 3 insertions(+), 4 deletions(-)

diff --git a/libavcodec/mpegaudiodec_template.c 
b/libavcodec/mpegaudiodec_template.c
index b146307dd96..cb86ea170de 100644
--- a/libavcodec/mpegaudiodec_template.c
+++ b/libavcodec/mpegaudiodec_template.c
@@ -1592,6 +1592,8 @@ static int decode_frame(AVCodecContext *avctx, AVFrame 
*frame,
         return AVERROR_INVALIDDATA;
     }
     /* update codec info */
+    if (avctx->codec_id != AV_CODEC_ID_AHX)
+        avctx->sample_rate = s->hdr.sample_rate;
     av_channel_layout_uninit(&avctx->ch_layout);
     avctx->ch_layout = s->hdr.nb_channels == 1 ? 
(AVChannelLayout)AV_CHANNEL_LAYOUT_MONO :
                                              
(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO;
@@ -1612,9 +1614,6 @@ static int decode_frame(AVCodecContext *avctx, AVFrame 
*frame,
     if (ret >= 0) {
         s->frame->nb_samples = avctx->frame_size;
         *got_frame_ptr       = 1;
-        if (avctx->codec_id != AV_CODEC_ID_AHX)
-            avctx->sample_rate = s->hdr.sample_rate;
-        //FIXME maybe move the other codec info stuff from above here too
     } else {
         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio 
frame.\n");
         /* Only return an error if the bad frame makes up the whole packet or
diff --git a/tests/ref/fate/mpegaudiodec-sample-rate-change 
b/tests/ref/fate/mpegaudiodec-sample-rate-change
index fab60c33d87..08fc72b5fc7 100644
--- a/tests/ref/fate/mpegaudiodec-sample-rate-change
+++ b/tests/ref/fate/mpegaudiodec-sample-rate-change
@@ -1,6 +1,6 @@
 packet 0: header 44100 Hz, frame 44100 Hz
 packet 1: header 44100 Hz, frame 44100 Hz
 packet 2: header 44100 Hz, frame 44100 Hz
-packet 3: header 48000 Hz, frame 44100 Hz
+packet 3: header 48000 Hz, frame 48000 Hz
 packet 4: header 48000 Hz, frame 48000 Hz
 packet 5: header 48000 Hz, frame 48000 Hz
-- 
2.54.0

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

Reply via email to