FFmpeg
Loading...
Searching...
No Matches
flacdec.c
Go to the documentation of this file.
1/*
2 * FLAC (Free Lossless Audio Codec) decoder
3 * Copyright (c) 2003 Alex Beregszaszi
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * FLAC (Free Lossless Audio Codec) decoder
25 * @author Alex Beregszaszi
26 * @see http://flac.sourceforge.net/
27 *
28 * This decoder can be used in 1 of 2 ways: Either raw FLAC data can be fed
29 * through, starting from the initial 'fLaC' signature; or by passing the
30 * 34-byte streaminfo structure through avctx->extradata[_size] followed
31 * by data starting with the 0xFFF8 marker.
32 */
33
34#include <limits.h>
35
36#include "libavutil/avassert.h"
37#include "libavutil/crc.h"
38#include "libavutil/mem.h"
39#include "libavutil/opt.h"
40#include "avcodec.h"
41#include "codec_internal.h"
42#include "get_bits.h"
43#include "golomb.h"
44#include "flac.h"
45#include "flacdsp.h"
46#include "flac_parse.h"
47#include "thread.h"
48#include "unary.h"
49
50
51typedef struct FLACContext {
52 AVClass *class;
54
55 AVCodecContext *avctx; ///< parent AVCodecContext
56 GetBitContext gb; ///< GetBitContext initialized to start at the current frame
57
58 int blocksize; ///< number of samples in the current frame
59 int sample_shift; ///< shift required to make output samples 16-bit or 32-bit
60 int ch_mode; ///< channel decorrelation type in the current frame
61 int got_streaminfo; ///< indicates if the STREAMINFO has been read
62 unsigned streaminfo_serial; ///< counts the STREAMINFOs taken from packet side data
63
64 int32_t *decoded[FLAC_MAX_CHANNELS]; ///< decoded samples
66 unsigned int decoded_buffer_size;
67 int64_t *decoded_33bps; ///< decoded samples for a 33 bps subframe
70 int buggy_lpc; ///< use workaround for old lavc encoded files
71
74
75static int allocate_buffers(FLACContext *s);
76
78{
79 enum AVSampleFormat req = s->avctx->request_sample_fmt;
80 int need32 = s->stream_info.bps > 16;
81 int want32 = av_get_bytes_per_sample(req) > 2;
82 int planar = av_sample_fmt_is_planar(req);
83
84 if (need32 || want32) {
85 if (planar)
86 s->avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
87 else
88 s->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
89 s->sample_shift = 32 - s->stream_info.bps;
90 } else {
91 if (planar)
92 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
93 else
94 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
95 s->sample_shift = 16 - s->stream_info.bps;
96 }
97}
98
99/**
100 * Set the decoder up for s->stream_info, which it cannot decode with until the
101 * buffers are allocated.
102 */
104{
105 int ret;
106
107 s->got_streaminfo = 0;
109 if (ret < 0)
110 return ret;
112 ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt,
113 s->stream_info.channels);
114 s->got_streaminfo = 1;
115
116 return 0;
117}
118
119static int apply_streaminfo(FLACContext *s, const uint8_t *streaminfo)
120{
121 FLACStreaminfo stream_info;
122 int ret = ff_flac_parse_streaminfo(s->avctx, &stream_info, streaminfo);
123 if (ret < 0)
124 return ret;
125 s->stream_info = stream_info;
126
127 return setup_streaminfo(s);
128}
129
131{
132 uint8_t *streaminfo;
133 FLACContext *s = avctx->priv_data;
134 s->avctx = avctx;
135
136 /* for now, the raw FLAC header is allowed to be passed to the decoder as
137 frame data instead of extradata. */
138 if (!avctx->extradata)
139 return 0;
140
141 if (!ff_flac_is_extradata_valid(avctx, &streaminfo))
142 return AVERROR_INVALIDDATA;
143
144 /* initialize based on the demuxer-supplied streamdata header */
145 return apply_streaminfo(s, streaminfo);
146}
147
149{
150 av_log(avctx, AV_LOG_DEBUG, " Max Blocksize: %d\n", s->max_blocksize);
151 av_log(avctx, AV_LOG_DEBUG, " Max Framesize: %d\n", s->max_framesize);
152 av_log(avctx, AV_LOG_DEBUG, " Samplerate: %d\n", s->samplerate);
153 av_log(avctx, AV_LOG_DEBUG, " Channels: %d\n", s->channels);
154 av_log(avctx, AV_LOG_DEBUG, " Bits: %d\n", s->bps);
155}
156
158{
159 int buf_size;
160 int ret;
161
162 av_assert0(s->stream_info.max_blocksize);
163
164 buf_size = av_samples_get_buffer_size(NULL, s->stream_info.channels,
165 s->stream_info.max_blocksize,
167 if (buf_size < 0)
168 return buf_size;
169
170 av_fast_malloc(&s->decoded_buffer, &s->decoded_buffer_size, buf_size);
171 if (!s->decoded_buffer)
172 return AVERROR(ENOMEM);
173
174 ret = av_samples_fill_arrays((uint8_t **)s->decoded, NULL,
175 s->decoded_buffer,
176 s->stream_info.channels,
177 s->stream_info.max_blocksize,
179 if (ret >= 0 && s->stream_info.bps == 32 && s->stream_info.channels == 2) {
180 buf_size = av_samples_get_buffer_size(NULL, 1,
181 s->stream_info.max_blocksize,
183 if (buf_size < 0)
184 return buf_size;
185
186 av_fast_malloc(&s->decoded_buffer_33bps, &s->decoded_buffer_size_33bps, buf_size);
187 if (!s->decoded_buffer_33bps)
188 return AVERROR(ENOMEM);
189
190 ret = av_samples_fill_arrays((uint8_t **)&s->decoded_33bps, NULL,
191 s->decoded_buffer_33bps,
192 1,
193 s->stream_info.max_blocksize,
195
196 }
197 return ret < 0 ? ret : 0;
198}
199
200/**
201 * Parse the STREAMINFO from an inline header.
202 * @param s the flac decoding context
203 * @param buf input buffer, starting with the "fLaC" marker
204 * @param buf_size buffer size
205 * @return non-zero if metadata is invalid
206 */
207static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
208{
209 int metadata_type, metadata_size;
210
211 if (buf_size < FLAC_STREAMINFO_SIZE+8) {
212 /* need more data */
213 return 0;
214 }
215 flac_parse_block_header(&buf[4], NULL, &metadata_type, &metadata_size);
216 if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
217 metadata_size != FLAC_STREAMINFO_SIZE) {
218 return AVERROR_INVALIDDATA;
219 }
220 return apply_streaminfo(s, &buf[8]);
221}
222
223/**
224 * Determine the size of an inline header.
225 * @param buf input buffer, starting with the "fLaC" marker
226 * @param buf_size buffer size
227 * @return number of bytes in the header, or 0 if more data is needed
228 */
229static int get_metadata_size(const uint8_t *buf, int buf_size)
230{
231 int metadata_last, metadata_size;
232 const uint8_t *buf_end = buf + buf_size;
233
234 buf += 4;
235 do {
236 if (buf_end - buf < 4)
237 return AVERROR_INVALIDDATA;
238 flac_parse_block_header(buf, &metadata_last, NULL, &metadata_size);
239 buf += 4;
240 if (buf_end - buf < metadata_size) {
241 /* need more data in order to read the complete header */
242 return AVERROR_INVALIDDATA;
243 }
244 buf += metadata_size;
245 } while (!metadata_last);
246
247 return buf_size - (buf_end - buf);
248}
249
250static int decode_residuals(FLACContext *s, int32_t *decoded, int pred_order)
251{
252 GetBitContext gb = s->gb;
253 int i, tmp, partition, method_type, rice_order;
254 int rice_bits, rice_esc;
255 int samples;
256
257 method_type = get_bits(&gb, 2);
258 rice_order = get_bits(&gb, 4);
259
260 samples = s->blocksize >> rice_order;
261 rice_bits = 4 + method_type;
262 rice_esc = (1 << rice_bits) - 1;
263
264 decoded += pred_order;
265 i = pred_order;
266
267 if (method_type > 1) {
268 av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
269 method_type);
270 return AVERROR_INVALIDDATA;
271 }
272
273 if (samples << rice_order != s->blocksize) {
274 av_log(s->avctx, AV_LOG_ERROR, "invalid rice order: %i blocksize %i\n",
275 rice_order, s->blocksize);
276 return AVERROR_INVALIDDATA;
277 }
278
279 if (pred_order > samples) {
280 av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
281 pred_order, samples);
282 return AVERROR_INVALIDDATA;
283 }
284
285 for (partition = 0; partition < (1 << rice_order); partition++) {
286 tmp = get_bits(&gb, rice_bits);
287 if (tmp == rice_esc) {
288 tmp = get_bits(&gb, 5);
289 for (; i < samples; i++)
290 *decoded++ = get_sbits_long(&gb, tmp);
291 } else {
292 int real_limit = (tmp > 1) ? (INT_MAX >> (tmp - 1)) + 2 : INT_MAX;
293 for (; i < samples; i++) {
294 int v = get_sr_golomb_flac(&gb, tmp, real_limit, 1);
295 if (v == 0x80000000){
296 av_log(s->avctx, AV_LOG_ERROR, "invalid residual\n");
297 return AVERROR_INVALIDDATA;
298 }
299
300 *decoded++ = v;
301 }
302 }
303 i= 0;
304 }
305
306 s->gb = gb;
307
308 return 0;
309}
310
312 int pred_order, int bps)
313{
314 const int blocksize = s->blocksize;
315 unsigned av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d);
316 int i;
317 int ret;
318
319 /* warm up samples */
320 for (i = 0; i < pred_order; i++) {
321 decoded[i] = get_sbits_long(&s->gb, bps);
322 }
323
324 if ((ret = decode_residuals(s, decoded, pred_order)) < 0)
325 return ret;
326
327 if (pred_order > 0)
328 a = decoded[pred_order-1];
329 if (pred_order > 1)
330 b = a - decoded[pred_order-2];
331 if (pred_order > 2)
332 c = b - decoded[pred_order-2] + decoded[pred_order-3];
333 if (pred_order > 3)
334 d = c - decoded[pred_order-2] + 2U*decoded[pred_order-3] - decoded[pred_order-4];
335
336 switch (pred_order) {
337 case 0:
338 break;
339 case 1:
340 for (i = pred_order; i < blocksize; i++)
341 decoded[i] = a += decoded[i];
342 break;
343 case 2:
344 for (i = pred_order; i < blocksize; i++)
345 decoded[i] = a += b += decoded[i];
346 break;
347 case 3:
348 for (i = pred_order; i < blocksize; i++)
349 decoded[i] = a += b += c += decoded[i];
350 break;
351 case 4:
352 for (i = pred_order; i < blocksize; i++)
353 decoded[i] = a += b += c += d += decoded[i];
354 break;
355 default:
356 av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);
357 return AVERROR_INVALIDDATA;
358 }
359
360 return 0;
361}
362
363#define DECODER_SUBFRAME_FIXED_WIDE(residual) { \
364 const int blocksize = s->blocksize; \
365 int ret; \
366 \
367 if ((ret = decode_residuals(s, residual, pred_order)) < 0) \
368 return ret; \
369 \
370 switch (pred_order) { \
371 case 0: \
372 for (int i = pred_order; i < blocksize; i++) \
373 decoded[i] = residual[i]; \
374 break; \
375 case 1: \
376 for (int i = pred_order; i < blocksize; i++) \
377 decoded[i] = (uint64_t)residual[i] + (uint64_t)decoded[i-1];\
378 break; \
379 case 2: \
380 for (int i = pred_order; i < blocksize; i++) \
381 decoded[i] = (uint64_t)residual[i] + 2*(uint64_t)decoded[i-1] - (uint64_t)decoded[i-2]; \
382 break; \
383 case 3: \
384 for (int i = pred_order; i < blocksize; i++) \
385 decoded[i] = (uint64_t)residual[i] + 3*(uint64_t)decoded[i-1] - 3*(uint64_t)decoded[i-2] + (uint64_t)decoded[i-3]; \
386 break; \
387 case 4: \
388 for (int i = pred_order; i < blocksize; i++) \
389 decoded[i] = (uint64_t)residual[i] + 4*(uint64_t)decoded[i-1] - 6*(uint64_t)decoded[i-2] + 4*(uint64_t)decoded[i-3] - (uint64_t)decoded[i-4]; \
390 break; \
391 default: \
392 av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order); \
393 return AVERROR_INVALIDDATA; \
394 } \
395 return 0; \
396}
397
399 int pred_order, int bps)
400{
401 /* warm up samples */
402 for (int i = 0; i < pred_order; i++) {
403 decoded[i] = get_sbits_long(&s->gb, bps);
404 }
406}
407
408
410 int32_t *residual, int pred_order)
411{
412 /* warm up samples */ \
413 for (int i = 0; i < pred_order; i++) { \
414 decoded[i] = get_sbits64(&s->gb, 33); \
415 } \
416 DECODER_SUBFRAME_FIXED_WIDE(residual);
417}
418
419static void lpc_analyze_remodulate(SUINT32 *decoded, const int coeffs[32],
420 int order, int qlevel, int len, int bps)
421{
422 int i, j;
423 int ebps = 1 << (bps-1);
424 unsigned sigma = 0;
425
426 for (i = order; i < len; i++)
427 sigma |= decoded[i] + ebps;
428
429 if (sigma < 2*ebps)
430 return;
431
432 for (i = len - 1; i >= order; i--) {
433 int64_t p = 0;
434 for (j = 0; j < order; j++)
435 p += coeffs[j] * (int64_t)(int32_t)decoded[i-order+j];
436 decoded[i] -= p >> qlevel;
437 }
438 for (i = order; i < len; i++, decoded++) {
439 int32_t p = 0;
440 for (j = 0; j < order; j++)
441 p += coeffs[j] * (uint32_t)decoded[j];
442 decoded[j] += p >> qlevel;
443 }
444}
445
446static int decode_subframe_lpc(FLACContext *s, int32_t *decoded, int pred_order,
447 int bps)
448{
449 int i, ret;
450 int coeff_prec, qlevel;
451 int coeffs[32];
452
453 /* warm up samples */
454 for (i = 0; i < pred_order; i++) {
455 decoded[i] = get_sbits_long(&s->gb, bps);
456 }
457
458 coeff_prec = get_bits(&s->gb, 4) + 1;
459 if (coeff_prec == 16) {
460 av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
461 return AVERROR_INVALIDDATA;
462 }
463 qlevel = get_sbits(&s->gb, 5);
464 if (qlevel < 0) {
465 av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
466 qlevel);
467 return AVERROR_INVALIDDATA;
468 }
469
470 for (i = 0; i < pred_order; i++) {
471 coeffs[pred_order - i - 1] = get_sbits(&s->gb, coeff_prec);
472 }
473
474 if ((ret = decode_residuals(s, decoded, pred_order)) < 0)
475 return ret;
476
477 if ( ( s->buggy_lpc && s->stream_info.bps <= 16)
478 || ( !s->buggy_lpc && bps <= 16
479 && bps + coeff_prec + av_log2(pred_order) <= 32)) {
480 s->dsp.lpc16(decoded, coeffs, pred_order, qlevel, s->blocksize);
481 } else {
482 s->dsp.lpc32(decoded, coeffs, pred_order, qlevel, s->blocksize);
483 if (s->stream_info.bps <= 16)
484 lpc_analyze_remodulate(decoded, coeffs, pred_order, qlevel, s->blocksize, bps);
485 }
486
487 return 0;
488}
489
491 int32_t *residual, int pred_order)
492{
493 int i, ret;
494 int coeff_prec, qlevel;
495 int coeffs[32];
496
497 /* warm up samples */
498 for (i = 0; i < pred_order; i++) {
499 decoded[i] = get_sbits64(&s->gb, 33);
500 }
501
502 coeff_prec = get_bits(&s->gb, 4) + 1;
503 if (coeff_prec == 16) {
504 av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
505 return AVERROR_INVALIDDATA;
506 }
507 qlevel = get_sbits(&s->gb, 5);
508 if (qlevel < 0) {
509 av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
510 qlevel);
511 return AVERROR_INVALIDDATA;
512 }
513
514 for (i = 0; i < pred_order; i++) {
515 coeffs[pred_order - i - 1] = get_sbits(&s->gb, coeff_prec);
516 }
517
518 if ((ret = decode_residuals(s, residual, pred_order)) < 0)
519 return ret;
520
521 s->dsp.lpc33(decoded, residual, coeffs, pred_order, qlevel, s->blocksize);
522
523 return 0;
524}
525
526static inline int decode_subframe(FLACContext *s, int channel)
527{
528 int32_t *decoded = s->decoded[channel];
529 int type, wasted = 0;
530 int bps = s->stream_info.bps;
531 int i, ret;
532
533 if (channel == 0) {
534 if (s->ch_mode == FLAC_CHMODE_RIGHT_SIDE)
535 bps++;
536 } else {
537 if (s->ch_mode == FLAC_CHMODE_LEFT_SIDE || s->ch_mode == FLAC_CHMODE_MID_SIDE)
538 bps++;
539 }
540
541 if (get_bits1(&s->gb)) {
542 av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
543 return AVERROR_INVALIDDATA;
544 }
545 type = get_bits(&s->gb, 6);
546
547 if (get_bits1(&s->gb)) {
548 int left = get_bits_left(&s->gb);
549 if ( left <= 0 ||
550 (left < bps && !show_bits_long(&s->gb, left)) ||
551 !show_bits_long(&s->gb, bps-1)) {
552 av_log(s->avctx, AV_LOG_ERROR,
553 "Invalid number of wasted bits > available bits (%d) - left=%d\n",
554 bps, left);
555 return AVERROR_INVALIDDATA;
556 }
557 wasted = 1 + get_unary(&s->gb, 1, get_bits_left(&s->gb));
558 bps -= wasted;
559 }
560
561//FIXME use av_log2 for types
562 if (type == 0) {
563 if (bps < 33) {
564 int32_t tmp = get_sbits_long(&s->gb, bps);
565 for (i = 0; i < s->blocksize; i++)
566 decoded[i] = tmp;
567 } else {
568 int64_t tmp = get_sbits64(&s->gb, 33);
569 for (i = 0; i < s->blocksize; i++)
570 s->decoded_33bps[i] = tmp;
571 }
572 } else if (type == 1) {
573 if (bps < 33) {
574 for (i = 0; i < s->blocksize; i++)
575 decoded[i] = get_sbits_long(&s->gb, bps);
576 } else {
577 for (i = 0; i < s->blocksize; i++)
578 s->decoded_33bps[i] = get_sbits64(&s->gb, 33);
579 }
580 } else if ((type >= 8) && (type <= 12)) {
581 int order = type & ~0x8;
582 if (bps < 33) {
583 if (bps + order <= 32) {
584 if ((ret = decode_subframe_fixed(s, decoded, order, bps)) < 0)
585 return ret;
586 } else {
587 if ((ret = decode_subframe_fixed_wide(s, decoded, order, bps)) < 0)
588 return ret;
589 }
590 } else {
591 if ((ret = decode_subframe_fixed_33bps(s, s->decoded_33bps, decoded, order)) < 0)
592 return ret;
593 }
594 } else if (type >= 32) {
595 if (bps < 33) {
596 if ((ret = decode_subframe_lpc(s, decoded, (type & ~0x20)+1, bps)) < 0)
597 return ret;
598 } else {
599 if ((ret = decode_subframe_lpc_33bps(s, s->decoded_33bps, decoded, (type & ~0x20)+1)) < 0)
600 return ret;
601 }
602 } else {
603 av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
604 return AVERROR_INVALIDDATA;
605 }
606
607 if (wasted) {
608 if (wasted+bps == 33) {
609 s->dsp.wasted33(s->decoded_33bps, decoded, wasted, s->blocksize);
610 } else if (wasted < 32) {
611 s->dsp.wasted32(decoded, wasted, s->blocksize);
612 }
613 }
614
615 return 0;
616}
617
619{
620 int ret;
621 GetBitContext *gb = &s->gb;
622 FLACFrameInfo fi;
623
624 if ((ret = ff_flac_decode_frame_header(s->avctx, gb, &fi, 0)) < 0) {
625 av_log(s->avctx, AV_LOG_ERROR, "invalid frame header\n");
626 return ret;
627 }
628
629 if ( s->stream_info.channels
630 && fi.channels != s->stream_info.channels
631 && s->got_streaminfo) {
632 s->stream_info.channels = fi.channels;
635 if (ret < 0)
636 return ret;
637 }
638 s->stream_info.channels = fi.channels;
640 s->ch_mode = fi.ch_mode;
641
642 if (!s->stream_info.bps && !fi.bps) {
643 av_log(s->avctx, AV_LOG_ERROR, "bps not found in STREAMINFO or frame header\n");
644 return AVERROR_INVALIDDATA;
645 }
646 if (!fi.bps) {
647 fi.bps = s->stream_info.bps;
648 } else if (s->stream_info.bps && fi.bps != s->stream_info.bps) {
649 av_log(s->avctx, AV_LOG_ERROR, "switching bps mid-stream is not "
650 "supported\n");
651 return AVERROR_INVALIDDATA;
652 }
653
654 if (!s->stream_info.bps) {
655 s->stream_info.bps = s->avctx->bits_per_raw_sample = fi.bps;
657 }
658
659 if (!s->stream_info.max_blocksize)
660 s->stream_info.max_blocksize = FLAC_MAX_BLOCKSIZE;
661 if (fi.blocksize > s->stream_info.max_blocksize) {
662 av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", fi.blocksize,
663 s->stream_info.max_blocksize);
664 return AVERROR_INVALIDDATA;
665 }
666 s->blocksize = fi.blocksize;
667
668 if (!s->stream_info.samplerate && !fi.samplerate) {
669 av_log(s->avctx, AV_LOG_ERROR, "sample rate not found in STREAMINFO"
670 " or frame header\n");
671 return AVERROR_INVALIDDATA;
672 }
673 if (fi.samplerate == 0)
674 fi.samplerate = s->stream_info.samplerate;
675 s->stream_info.samplerate = s->avctx->sample_rate = fi.samplerate;
676
677 if (!s->got_streaminfo) {
679 if (ret < 0)
680 return ret;
681 s->got_streaminfo = 1;
682 dump_headers(s->avctx, &s->stream_info);
683 }
684 ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt,
685 s->stream_info.channels);
686
687// dump_headers(s->avctx, &s->stream_info);
688
689 return 0;
690}
691
693{
694 int i, ret;
695 GetBitContext *gb = &s->gb;
696
697 /* subframes */
698 for (i = 0; i < s->stream_info.channels; i++) {
699 if ((ret = decode_subframe(s, i)) < 0)
700 return ret;
701 }
702
703 align_get_bits(gb);
704
705 /* frame footer */
706 skip_bits(gb, 16); /* data crc */
707
708 return 0;
709}
710
711static void decorrelate_33bps(int ch_mode, int32_t **decoded, int64_t *decoded_33bps, int len)
712{
713 int i;
714 if (ch_mode == FLAC_CHMODE_LEFT_SIDE ) {
715 for (i = 0; i < len; i++)
716 decoded[1][i] = decoded[0][i] - (uint64_t)decoded_33bps[i];
717 } else if (ch_mode == FLAC_CHMODE_RIGHT_SIDE ) {
718 for (i = 0; i < len; i++)
719 decoded[0][i] = decoded[1][i] + (uint64_t)decoded_33bps[i];
720 } else if (ch_mode == FLAC_CHMODE_MID_SIDE ) {
721 for (i = 0; i < len; i++) {
722 uint64_t a = decoded[0][i];
723 int64_t b = decoded_33bps[i];
724 a -= b >> 1;
725 decoded[0][i] = (a + b);
726 decoded[1][i] = a;
727 }
728 }
729}
730
732 int *got_frame_ptr, AVPacket *avpkt)
733{
734 const uint8_t *buf = avpkt->data;
735 int buf_size = avpkt->size;
736 FLACContext *s = avctx->priv_data;
737 const uint8_t *streaminfo;
738 size_t streaminfo_size;
739 int bytes_read = 0;
740 int ret;
741
742 *got_frame_ptr = 0;
743
744 if (!ff_thread_can_start_frame(avctx)) {
745 av_log(avctx, AV_LOG_ERROR, "frame threads need one FLAC frame per packet\n");
747 }
748
750 &streaminfo_size);
751 if (streaminfo) {
752 if (streaminfo_size >= 8 + FLAC_STREAMINFO_SIZE &&
753 AV_RB32(streaminfo) == MKBETAG('f','L','a','C'))
754 streaminfo += 8;
755 else if (streaminfo_size != FLAC_STREAMINFO_SIZE)
756 return AVERROR_INVALIDDATA;
757 if ((ret = apply_streaminfo(s, streaminfo)) < 0)
758 return ret;
759 s->streaminfo_serial++;
760 }
761
762 if (buf_size > 5 && !memcmp(buf, "\177FLAC", 5)) {
763 av_log(s->avctx, AV_LOG_DEBUG, "skipping flac header packet 1\n");
764 return buf_size;
765 }
766
767 if (buf_size > 0 && (*buf & 0x7F) == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
768 av_log(s->avctx, AV_LOG_DEBUG, "skipping vorbis comment\n");
769 return buf_size;
770 }
771
772 /* check that there is at least the smallest decodable amount of data.
773 this amount corresponds to the smallest valid FLAC frame possible.
774 FF F8 69 02 00 00 9A 00 00 34 */
775 if (buf_size < FLAC_MIN_FRAME_SIZE)
776 return buf_size;
777
778 /* check for inline header */
779 if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
780 if (!s->got_streaminfo && (ret = parse_streaminfo(s, buf, buf_size))) {
781 av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
782 return ret;
783 }
784 return get_metadata_size(buf, buf_size);
785 }
786
787 /* decode frame */
788 if ((ret = init_get_bits8(&s->gb, buf, buf_size)) < 0)
789 return ret;
790 if ((ret = decode_frame_header(s)) < 0) {
791 av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
792 return ret;
793 }
794
795 /* get output buffer */
796 frame->nb_samples = s->blocksize;
797 if ((ret = ff_thread_get_buffer(avctx, frame, 0)) < 0)
798 return ret;
799
801
802 if ((ret = decode_subframes(s)) < 0) {
803 av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
804 return ret;
805 }
806 bytes_read = get_bits_count(&s->gb)/8;
807
808 if ((s->avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_COMPLIANT)) &&
810 0, buf, bytes_read)) {
811 av_log(s->avctx, AV_LOG_ERROR, "CRC error at PTS %"PRId64"\n", avpkt->pts);
812 if (s->avctx->err_recognition & AV_EF_EXPLODE)
813 return AVERROR_INVALIDDATA;
814 }
815
816 if (s->stream_info.bps == 32 && s->ch_mode > 0) {
817 decorrelate_33bps(s->ch_mode, s->decoded, s->decoded_33bps, s->blocksize);
818 s->dsp.decorrelate[0](frame->data, s->decoded, s->stream_info.channels,
819 s->blocksize, s->sample_shift);
820 } else {
821 s->dsp.decorrelate[s->ch_mode](frame->data, s->decoded,
822 s->stream_info.channels,
823 s->blocksize, s->sample_shift);
824 }
825
826 if (bytes_read > buf_size) {
827 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
828 return AVERROR_INVALIDDATA;
829 }
830 if (bytes_read < buf_size) {
831 av_log(s->avctx, AV_LOG_DEBUG, "underread: %d orig size: %d\n",
832 buf_size - bytes_read, buf_size);
833 }
834
835 *got_frame_ptr = 1;
836
837 return bytes_read;
838}
839
840#if HAVE_THREADS
841/**
842 * Hand the stream parameters on to the next frame thread, so that a STREAMINFO
843 * taken from packet side data holds for the frames after the one carrying it.
844 */
845static int flac_update_thread_context(AVCodecContext *dst,
846 const AVCodecContext *src)
847{
848 FLACContext *s = dst->priv_data;
849 const FLACContext *s1 = src->priv_data;
850
851 if (s == s1 || s->streaminfo_serial == s1->streaminfo_serial)
852 return 0;
853
854 s->streaminfo_serial = s1->streaminfo_serial;
855 s->stream_info = s1->stream_info;
856
857 return setup_streaminfo(s);
858}
859#endif
860
862{
863 FLACContext *s = avctx->priv_data;
864
865 av_freep(&s->decoded_buffer);
866 av_freep(&s->decoded_buffer_33bps);
867
868 return 0;
869}
870
871static const AVOption options[] = {
872{ "use_buggy_lpc", "emulate old buggy lavc behavior", offsetof(FLACContext, buggy_lpc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM },
873{ NULL },
874};
875
877 .class_name = "FLAC decoder",
878 .item_name = av_default_item_name,
879 .option = options,
880 .version = LIBAVUTIL_VERSION_INT,
881};
882
884 .p.name = "flac",
885 CODEC_LONG_NAME("FLAC (Free Lossless Audio Codec)"),
886 .p.type = AVMEDIA_TYPE_AUDIO,
887 .p.id = AV_CODEC_ID_FLAC,
888 .priv_data_size = sizeof(FLACContext),
892 UPDATE_THREAD_CONTEXT(flac_update_thread_context),
893 .p.capabilities = AV_CODEC_CAP_CHANNEL_CONF |
898 .p.priv_class = &flac_decoder_class,
899};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:97
const FFCodec ff_flac_decoder
Definition flacdec.c:883
int32_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Libavcodec external API header.
static int BS_FUNC left(const BSCTX *bc)
Return the number of the bits left in a buffer.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define UPDATE_THREAD_CONTEXT(func)
#define FF_CODEC_DECODE_CB(func)
#define CODEC_LONG_NAME(str)
#define CODEC_SAMPLEFMTS(...)
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
#define SUINT32
#define AV_EF_CRCCHECK
Verify checksums embedded in the bitstream (could be of either encoded or decoded data,...
Definition defs.h:48
#define AV_EF_COMPLIANT
consider all spec non compliances as errors
Definition defs.h:55
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition defs.h:51
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
channel
Use these values when setting the channel map with ebur128_set_channel().
Definition ebur128.h:39
int ret
Definition ffplay.c:391
int ff_flac_decode_frame_header(void *logctx, GetBitContext *gb, FLACFrameInfo *fi, int log_level_offset)
Validate and decode a frame header.
Definition flac.c:51
int ff_flac_is_extradata_valid(AVCodecContext *avctx, uint8_t **streaminfo_start)
Validate the FLAC extradata.
Definition flac.c:149
void ff_flac_set_channel_layout(AVCodecContext *avctx, int channels)
Definition flac.c:173
int ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s, const uint8_t *buffer)
Parse the Streaminfo metadata block.
Definition flac.c:187
FLAC (Free Lossless Audio Codec) common stuff.
#define FLAC_MIN_FRAME_SIZE
Definition flac.h:36
#define FLAC_MAX_BLOCKSIZE
Definition flac.h:35
@ FLAC_CHMODE_RIGHT_SIDE
Definition flac.h:41
@ FLAC_CHMODE_MID_SIDE
Definition flac.h:42
@ FLAC_CHMODE_LEFT_SIDE
Definition flac.h:40
@ FLAC_METADATA_TYPE_VORBIS_COMMENT
Definition flac.h:50
@ FLAC_METADATA_TYPE_STREAMINFO
Definition flac.h:46
static av_always_inline void flac_parse_block_header(const uint8_t *block_header, int *last, int *type, int *size)
Parse the metadata block parameters from the header.
Definition flac.h:63
#define FLAC_MAX_CHANNELS
Definition flac.h:33
#define FLAC_STREAMINFO_SIZE
Definition flac.h:32
FLAC (Free Lossless Audio Codec) decoder/parser common functions.
bitstream reader API header.
static int get_sbits_long(GetBitContext *s, int n)
Read 0-32 bits as a signed integer.
Definition get_bits.h:474
static unsigned int show_bits_long(GetBitContext *s, int n)
Show 0-32 bits.
Definition get_bits.h:498
static int get_sbits(GetBitContext *s, int n)
Definition get_bits.h:322
static int get_bits_left(GetBitContext *gb)
Definition get_bits.h:688
static unsigned int get_bits1(GetBitContext *s)
Definition get_bits.h:391
static void skip_bits(GetBitContext *s, int n)
Definition get_bits.h:383
static int init_get_bits8(GetBitContext *s, const uint8_t *buffer, int byte_size)
Initialize GetBitContext.
Definition get_bits.h:544
static const uint8_t * align_get_bits(GetBitContext *s)
Definition get_bits.h:560
static int get_bits_count(const GetBitContext *s)
Definition get_bits.h:254
static int64_t get_sbits64(GetBitContext *s, int n)
Read 0-64 bits as a signed integer.
Definition get_bits.h:486
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition get_bits.h:337
exp golomb vlc stuff
static int get_sr_golomb_flac(GetBitContext *gb, int k, int limit, int esc_len)
read signed golomb rice code (flac).
Definition golomb.h:544
#define AV_OPT_FLAG_AUDIO_PARAM
Definition opt.h:356
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition opt.h:355
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
#define AV_CODEC_CAP_CHANNEL_CONF
Codec should fill in channel configuration and samplerate instead of container.
Definition codec.h:94
#define AV_CODEC_CAP_FRAME_THREADS
Codec supports frame-level multithreading.
Definition codec.h:98
@ AV_CODEC_ID_FLAC
Definition codec_id.h:470
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition packet.h:56
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition packet.c:252
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition crc.c:421
@ AV_CRC_16_ANSI
Definition crc.h:50
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition mem.c:661
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt)
Check if the sample format is planar.
Definition samplefmt.c:115
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition samplefmt.c:109
int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align)
Get the required buffer size for the given audio parameters.
Definition samplefmt.c:122
AVSampleFormat
Audio sample formats.
Definition samplefmt.h:55
@ AV_SAMPLE_FMT_S16P
signed 16 bits, planar
Definition samplefmt.h:64
@ AV_SAMPLE_FMT_S32P
signed 32 bits, planar
Definition samplefmt.h:65
@ AV_SAMPLE_FMT_S32
signed 32 bits
Definition samplefmt.h:59
@ AV_SAMPLE_FMT_S64P
signed 64 bits, planar
Definition samplefmt.h:69
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition samplefmt.h:58
int av_samples_fill_arrays(uint8_t **audio_data, int *linesize, const uint8_t *buf, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align)
Fill plane data pointers and linesize for samples with sample format sample_fmt.
Definition samplefmt.c:154
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
int a
#define b
Definition input.c:43
#define av_log2
Definition intmath.h:84
#define AV_RB32(p)
enum MPFType type
Definition jpegmpfenc.c:55
av_cold void CBS_FUNC close(CodedBitstreamContext **ctx_ptr)
Close a context and free all internal state.
Definition cbs.c:118
#define DECODER_SUBFRAME_FIXED_WIDE(residual)
Definition flacdec.c:363
static int decode_subframe_lpc(FLACContext *s, int32_t *decoded, int pred_order, int bps)
Definition flacdec.c:446
static int flac_decode_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, AVPacket *avpkt)
Definition flacdec.c:731
static const AVClass flac_decoder_class
Definition flacdec.c:876
static av_cold int flac_decode_init(AVCodecContext *avctx)
Definition flacdec.c:130
static int decode_residuals(FLACContext *s, int32_t *decoded, int pred_order)
Definition flacdec.c:250
static int allocate_buffers(FLACContext *s)
Definition flacdec.c:157
static int decode_subframes(FLACContext *s)
Definition flacdec.c:692
static int decode_frame_header(FLACContext *s)
Definition flacdec.c:618
static void decorrelate_33bps(int ch_mode, int32_t **decoded, int64_t *decoded_33bps, int len)
Definition flacdec.c:711
static av_cold int flac_decode_close(AVCodecContext *avctx)
Definition flacdec.c:861
static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
Definition flacdec.c:148
static int decode_subframe_fixed_wide(FLACContext *s, int32_t *decoded, int pred_order, int bps)
Definition flacdec.c:398
static int decode_subframe_lpc_33bps(FLACContext *s, int64_t *decoded, int32_t *residual, int pred_order)
Definition flacdec.c:490
static void lpc_analyze_remodulate(SUINT32 *decoded, const int coeffs[32], int order, int qlevel, int len, int bps)
Definition flacdec.c:419
static int decode_subframe_fixed(FLACContext *s, int32_t *decoded, int pred_order, int bps)
Definition flacdec.c:311
static int decode_subframe_fixed_33bps(FLACContext *s, int64_t *decoded, int32_t *residual, int pred_order)
Definition flacdec.c:409
static void flac_set_bps(FLACContext *s)
Definition flacdec.c:77
static int get_metadata_size(const uint8_t *buf, int buf_size)
Determine the size of an inline header.
Definition flacdec.c:229
static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
Parse the STREAMINFO from an inline header.
Definition flacdec.c:207
static int apply_streaminfo(FLACContext *s, const uint8_t *streaminfo)
Definition flacdec.c:119
static int setup_streaminfo(FLACContext *s)
Set the decoder up for s->stream_info, which it cannot decode with until the buffers are allocated.
Definition flacdec.c:103
static int decode_subframe(FLACContext *s, int channel)
Definition flacdec.c:526
av_cold void ff_flacdsp_init(FLACDSPContext *c, enum AVSampleFormat fmt, int channels)
Definition flacdsp.c:114
Multithreading API for decoders.
#define av_uninit(x)
Definition attributes.h:187
#define av_cold
Definition attributes.h:117
#define MKBETAG(a, b, c, d)
Definition macros.h:56
Memory handling functions.
unsigned bps
Definition movenc.c:2129
AVOptions.
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f, int flags)
Wrapper around get_buffer() for frame-multithreaded codecs.
void ff_thread_finish_setup(AVCodecContext *avctx)
If the codec defines update_thread_context(), call this when they are ready for the next thread to st...
int ff_thread_can_start_frame(AVCodecContext *avctx)
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
void * priv_data
Definition avcodec.h:470
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:587
int size
Definition packet.h:611
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:603
uint8_t * data
Definition packet.h:610
int blocksize
number of samples in the current frame
Definition flacdec.c:58
unsigned streaminfo_serial
counts the STREAMINFOs taken from packet side data
Definition flacdec.c:62
unsigned int decoded_buffer_size_33bps
Definition flacdec.c:69
AVCodecContext * avctx
parent AVCodecContext
Definition flacdec.c:55
unsigned int decoded_buffer_size
Definition flacdec.c:66
GetBitContext gb
GetBitContext initialized to start at the current frame.
Definition flacdec.c:56
int32_t * decoded[FLAC_MAX_CHANNELS]
decoded samples
Definition flacdec.c:64
FLACStreaminfo stream_info
Definition flacdec.c:53
uint8_t * decoded_buffer_33bps
Definition flacdec.c:68
int ch_mode
channel decorrelation type in the current frame
Definition flacdec.c:60
int buggy_lpc
use workaround for old lavc encoded files
Definition flacdec.c:70
uint8_t * decoded_buffer
Definition flacdec.c:65
FLACDSPContext dsp
Definition flacdec.c:72
int64_t * decoded_33bps
decoded samples for a 33 bps subframe
Definition flacdec.c:67
int got_streaminfo
indicates if the STREAMINFO has been read
Definition flacdec.c:61
int sample_shift
shift required to make output samples 16-bit or 32-bit
Definition flacdec.c:59
int blocksize
block size of the frame
Definition flac_parse.h:46
int channels
number of channels
Definition flac_parse.h:44
int samplerate
sample rate
Definition flac_parse.h:43
int ch_mode
channel decorrelation mode
Definition flac_parse.h:47
int bps
bits-per-sample
Definition flac_parse.h:45
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
#define src
Definition vp8dsp.c:248
static int get_unary(GetBitContext *gb, int stop, int len)
Get unary code of limited length.
Definition unary.h:46
int len
static double c[64]