[FFmpeg-cvslog] avcodec/mpegaudioenc: Avoid intermediate buffer

Andreas Rheinhardt git at videolan.org
Mon Apr 14 00:18:30 EEST 2025


ffmpeg | branch: master | Andreas Rheinhardt <andreas.rheinhardt at outlook.com> | Thu Apr 10 22:13:17 2025 +0200| [87f3e20931444a4c57c8e06576b71eb57014d5cb] | committer: Andreas Rheinhardt

avcodec/mpegaudioenc: Avoid intermediate buffer

We know the final size before encoding, so we can switch to
ff_get_encode_buffer() which avoids an implicit memcpy().

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt at outlook.com>

> http://git.videolan.org/gitweb.cgi/ffmpeg.git/?a=commit;h=87f3e20931444a4c57c8e06576b71eb57014d5cb
---

 libavcodec/mpegaudioenc.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/libavcodec/mpegaudioenc.c b/libavcodec/mpegaudioenc.c
index b10487b7ff..9a6aae6f78 100644
--- a/libavcodec/mpegaudioenc.c
+++ b/libavcodec/mpegaudioenc.c
@@ -508,7 +508,7 @@ static void psycho_acoustic_model(MpegAudioContext *s, short smr[SBLIMIT])
 /* Try to maximize the smr while using a number of bits inferior to
    the frame size. I tried to make the code simpler, faster and
    smaller than other encoders :-) */
-static void compute_bit_allocation(MpegAudioContext *s,
+static unsigned compute_bit_allocation(MpegAudioContext *s,
                                    short smr1[MPA_MAX_CHANNELS][SBLIMIT],
                                    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT],
                                    int *padding)
@@ -598,6 +598,7 @@ static void compute_bit_allocation(MpegAudioContext *s,
     }
     *padding = max_frame_size - current_frame_size;
     av_assert0(*padding >= 0);
+    return max_frame_size / 8U;
 }
 
 /// Quantization & write sub band samples
@@ -740,6 +741,8 @@ static void encode_frame(MpegAudioContext *s,
         encode_subbands(s, p, bit_alloc, 0);
 #endif
 
+    av_assert1(put_bits_left(p) == padding);
+
     /* padding */
     for(i=0;i<padding;i++)
         put_bits(p, 1, 0);
@@ -765,9 +768,10 @@ static int MPA_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
     for(i=0;i<s->nb_channels;i++) {
         psycho_acoustic_model(s, smr[i]);
     }
-    compute_bit_allocation(s, smr, bit_alloc, &padding);
+    unsigned frame_size = compute_bit_allocation(s, smr, bit_alloc, &padding);
 
-    if ((ret = ff_alloc_packet(avctx, avpkt, MPA_MAX_CODED_FRAME_SIZE)) < 0)
+    ret = ff_get_encode_buffer(avctx, avpkt, frame_size, 0);
+    if (ret < 0)
         return ret;
 
     init_put_bits(&s->pb, avpkt->data, avpkt->size);
@@ -776,7 +780,6 @@ static int MPA_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
 
     /* flush */
     flush_put_bits(&s->pb);
-    avpkt->size = put_bytes_output(&s->pb);
 
     if (frame->pts != AV_NOPTS_VALUE)
         avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding);



More information about the ffmpeg-cvslog mailing list