Browse code

api-example: Try to avoid decoding incomplete frames

Use a larger input audio buffer, refill it when it has less than 4 KB data
left.

Originally committed as revision 23323 to svn://svn.ffmpeg.org/ffmpeg/trunk

Martin Storsjö authored on 2010/05/26 04:13:28
Showing 1 changed files
... ...
@@ -39,6 +39,8 @@
39 39
 #include "libavutil/mathematics.h"
40 40
 
41 41
 #define INBUF_SIZE 4096
42
+#define AUDIO_INBUF_SIZE 20480
43
+#define AUDIO_REFILL_THRESH 4096
42 44
 
43 45
 /*
44 46
  * Audio encoding example
... ...
@@ -118,7 +120,7 @@ static void audio_decode_example(const char *outfilename, const char *filename)
118 118
     int out_size, len;
119 119
     FILE *f, *outfile;
120 120
     uint8_t *outbuf;
121
-    uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
121
+    uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
122 122
     AVPacket avpkt;
123 123
 
124 124
     av_init_packet(&avpkt);
... ...
@@ -155,12 +157,8 @@ static void audio_decode_example(const char *outfilename, const char *filename)
155 155
 
156 156
     /* decode until eof */
157 157
     avpkt.data = inbuf;
158
-    for(;;) {
159
-        avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
160
-        if (avpkt.size == 0)
161
-            break;
158
+        avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
162 159
 
163
-        avpkt.data = inbuf;
164 160
         while (avpkt.size > 0) {
165 161
             out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
166 162
             len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
... ...
@@ -174,8 +172,19 @@ static void audio_decode_example(const char *outfilename, const char *filename)
174 174
             }
175 175
             avpkt.size -= len;
176 176
             avpkt.data += len;
177
+            if (avpkt.size < AUDIO_REFILL_THRESH) {
178
+                /* Refill the input buffer, to avoid trying to decode
179
+                 * incomplete frames. Instead of this, one could also use
180
+                 * a parser, or use a proper container format through
181
+                 * libavformat. */
182
+                memmove(inbuf, avpkt.data, avpkt.size);
183
+                avpkt.data = inbuf;
184
+                len = fread(avpkt.data + avpkt.size, 1,
185
+                            AUDIO_INBUF_SIZE - avpkt.size, f);
186
+                if (len > 0)
187
+                    avpkt.size += len;
188
+            }
177 189
         }
178
-    }
179 190
 
180 191
     fclose(outfile);
181 192
     fclose(f);