flacdec: 10l to me. I miscalculated the smallest FLAC frame. It is 16
[libav.git] / libavcodec / flacdec.c
CommitLineData
4f52c312
MN
1/*
2 * FLAC (Free Lossless Audio Codec) decoder
3 * Copyright (c) 2003 Alex Beregszaszi
4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
4f52c312
MN
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
4f52c312 11 *
b78e7197 12 * FFmpeg is distributed in the hope that it will be useful,
4f52c312
MN
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
b78e7197 18 * License along with FFmpeg; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
4f52c312
MN
20 */
21
22/**
bad5537e 23 * @file libavcodec/flacdec.c
4f52c312
MN
24 * FLAC (Free Lossless Audio Codec) decoder
25 * @author Alex Beregszaszi
9eda2f94
MM
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.
4f52c312 34 */
115329f1 35
ac2570a8 36#include <limits.h>
115329f1 37
245976da 38#include "libavutil/crc.h"
4f52c312 39#include "avcodec.h"
5b37e2fc 40#include "internal.h"
caa336b4 41#include "bitstream.h"
a8ec12bc 42#include "bytestream.h"
4f52c312 43#include "golomb.h"
9d48410f 44#include "flac.h"
4f52c312 45
ac2570a8
MN
46#undef NDEBUG
47#include <assert.h>
48
4f52c312
MN
49#define MAX_CHANNELS 8
50#define MAX_BLOCKSIZE 65535
51
9d656110 52enum decorrelation_type {
4f52c312
MN
53 INDEPENDENT,
54 LEFT_SIDE,
55 RIGHT_SIDE,
56 MID_SIDE,
57};
58
59typedef struct FLACContext {
9d48410f
JR
60 FLACSTREAMINFO
61
64cb3765
JR
62 AVCodecContext *avctx; ///< parent AVCodecContext
63 GetBitContext gb; ///< GetBitContext initialized to start at the current frame
4f52c312 64
64cb3765
JR
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
7f3a6a05
JR
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
64cb3765 69 enum decorrelation_type decorrelation; ///< channel decorrelation type in the current frame
7d030358 70 int got_streaminfo; ///< indicates if the STREAMINFO has been read
4f52c312 71
64cb3765 72 int32_t *decoded[MAX_CHANNELS]; ///< decoded samples
ac2570a8 73 uint8_t *bitstream;
1e77df15
MN
74 unsigned int bitstream_size;
75 unsigned int bitstream_index;
f038fe8b 76 unsigned int allocated_bitstream_size;
4f52c312
MN
77} FLACContext;
78
cf2baeb3 79static const int sample_rate_table[] =
959e0006
JR
80{ 0,
81 88200, 176400, 192000,
4f52c312 82 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
115329f1 83 0, 0, 0, 0 };
4f52c312 84
cf2baeb3 85static const int sample_size_table[] =
4f52c312
MN
86{ 0, 8, 12, 0, 16, 20, 24, 0 };
87
cf2baeb3 88static const int blocksize_table[] = {
115329f1
DB
89 0, 192, 576<<0, 576<<1, 576<<2, 576<<3, 0, 0,
90256<<0, 256<<1, 256<<2, 256<<3, 256<<4, 256<<5, 256<<6, 256<<7
0496a034
MN
91};
92
1bec121f
JR
93static int64_t get_utf8(GetBitContext *gb)
94{
9d82b0dd
MN
95 int64_t val;
96 GET_UTF8(val, get_bits(gb, 8), return -1;)
ac2570a8 97 return val;
4f52c312
MN
98}
99
17c90b9d 100static void allocate_buffers(FLACContext *s);
59c6178a
JR
101
102int 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}
9eda2f94 128
1bec121f 129static av_cold int flac_decode_init(AVCodecContext *avctx)
4f52c312 130{
59c6178a
JR
131 enum FLACExtradataFormat format;
132 uint8_t *streaminfo;
9eda2f94
MM
133 FLACContext *s = avctx->priv_data;
134 s->avctx = avctx;
135
faeb2bd4
JR
136 avctx->sample_fmt = SAMPLE_FMT_S16;
137
59c6178a
JR
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
26adc8d0
JR
146 /* initialize based on the demuxer-supplied streamdata header */
147 ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
148 allocate_buffers(s);
7d030358 149 s->got_streaminfo = 1;
9eda2f94 150
4f52c312
MN
151 return 0;
152}
153
9482171b 154static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
4f52c312 155{
95db6659 156 av_log(avctx, AV_LOG_DEBUG, " Max Blocksize: %d\n", s->max_blocksize);
4bc07e78
JR
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);
4f52c312
MN
161}
162
1bec121f
JR
163static void allocate_buffers(FLACContext *s)
164{
4f52c312
MN
165 int i;
166
ac2570a8
MN
167 assert(s->max_blocksize);
168
1bec121f 169 if (s->max_framesize == 0 && s->max_blocksize) {
9f3d3ecf
JR
170 // FIXME header overhead
171 s->max_framesize= (s->channels * s->bps * s->max_blocksize + 7)/ 8;
ac2570a8
MN
172 }
173
1bec121f 174 for (i = 0; i < s->channels; i++) {
9f3d3ecf
JR
175 s->decoded[i] = av_realloc(s->decoded[i],
176 sizeof(int32_t)*s->max_blocksize);
ac2570a8
MN
177 }
178
1bec121f 179 if (s->allocated_bitstream_size < s->max_framesize)
9f3d3ecf
JR
180 s->bitstream= av_fast_realloc(s->bitstream,
181 &s->allocated_bitstream_size,
182 s->max_framesize);
ac2570a8
MN
183}
184
9482171b
JR
185void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
186 const uint8_t *buffer)
ac2570a8 187{
a128cc91
JR
188 GetBitContext gb;
189 init_get_bits(&gb, buffer, FLAC_STREAMINFO_SIZE*8);
190
95db6659 191 skip_bits(&gb, 16); /* skip min blocksize */
a128cc91 192 s->max_blocksize = get_bits(&gb, 16);
2e78513c
JR
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 }
4f52c312 198
a128cc91
JR
199 skip_bits(&gb, 24); /* skip min frame size */
200 s->max_framesize = get_bits_long(&gb, 24);
115329f1 201
a128cc91
JR
202 s->samplerate = get_bits_long(&gb, 20);
203 s->channels = get_bits(&gb, 3) + 1;
204 s->bps = get_bits(&gb, 5) + 1;
115329f1 205
a128cc91
JR
206 avctx->channels = s->channels;
207 avctx->sample_rate = s->samplerate;
82159ad9
JR
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;
4f52c312 213
aeb987ce 214 s->samples = get_bits_long(&gb, 32) << 4;
ee4d0322 215 s->samples |= get_bits(&gb, 4);
115329f1 216
ee4d0322
JR
217 skip_bits_long(&gb, 64); /* md5 sum */
218 skip_bits_long(&gb, 64); /* md5 sum */
115329f1 219
4bc07e78 220 dump_headers(avctx, s);
17c90b9d
AJ
221}
222
223/**
a8ec12bc
JR
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
55a72738 228 * @return non-zero if metadata is invalid
17c90b9d 229 */
a8ec12bc 230static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
17c90b9d 231{
a8ec12bc 232 int metadata_type, metadata_size;
17c90b9d 233
a8ec12bc
JR
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;
17c90b9d 248
a8ec12bc
JR
249 return 0;
250}
17c90b9d 251
a8ec12bc
JR
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 */
258static 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;
e0168e3b 262
a8ec12bc
JR
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;
6a85fb34 270 }
a8ec12bc 271 buf += metadata_size;
6a85fb34 272 } while (!metadata_last);
17c90b9d 273
a8ec12bc 274 return buf_size - (buf_end - buf);
4f52c312
MN
275}
276
277static 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);
1bec121f 283 if (method_type > 1) {
9f3d3ecf
JR
284 av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
285 method_type);
4f52c312 286 return -1;
ac2570a8 287 }
115329f1 288
4f52c312
MN
289 rice_order = get_bits(&s->gb, 4);
290
ac2570a8 291 samples= s->blocksize >> rice_order;
5484dad7 292 if (pred_order > samples) {
9f3d3ecf
JR
293 av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
294 pred_order, samples);
5484dad7
RD
295 return -1;
296 }
4f52c312 297
115329f1 298 sample=
ac2570a8 299 i= pred_order;
1bec121f 300 for (partition = 0; partition < (1 << rice_order); partition++) {
e471443a 301 tmp = get_bits(&s->gb, method_type == 0 ? 4 : 5);
1bec121f 302 if (tmp == (method_type == 0 ? 15 : 31)) {
4f52c312 303 tmp = get_bits(&s->gb, 5);
4f52c312 304 for (; i < samples; i++, sample++)
9de6e090 305 s->decoded[channel][sample] = get_sbits_long(&s->gb, tmp);
1bec121f
JR
306 } else {
307 for (; i < samples; i++, sample++) {
4fd12598 308 s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
ac2570a8 309 }
4f52c312 310 }
ac2570a8 311 i= 0;
4f52c312
MN
312 }
313
4f52c312 314 return 0;
115329f1 315}
4f52c312
MN
316
317static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)
318{
08965b22
LM
319 const int blocksize = s->blocksize;
320 int32_t *decoded = s->decoded[channel];
7846418b 321 int av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d), i;
115329f1 322
4f52c312 323 /* warm up samples */
1bec121f 324 for (i = 0; i < pred_order; i++) {
9de6e090 325 decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
4f52c312 326 }
115329f1 327
4f52c312
MN
328 if (decode_residuals(s, channel, pred_order) < 0)
329 return -1;
330
1bec121f 331 if (pred_order > 0)
1f4fa6a4 332 a = decoded[pred_order-1];
1bec121f 333 if (pred_order > 1)
1f4fa6a4 334 b = a - decoded[pred_order-2];
1bec121f 335 if (pred_order > 2)
1f4fa6a4 336 c = b - decoded[pred_order-2] + decoded[pred_order-3];
1bec121f 337 if (pred_order > 3)
1f4fa6a4 338 d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
08965b22 339
1bec121f
JR
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;
4f52c312 362 }
ac2570a8 363
4f52c312
MN
364 return 0;
365}
366
367static int decode_subframe_lpc(FLACContext *s, int channel, int pred_order)
368{
0187178e 369 int i, j;
4f52c312
MN
370 int coeff_prec, qlevel;
371 int coeffs[pred_order];
d1a5c421 372 int32_t *decoded = s->decoded[channel];
115329f1 373
4f52c312 374 /* warm up samples */
1bec121f 375 for (i = 0; i < pred_order; i++) {
9de6e090 376 decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
4f52c312 377 }
115329f1 378
4f52c312 379 coeff_prec = get_bits(&s->gb, 4) + 1;
1bec121f 380 if (coeff_prec == 16) {
5305f40b 381 av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
4f52c312
MN
382 return -1;
383 }
ac2570a8 384 qlevel = get_sbits(&s->gb, 5);
1bec121f 385 if (qlevel < 0) {
9f3d3ecf
JR
386 av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
387 qlevel);
9d656110
MN
388 return -1;
389 }
390
1bec121f 391 for (i = 0; i < pred_order; i++) {
ac2570a8 392 coeffs[i] = get_sbits(&s->gb, coeff_prec);
4f52c312 393 }
115329f1 394
4f52c312
MN
395 if (decode_residuals(s, channel, pred_order) < 0)
396 return -1;
397
0187178e
LB
398 if (s->bps > 16) {
399 int64_t sum;
1bec121f 400 for (i = pred_order; i < s->blocksize; i++) {
0187178e
LB
401 sum = 0;
402 for (j = 0; j < pred_order; j++)
d1a5c421
LM
403 sum += (int64_t)coeffs[j] * decoded[i-j-1];
404 decoded[i] += sum >> qlevel;
0187178e
LB
405 }
406 } else {
1bec121f 407 for (i = pred_order; i < s->blocksize-1; i += 2) {
d1a5c421
LM
408 int c;
409 int d = decoded[i-pred_order];
410 int s0 = 0, s1 = 0;
1bec121f 411 for (j = pred_order-1; j > 0; j--) {
d1a5c421 412 c = coeffs[j];
bd49d4fd 413 s0 += c*d;
d1a5c421
LM
414 d = decoded[i-j];
415 s1 += c*d;
bd49d4fd 416 }
d1a5c421
LM
417 c = coeffs[0];
418 s0 += c*d;
419 d = decoded[i] += s0 >> qlevel;
420 s1 += c*d;
421 decoded[i+1] += s1 >> qlevel;
bd49d4fd 422 }
1bec121f 423 if (i < s->blocksize) {
bd49d4fd 424 int sum = 0;
0187178e 425 for (j = 0; j < pred_order; j++)
d1a5c421
LM
426 sum += coeffs[j] * decoded[i-j-1];
427 decoded[i] += sum >> qlevel;
0187178e 428 }
4f52c312 429 }
115329f1 430
4f52c312
MN
431 return 0;
432}
433
434static inline int decode_subframe(FLACContext *s, int channel)
435{
436 int type, wasted = 0;
437 int i, tmp;
115329f1 438
4f52c312 439 s->curr_bps = s->bps;
1bec121f
JR
440 if (channel == 0) {
441 if (s->decorrelation == RIGHT_SIDE)
ac2570a8 442 s->curr_bps++;
1bec121f
JR
443 } else {
444 if (s->decorrelation == LEFT_SIDE || s->decorrelation == MID_SIDE)
ac2570a8
MN
445 s->curr_bps++;
446 }
447
1bec121f 448 if (get_bits1(&s->gb)) {
1cef211d 449 av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
4f52c312
MN
450 return -1;
451 }
452 type = get_bits(&s->gb, 6);
c5706efd 453
1bec121f 454 if (get_bits1(&s->gb)) {
4f52c312
MN
455 wasted = 1;
456 while (!get_bits1(&s->gb))
457 wasted++;
458 s->curr_bps -= wasted;
459 }
a3d2379b
JR
460 if (s->curr_bps > 32) {
461 ff_log_missing_feature(s->avctx, "decorrelated bit depth > 32", 0);
462 return -1;
463 }
c5706efd 464
ac2570a8 465//FIXME use av_log2 for types
1bec121f 466 if (type == 0) {
9de6e090 467 tmp = get_sbits_long(&s->gb, s->curr_bps);
4f52c312
MN
468 for (i = 0; i < s->blocksize; i++)
469 s->decoded[channel][i] = tmp;
1bec121f 470 } else if (type == 1) {
4f52c312 471 for (i = 0; i < s->blocksize; i++)
9de6e090 472 s->decoded[channel][i] = get_sbits_long(&s->gb, s->curr_bps);
1bec121f 473 } else if ((type >= 8) && (type <= 12)) {
4f52c312
MN
474 if (decode_subframe_fixed(s, channel, type & ~0x8) < 0)
475 return -1;
1bec121f 476 } else if (type >= 32) {
4f52c312
MN
477 if (decode_subframe_lpc(s, channel, (type & ~0x20)+1) < 0)
478 return -1;
1bec121f 479 } else {
1cef211d 480 av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
4f52c312
MN
481 return -1;
482 }
115329f1 483
1bec121f 484 if (wasted) {
4f52c312
MN
485 int i;
486 for (i = 0; i < s->blocksize; i++)
487 s->decoded[channel][i] <<= wasted;
488 }
489
490 return 0;
491}
492
ac66834c 493static int decode_frame(FLACContext *s, int alloc_data_size)
4f52c312 494{
9d656110 495 int blocksize_code, sample_rate_code, sample_size_code, assignment, i, crc8;
0496a034 496 int decorrelation, bps, blocksize, samplerate;
115329f1 497
4f52c312 498 blocksize_code = get_bits(&s->gb, 4);
4f52c312
MN
499
500 sample_rate_code = get_bits(&s->gb, 4);
115329f1 501
4f52c312 502 assignment = get_bits(&s->gb, 4); /* channel assignment */
0496a034
MN
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;
1bec121f 507 else {
9f3d3ecf
JR
508 av_log(s->avctx, AV_LOG_ERROR, "unsupported channel assignment %d (channels=%d)\n",
509 assignment, s->channels);
4f52c312
MN
510 return -1;
511 }
115329f1 512
4f52c312 513 sample_size_code = get_bits(&s->gb, 3);
1bec121f 514 if (sample_size_code == 0)
0496a034 515 bps= s->bps;
1bec121f 516 else if ((sample_size_code != 3) && (sample_size_code != 7))
0496a034 517 bps = sample_size_table[sample_size_code];
1bec121f 518 else {
9f3d3ecf
JR
519 av_log(s->avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",
520 sample_size_code);
4f52c312
MN
521 return -1;
522 }
82159ad9
JR
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;
4f52c312 533
1bec121f 534 if (get_bits1(&s->gb)) {
1cef211d 535 av_log(s->avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");
0496a034 536 return -1;
4f52c312 537 }
115329f1 538
1bec121f 539 if (get_utf8(&s->gb) < 0) {
0496a034
MN
540 av_log(s->avctx, AV_LOG_ERROR, "utf8 fscked\n");
541 return -1;
542 }
115329f1 543
dde318d5
JR
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)
0496a034 548 blocksize = get_bits(&s->gb, 8)+1;
ac2570a8 549 else if (blocksize_code == 7)
0496a034 550 blocksize = get_bits(&s->gb, 16)+1;
115329f1 551 else
0496a034 552 blocksize = blocksize_table[blocksize_code];
4f52c312 553
1bec121f 554 if (blocksize > s->max_blocksize) {
9f3d3ecf
JR
555 av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", blocksize,
556 s->max_blocksize);
ac2570a8
MN
557 return -1;
558 }
559
549bccdb 560 if (blocksize * s->channels * (s->is32 ? 4 : 2) > alloc_data_size)
ac66834c
MN
561 return -1;
562
1bec121f 563 if (sample_rate_code == 0)
0496a034 564 samplerate= s->samplerate;
1bec121f 565 else if (sample_rate_code < 12)
0496a034 566 samplerate = sample_rate_table[sample_rate_code];
ac2570a8 567 else if (sample_rate_code == 12)
0496a034 568 samplerate = get_bits(&s->gb, 8) * 1000;
ac2570a8 569 else if (sample_rate_code == 13)
0496a034 570 samplerate = get_bits(&s->gb, 16);
ac2570a8 571 else if (sample_rate_code == 14)
0496a034 572 samplerate = get_bits(&s->gb, 16) * 10;
1bec121f 573 else {
9f3d3ecf
JR
574 av_log(s->avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",
575 sample_rate_code);
ac2570a8 576 return -1;
4f52c312
MN
577 }
578
9d656110 579 skip_bits(&s->gb, 8);
3abe5fbd
AJ
580 crc8 = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
581 s->gb.buffer, get_bits_count(&s->gb)/8);
1bec121f 582 if (crc8) {
160d679c 583 av_log(s->avctx, AV_LOG_ERROR, "header crc mismatch crc=%2X\n", crc8);
9d656110
MN
584 return -1;
585 }
115329f1 586
0496a034
MN
587 s->blocksize = blocksize;
588 s->samplerate = samplerate;
589 s->bps = bps;
590 s->decorrelation= decorrelation;
4f52c312 591
9482171b 592// dump_headers(s->avctx, (FLACStreaminfo *)s);
4f52c312
MN
593
594 /* subframes */
1bec121f 595 for (i = 0; i < s->channels; i++) {
4f52c312
MN
596 if (decode_subframe(s, i) < 0)
597 return -1;
598 }
115329f1 599
4f52c312
MN
600 align_get_bits(&s->gb);
601
602 /* frame footer */
603 skip_bits(&s->gb, 16); /* data crc */
604
605 return 0;
606}
607
608static int flac_decode_frame(AVCodecContext *avctx,
609 void *data, int *data_size,
1545c5e5 610 const uint8_t *buf, int buf_size)
4f52c312
MN
611{
612 FLACContext *s = avctx->priv_data;
fd6fd470 613 int i, j = 0, input_buf_size = 0, bytes_read = 0;
82159ad9
JR
614 int16_t *samples_16 = data;
615 int32_t *samples_32 = data;
ac66834c
MN
616 int alloc_data_size= *data_size;
617
618 *data_size=0;
4f52c312 619
1bec121f 620 if (s->max_framesize == 0) {
d3ce0792 621 s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header
ac2570a8
MN
622 s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
623 }
624
1bec121f 625 if (1 && s->max_framesize) { //FIXME truncated
1df0390e
JR
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;
ac2570a8 629
1df0390e
JR
630 if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)
631 return -1;
e0168e3b 632
1df0390e
JR
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);
e0168e3b 635
1df0390e 636 if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {
9f3d3ecf
JR
637 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
638 s->bitstream_size);
1df0390e
JR
639 s->bitstream_index=0;
640 }
9f3d3ecf
JR
641 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],
642 buf, buf_size);
1df0390e
JR
643 buf= &s->bitstream[s->bitstream_index];
644 buf_size += s->bitstream_size;
645 s->bitstream_size= buf_size;
115329f1 646
1df0390e
JR
647 if (buf_size < s->max_framesize && input_buf_size) {
648 return input_buf_size;
649 }
ac2570a8 650 }
4f52c312 651
5ef4fa87
JR
652 /* check that there is at least the smallest decodable amount of data.
653 this amount corresponds to the smallest valid FLAC frame possible. */
5756bc7b 654 if (buf_size < 16)
5ef4fa87
JR
655 goto end;
656
55a72738 657 /* check for inline header */
a8ec12bc
JR
658 if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
659 if (!s->got_streaminfo && parse_streaminfo(s, buf, buf_size)) {
55a72738
JR
660 av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
661 return -1;
662 }
a8ec12bc 663 bytes_read = get_metadata_size(buf, buf_size);
2b4b8c82 664 goto end;
55a72738 665 }
2b4b8c82 666
fd6fd470
JR
667 /* check for frame sync code and resync stream if necessary */
668 if ((AV_RB16(buf) & 0xFFFE) != 0xFFF8) {
669 const uint8_t *buf_end = buf + buf_size;
13de8a08 670 av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");
fd6fd470
JR
671 while (buf+2 < buf_end && (AV_RB16(buf) & 0xFFFE) != 0xFFF8)
672 buf++;
673 bytes_read = buf_size - (buf_end - buf);
674 goto end; // we may not have enough bits left to decode a frame, so try next time
13de8a08 675 }
fd6fd470
JR
676
677 /* decode frame */
678 init_get_bits(&s->gb, buf, buf_size*8);
13de8a08 679 skip_bits(&s->gb, 16);
1bec121f 680 if (decode_frame(s, alloc_data_size) < 0) {
13de8a08
JR
681 av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
682 s->bitstream_size=0;
683 s->bitstream_index=0;
684 return -1;
685 }
bf1d7e28
JR
686 *data_size = s->blocksize * s->channels * (s->is32 ? 4 : 2);
687 bytes_read = (get_bits_count(&s->gb)+7)/8;
ac2570a8 688
c448303d
MN
689#define DECORRELATE(left, right)\
690 assert(s->channels == 2);\
1bec121f 691 for (i = 0; i < s->blocksize; i++) {\
c448303d
MN
692 int a= s->decoded[0][i];\
693 int b= s->decoded[1][i];\
82159ad9
JR
694 if (s->is32) {\
695 *samples_32++ = (left) << s->sample_shift;\
696 *samples_32++ = (right) << s->sample_shift;\
697 } else {\
698 *samples_16++ = (left) << s->sample_shift;\
699 *samples_16++ = (right) << s->sample_shift;\
700 }\
c448303d
MN
701 }\
702 break;
703
1bec121f
JR
704 switch (s->decorrelation) {
705 case INDEPENDENT:
706 for (j = 0; j < s->blocksize; j++) {
82159ad9
JR
707 for (i = 0; i < s->channels; i++) {
708 if (s->is32)
709 *samples_32++ = s->decoded[i][j] << s->sample_shift;
710 else
711 *samples_16++ = s->decoded[i][j] << s->sample_shift;
712 }
1bec121f
JR
713 }
714 break;
715 case LEFT_SIDE:
716 DECORRELATE(a,a-b)
717 case RIGHT_SIDE:
718 DECORRELATE(a+b,b)
719 case MID_SIDE:
720 DECORRELATE( (a-=b>>1) + b, a)
4f52c312 721 }
4f52c312 722
a8ec12bc 723end:
c5199729
JR
724 if (bytes_read > buf_size) {
725 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
9d656110
MN
726 s->bitstream_size=0;
727 s->bitstream_index=0;
ac2570a8
MN
728 return -1;
729 }
4f52c312 730
1bec121f 731 if (s->bitstream_size) {
c5199729
JR
732 s->bitstream_index += bytes_read;
733 s->bitstream_size -= bytes_read;
ac2570a8 734 return input_buf_size;
1bec121f 735 } else
c5199729 736 return bytes_read;
4f52c312
MN
737}
738
98a6fff9 739static av_cold int flac_decode_close(AVCodecContext *avctx)
4f52c312
MN
740{
741 FLACContext *s = avctx->priv_data;
742 int i;
115329f1 743
1bec121f 744 for (i = 0; i < s->channels; i++) {
ac2570a8 745 av_freep(&s->decoded[i]);
4f52c312 746 }
ac2570a8 747 av_freep(&s->bitstream);
115329f1 748
4f52c312
MN
749 return 0;
750}
751
1bec121f
JR
752static void flac_flush(AVCodecContext *avctx)
753{
1e31d32c
MN
754 FLACContext *s = avctx->priv_data;
755
756 s->bitstream_size=
757 s->bitstream_index= 0;
758}
759
4f52c312
MN
760AVCodec flac_decoder = {
761 "flac",
762 CODEC_TYPE_AUDIO,
763 CODEC_ID_FLAC,
764 sizeof(FLACContext),
765 flac_decode_init,
766 NULL,
767 flac_decode_close,
768 flac_decode_frame,
4c453ddb 769 CODEC_CAP_DELAY,
115329f1 770 .flush= flac_flush,
fe4bf374 771 .long_name= NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
4f52c312 772};