From 0f5c3f2132a44330ee2f9f66e68be5614bd7cb7a Mon Sep 17 00:00:00 2001
From: Hauke Duden <H.NS.Duden@gmx.net>
Date: Fri, 16 Apr 2004 01:48:05 +0000
Subject: [PATCH] fixed buffering for low bitrates patch by (Hauke Duden
 <H.NS.Duden at gmx dot net>)

Originally committed as revision 3020 to svn://svn.ffmpeg.org/ffmpeg/trunk
---
 libavcodec/mp3lameaudio.c | 28 +++++++++++++++++++---------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/libavcodec/mp3lameaudio.c b/libavcodec/mp3lameaudio.c
index 637c7271f49..f53aee9272a 100644
--- a/libavcodec/mp3lameaudio.c
+++ b/libavcodec/mp3lameaudio.c
@@ -57,7 +57,7 @@ static int MP3lame_encode_init(AVCodecContext *avctx)
 	if (lame_init_params(s->gfp) < 0)
 		goto err_close;
 
-	avctx->frame_size = MPA_FRAME_SIZE;
+	avctx->frame_size = lame_get_framesize(s->gfp);
     
         avctx->coded_frame= avcodec_alloc_frame();
         avctx->coded_frame->key_frame= 1;
@@ -133,31 +133,41 @@ int MP3lame_encode_frame(AVCodecContext *avctx,
 {
 	Mp3AudioContext *s = avctx->priv_data;
 	int len, i;
+	int lame_result;
 
 	/* lame 3.91 dies on '1-channel interleaved' data */
 	if (s->stereo) {
-            s->buffer_index += lame_encode_buffer_interleaved(
+            lame_result = lame_encode_buffer_interleaved(
                 s->gfp, 
                 data,
-		MPA_FRAME_SIZE, 
+                avctx->frame_size, 
                 s->buffer + s->buffer_index, 
                 BUFFER_SIZE - s->buffer_index
                 );
 	} else {
-            s->buffer_index += lame_encode_buffer(
+            lame_result = lame_encode_buffer(
                 s->gfp, 
                 data, 
                 data, 
-                MPA_FRAME_SIZE,
+                avctx->frame_size,
                 s->buffer + s->buffer_index, 
                 BUFFER_SIZE - s->buffer_index
                 );
-	}
-        if(s->buffer_index<4)
-            return 0;
+    }
+
+    if(lame_result==-1) {
+        /* output buffer too small */
+        av_log(avctx, AV_LOG_ERROR, "lame: output buffer too small (buffer index: %d, free bytes: %d)\n", s->buffer_index, BUFFER_SIZE - s->buffer_index);
+        return 0;
+    }
+
+    s->buffer_index += lame_result;
+
+    if(s->buffer_index<4)
+        return 0;
 
         len= mp3len(s->buffer, NULL, NULL);
-//av_log(avctx, AV_LOG_DEBUG, "in:%d packet-len:%d index:%d\n", MPA_FRAME_SIZE, len, s->buffer_index);
+//av_log(avctx, AV_LOG_DEBUG, "in:%d packet-len:%d index:%d\n", avctx->frame_size, len, s->buffer_index);
         if(len <= s->buffer_index){
             memcpy(frame, s->buffer, len);
             s->buffer_index -= len;
-- 
GitLab