flacdec.c 23.2 KB
Newer Older
1 2 3 4
/*
 * FLAC (Free Lossless Audio Codec) decoder
 * Copyright (c) 2003 Alex Beregszaszi
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * 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 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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 25
 * FLAC (Free Lossless Audio Codec) decoder
 * @author Alex Beregszaszi
26 27 28 29 30 31 32 33
 *
 * For more information on the FLAC format, visit:
 *  http://flac.sourceforge.net/
 *
 * This decoder can be used in 1 of 2 ways: Either raw FLAC data can be fed
 * through, starting from the initial 'fLaC' signature; or by passing the
 * 34-byte streaminfo structure through avctx->extradata[_size] followed
 * by data starting with the 0xFFF8 marker.
34
 */
35

M
Michael Niedermayer 已提交
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
#include "flacdata.h"
46

M
Michael Niedermayer 已提交
47 48 49
#undef NDEBUG
#include <assert.h>

50
typedef struct FLACContext {
51 52
    FLACSTREAMINFO

53 54
    AVCodecContext *avctx;                  ///< parent AVCodecContext
    GetBitContext gb;                       ///< GetBitContext initialized to start at the current frame
55

56 57
    int blocksize;                          ///< number of samples in the current frame
    int curr_bps;                           ///< bps for current subframe, adjusted for channel correlation and wasted bits
58 59
    int sample_shift;                       ///< shift required to make output samples 16-bit or 32-bit
    int is32;                               ///< flag to indicate if output should be 32-bit instead of 16-bit
60
    int ch_mode;                            ///< channel decorrelation type in the current frame
61
    int got_streaminfo;                     ///< indicates if the STREAMINFO has been read
62

63
    int32_t *decoded[FLAC_MAX_CHANNELS];    ///< decoded samples
M
Michael Niedermayer 已提交
64
    uint8_t *bitstream;
65 66
    unsigned int bitstream_size;
    unsigned int bitstream_index;
67
    unsigned int allocated_bitstream_size;
68 69
} FLACContext;

S
Stefan Gehrer 已提交
70
static const int sample_size_table[] =
71 72
{ 0, 8, 12, 0, 16, 20, 24, 0 };

73 74
static int64_t get_utf8(GetBitContext *gb)
{
75 76
    int64_t val;
    GET_UTF8(val, get_bits(gb, 8), return -1;)
M
Michael Niedermayer 已提交
77
    return val;
78 79
}

80
static void allocate_buffers(FLACContext *s);
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

int ff_flac_is_extradata_valid(AVCodecContext *avctx,
                               enum FLACExtradataFormat *format,
                               uint8_t **streaminfo_start)
{
    if (!avctx->extradata || avctx->extradata_size < FLAC_STREAMINFO_SIZE) {
        av_log(avctx, AV_LOG_ERROR, "extradata NULL or too small.\n");
        return 0;
    }
    if (AV_RL32(avctx->extradata) != MKTAG('f','L','a','C')) {
        /* extradata contains STREAMINFO only */
        if (avctx->extradata_size != FLAC_STREAMINFO_SIZE) {
            av_log(avctx, AV_LOG_WARNING, "extradata contains %d bytes too many.\n",
                   FLAC_STREAMINFO_SIZE-avctx->extradata_size);
        }
        *format = FLAC_EXTRADATA_FORMAT_STREAMINFO;
        *streaminfo_start = avctx->extradata;
    } else {
        if (avctx->extradata_size < 8+FLAC_STREAMINFO_SIZE) {
            av_log(avctx, AV_LOG_ERROR, "extradata too small.\n");
            return 0;
        }
        *format = FLAC_EXTRADATA_FORMAT_FULL_HEADER;
        *streaminfo_start = &avctx->extradata[8];
    }
    return 1;
}
108

109
static av_cold int flac_decode_init(AVCodecContext *avctx)
110
{
111 112
    enum FLACExtradataFormat format;
    uint8_t *streaminfo;
113 114 115
    FLACContext *s = avctx->priv_data;
    s->avctx = avctx;

116 117
    avctx->sample_fmt = SAMPLE_FMT_S16;

118 119 120 121 122 123 124 125
    /* for now, the raw FLAC header is allowed to be passed to the decoder as
       frame data instead of extradata. */
    if (!avctx->extradata)
        return 0;

    if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
        return -1;

126 127 128
    /* initialize based on the demuxer-supplied streamdata header */
    ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
    allocate_buffers(s);
129
    s->got_streaminfo = 1;
130

131 132 133
    return 0;
}

134
static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
135
{
136
    av_log(avctx, AV_LOG_DEBUG, "  Max Blocksize: %d\n", s->max_blocksize);
137 138 139 140
    av_log(avctx, AV_LOG_DEBUG, "  Max Framesize: %d\n", s->max_framesize);
    av_log(avctx, AV_LOG_DEBUG, "  Samplerate: %d\n", s->samplerate);
    av_log(avctx, AV_LOG_DEBUG, "  Channels: %d\n", s->channels);
    av_log(avctx, AV_LOG_DEBUG, "  Bits: %d\n", s->bps);
141 142
}

143 144
static void allocate_buffers(FLACContext *s)
{
145 146
    int i;

M
Michael Niedermayer 已提交
147 148
    assert(s->max_blocksize);

149
    if (s->max_framesize == 0 && s->max_blocksize) {
150 151
        // FIXME header overhead
        s->max_framesize= (s->channels * s->bps * s->max_blocksize + 7)/ 8;
M
Michael Niedermayer 已提交
152 153
    }

154
    for (i = 0; i < s->channels; i++) {
155 156
        s->decoded[i] = av_realloc(s->decoded[i],
                                   sizeof(int32_t)*s->max_blocksize);
M
Michael Niedermayer 已提交
157 158
    }

159
    if (s->allocated_bitstream_size < s->max_framesize)
160 161 162
        s->bitstream= av_fast_realloc(s->bitstream,
                                      &s->allocated_bitstream_size,
                                      s->max_framesize);
M
Michael Niedermayer 已提交
163 164
}

165 166
void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
                              const uint8_t *buffer)
M
Michael Niedermayer 已提交
167
{
168 169 170
    GetBitContext gb;
    init_get_bits(&gb, buffer, FLAC_STREAMINFO_SIZE*8);

171
    skip_bits(&gb, 16); /* skip min blocksize */
172
    s->max_blocksize = get_bits(&gb, 16);
173
    if (s->max_blocksize < FLAC_MIN_BLOCKSIZE) {
174 175 176 177
        av_log(avctx, AV_LOG_WARNING, "invalid max blocksize: %d\n",
               s->max_blocksize);
        s->max_blocksize = 16;
    }
178

179 180
    skip_bits(&gb, 24); /* skip min frame size */
    s->max_framesize = get_bits_long(&gb, 24);
181

182 183 184
    s->samplerate = get_bits_long(&gb, 20);
    s->channels = get_bits(&gb, 3) + 1;
    s->bps = get_bits(&gb, 5) + 1;
185

186 187
    avctx->channels = s->channels;
    avctx->sample_rate = s->samplerate;
188 189 190 191 192
    avctx->bits_per_raw_sample = s->bps;
    if (s->bps > 16)
        avctx->sample_fmt = SAMPLE_FMT_S32;
    else
        avctx->sample_fmt = SAMPLE_FMT_S16;
193

194
    s->samples  = get_bits_long(&gb, 32) << 4;
195
    s->samples |= get_bits(&gb, 4);
196

197 198
    skip_bits_long(&gb, 64); /* md5 sum */
    skip_bits_long(&gb, 64); /* md5 sum */
199

200
    dump_headers(avctx, s);
201 202
}

203 204 205 206 207 208 209 210 211 212 213 214
void ff_flac_parse_block_header(const uint8_t *block_header,
                                int *last, int *type, int *size)
{
    int tmp = bytestream_get_byte(&block_header);
    if (last)
        *last = tmp & 0x80;
    if (type)
        *type = tmp & 0x7F;
    if (size)
        *size = bytestream_get_be24(&block_header);
}

215
/**
216 217 218 219
 * Parse the STREAMINFO from an inline header.
 * @param s the flac decoding context
 * @param buf input buffer, starting with the "fLaC" marker
 * @param buf_size buffer size
220
 * @return non-zero if metadata is invalid
221
 */
222
static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
223
{
224
    int metadata_type, metadata_size;
225

226 227 228 229
    if (buf_size < FLAC_STREAMINFO_SIZE+8) {
        /* need more data */
        return 0;
    }
230
    ff_flac_parse_block_header(&buf[4], NULL, &metadata_type, &metadata_size);
231 232 233 234
    if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
        metadata_size != FLAC_STREAMINFO_SIZE) {
        return AVERROR_INVALIDDATA;
    }
235
    ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, &buf[8]);
236 237
    allocate_buffers(s);
    s->got_streaminfo = 1;
238

239 240
    return 0;
}
241

242 243 244 245 246 247 248 249 250 251
/**
 * Determine the size of an inline header.
 * @param buf input buffer, starting with the "fLaC" marker
 * @param buf_size buffer size
 * @return number of bytes in the header, or 0 if more data is needed
 */
static int get_metadata_size(const uint8_t *buf, int buf_size)
{
    int metadata_last, metadata_size;
    const uint8_t *buf_end = buf + buf_size;
252

253 254
    buf += 4;
    do {
255 256
        ff_flac_parse_block_header(buf, &metadata_last, NULL, &metadata_size);
        buf += 4;
257 258 259
        if (buf + metadata_size > buf_end) {
            /* need more data in order to read the complete header */
            return 0;
260
        }
261
        buf += metadata_size;
262
    } while (!metadata_last);
263

264
    return buf_size - (buf_end - buf);
265 266 267 268 269 270 271 272
}

static int decode_residuals(FLACContext *s, int channel, int pred_order)
{
    int i, tmp, partition, method_type, rice_order;
    int sample = 0, samples;

    method_type = get_bits(&s->gb, 2);
273
    if (method_type > 1) {
274 275
        av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
               method_type);
276
        return -1;
M
Michael Niedermayer 已提交
277
    }
278

279 280
    rice_order = get_bits(&s->gb, 4);

M
Michael Niedermayer 已提交
281
    samples= s->blocksize >> rice_order;
282
    if (pred_order > samples) {
283 284
        av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
               pred_order, samples);
285 286
        return -1;
    }
287

288
    sample=
M
Michael Niedermayer 已提交
289
    i= pred_order;
290
    for (partition = 0; partition < (1 << rice_order); partition++) {
291
        tmp = get_bits(&s->gb, method_type == 0 ? 4 : 5);
292
        if (tmp == (method_type == 0 ? 15 : 31)) {
293 294
            tmp = get_bits(&s->gb, 5);
            for (; i < samples; i++, sample++)
295
                s->decoded[channel][sample] = get_sbits_long(&s->gb, tmp);
296 297
        } else {
            for (; i < samples; i++, sample++) {
298
                s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
M
Michael Niedermayer 已提交
299
            }
300
        }
M
Michael Niedermayer 已提交
301
        i= 0;
302 303 304
    }

    return 0;
305
}
306 307 308

static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)
{
309 310
    const int blocksize = s->blocksize;
    int32_t *decoded = s->decoded[channel];
311
    int av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d), i;
312

313
    /* warm up samples */
314
    for (i = 0; i < pred_order; i++) {
315
        decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
316
    }
317

318 319 320
    if (decode_residuals(s, channel, pred_order) < 0)
        return -1;

321
    if (pred_order > 0)
R
Indent.  
Ramiro Polla 已提交
322
        a = decoded[pred_order-1];
323
    if (pred_order > 1)
R
Indent.  
Ramiro Polla 已提交
324
        b = a - decoded[pred_order-2];
325
    if (pred_order > 2)
R
Indent.  
Ramiro Polla 已提交
326
        c = b - decoded[pred_order-2] + decoded[pred_order-3];
327
    if (pred_order > 3)
R
Indent.  
Ramiro Polla 已提交
328
        d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    switch (pred_order) {
    case 0:
        break;
    case 1:
        for (i = pred_order; i < blocksize; i++)
            decoded[i] = a += decoded[i];
        break;
    case 2:
        for (i = pred_order; i < blocksize; i++)
            decoded[i] = a += b += decoded[i];
        break;
    case 3:
        for (i = pred_order; i < blocksize; i++)
            decoded[i] = a += b += c += decoded[i];
        break;
    case 4:
        for (i = pred_order; i < blocksize; i++)
            decoded[i] = a += b += c += d += decoded[i];
        break;
    default:
        av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);
        return -1;
352
    }
M
Michael Niedermayer 已提交
353

354 355 356 357 358
    return 0;
}

static int decode_subframe_lpc(FLACContext *s, int channel, int pred_order)
{
359
    int i, j;
360 361
    int coeff_prec, qlevel;
    int coeffs[pred_order];
362
    int32_t *decoded = s->decoded[channel];
363

364
    /* warm up samples */
365
    for (i = 0; i < pred_order; i++) {
366
        decoded[i] = get_sbits_long(&s->gb, s->curr_bps);
367
    }
368

369
    coeff_prec = get_bits(&s->gb, 4) + 1;
370
    if (coeff_prec == 16) {
371
        av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
372 373
        return -1;
    }
M
Michael Niedermayer 已提交
374
    qlevel = get_sbits(&s->gb, 5);
375
    if (qlevel < 0) {
376 377
        av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
               qlevel);
378 379 380
        return -1;
    }

381
    for (i = 0; i < pred_order; i++) {
M
Michael Niedermayer 已提交
382
        coeffs[i] = get_sbits(&s->gb, coeff_prec);
383
    }
384

385 386 387
    if (decode_residuals(s, channel, pred_order) < 0)
        return -1;

388 389
    if (s->bps > 16) {
        int64_t sum;
390
        for (i = pred_order; i < s->blocksize; i++) {
391 392
            sum = 0;
            for (j = 0; j < pred_order; j++)
393 394
                sum += (int64_t)coeffs[j] * decoded[i-j-1];
            decoded[i] += sum >> qlevel;
395 396
        }
    } else {
397
        for (i = pred_order; i < s->blocksize-1; i += 2) {
398 399 400
            int c;
            int d = decoded[i-pred_order];
            int s0 = 0, s1 = 0;
401
            for (j = pred_order-1; j > 0; j--) {
402
                c = coeffs[j];
L
Loren Merritt 已提交
403
                s0 += c*d;
404 405
                d = decoded[i-j];
                s1 += c*d;
L
Loren Merritt 已提交
406
            }
407 408 409 410 411
            c = coeffs[0];
            s0 += c*d;
            d = decoded[i] += s0 >> qlevel;
            s1 += c*d;
            decoded[i+1] += s1 >> qlevel;
L
Loren Merritt 已提交
412
        }
413
        if (i < s->blocksize) {
L
Loren Merritt 已提交
414
            int sum = 0;
415
            for (j = 0; j < pred_order; j++)
416 417
                sum += coeffs[j] * decoded[i-j-1];
            decoded[i] += sum >> qlevel;
418
        }
419
    }
420

421 422 423 424 425 426 427
    return 0;
}

static inline int decode_subframe(FLACContext *s, int channel)
{
    int type, wasted = 0;
    int i, tmp;
428

429
    s->curr_bps = s->bps;
430
    if (channel == 0) {
431
        if (s->ch_mode == FLAC_CHMODE_RIGHT_SIDE)
M
Michael Niedermayer 已提交
432
            s->curr_bps++;
433
    } else {
434
        if (s->ch_mode == FLAC_CHMODE_LEFT_SIDE || s->ch_mode == FLAC_CHMODE_MID_SIDE)
M
Michael Niedermayer 已提交
435 436 437
            s->curr_bps++;
    }

438
    if (get_bits1(&s->gb)) {
439
        av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
440 441 442
        return -1;
    }
    type = get_bits(&s->gb, 6);
443

444
    if (get_bits1(&s->gb)) {
445 446 447 448 449
        wasted = 1;
        while (!get_bits1(&s->gb))
            wasted++;
        s->curr_bps -= wasted;
    }
450 451 452 453
    if (s->curr_bps > 32) {
        ff_log_missing_feature(s->avctx, "decorrelated bit depth > 32", 0);
        return -1;
    }
454

M
Michael Niedermayer 已提交
455
//FIXME use av_log2 for types
456
    if (type == 0) {
457
        tmp = get_sbits_long(&s->gb, s->curr_bps);
458 459
        for (i = 0; i < s->blocksize; i++)
            s->decoded[channel][i] = tmp;
460
    } else if (type == 1) {
461
        for (i = 0; i < s->blocksize; i++)
462
            s->decoded[channel][i] = get_sbits_long(&s->gb, s->curr_bps);
463
    } else if ((type >= 8) && (type <= 12)) {
464 465
        if (decode_subframe_fixed(s, channel, type & ~0x8) < 0)
            return -1;
466
    } else if (type >= 32) {
467 468
        if (decode_subframe_lpc(s, channel, (type & ~0x20)+1) < 0)
            return -1;
469
    } else {
470
        av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
471 472
        return -1;
    }
473

474
    if (wasted) {
475 476 477 478 479 480 481 482
        int i;
        for (i = 0; i < s->blocksize; i++)
            s->decoded[channel][i] <<= wasted;
    }

    return 0;
}

M
Michael Niedermayer 已提交
483
static int decode_frame(FLACContext *s, int alloc_data_size)
484
{
485
    int blocksize_code, sample_rate_code, sample_size_code, i, crc8;
486
    int ch_mode, bps, blocksize, samplerate;
487

488 489 490
    blocksize_code = get_bits(&s->gb, 4);

    sample_rate_code = get_bits(&s->gb, 4);
491

492 493
    ch_mode = get_bits(&s->gb, 4); /* channel assignment */
    if (ch_mode < FLAC_MAX_CHANNELS && s->channels == ch_mode+1) {
494
        ch_mode = FLAC_CHMODE_INDEPENDENT;
495
    } else if (ch_mode > FLAC_CHMODE_MID_SIDE || s->channels != 2) {
496
        av_log(s->avctx, AV_LOG_ERROR, "unsupported channel assignment %d (channels=%d)\n",
497
               ch_mode, s->channels);
498 499
        return -1;
    }
500

501
    sample_size_code = get_bits(&s->gb, 3);
502
    if (sample_size_code == 0)
M
Michael Niedermayer 已提交
503
        bps= s->bps;
504
    else if ((sample_size_code != 3) && (sample_size_code != 7))
M
Michael Niedermayer 已提交
505
        bps = sample_size_table[sample_size_code];
506
    else {
507 508
        av_log(s->avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",
               sample_size_code);
509 510
        return -1;
    }
511 512 513 514 515 516 517 518 519 520
    if (bps > 16) {
        s->avctx->sample_fmt = SAMPLE_FMT_S32;
        s->sample_shift = 32 - bps;
        s->is32 = 1;
    } else {
        s->avctx->sample_fmt = SAMPLE_FMT_S16;
        s->sample_shift = 16 - bps;
        s->is32 = 0;
    }
    s->bps = s->avctx->bits_per_raw_sample = bps;
521

522
    if (get_bits1(&s->gb)) {
523
        av_log(s->avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");
M
Michael Niedermayer 已提交
524
        return -1;
525
    }
526

527
    if (get_utf8(&s->gb) < 0) {
M
Michael Niedermayer 已提交
528 529 530
        av_log(s->avctx, AV_LOG_ERROR, "utf8 fscked\n");
        return -1;
    }
531

532 533 534 535
    if (blocksize_code == 0) {
        av_log(s->avctx, AV_LOG_ERROR, "reserved blocksize code: 0\n");
        return -1;
    } else if (blocksize_code == 6)
M
Michael Niedermayer 已提交
536
        blocksize = get_bits(&s->gb, 8)+1;
M
Michael Niedermayer 已提交
537
    else if (blocksize_code == 7)
M
Michael Niedermayer 已提交
538
        blocksize = get_bits(&s->gb, 16)+1;
539
    else
540
        blocksize = ff_flac_blocksize_table[blocksize_code];
541

542
    if (blocksize > s->max_blocksize) {
543 544
        av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", blocksize,
               s->max_blocksize);
M
Michael Niedermayer 已提交
545 546 547
        return -1;
    }

548
    if (blocksize * s->channels * (s->is32 ? 4 : 2) > alloc_data_size)
M
Michael Niedermayer 已提交
549 550
        return -1;

551
    if (sample_rate_code == 0)
M
Michael Niedermayer 已提交
552
        samplerate= s->samplerate;
553
    else if (sample_rate_code < 12)
554
        samplerate = ff_flac_sample_rate_table[sample_rate_code];
M
Michael Niedermayer 已提交
555
    else if (sample_rate_code == 12)
M
Michael Niedermayer 已提交
556
        samplerate = get_bits(&s->gb, 8) * 1000;
M
Michael Niedermayer 已提交
557
    else if (sample_rate_code == 13)
M
Michael Niedermayer 已提交
558
        samplerate = get_bits(&s->gb, 16);
M
Michael Niedermayer 已提交
559
    else if (sample_rate_code == 14)
M
Michael Niedermayer 已提交
560
        samplerate = get_bits(&s->gb, 16) * 10;
561
    else {
562 563
        av_log(s->avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",
               sample_rate_code);
M
Michael Niedermayer 已提交
564
        return -1;
565 566
    }

567
    skip_bits(&s->gb, 8);
A
Aurelien Jacobs 已提交
568 569
    crc8 = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
                  s->gb.buffer, get_bits_count(&s->gb)/8);
570
    if (crc8) {
571
        av_log(s->avctx, AV_LOG_ERROR, "header crc mismatch crc=%2X\n", crc8);
572 573
        return -1;
    }
574

M
Michael Niedermayer 已提交
575 576 577
    s->blocksize    = blocksize;
    s->samplerate   = samplerate;
    s->bps          = bps;
578
    s->ch_mode      = ch_mode;
579

580
//    dump_headers(s->avctx, (FLACStreaminfo *)s);
581 582

    /* subframes */
583
    for (i = 0; i < s->channels; i++) {
584 585 586
        if (decode_subframe(s, i) < 0)
            return -1;
    }
587

588 589 590 591 592 593 594 595 596 597
    align_get_bits(&s->gb);

    /* frame footer */
    skip_bits(&s->gb, 16); /* data crc */

    return 0;
}

static int flac_decode_frame(AVCodecContext *avctx,
                            void *data, int *data_size,
M
const  
Michael Niedermayer 已提交
598
                            const uint8_t *buf, int buf_size)
599 600
{
    FLACContext *s = avctx->priv_data;
601
    int i, j = 0, input_buf_size = 0, bytes_read = 0;
602 603
    int16_t *samples_16 = data;
    int32_t *samples_32 = data;
M
Michael Niedermayer 已提交
604 605 606
    int alloc_data_size= *data_size;

    *data_size=0;
607

608
    if (s->max_framesize == 0) {
609
        s->max_framesize= FFMAX(4, buf_size); // should hopefully be enough for the first header
M
Michael Niedermayer 已提交
610 611 612
        s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
    }

613
    if (1 && s->max_framesize) { //FIXME truncated
J
Justin Ruggles 已提交
614 615 616
        if (s->bitstream_size < 4 || AV_RL32(s->bitstream) != MKTAG('f','L','a','C'))
            buf_size= FFMIN(buf_size, s->max_framesize - FFMIN(s->bitstream_size, s->max_framesize));
        input_buf_size= buf_size;
M
Michael Niedermayer 已提交
617

J
Justin Ruggles 已提交
618 619
        if (s->bitstream_size + buf_size < buf_size || s->bitstream_index + s->bitstream_size + buf_size < s->bitstream_index)
            return -1;
620

J
Justin Ruggles 已提交
621 622
        if (s->allocated_bitstream_size < s->bitstream_size + buf_size)
            s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->bitstream_size + buf_size);
623

J
Justin Ruggles 已提交
624
        if (s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size) {
625 626
            memmove(s->bitstream, &s->bitstream[s->bitstream_index],
                    s->bitstream_size);
J
Justin Ruggles 已提交
627 628
            s->bitstream_index=0;
        }
629 630
        memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size],
               buf, buf_size);
J
Justin Ruggles 已提交
631 632 633
        buf= &s->bitstream[s->bitstream_index];
        buf_size += s->bitstream_size;
        s->bitstream_size= buf_size;
634

J
Justin Ruggles 已提交
635 636 637
        if (buf_size < s->max_framesize && input_buf_size) {
            return input_buf_size;
        }
M
Michael Niedermayer 已提交
638
    }
639

640
    /* check that there is at least the smallest decodable amount of data.
641 642
       this amount corresponds to the smallest valid FLAC frame possible.
       FF F8 69 02 00 00 9A 00 00 34 46 */
643
    if (buf_size < 11)
644 645
        goto end;

646
    /* check for inline header */
647 648
    if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
        if (!s->got_streaminfo && parse_streaminfo(s, buf, buf_size)) {
649 650 651
            av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
            return -1;
        }
652
        bytes_read = get_metadata_size(buf, buf_size);
653
        goto end;
654
    }
655

656 657 658
    /* check for frame sync code and resync stream if necessary */
    if ((AV_RB16(buf) & 0xFFFE) != 0xFFF8) {
        const uint8_t *buf_end = buf + buf_size;
J
Justin Ruggles 已提交
659
        av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");
660 661 662 663
        while (buf+2 < buf_end && (AV_RB16(buf) & 0xFFFE) != 0xFFF8)
            buf++;
        bytes_read = buf_size - (buf_end - buf);
        goto end; // we may not have enough bits left to decode a frame, so try next time
J
Justin Ruggles 已提交
664
    }
665 666 667

    /* decode frame */
    init_get_bits(&s->gb, buf, buf_size*8);
J
Justin Ruggles 已提交
668
    skip_bits(&s->gb, 16);
669
    if (decode_frame(s, alloc_data_size) < 0) {
J
Justin Ruggles 已提交
670 671 672 673 674
        av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
        s->bitstream_size=0;
        s->bitstream_index=0;
        return -1;
    }
675 676
    *data_size = s->blocksize * s->channels * (s->is32 ? 4 : 2);
    bytes_read = (get_bits_count(&s->gb)+7)/8;
M
Michael Niedermayer 已提交
677

678 679
#define DECORRELATE(left, right)\
            assert(s->channels == 2);\
680
            for (i = 0; i < s->blocksize; i++) {\
681 682
                int a= s->decoded[0][i];\
                int b= s->decoded[1][i];\
683 684 685 686 687 688 689
                if (s->is32) {\
                    *samples_32++ = (left)  << s->sample_shift;\
                    *samples_32++ = (right) << s->sample_shift;\
                } else {\
                    *samples_16++ = (left)  << s->sample_shift;\
                    *samples_16++ = (right) << s->sample_shift;\
                }\
690 691 692
            }\
            break;

693
    switch (s->ch_mode) {
694
    case FLAC_CHMODE_INDEPENDENT:
695
        for (j = 0; j < s->blocksize; j++) {
696 697 698 699 700 701
            for (i = 0; i < s->channels; i++) {
                if (s->is32)
                    *samples_32++ = s->decoded[i][j] << s->sample_shift;
                else
                    *samples_16++ = s->decoded[i][j] << s->sample_shift;
            }
702 703
        }
        break;
704
    case FLAC_CHMODE_LEFT_SIDE:
705
        DECORRELATE(a,a-b)
706
    case FLAC_CHMODE_RIGHT_SIDE:
707
        DECORRELATE(a+b,b)
708
    case FLAC_CHMODE_MID_SIDE:
709
        DECORRELATE( (a-=b>>1) + b, a)
710 711
    }

712
end:
713 714
    if (bytes_read > buf_size) {
        av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
715 716
        s->bitstream_size=0;
        s->bitstream_index=0;
M
Michael Niedermayer 已提交
717 718
        return -1;
    }
719

720
    if (s->bitstream_size) {
721 722
        s->bitstream_index += bytes_read;
        s->bitstream_size  -= bytes_read;
M
Michael Niedermayer 已提交
723
        return input_buf_size;
724
    } else
725
        return bytes_read;
726 727
}

728
static av_cold int flac_decode_close(AVCodecContext *avctx)
729 730 731
{
    FLACContext *s = avctx->priv_data;
    int i;
732

733
    for (i = 0; i < s->channels; i++) {
M
Michael Niedermayer 已提交
734
        av_freep(&s->decoded[i]);
735
    }
M
Michael Niedermayer 已提交
736
    av_freep(&s->bitstream);
737

738 739 740
    return 0;
}

741 742
static void flac_flush(AVCodecContext *avctx)
{
M
Michael Niedermayer 已提交
743 744 745 746 747 748
    FLACContext *s = avctx->priv_data;

    s->bitstream_size=
    s->bitstream_index= 0;
}

749 750 751 752 753 754 755 756 757
AVCodec flac_decoder = {
    "flac",
    CODEC_TYPE_AUDIO,
    CODEC_ID_FLAC,
    sizeof(FLACContext),
    flac_decode_init,
    NULL,
    flac_decode_close,
    flac_decode_frame,
758
    CODEC_CAP_DELAY,
759
    .flush= flac_flush,
760
    .long_name= NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
761
};