2 * FLAC (Free Lossless Audio Codec) decoder
3 * Copyright (c) 2003 Alex Beregszaszi
5 * This file is part of FFmpeg.
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.
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.
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
24 * FLAC (Free Lossless Audio Codec) decoder
25 * @author Alex Beregszaszi
27 * For more information on the FLAC format, visit:
28 * http://flac.sourceforge.net/
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.
38 #define ALT_BITSTREAM_READER
39 #include "libavutil/crc.h"
41 #include "bitstream.h"
48 #define MAX_CHANNELS 8
49 #define MAX_BLOCKSIZE 65535
50 #define FLAC_STREAMINFO_SIZE 34
52 enum decorrelation_type {
59 typedef struct FLACContext {
62 AVCodecContext *avctx;
65 int blocksize/*, last_blocksize*/;
67 enum decorrelation_type decorrelation;
69 int32_t *decoded[MAX_CHANNELS];
71 unsigned int bitstream_size;
72 unsigned int bitstream_index;
73 unsigned int allocated_bitstream_size;
76 #define METADATA_TYPE_STREAMINFO 0
78 static const int sample_rate_table[] =
80 88200, 176400, 192000,
81 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
84 static const int sample_size_table[] =
85 { 0, 8, 12, 0, 16, 20, 24, 0 };
87 static const int blocksize_table[] = {
88 0, 192, 576<<0, 576<<1, 576<<2, 576<<3, 0, 0,
89 256<<0, 256<<1, 256<<2, 256<<3, 256<<4, 256<<5, 256<<6, 256<<7
92 static int64_t get_utf8(GetBitContext *gb)
95 GET_UTF8(val, get_bits(gb, 8), return -1;)
99 static void allocate_buffers(FLACContext *s);
100 static int metadata_parse(FLACContext *s);
102 static av_cold int flac_decode_init(AVCodecContext *avctx)
104 FLACContext *s = avctx->priv_data;
107 if (avctx->extradata_size > 4) {
108 /* initialize based on the demuxer-supplied streamdata header */
109 if (avctx->extradata_size == FLAC_STREAMINFO_SIZE) {
110 ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s,
114 init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
119 avctx->sample_fmt = SAMPLE_FMT_S16;
123 static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
125 av_log(avctx, AV_LOG_DEBUG, " Blocksize: %d .. %d\n", s->min_blocksize,
127 av_log(avctx, AV_LOG_DEBUG, " Max Framesize: %d\n", s->max_framesize);
128 av_log(avctx, AV_LOG_DEBUG, " Samplerate: %d\n", s->samplerate);
129 av_log(avctx, AV_LOG_DEBUG, " Channels: %d\n", s->channels);
130 av_log(avctx, AV_LOG_DEBUG, " Bits: %d\n", s->bps);
133 static void allocate_buffers(FLACContext *s)
137 assert(s->max_blocksize);
139 if (s->max_framesize == 0 && s->max_blocksize) {
140 // FIXME header overhead
141 s->max_framesize= (s->channels * s->bps * s->max_blocksize + 7)/ 8;
144 for (i = 0; i < s->channels; i++) {
145 s->decoded[i] = av_realloc(s->decoded[i],
146 sizeof(int32_t)*s->max_blocksize);
149 if (s->allocated_bitstream_size < s->max_framesize)
150 s->bitstream= av_fast_realloc(s->bitstream,
151 &s->allocated_bitstream_size,
155 void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
156 const uint8_t *buffer)
159 init_get_bits(&gb, buffer, FLAC_STREAMINFO_SIZE*8);
161 /* mandatory streaminfo */
162 s->min_blocksize = get_bits(&gb, 16);
163 s->max_blocksize = get_bits(&gb, 16);
165 skip_bits(&gb, 24); /* skip min frame size */
166 s->max_framesize = get_bits_long(&gb, 24);
168 s->samplerate = get_bits_long(&gb, 20);
169 s->channels = get_bits(&gb, 3) + 1;
170 s->bps = get_bits(&gb, 5) + 1;
172 avctx->channels = s->channels;
173 avctx->sample_rate = s->samplerate;
175 skip_bits(&gb, 36); /* total num of samples */
177 skip_bits(&gb, 64); /* md5 sum */
178 skip_bits(&gb, 64); /* md5 sum */
180 dump_headers(avctx, s);
184 * Parse a list of metadata blocks. This list of blocks must begin with
186 * @param s the flac decoding context containing the gb bit reader used to
188 * @return 1 if some metadata was read, 0 if no fLaC marker was found
190 static int metadata_parse(FLACContext *s)
192 int i, metadata_last, metadata_type, metadata_size, streaminfo_updated=0;
193 int initial_pos= get_bits_count(&s->gb);
195 if (show_bits_long(&s->gb, 32) == MKBETAG('f','L','a','C')) {
196 skip_bits(&s->gb, 32);
199 metadata_last = get_bits1(&s->gb);
200 metadata_type = get_bits(&s->gb, 7);
201 metadata_size = get_bits_long(&s->gb, 24);
203 if (get_bits_count(&s->gb) + 8*metadata_size > s->gb.size_in_bits) {
204 skip_bits_long(&s->gb, initial_pos - get_bits_count(&s->gb));
209 switch (metadata_type) {
210 case METADATA_TYPE_STREAMINFO:
211 ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s,
212 s->gb.buffer+get_bits_count(&s->gb)/8);
213 streaminfo_updated = 1;
216 for (i = 0; i < metadata_size; i++)
217 skip_bits(&s->gb, 8);
220 } while (!metadata_last);
222 if (streaminfo_updated)
229 static int decode_residuals(FLACContext *s, int channel, int pred_order)
231 int i, tmp, partition, method_type, rice_order;
232 int sample = 0, samples;
234 method_type = get_bits(&s->gb, 2);
235 if (method_type > 1) {
236 av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
241 rice_order = get_bits(&s->gb, 4);
243 samples= s->blocksize >> rice_order;
244 if (pred_order > samples) {
245 av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
246 pred_order, samples);
252 for (partition = 0; partition < (1 << rice_order); partition++) {
253 tmp = get_bits(&s->gb, method_type == 0 ? 4 : 5);
254 if (tmp == (method_type == 0 ? 15 : 31)) {
255 tmp = get_bits(&s->gb, 5);
256 for (; i < samples; i++, sample++)
257 s->decoded[channel][sample] = get_sbits(&s->gb, tmp);
259 for (; i < samples; i++, sample++) {
260 s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
269 static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)
271 const int blocksize = s->blocksize;
272 int32_t *decoded = s->decoded[channel];
275 /* warm up samples */
276 for (i = 0; i < pred_order; i++) {
277 decoded[i] = get_sbits(&s->gb, s->curr_bps);
280 if (decode_residuals(s, channel, pred_order) < 0)
284 a = decoded[pred_order-1];
286 b = a - decoded[pred_order-2];
288 c = b - decoded[pred_order-2] + decoded[pred_order-3];
290 d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
292 switch (pred_order) {
296 for (i = pred_order; i < blocksize; i++)
297 decoded[i] = a += decoded[i];
300 for (i = pred_order; i < blocksize; i++)
301 decoded[i] = a += b += decoded[i];
304 for (i = pred_order; i < blocksize; i++)
305 decoded[i] = a += b += c += decoded[i];
308 for (i = pred_order; i < blocksize; i++)
309 decoded[i] = a += b += c += d += decoded[i];
312 av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);
319 static int decode_subframe_lpc(FLACContext *s, int channel, int pred_order)
322 int coeff_prec, qlevel;
323 int coeffs[pred_order];
324 int32_t *decoded = s->decoded[channel];
326 /* warm up samples */
327 for (i = 0; i < pred_order; i++) {
328 decoded[i] = get_sbits(&s->gb, s->curr_bps);
331 coeff_prec = get_bits(&s->gb, 4) + 1;
332 if (coeff_prec == 16) {
333 av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
336 qlevel = get_sbits(&s->gb, 5);
338 av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
343 for (i = 0; i < pred_order; i++) {
344 coeffs[i] = get_sbits(&s->gb, coeff_prec);
347 if (decode_residuals(s, channel, pred_order) < 0)
352 for (i = pred_order; i < s->blocksize; i++) {
354 for (j = 0; j < pred_order; j++)
355 sum += (int64_t)coeffs[j] * decoded[i-j-1];
356 decoded[i] += sum >> qlevel;
359 for (i = pred_order; i < s->blocksize-1; i += 2) {
361 int d = decoded[i-pred_order];
363 for (j = pred_order-1; j > 0; j--) {
371 d = decoded[i] += s0 >> qlevel;
373 decoded[i+1] += s1 >> qlevel;
375 if (i < s->blocksize) {
377 for (j = 0; j < pred_order; j++)
378 sum += coeffs[j] * decoded[i-j-1];
379 decoded[i] += sum >> qlevel;
386 static inline int decode_subframe(FLACContext *s, int channel)
388 int type, wasted = 0;
391 s->curr_bps = s->bps;
393 if (s->decorrelation == RIGHT_SIDE)
396 if (s->decorrelation == LEFT_SIDE || s->decorrelation == MID_SIDE)
400 if (get_bits1(&s->gb)) {
401 av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
404 type = get_bits(&s->gb, 6);
406 if (get_bits1(&s->gb)) {
408 while (!get_bits1(&s->gb))
410 s->curr_bps -= wasted;
413 //FIXME use av_log2 for types
415 tmp = get_sbits(&s->gb, s->curr_bps);
416 for (i = 0; i < s->blocksize; i++)
417 s->decoded[channel][i] = tmp;
418 } else if (type == 1) {
419 for (i = 0; i < s->blocksize; i++)
420 s->decoded[channel][i] = get_sbits(&s->gb, s->curr_bps);
421 } else if ((type >= 8) && (type <= 12)) {
422 if (decode_subframe_fixed(s, channel, type & ~0x8) < 0)
424 } else if (type >= 32) {
425 if (decode_subframe_lpc(s, channel, (type & ~0x20)+1) < 0)
428 av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
434 for (i = 0; i < s->blocksize; i++)
435 s->decoded[channel][i] <<= wasted;
441 static int decode_frame(FLACContext *s, int alloc_data_size)
443 int blocksize_code, sample_rate_code, sample_size_code, assignment, i, crc8;
444 int decorrelation, bps, blocksize, samplerate;
446 blocksize_code = get_bits(&s->gb, 4);
448 sample_rate_code = get_bits(&s->gb, 4);
450 assignment = get_bits(&s->gb, 4); /* channel assignment */
451 if (assignment < 8 && s->channels == assignment+1)
452 decorrelation = INDEPENDENT;
453 else if (assignment >=8 && assignment < 11 && s->channels == 2)
454 decorrelation = LEFT_SIDE + assignment - 8;
456 av_log(s->avctx, AV_LOG_ERROR, "unsupported channel assignment %d (channels=%d)\n",
457 assignment, s->channels);
461 sample_size_code = get_bits(&s->gb, 3);
462 if (sample_size_code == 0)
464 else if ((sample_size_code != 3) && (sample_size_code != 7))
465 bps = sample_size_table[sample_size_code];
467 av_log(s->avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",
472 if (get_bits1(&s->gb)) {
473 av_log(s->avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");
477 if (get_utf8(&s->gb) < 0) {
478 av_log(s->avctx, AV_LOG_ERROR, "utf8 fscked\n");
482 if (blocksize_code == 0)
483 blocksize = s->min_blocksize;
484 else if (blocksize_code == 6)
485 blocksize = get_bits(&s->gb, 8)+1;
486 else if (blocksize_code == 7)
487 blocksize = get_bits(&s->gb, 16)+1;
489 blocksize = blocksize_table[blocksize_code];
491 if (blocksize > s->max_blocksize) {
492 av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", blocksize,
497 if (blocksize * s->channels * sizeof(int16_t) > alloc_data_size)
500 if (sample_rate_code == 0)
501 samplerate= s->samplerate;
502 else if (sample_rate_code < 12)
503 samplerate = sample_rate_table[sample_rate_code];
504 else if (sample_rate_code == 12)
505 samplerate = get_bits(&s->gb, 8) * 1000;
506 else if (sample_rate_code == 13)
507 samplerate = get_bits(&s->gb, 16);
508 else if (sample_rate_code == 14)
509 samplerate = get_bits(&s->gb, 16) * 10;
511 av_log(s->avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",
516 skip_bits(&s->gb, 8);
517 crc8 = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
518 s->gb.buffer, get_bits_count(&s->gb)/8);
520 av_log(s->avctx, AV_LOG_ERROR, "header crc mismatch crc=%2X\n", crc8);
524 s->blocksize = blocksize;
525 s->samplerate = samplerate;
527 s->decorrelation= decorrelation;
529 // dump_headers(s->avctx, (FLACStreaminfo *)s);
532 for (i = 0; i < s->channels; i++) {
533 if (decode_subframe(s, i) < 0)
537 align_get_bits(&s->gb);
540 skip_bits(&s->gb, 16); /* data crc */
545 static int flac_decode_frame(AVCodecContext *avctx,
546 void *data, int *data_size,
547 const uint8_t *buf, int buf_size)
549 FLACContext *s = avctx->priv_data;
550 int tmp = 0, i, j = 0, input_buf_size = 0;
551 int16_t *samples = data;
552 int alloc_data_size= *data_size;
556 if (s->max_framesize == 0) {
557 s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header
558 s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
561 if (1 && s->max_framesize) { //FIXME truncated
562 if (s->bitstream_size < 4 || AV_RL32(s->bitstream) != MKTAG('f','L','a','C'))
563 buf_size= FFMIN(buf_size, s->max_framesize - FFMIN(s->bitstream_size, s->max_framesize));
564 input_buf_size= buf_size;
566 if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)
569 if (s->allocated_bitstream_size < s->bitstream_size + buf_size)
570 s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->bitstream_size + buf_size);
572 if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {
573 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
575 s->bitstream_index=0;
577 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],
579 buf= &s->bitstream[s->bitstream_index];
580 buf_size += s->bitstream_size;
581 s->bitstream_size= buf_size;
583 if (buf_size < s->max_framesize && input_buf_size) {
584 return input_buf_size;
588 init_get_bits(&s->gb, buf, buf_size*8);
590 if (metadata_parse(s))
593 tmp = show_bits(&s->gb, 16);
594 if ((tmp & 0xFFFE) != 0xFFF8) {
595 av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");
596 while (get_bits_count(&s->gb)/8+2 < buf_size && (show_bits(&s->gb, 16) & 0xFFFE) != 0xFFF8)
597 skip_bits(&s->gb, 8);
598 goto end; // we may not have enough bits left to decode a frame, so try next time
600 skip_bits(&s->gb, 16);
601 if (decode_frame(s, alloc_data_size) < 0) {
602 av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
604 s->bitstream_index=0;
608 #define DECORRELATE(left, right)\
609 assert(s->channels == 2);\
610 for (i = 0; i < s->blocksize; i++) {\
611 int a= s->decoded[0][i];\
612 int b= s->decoded[1][i];\
613 *samples++ = ((left) << (24 - s->bps)) >> 8;\
614 *samples++ = ((right) << (24 - s->bps)) >> 8;\
618 switch (s->decorrelation) {
620 for (j = 0; j < s->blocksize; j++) {
621 for (i = 0; i < s->channels; i++)
622 *samples++ = (s->decoded[i][j] << (24 - s->bps)) >> 8;
630 DECORRELATE( (a-=b>>1) + b, a)
633 *data_size = (int8_t *)samples - (int8_t *)data;
636 i= (get_bits_count(&s->gb)+7)/8;
638 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
640 s->bitstream_index=0;
644 if (s->bitstream_size) {
645 s->bitstream_index += i;
646 s->bitstream_size -= i;
647 return input_buf_size;
652 static av_cold int flac_decode_close(AVCodecContext *avctx)
654 FLACContext *s = avctx->priv_data;
657 for (i = 0; i < s->channels; i++) {
658 av_freep(&s->decoded[i]);
660 av_freep(&s->bitstream);
665 static void flac_flush(AVCodecContext *avctx)
667 FLACContext *s = avctx->priv_data;
670 s->bitstream_index= 0;
673 AVCodec flac_decoder = {
684 .long_name= NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),