]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/flacdec.c
flacdec: cosmetics: Add a comment with the data of the smallest FLAC
[frescor/ffmpeg.git] / libavcodec / flacdec.c
1 /*
2  * FLAC (Free Lossless Audio Codec) decoder
3  * Copyright (c) 2003 Alex Beregszaszi
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file libavcodec/flacdec.c
24  * FLAC (Free Lossless Audio Codec) decoder
25  * @author Alex Beregszaszi
26  *
27  * For more information on the FLAC format, visit:
28  *  http://flac.sourceforge.net/
29  *
30  * This decoder can be used in 1 of 2 ways: Either raw FLAC data can be fed
31  * through, starting from the initial 'fLaC' signature; or by passing the
32  * 34-byte streaminfo structure through avctx->extradata[_size] followed
33  * by data starting with the 0xFFF8 marker.
34  */
35
36 #include <limits.h>
37
38 #include "libavutil/crc.h"
39 #include "avcodec.h"
40 #include "internal.h"
41 #include "bitstream.h"
42 #include "bytestream.h"
43 #include "golomb.h"
44 #include "flac.h"
45
46 #undef NDEBUG
47 #include <assert.h>
48
49 #define MAX_CHANNELS 8
50 #define MAX_BLOCKSIZE 65535
51
52 enum decorrelation_type {
53     INDEPENDENT,
54     LEFT_SIDE,
55     RIGHT_SIDE,
56     MID_SIDE,
57 };
58
59 typedef struct FLACContext {
60     FLACSTREAMINFO
61
62     AVCodecContext *avctx;                  ///< parent AVCodecContext
63     GetBitContext gb;                       ///< GetBitContext initialized to start at the current frame
64
65     int blocksize;                          ///< number of samples in the current frame
66     int curr_bps;                           ///< bps for current subframe, adjusted for channel correlation and wasted bits
67     int sample_shift;                       ///< shift required to make output samples 16-bit or 32-bit
68     int is32;                               ///< flag to indicate if output should be 32-bit instead of 16-bit
69     enum decorrelation_type decorrelation;  ///< channel decorrelation type in the current frame
70     int got_streaminfo;                     ///< indicates if the STREAMINFO has been read
71
72     int32_t *decoded[MAX_CHANNELS];         ///< decoded samples
73     uint8_t *bitstream;
74     unsigned int bitstream_size;
75     unsigned int bitstream_index;
76     unsigned int allocated_bitstream_size;
77 } FLACContext;
78
79 static const int sample_rate_table[] =
80 { 0,
81   88200, 176400, 192000,
82   8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
83   0, 0, 0, 0 };
84
85 static const int sample_size_table[] =
86 { 0, 8, 12, 0, 16, 20, 24, 0 };
87
88 static const int blocksize_table[] = {
89      0,    192, 576<<0, 576<<1, 576<<2, 576<<3,      0,      0,
90 256<<0, 256<<1, 256<<2, 256<<3, 256<<4, 256<<5, 256<<6, 256<<7
91 };
92
93 static int64_t get_utf8(GetBitContext *gb)
94 {
95     int64_t val;
96     GET_UTF8(val, get_bits(gb, 8), return -1;)
97     return val;
98 }
99
100 static void allocate_buffers(FLACContext *s);
101
102 int ff_flac_is_extradata_valid(AVCodecContext *avctx,
103                                enum FLACExtradataFormat *format,
104                                uint8_t **streaminfo_start)
105 {
106     if (!avctx->extradata || avctx->extradata_size < FLAC_STREAMINFO_SIZE) {
107         av_log(avctx, AV_LOG_ERROR, "extradata NULL or too small.\n");
108         return 0;
109     }
110     if (AV_RL32(avctx->extradata) != MKTAG('f','L','a','C')) {
111         /* extradata contains STREAMINFO only */
112         if (avctx->extradata_size != FLAC_STREAMINFO_SIZE) {
113             av_log(avctx, AV_LOG_WARNING, "extradata contains %d bytes too many.\n",
114                    FLAC_STREAMINFO_SIZE-avctx->extradata_size);
115         }
116         *format = FLAC_EXTRADATA_FORMAT_STREAMINFO;
117         *streaminfo_start = avctx->extradata;
118     } else {
119         if (avctx->extradata_size < 8+FLAC_STREAMINFO_SIZE) {
120             av_log(avctx, AV_LOG_ERROR, "extradata too small.\n");
121             return 0;
122         }
123         *format = FLAC_EXTRADATA_FORMAT_FULL_HEADER;
124         *streaminfo_start = &avctx->extradata[8];
125     }
126     return 1;
127 }
128
129 static av_cold int flac_decode_init(AVCodecContext *avctx)
130 {
131     enum FLACExtradataFormat format;
132     uint8_t *streaminfo;
133     FLACContext *s = avctx->priv_data;
134     s->avctx = avctx;
135
136     avctx->sample_fmt = SAMPLE_FMT_S16;
137
138     /* for now, the raw FLAC header is allowed to be passed to the decoder as
139        frame data instead of extradata. */
140     if (!avctx->extradata)
141         return 0;
142
143     if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
144         return -1;
145
146     /* initialize based on the demuxer-supplied streamdata header */
147     ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
148     allocate_buffers(s);
149     s->got_streaminfo = 1;
150
151     return 0;
152 }
153
154 static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
155 {
156     av_log(avctx, AV_LOG_DEBUG, "  Max Blocksize: %d\n", s->max_blocksize);
157     av_log(avctx, AV_LOG_DEBUG, "  Max Framesize: %d\n", s->max_framesize);
158     av_log(avctx, AV_LOG_DEBUG, "  Samplerate: %d\n", s->samplerate);
159     av_log(avctx, AV_LOG_DEBUG, "  Channels: %d\n", s->channels);
160     av_log(avctx, AV_LOG_DEBUG, "  Bits: %d\n", s->bps);
161 }
162
163 static void allocate_buffers(FLACContext *s)
164 {
165     int i;
166
167     assert(s->max_blocksize);
168
169     if (s->max_framesize == 0 && s->max_blocksize) {
170         // FIXME header overhead
171         s->max_framesize= (s->channels * s->bps * s->max_blocksize + 7)/ 8;
172     }
173
174     for (i = 0; i < s->channels; i++) {
175         s->decoded[i] = av_realloc(s->decoded[i],
176                                    sizeof(int32_t)*s->max_blocksize);
177     }
178
179     if (s->allocated_bitstream_size < s->max_framesize)
180         s->bitstream= av_fast_realloc(s->bitstream,
181                                       &s->allocated_bitstream_size,
182                                       s->max_framesize);
183 }
184
185 void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
186                               const uint8_t *buffer)
187 {
188     GetBitContext gb;
189     init_get_bits(&gb, buffer, FLAC_STREAMINFO_SIZE*8);
190
191     skip_bits(&gb, 16); /* skip min blocksize */
192     s->max_blocksize = get_bits(&gb, 16);
193     if (s->max_blocksize < 16) {
194         av_log(avctx, AV_LOG_WARNING, "invalid max blocksize: %d\n",
195                s->max_blocksize);
196         s->max_blocksize = 16;
197     }
198
199     skip_bits(&gb, 24); /* skip min frame size */
200     s->max_framesize = get_bits_long(&gb, 24);
201
202     s->samplerate = get_bits_long(&gb, 20);
203     s->channels = get_bits(&gb, 3) + 1;
204     s->bps = get_bits(&gb, 5) + 1;
205
206     avctx->channels = s->channels;
207     avctx->sample_rate = s->samplerate;
208     avctx->bits_per_raw_sample = s->bps;
209     if (s->bps > 16)
210         avctx->sample_fmt = SAMPLE_FMT_S32;
211     else
212         avctx->sample_fmt = SAMPLE_FMT_S16;
213
214     s->samples  = get_bits_long(&gb, 32) << 4;
215     s->samples |= get_bits(&gb, 4);
216
217     skip_bits_long(&gb, 64); /* md5 sum */
218     skip_bits_long(&gb, 64); /* md5 sum */
219
220     dump_headers(avctx, s);
221 }
222
223 /**
224  * Parse the STREAMINFO from an inline header.
225  * @param s the flac decoding context
226  * @param buf input buffer, starting with the "fLaC" marker
227  * @param buf_size buffer size
228  * @return non-zero if metadata is invalid
229  */
230 static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
231 {
232     int metadata_type, metadata_size;
233
234     if (buf_size < FLAC_STREAMINFO_SIZE+8) {
235         /* need more data */
236         return 0;
237     }
238     buf += 4;
239     metadata_type = bytestream_get_byte(&buf) & 0x7F;
240     metadata_size = bytestream_get_be24(&buf);
241     if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
242         metadata_size != FLAC_STREAMINFO_SIZE) {
243         return AVERROR_INVALIDDATA;
244     }
245     ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, buf);
246     allocate_buffers(s);
247     s->got_streaminfo = 1;
248
249     return 0;
250 }
251
252 /**
253  * Determine the size of an inline header.
254  * @param buf input buffer, starting with the "fLaC" marker
255  * @param buf_size buffer size
256  * @return number of bytes in the header, or 0 if more data is needed
257  */
258 static int get_metadata_size(const uint8_t *buf, int buf_size)
259 {
260     int metadata_last, metadata_size;
261     const uint8_t *buf_end = buf + buf_size;
262
263     buf += 4;
264     do {
265         metadata_last = bytestream_get_byte(&buf) & 0x80;
266         metadata_size = bytestream_get_be24(&buf);
267         if (buf + metadata_size > buf_end) {
268             /* need more data in order to read the complete header */
269             return 0;
270         }
271         buf += metadata_size;
272     } while (!metadata_last);
273
274     return buf_size - (buf_end - buf);
275 }
276
277 static int decode_residuals(FLACContext *s, int channel, int pred_order)
278 {
279     int i, tmp, partition, method_type, rice_order;
280     int sample = 0, samples;
281
282     method_type = get_bits(&s->gb, 2);
283     if (method_type > 1) {
284         av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
285                method_type);
286         return -1;
287     }
288
289     rice_order = get_bits(&s->gb, 4);
290
291     samples= s->blocksize >> rice_order;
292     if (pred_order > samples) {
293         av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
294                pred_order, samples);
295         return -1;
296     }
297
298     sample=
299     i= pred_order;
300     for (partition = 0; partition < (1 << rice_order); partition++) {
301         tmp = get_bits(&s->gb, method_type == 0 ? 4 : 5);
302         if (tmp == (method_type == 0 ? 15 : 31)) {
303             tmp = get_bits(&s->gb, 5);
304             for (; i < samples; i++, sample++)
305                 s->decoded[channel][sample] = get_sbits_long(&s->gb, tmp);
306         } else {
307             for (; i < samples; i++, sample++) {
308                 s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
309             }
310         }
311         i= 0;
312     }
313
314     return 0;
315 }
316
317 static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)
318 {
319     const int blocksize = s->blocksize;
320     int32_t *decoded = s->decoded[channel];
321     int av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d), i;
322
323     /* warm up samples */
324     for (i = 0; i < pred_order; i++) {
325         decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
326     }
327
328     if (decode_residuals(s, channel, pred_order) < 0)
329         return -1;
330
331     if (pred_order > 0)
332         a = decoded[pred_order-1];
333     if (pred_order > 1)
334         b = a - decoded[pred_order-2];
335     if (pred_order > 2)
336         c = b - decoded[pred_order-2] + decoded[pred_order-3];
337     if (pred_order > 3)
338         d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
339
340     switch (pred_order) {
341     case 0:
342         break;
343     case 1:
344         for (i = pred_order; i < blocksize; i++)
345             decoded[i] = a += decoded[i];
346         break;
347     case 2:
348         for (i = pred_order; i < blocksize; i++)
349             decoded[i] = a += b += decoded[i];
350         break;
351     case 3:
352         for (i = pred_order; i < blocksize; i++)
353             decoded[i] = a += b += c += decoded[i];
354         break;
355     case 4:
356         for (i = pred_order; i < blocksize; i++)
357             decoded[i] = a += b += c += d += decoded[i];
358         break;
359     default:
360         av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);
361         return -1;
362     }
363
364     return 0;
365 }
366
367 static int decode_subframe_lpc(FLACContext *s, int channel, int pred_order)
368 {
369     int i, j;
370     int coeff_prec, qlevel;
371     int coeffs[pred_order];
372     int32_t *decoded = s->decoded[channel];
373
374     /* warm up samples */
375     for (i = 0; i < pred_order; i++) {
376         decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
377     }
378
379     coeff_prec = get_bits(&s->gb, 4) + 1;
380     if (coeff_prec == 16) {
381         av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
382         return -1;
383     }
384     qlevel = get_sbits(&s->gb, 5);
385     if (qlevel < 0) {
386         av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
387                qlevel);
388         return -1;
389     }
390
391     for (i = 0; i < pred_order; i++) {
392         coeffs[i] = get_sbits(&s->gb, coeff_prec);
393     }
394
395     if (decode_residuals(s, channel, pred_order) < 0)
396         return -1;
397
398     if (s->bps > 16) {
399         int64_t sum;
400         for (i = pred_order; i < s->blocksize; i++) {
401             sum = 0;
402             for (j = 0; j < pred_order; j++)
403                 sum += (int64_t)coeffs[j] * decoded[i-j-1];
404             decoded[i] += sum >> qlevel;
405         }
406     } else {
407         for (i = pred_order; i < s->blocksize-1; i += 2) {
408             int c;
409             int d = decoded[i-pred_order];
410             int s0 = 0, s1 = 0;
411             for (j = pred_order-1; j > 0; j--) {
412                 c = coeffs[j];
413                 s0 += c*d;
414                 d = decoded[i-j];
415                 s1 += c*d;
416             }
417             c = coeffs[0];
418             s0 += c*d;
419             d = decoded[i] += s0 >> qlevel;
420             s1 += c*d;
421             decoded[i+1] += s1 >> qlevel;
422         }
423         if (i < s->blocksize) {
424             int sum = 0;
425             for (j = 0; j < pred_order; j++)
426                 sum += coeffs[j] * decoded[i-j-1];
427             decoded[i] += sum >> qlevel;
428         }
429     }
430
431     return 0;
432 }
433
434 static inline int decode_subframe(FLACContext *s, int channel)
435 {
436     int type, wasted = 0;
437     int i, tmp;
438
439     s->curr_bps = s->bps;
440     if (channel == 0) {
441         if (s->decorrelation == RIGHT_SIDE)
442             s->curr_bps++;
443     } else {
444         if (s->decorrelation == LEFT_SIDE || s->decorrelation == MID_SIDE)
445             s->curr_bps++;
446     }
447
448     if (get_bits1(&s->gb)) {
449         av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
450         return -1;
451     }
452     type = get_bits(&s->gb, 6);
453
454     if (get_bits1(&s->gb)) {
455         wasted = 1;
456         while (!get_bits1(&s->gb))
457             wasted++;
458         s->curr_bps -= wasted;
459     }
460     if (s->curr_bps > 32) {
461         ff_log_missing_feature(s->avctx, "decorrelated bit depth > 32", 0);
462         return -1;
463     }
464
465 //FIXME use av_log2 for types
466     if (type == 0) {
467         tmp = get_sbits_long(&s->gb, s->curr_bps);
468         for (i = 0; i < s->blocksize; i++)
469             s->decoded[channel][i] = tmp;
470     } else if (type == 1) {
471         for (i = 0; i < s->blocksize; i++)
472             s->decoded[channel][i] = get_sbits_long(&s->gb, s->curr_bps);
473     } else if ((type >= 8) && (type <= 12)) {
474         if (decode_subframe_fixed(s, channel, type & ~0x8) < 0)
475             return -1;
476     } else if (type >= 32) {
477         if (decode_subframe_lpc(s, channel, (type & ~0x20)+1) < 0)
478             return -1;
479     } else {
480         av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
481         return -1;
482     }
483
484     if (wasted) {
485         int i;
486         for (i = 0; i < s->blocksize; i++)
487             s->decoded[channel][i] <<= wasted;
488     }
489
490     return 0;
491 }
492
493 static int decode_frame(FLACContext *s, int alloc_data_size)
494 {
495     int blocksize_code, sample_rate_code, sample_size_code, assignment, i, crc8;
496     int decorrelation, bps, blocksize, samplerate;
497
498     blocksize_code = get_bits(&s->gb, 4);
499
500     sample_rate_code = get_bits(&s->gb, 4);
501
502     assignment = get_bits(&s->gb, 4); /* channel assignment */
503     if (assignment < 8 && s->channels == assignment+1)
504         decorrelation = INDEPENDENT;
505     else if (assignment >=8 && assignment < 11 && s->channels == 2)
506         decorrelation = LEFT_SIDE + assignment - 8;
507     else {
508         av_log(s->avctx, AV_LOG_ERROR, "unsupported channel assignment %d (channels=%d)\n",
509                assignment, s->channels);
510         return -1;
511     }
512
513     sample_size_code = get_bits(&s->gb, 3);
514     if (sample_size_code == 0)
515         bps= s->bps;
516     else if ((sample_size_code != 3) && (sample_size_code != 7))
517         bps = sample_size_table[sample_size_code];
518     else {
519         av_log(s->avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",
520                sample_size_code);
521         return -1;
522     }
523     if (bps > 16) {
524         s->avctx->sample_fmt = SAMPLE_FMT_S32;
525         s->sample_shift = 32 - bps;
526         s->is32 = 1;
527     } else {
528         s->avctx->sample_fmt = SAMPLE_FMT_S16;
529         s->sample_shift = 16 - bps;
530         s->is32 = 0;
531     }
532     s->bps = s->avctx->bits_per_raw_sample = bps;
533
534     if (get_bits1(&s->gb)) {
535         av_log(s->avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");
536         return -1;
537     }
538
539     if (get_utf8(&s->gb) < 0) {
540         av_log(s->avctx, AV_LOG_ERROR, "utf8 fscked\n");
541         return -1;
542     }
543
544     if (blocksize_code == 0) {
545         av_log(s->avctx, AV_LOG_ERROR, "reserved blocksize code: 0\n");
546         return -1;
547     } else if (blocksize_code == 6)
548         blocksize = get_bits(&s->gb, 8)+1;
549     else if (blocksize_code == 7)
550         blocksize = get_bits(&s->gb, 16)+1;
551     else
552         blocksize = blocksize_table[blocksize_code];
553
554     if (blocksize > s->max_blocksize) {
555         av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", blocksize,
556                s->max_blocksize);
557         return -1;
558     }
559
560     if (blocksize * s->channels * (s->is32 ? 4 : 2) > alloc_data_size)
561         return -1;
562
563     if (sample_rate_code == 0)
564         samplerate= s->samplerate;
565     else if (sample_rate_code < 12)
566         samplerate = sample_rate_table[sample_rate_code];
567     else if (sample_rate_code == 12)
568         samplerate = get_bits(&s->gb, 8) * 1000;
569     else if (sample_rate_code == 13)
570         samplerate = get_bits(&s->gb, 16);
571     else if (sample_rate_code == 14)
572         samplerate = get_bits(&s->gb, 16) * 10;
573     else {
574         av_log(s->avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",
575                sample_rate_code);
576         return -1;
577     }
578
579     skip_bits(&s->gb, 8);
580     crc8 = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
581                   s->gb.buffer, get_bits_count(&s->gb)/8);
582     if (crc8) {
583         av_log(s->avctx, AV_LOG_ERROR, "header crc mismatch crc=%2X\n", crc8);
584         return -1;
585     }
586
587     s->blocksize    = blocksize;
588     s->samplerate   = samplerate;
589     s->bps          = bps;
590     s->decorrelation= decorrelation;
591
592 //    dump_headers(s->avctx, (FLACStreaminfo *)s);
593
594     /* subframes */
595     for (i = 0; i < s->channels; i++) {
596         if (decode_subframe(s, i) < 0)
597             return -1;
598     }
599
600     align_get_bits(&s->gb);
601
602     /* frame footer */
603     skip_bits(&s->gb, 16); /* data crc */
604
605     return 0;
606 }
607
608 static int flac_decode_frame(AVCodecContext *avctx,
609                             void *data, int *data_size,
610                             const uint8_t *buf, int buf_size)
611 {
612     FLACContext *s = avctx->priv_data;
613     int i, j = 0, input_buf_size = 0, bytes_read = 0;
614     int16_t *samples_16 = data;
615     int32_t *samples_32 = data;
616     int alloc_data_size= *data_size;
617
618     *data_size=0;
619
620     if (s->max_framesize == 0) {
621         s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header
622         s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
623     }
624
625     if (1 && s->max_framesize) { //FIXME truncated
626         if (s->bitstream_size < 4 || AV_RL32(s->bitstream) != MKTAG('f','L','a','C'))
627             buf_size= FFMIN(buf_size, s->max_framesize - FFMIN(s->bitstream_size, s->max_framesize));
628         input_buf_size= buf_size;
629
630         if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)
631             return -1;
632
633         if (s->allocated_bitstream_size < s->bitstream_size + buf_size)
634             s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->bitstream_size + buf_size);
635
636         if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {
637             memmove(s->bitstream, &s->bitstream[s->bitstream_index],
638                     s->bitstream_size);
639             s->bitstream_index=0;
640         }
641         memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],
642                buf, buf_size);
643         buf= &s->bitstream[s->bitstream_index];
644         buf_size += s->bitstream_size;
645         s->bitstream_size= buf_size;
646
647         if (buf_size < s->max_framesize && input_buf_size) {
648             return input_buf_size;
649         }
650     }
651
652     /* check that there is at least the smallest decodable amount of data.
653        this amount corresponds to the smallest valid FLAC frame possible.
654        FF F8 69 02 00 00 9A 00 00 34 46 */
655     if (buf_size < 11)
656         goto end;
657
658     /* check for inline header */
659     if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
660         if (!s->got_streaminfo && parse_streaminfo(s, buf, buf_size)) {
661             av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
662             return -1;
663         }
664         bytes_read = get_metadata_size(buf, buf_size);
665         goto end;
666     }
667
668     /* check for frame sync code and resync stream if necessary */
669     if ((AV_RB16(buf) & 0xFFFE) != 0xFFF8) {
670         const uint8_t *buf_end = buf + buf_size;
671         av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");
672         while (buf+2 < buf_end && (AV_RB16(buf) & 0xFFFE) != 0xFFF8)
673             buf++;
674         bytes_read = buf_size - (buf_end - buf);
675         goto end; // we may not have enough bits left to decode a frame, so try next time
676     }
677
678     /* decode frame */
679     init_get_bits(&s->gb, buf, buf_size*8);
680     skip_bits(&s->gb, 16);
681     if (decode_frame(s, alloc_data_size) < 0) {
682         av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
683         s->bitstream_size=0;
684         s->bitstream_index=0;
685         return -1;
686     }
687     *data_size = s->blocksize * s->channels * (s->is32 ? 4 : 2);
688     bytes_read = (get_bits_count(&s->gb)+7)/8;
689
690 #define DECORRELATE(left, right)\
691             assert(s->channels == 2);\
692             for (i = 0; i < s->blocksize; i++) {\
693                 int a= s->decoded[0][i];\
694                 int b= s->decoded[1][i];\
695                 if (s->is32) {\
696                     *samples_32++ = (left)  << s->sample_shift;\
697                     *samples_32++ = (right) << s->sample_shift;\
698                 } else {\
699                     *samples_16++ = (left)  << s->sample_shift;\
700                     *samples_16++ = (right) << s->sample_shift;\
701                 }\
702             }\
703             break;
704
705     switch (s->decorrelation) {
706     case INDEPENDENT:
707         for (j = 0; j < s->blocksize; j++) {
708             for (i = 0; i < s->channels; i++) {
709                 if (s->is32)
710                     *samples_32++ = s->decoded[i][j] << s->sample_shift;
711                 else
712                     *samples_16++ = s->decoded[i][j] << s->sample_shift;
713             }
714         }
715         break;
716     case LEFT_SIDE:
717         DECORRELATE(a,a-b)
718     case RIGHT_SIDE:
719         DECORRELATE(a+b,b)
720     case MID_SIDE:
721         DECORRELATE( (a-=b>>1) + b, a)
722     }
723
724 end:
725     if (bytes_read > buf_size) {
726         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
727         s->bitstream_size=0;
728         s->bitstream_index=0;
729         return -1;
730     }
731
732     if (s->bitstream_size) {
733         s->bitstream_index += bytes_read;
734         s->bitstream_size  -= bytes_read;
735         return input_buf_size;
736     } else
737         return bytes_read;
738 }
739
740 static av_cold int flac_decode_close(AVCodecContext *avctx)
741 {
742     FLACContext *s = avctx->priv_data;
743     int i;
744
745     for (i = 0; i < s->channels; i++) {
746         av_freep(&s->decoded[i]);
747     }
748     av_freep(&s->bitstream);
749
750     return 0;
751 }
752
753 static void flac_flush(AVCodecContext *avctx)
754 {
755     FLACContext *s = avctx->priv_data;
756
757     s->bitstream_size=
758     s->bitstream_index= 0;
759 }
760
761 AVCodec flac_decoder = {
762     "flac",
763     CODEC_TYPE_AUDIO,
764     CODEC_ID_FLAC,
765     sizeof(FLACContext),
766     flac_decode_init,
767     NULL,
768     flac_decode_close,
769     flac_decode_frame,
770     CODEC_CAP_DELAY,
771     .flush= flac_flush,
772     .long_name= NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
773 };