[FFmpeg-devel] [PATCH 21/39] avcodec/flacenc: Avoid copying packet data, allow user-supplied buffers

Andreas Rheinhardt andreas.rheinhardt at outlook.com
Fri May 21 12:17:24 EEST 2021


The FLAC encoder calculates the size in advance, so one can avoid
an intermediate buffer for the packet data by using
ff_get_encode_buffer() and also set AV_CODEC_CAP_DR1 at the same time.

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt at outlook.com>
---
The size was actually exact in all my tests; it seems the only way for
which the size could be inexact were if the limit in
set_sr_golomb_flac() (or rather set_ur_golomb_jpegls()) were triggered,
but I am not sure whether this is even possible (it better be not,
because if it were possible, the put_bits(pb, esc_len, i - 1) (with
esc_len == 0) would run into the av_assert2() in put_bits()).

 libavcodec/flacenc.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/libavcodec/flacenc.c b/libavcodec/flacenc.c
index 37ed1e4cce..e5a6dbe68d 100644
--- a/libavcodec/flacenc.c
+++ b/libavcodec/flacenc.c
@@ -27,6 +27,7 @@
 
 #include "avcodec.h"
 #include "bswapdsp.h"
+#include "encode.h"
 #include "put_bits.h"
 #include "golomb.h"
 #include "internal.h"
@@ -1378,7 +1379,7 @@ static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
         }
     }
 
-    if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes, 0)) < 0)
+    if ((ret = ff_get_encode_buffer(avctx, avpkt, frame_bytes, 0)) < 0)
         return ret;
 
     out_bytes = write_frame(s, avpkt);
@@ -1396,10 +1397,11 @@ static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
 
     avpkt->pts      = frame->pts;
     avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
-    avpkt->size     = out_bytes;
 
     s->next_pts = avpkt->pts + avpkt->duration;
 
+    av_shrink_packet(avpkt, out_bytes);
+
     *got_packet_ptr = 1;
     return 0;
 }
@@ -1463,7 +1465,8 @@ const AVCodec ff_flac_encoder = {
     .init           = flac_encode_init,
     .encode2        = flac_encode_frame,
     .close          = flac_encode_close,
-    .capabilities   = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
+    .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
+                      AV_CODEC_CAP_SMALL_LAST_FRAME,
     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
                                                      AV_SAMPLE_FMT_S32,
                                                      AV_SAMPLE_FMT_NONE },
-- 
2.27.0



More information about the ffmpeg-devel mailing list