Statistics
| Branch: | Revision:

ffmpeg / libavcodec / flacdec.c @ 8d1e885f

History | View | Annotate | Download (23.4 KB)

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