3 * Copyright (c) 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/attributes.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/float_dsp.h"
32 #include "libavutil/libm.h"
37 #include "mpegaudiodsp.h"
41 * - test lsf / mpeg25 extensively.
44 #include "mpegaudio.h"
45 #include "mpegaudiodecheader.h"
47 #define BACKSTEP_SIZE 512
49 #define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
51 /* layer 3 "granule" */
52 typedef struct GranuleDef {
57 int scalefac_compress;
62 uint8_t scalefac_scale;
63 uint8_t count1table_select;
64 int region_size[3]; /* number of huffman codes in each region */
66 int short_start, long_end; /* long/short band indexes */
67 uint8_t scale_factors[40];
68 DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
71 typedef struct MPADecodeContext {
73 uint8_t last_buf[LAST_BUF_SIZE];
76 /* next header (used in free format parsing) */
77 uint32_t free_format_next_header;
80 DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
81 int synth_buf_offset[MPA_MAX_CHANNELS];
82 DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
83 INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
84 GranuleDef granules[2][2]; /* Used in Layer 3 */
85 int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
88 AVCodecContext* avctx;
90 void (*butterflies_float)(float *av_restrict v1, float *av_restrict v2, int len);
97 #include "mpegaudiodata.h"
98 #include "mpegaudiodectab.h"
100 /* vlc structure for decoding layer 3 huffman tables */
101 static VLC huff_vlc[16];
102 static VLC_TYPE huff_vlc_tables[
103 0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
104 142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
106 static const int huff_vlc_tables_sizes[16] = {
107 0, 128, 128, 128, 130, 128, 154, 166,
108 142, 204, 190, 170, 542, 460, 662, 414
110 static VLC huff_quad_vlc[2];
111 static VLC_TYPE huff_quad_vlc_tables[128+16][2];
112 static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
113 /* computed from band_size_long */
114 static uint16_t band_index_long[9][23];
115 #include "mpegaudio_tablegen.h"
116 /* intensity stereo coef table */
117 static INTFLOAT is_table[2][16];
118 static INTFLOAT is_table_lsf[2][2][16];
119 static INTFLOAT csa_table[8][4];
121 static int16_t division_tab3[1 << 6 ];
122 static int16_t division_tab5[1 << 8 ];
123 static int16_t division_tab9[1 << 11];
125 static int16_t * const division_tabs[4] = {
126 division_tab3, division_tab5, NULL, division_tab9
129 /* lower 2 bits: modulo 3, higher bits: shift */
130 static uint16_t scale_factor_modshift[64];
131 /* [i][j]: 2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
132 static int32_t scale_factor_mult[15][3];
133 /* mult table for layer 2 group quantization */
135 #define SCALE_GEN(v) \
136 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
138 static const int32_t scale_factor_mult2[3][3] = {
139 SCALE_GEN(4.0 / 3.0), /* 3 steps */
140 SCALE_GEN(4.0 / 5.0), /* 5 steps */
141 SCALE_GEN(4.0 / 9.0), /* 9 steps */
145 * Convert region offsets to region sizes and truncate
146 * size to big_values.
148 static void region_offset2size(GranuleDef *g)
151 g->region_size[2] = 576 / 2;
152 for (i = 0; i < 3; i++) {
153 k = FFMIN(g->region_size[i], g->big_values);
154 g->region_size[i] = k - j;
159 static void init_short_region(MPADecodeContext *s, GranuleDef *g)
161 if (g->block_type == 2) {
162 if (s->sample_rate_index != 8)
163 g->region_size[0] = (36 / 2);
165 g->region_size[0] = (72 / 2);
167 if (s->sample_rate_index <= 2)
168 g->region_size[0] = (36 / 2);
169 else if (s->sample_rate_index != 8)
170 g->region_size[0] = (54 / 2);
172 g->region_size[0] = (108 / 2);
174 g->region_size[1] = (576 / 2);
177 static void init_long_region(MPADecodeContext *s, GranuleDef *g,
181 g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
182 /* should not overflow */
183 l = FFMIN(ra1 + ra2 + 2, 22);
184 g->region_size[1] = band_index_long[s->sample_rate_index][ l] >> 1;
187 static void compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
189 if (g->block_type == 2) {
190 if (g->switch_point) {
191 if(s->sample_rate_index == 8)
192 avpriv_request_sample(s->avctx, "switch point in 8khz");
193 /* if switched mode, we handle the 36 first samples as
194 long blocks. For 8000Hz, we handle the 72 first
195 exponents as long blocks */
196 if (s->sample_rate_index <= 2)
212 /* layer 1 unscaling */
213 /* n = number of bits of the mantissa minus 1 */
214 static inline int l1_unscale(int n, int mant, int scale_factor)
219 shift = scale_factor_modshift[scale_factor];
222 val = MUL64((int)(mant + (-1U << n) + 1), scale_factor_mult[n-1][mod]);
224 /* NOTE: at this point, 1 <= shift >= 21 + 15 */
225 return (int)((val + (1LL << (shift - 1))) >> shift);
228 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
232 shift = scale_factor_modshift[scale_factor];
236 val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
237 /* NOTE: at this point, 0 <= shift <= 21 */
239 val = (val + (1 << (shift - 1))) >> shift;
243 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
244 static inline int l3_unscale(int value, int exponent)
249 e = table_4_3_exp [4 * value + (exponent & 3)];
250 m = table_4_3_value[4 * value + (exponent & 3)];
254 av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
258 m = (m + ((1U << e) >> 1)) >> e;
263 static av_cold void decode_init_static(void)
268 /* scale factors table for layer 1/2 */
269 for (i = 0; i < 64; i++) {
271 /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
274 scale_factor_modshift[i] = mod | (shift << 2);
277 /* scale factor multiply for layer 1 */
278 for (i = 0; i < 15; i++) {
281 norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
282 scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0 * 2.0), FRAC_BITS);
283 scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
284 scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
285 ff_dlog(NULL, "%d: norm=%x s=%"PRIx32" %"PRIx32" %"PRIx32"\n", i,
287 scale_factor_mult[i][0],
288 scale_factor_mult[i][1],
289 scale_factor_mult[i][2]);
292 RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
294 /* huffman decode tables */
296 for (i = 1; i < 16; i++) {
297 const HuffTable *h = &mpa_huff_tables[i];
299 uint8_t tmp_bits [512] = { 0 };
300 uint16_t tmp_codes[512] = { 0 };
305 for (x = 0; x < xsize; x++) {
306 for (y = 0; y < xsize; y++) {
307 tmp_bits [(x << 5) | y | ((x && y) << 4)]= h->bits [j ];
308 tmp_codes[(x << 5) | y | ((x && y) << 4)]= h->codes[j++];
313 huff_vlc[i].table = huff_vlc_tables+offset;
314 huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
315 init_vlc(&huff_vlc[i], 7, 512,
316 tmp_bits, 1, 1, tmp_codes, 2, 2,
317 INIT_VLC_USE_NEW_STATIC);
318 offset += huff_vlc_tables_sizes[i];
320 av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
323 for (i = 0; i < 2; i++) {
324 huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
325 huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
326 init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
327 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
328 INIT_VLC_USE_NEW_STATIC);
329 offset += huff_quad_vlc_tables_sizes[i];
331 av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
333 for (i = 0; i < 9; i++) {
335 for (j = 0; j < 22; j++) {
336 band_index_long[i][j] = k;
337 k += band_size_long[i][j];
339 band_index_long[i][22] = k;
342 /* compute n ^ (4/3) and store it in mantissa/exp format */
344 mpegaudio_tableinit();
346 for (i = 0; i < 4; i++) {
347 if (ff_mpa_quant_bits[i] < 0) {
348 for (j = 0; j < (1 << (-ff_mpa_quant_bits[i] + 1)); j++) {
349 int val1, val2, val3, steps;
351 steps = ff_mpa_quant_steps[i];
356 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
362 for (i = 0; i < 7; i++) {
366 f = tan((double)i * M_PI / 12.0);
367 v = FIXR(f / (1.0 + f));
372 is_table[1][6 - i] = v;
375 for (i = 7; i < 16; i++)
376 is_table[0][i] = is_table[1][i] = 0.0;
378 for (i = 0; i < 16; i++) {
382 for (j = 0; j < 2; j++) {
383 e = -(j + 1) * ((i + 1) >> 1);
386 is_table_lsf[j][k ^ 1][i] = FIXR(f);
387 is_table_lsf[j][k ][i] = FIXR(1.0);
388 ff_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
389 i, j, (float) is_table_lsf[j][0][i],
390 (float) is_table_lsf[j][1][i]);
394 for (i = 0; i < 8; i++) {
397 cs = 1.0 / sqrt(1.0 + ci * ci);
400 csa_table[i][0] = FIXHR(cs/4);
401 csa_table[i][1] = FIXHR(ca/4);
402 csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
403 csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
405 csa_table[i][0] = cs;
406 csa_table[i][1] = ca;
407 csa_table[i][2] = ca + cs;
408 csa_table[i][3] = ca - cs;
413 static av_cold int decode_init(AVCodecContext * avctx)
415 static int initialized_tables = 0;
416 MPADecodeContext *s = avctx->priv_data;
418 if (!initialized_tables) {
419 decode_init_static();
420 initialized_tables = 1;
427 AVFloatDSPContext *fdsp;
428 fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
430 return AVERROR(ENOMEM);
431 s->butterflies_float = fdsp->butterflies_float;
436 ff_mpadsp_init(&s->mpadsp);
438 if (avctx->request_sample_fmt == OUT_FMT &&
439 avctx->codec_id != AV_CODEC_ID_MP3ON4)
440 avctx->sample_fmt = OUT_FMT;
442 avctx->sample_fmt = OUT_FMT_P;
443 s->err_recognition = avctx->err_recognition;
445 if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
451 #define C3 FIXHR(0.86602540378443864676/2)
452 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
453 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
454 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
456 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
458 static void imdct12(INTFLOAT *out, SUINTFLOAT *in)
460 SUINTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
463 in1 = in[1*3] + in[0*3];
464 in2 = in[2*3] + in[1*3];
465 in3 = in[3*3] + in[2*3];
466 in4 = in[4*3] + in[3*3];
467 in5 = in[5*3] + in[4*3];
471 in2 = MULH3(in2, C3, 2);
472 in3 = MULH3(in3, C3, 4);
475 t2 = MULH3(in1 - in5, C4, 2);
485 in1 = MULH3(in5 + in3, C5, 1);
492 in5 = MULH3(in5 - in3, C6, 2);
499 static int handle_crc(MPADecodeContext *s, int sec_len)
501 if (s->error_protection && (s->err_recognition & AV_EF_CRCCHECK)) {
502 const uint8_t *buf = s->gb.buffer - HEADER_SIZE;
503 int sec_byte_len = sec_len >> 3;
504 int sec_rem_bits = sec_len & 7;
505 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_16_ANSI);
507 uint32_t crc_val = av_crc(crc_tab, UINT16_MAX, &buf[2], 2);
508 crc_val = av_crc(crc_tab, crc_val, &buf[6], sec_byte_len);
511 ((buf[6 + sec_byte_len] & (0xFF00 >> sec_rem_bits)) << 24) +
512 ((s->crc << 16) >> sec_rem_bits));
514 crc_val = av_crc(crc_tab, crc_val, tmp_buf, 3);
517 av_log(s->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", crc_val);
518 if (s->err_recognition & AV_EF_EXPLODE)
519 return AVERROR_INVALIDDATA;
525 /* return the number of decoded frames */
526 static int mp_decode_layer1(MPADecodeContext *s)
528 int bound, i, v, n, ch, j, mant;
529 uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
530 uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
533 ret = handle_crc(s, (s->nb_channels == 1) ? 8*16 : 8*32);
537 if (s->mode == MPA_JSTEREO)
538 bound = (s->mode_ext + 1) * 4;
542 /* allocation bits */
543 for (i = 0; i < bound; i++) {
544 for (ch = 0; ch < s->nb_channels; ch++) {
545 allocation[ch][i] = get_bits(&s->gb, 4);
548 for (i = bound; i < SBLIMIT; i++)
549 allocation[0][i] = get_bits(&s->gb, 4);
552 for (i = 0; i < bound; i++) {
553 for (ch = 0; ch < s->nb_channels; ch++) {
554 if (allocation[ch][i])
555 scale_factors[ch][i] = get_bits(&s->gb, 6);
558 for (i = bound; i < SBLIMIT; i++) {
559 if (allocation[0][i]) {
560 scale_factors[0][i] = get_bits(&s->gb, 6);
561 scale_factors[1][i] = get_bits(&s->gb, 6);
565 /* compute samples */
566 for (j = 0; j < 12; j++) {
567 for (i = 0; i < bound; i++) {
568 for (ch = 0; ch < s->nb_channels; ch++) {
569 n = allocation[ch][i];
571 mant = get_bits(&s->gb, n + 1);
572 v = l1_unscale(n, mant, scale_factors[ch][i]);
576 s->sb_samples[ch][j][i] = v;
579 for (i = bound; i < SBLIMIT; i++) {
580 n = allocation[0][i];
582 mant = get_bits(&s->gb, n + 1);
583 v = l1_unscale(n, mant, scale_factors[0][i]);
584 s->sb_samples[0][j][i] = v;
585 v = l1_unscale(n, mant, scale_factors[1][i]);
586 s->sb_samples[1][j][i] = v;
588 s->sb_samples[0][j][i] = 0;
589 s->sb_samples[1][j][i] = 0;
596 static int mp_decode_layer2(MPADecodeContext *s)
598 int sblimit; /* number of used subbands */
599 const unsigned char *alloc_table;
600 int table, bit_alloc_bits, i, j, ch, bound, v;
601 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
602 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
603 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
604 int scale, qindex, bits, steps, k, l, m, b;
607 /* select decoding table */
608 table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
609 s->sample_rate, s->lsf);
610 sblimit = ff_mpa_sblimit_table[table];
611 alloc_table = ff_mpa_alloc_tables[table];
613 if (s->mode == MPA_JSTEREO)
614 bound = (s->mode_ext + 1) * 4;
618 ff_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
624 /* parse bit allocation */
626 for (i = 0; i < bound; i++) {
627 bit_alloc_bits = alloc_table[j];
628 for (ch = 0; ch < s->nb_channels; ch++)
629 bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
630 j += 1 << bit_alloc_bits;
632 for (i = bound; i < sblimit; i++) {
633 bit_alloc_bits = alloc_table[j];
634 v = get_bits(&s->gb, bit_alloc_bits);
637 j += 1 << bit_alloc_bits;
641 for (i = 0; i < sblimit; i++) {
642 for (ch = 0; ch < s->nb_channels; ch++) {
643 if (bit_alloc[ch][i])
644 scale_code[ch][i] = get_bits(&s->gb, 2);
648 ret = handle_crc(s, get_bits_count(&s->gb) - 16);
653 for (i = 0; i < sblimit; i++) {
654 for (ch = 0; ch < s->nb_channels; ch++) {
655 if (bit_alloc[ch][i]) {
656 sf = scale_factors[ch][i];
657 switch (scale_code[ch][i]) {
660 sf[0] = get_bits(&s->gb, 6);
661 sf[1] = get_bits(&s->gb, 6);
662 sf[2] = get_bits(&s->gb, 6);
665 sf[0] = get_bits(&s->gb, 6);
670 sf[0] = get_bits(&s->gb, 6);
671 sf[2] = get_bits(&s->gb, 6);
675 sf[0] = get_bits(&s->gb, 6);
676 sf[2] = get_bits(&s->gb, 6);
685 for (k = 0; k < 3; k++) {
686 for (l = 0; l < 12; l += 3) {
688 for (i = 0; i < bound; i++) {
689 bit_alloc_bits = alloc_table[j];
690 for (ch = 0; ch < s->nb_channels; ch++) {
691 b = bit_alloc[ch][i];
693 scale = scale_factors[ch][i][k];
694 qindex = alloc_table[j+b];
695 bits = ff_mpa_quant_bits[qindex];
698 /* 3 values at the same time */
699 v = get_bits(&s->gb, -bits);
700 v2 = division_tabs[qindex][v];
701 steps = ff_mpa_quant_steps[qindex];
703 s->sb_samples[ch][k * 12 + l + 0][i] =
704 l2_unscale_group(steps, v2 & 15, scale);
705 s->sb_samples[ch][k * 12 + l + 1][i] =
706 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
707 s->sb_samples[ch][k * 12 + l + 2][i] =
708 l2_unscale_group(steps, v2 >> 8 , scale);
710 for (m = 0; m < 3; m++) {
711 v = get_bits(&s->gb, bits);
712 v = l1_unscale(bits - 1, v, scale);
713 s->sb_samples[ch][k * 12 + l + m][i] = v;
717 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
718 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
719 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
722 /* next subband in alloc table */
723 j += 1 << bit_alloc_bits;
725 /* XXX: find a way to avoid this duplication of code */
726 for (i = bound; i < sblimit; i++) {
727 bit_alloc_bits = alloc_table[j];
730 int mant, scale0, scale1;
731 scale0 = scale_factors[0][i][k];
732 scale1 = scale_factors[1][i][k];
733 qindex = alloc_table[j + b];
734 bits = ff_mpa_quant_bits[qindex];
736 /* 3 values at the same time */
737 v = get_bits(&s->gb, -bits);
738 steps = ff_mpa_quant_steps[qindex];
741 s->sb_samples[0][k * 12 + l + 0][i] =
742 l2_unscale_group(steps, mant, scale0);
743 s->sb_samples[1][k * 12 + l + 0][i] =
744 l2_unscale_group(steps, mant, scale1);
747 s->sb_samples[0][k * 12 + l + 1][i] =
748 l2_unscale_group(steps, mant, scale0);
749 s->sb_samples[1][k * 12 + l + 1][i] =
750 l2_unscale_group(steps, mant, scale1);
751 s->sb_samples[0][k * 12 + l + 2][i] =
752 l2_unscale_group(steps, v, scale0);
753 s->sb_samples[1][k * 12 + l + 2][i] =
754 l2_unscale_group(steps, v, scale1);
756 for (m = 0; m < 3; m++) {
757 mant = get_bits(&s->gb, bits);
758 s->sb_samples[0][k * 12 + l + m][i] =
759 l1_unscale(bits - 1, mant, scale0);
760 s->sb_samples[1][k * 12 + l + m][i] =
761 l1_unscale(bits - 1, mant, scale1);
765 s->sb_samples[0][k * 12 + l + 0][i] = 0;
766 s->sb_samples[0][k * 12 + l + 1][i] = 0;
767 s->sb_samples[0][k * 12 + l + 2][i] = 0;
768 s->sb_samples[1][k * 12 + l + 0][i] = 0;
769 s->sb_samples[1][k * 12 + l + 1][i] = 0;
770 s->sb_samples[1][k * 12 + l + 2][i] = 0;
772 /* next subband in alloc table */
773 j += 1 << bit_alloc_bits;
775 /* fill remaining samples to zero */
776 for (i = sblimit; i < SBLIMIT; i++) {
777 for (ch = 0; ch < s->nb_channels; ch++) {
778 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
779 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
780 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
788 #define SPLIT(dst,sf,n) \
790 int m = (sf * 171) >> 9; \
793 } else if (n == 4) { \
796 } else if (n == 5) { \
797 int m = (sf * 205) >> 10; \
800 } else if (n == 6) { \
801 int m = (sf * 171) >> 10; \
808 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
811 SPLIT(slen[3], sf, n3)
812 SPLIT(slen[2], sf, n2)
813 SPLIT(slen[1], sf, n1)
817 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
820 const uint8_t *bstab, *pretab;
821 int len, i, j, k, l, v0, shift, gain, gains[3];
825 gain = g->global_gain - 210;
826 shift = g->scalefac_scale + 1;
828 bstab = band_size_long[s->sample_rate_index];
829 pretab = mpa_pretab[g->preflag];
830 for (i = 0; i < g->long_end; i++) {
831 v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
833 for (j = len; j > 0; j--)
837 if (g->short_start < 13) {
838 bstab = band_size_short[s->sample_rate_index];
839 gains[0] = gain - (g->subblock_gain[0] << 3);
840 gains[1] = gain - (g->subblock_gain[1] << 3);
841 gains[2] = gain - (g->subblock_gain[2] << 3);
843 for (i = g->short_start; i < 13; i++) {
845 for (l = 0; l < 3; l++) {
846 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
847 for (j = len; j > 0; j--)
854 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
857 if (s->in_gb.buffer && *pos >= s->gb.size_in_bits - s->extrasize * 8) {
859 s->in_gb.buffer = NULL;
861 av_assert2((get_bits_count(&s->gb) & 7) == 0);
862 skip_bits_long(&s->gb, *pos - *end_pos);
864 *end_pos = *end_pos2 + get_bits_count(&s->gb) - *pos;
865 *pos = get_bits_count(&s->gb);
869 /* Following is an optimized code for
871 if(get_bits1(&s->gb))
876 #define READ_FLIP_SIGN(dst,src) \
877 v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31); \
880 #define READ_FLIP_SIGN(dst,src) \
881 v = -get_bits1(&s->gb); \
882 *(dst) = (*(src) ^ v) - v;
885 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
886 int16_t *exponents, int end_pos2)
890 int last_pos, bits_left;
892 int end_pos = FFMIN(end_pos2, s->gb.size_in_bits - s->extrasize * 8);
894 /* low frequencies (called big values) */
896 for (i = 0; i < 3; i++) {
897 int j, k, l, linbits;
898 j = g->region_size[i];
901 /* select vlc table */
902 k = g->table_select[i];
903 l = mpa_huff_data[k][0];
904 linbits = mpa_huff_data[k][1];
908 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
913 /* read huffcode and compute each couple */
917 int pos = get_bits_count(&s->gb);
920 switch_buffer(s, &pos, &end_pos, &end_pos2);
924 y = get_vlc2(&s->gb, vlc->table, 7, 3);
927 g->sb_hybrid[s_index ] =
928 g->sb_hybrid[s_index + 1] = 0;
933 exponent= exponents[s_index];
935 ff_dlog(s->avctx, "region=%d n=%d y=%d exp=%d\n",
936 i, g->region_size[i] - j, y, exponent);
941 READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
943 x += get_bitsz(&s->gb, linbits);
944 v = l3_unscale(x, exponent);
945 if (get_bits1(&s->gb))
947 g->sb_hybrid[s_index] = v;
950 READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
952 y += get_bitsz(&s->gb, linbits);
953 v = l3_unscale(y, exponent);
954 if (get_bits1(&s->gb))
956 g->sb_hybrid[s_index + 1] = v;
963 READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
965 x += get_bitsz(&s->gb, linbits);
966 v = l3_unscale(x, exponent);
967 if (get_bits1(&s->gb))
969 g->sb_hybrid[s_index+!!y] = v;
971 g->sb_hybrid[s_index + !y] = 0;
977 /* high frequencies */
978 vlc = &huff_quad_vlc[g->count1table_select];
980 while (s_index <= 572) {
982 pos = get_bits_count(&s->gb);
983 if (pos >= end_pos) {
984 if (pos > end_pos2 && last_pos) {
985 /* some encoders generate an incorrect size for this
986 part. We must go back into the data */
988 skip_bits_long(&s->gb, last_pos - pos);
989 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
990 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
994 switch_buffer(s, &pos, &end_pos, &end_pos2);
1000 code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1001 ff_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1002 g->sb_hybrid[s_index + 0] =
1003 g->sb_hybrid[s_index + 1] =
1004 g->sb_hybrid[s_index + 2] =
1005 g->sb_hybrid[s_index + 3] = 0;
1007 static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
1009 int pos = s_index + idxtab[code];
1010 code ^= 8 >> idxtab[code];
1011 READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
1015 /* skip extension bits */
1016 bits_left = end_pos2 - get_bits_count(&s->gb);
1017 if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1018 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1020 } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1021 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1024 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1025 skip_bits_long(&s->gb, bits_left);
1027 i = get_bits_count(&s->gb);
1028 switch_buffer(s, &i, &end_pos, &end_pos2);
1033 /* Reorder short blocks from bitstream order to interleaved order. It
1034 would be faster to do it in parsing, but the code would be far more
1036 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1039 INTFLOAT *ptr, *dst, *ptr1;
1042 if (g->block_type != 2)
1045 if (g->switch_point) {
1046 if (s->sample_rate_index != 8)
1047 ptr = g->sb_hybrid + 36;
1049 ptr = g->sb_hybrid + 72;
1054 for (i = g->short_start; i < 13; i++) {
1055 len = band_size_short[s->sample_rate_index][i];
1058 for (j = len; j > 0; j--) {
1059 *dst++ = ptr[0*len];
1060 *dst++ = ptr[1*len];
1061 *dst++ = ptr[2*len];
1065 memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1069 #define ISQRT2 FIXR(0.70710678118654752440)
1071 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1074 int sf_max, sf, len, non_zero_found;
1075 INTFLOAT (*is_tab)[16], *tab0, *tab1, v1, v2;
1076 SUINTFLOAT tmp0, tmp1;
1077 int non_zero_found_short[3];
1079 /* intensity stereo */
1080 if (s->mode_ext & MODE_EXT_I_STEREO) {
1085 is_tab = is_table_lsf[g1->scalefac_compress & 1];
1089 tab0 = g0->sb_hybrid + 576;
1090 tab1 = g1->sb_hybrid + 576;
1092 non_zero_found_short[0] = 0;
1093 non_zero_found_short[1] = 0;
1094 non_zero_found_short[2] = 0;
1095 k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1096 for (i = 12; i >= g1->short_start; i--) {
1097 /* for last band, use previous scale factor */
1100 len = band_size_short[s->sample_rate_index][i];
1101 for (l = 2; l >= 0; l--) {
1104 if (!non_zero_found_short[l]) {
1105 /* test if non zero band. if so, stop doing i-stereo */
1106 for (j = 0; j < len; j++) {
1108 non_zero_found_short[l] = 1;
1112 sf = g1->scale_factors[k + l];
1118 for (j = 0; j < len; j++) {
1120 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1121 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1125 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1126 /* lower part of the spectrum : do ms stereo
1128 for (j = 0; j < len; j++) {
1131 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1132 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1139 non_zero_found = non_zero_found_short[0] |
1140 non_zero_found_short[1] |
1141 non_zero_found_short[2];
1143 for (i = g1->long_end - 1;i >= 0;i--) {
1144 len = band_size_long[s->sample_rate_index][i];
1147 /* test if non zero band. if so, stop doing i-stereo */
1148 if (!non_zero_found) {
1149 for (j = 0; j < len; j++) {
1155 /* for last band, use previous scale factor */
1156 k = (i == 21) ? 20 : i;
1157 sf = g1->scale_factors[k];
1162 for (j = 0; j < len; j++) {
1164 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1165 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1169 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1170 /* lower part of the spectrum : do ms stereo
1172 for (j = 0; j < len; j++) {
1175 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1176 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1181 } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1182 /* ms stereo ONLY */
1183 /* NOTE: the 1/sqrt(2) normalization factor is included in the
1186 s->butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1188 tab0 = g0->sb_hybrid;
1189 tab1 = g1->sb_hybrid;
1190 for (i = 0; i < 576; i++) {
1193 tab0[i] = tmp0 + tmp1;
1194 tab1[i] = tmp0 - tmp1;
1202 # include "mips/compute_antialias_float.h"
1203 #endif /* HAVE_MIPSFPU */
1206 # include "mips/compute_antialias_fixed.h"
1207 #endif /* HAVE_MIPSDSP */
1208 #endif /* USE_FLOATS */
1210 #ifndef compute_antialias
1212 #define AA(j) do { \
1213 float tmp0 = ptr[-1-j]; \
1214 float tmp1 = ptr[ j]; \
1215 ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1]; \
1216 ptr[ j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0]; \
1219 #define AA(j) do { \
1220 SUINT tmp0 = ptr[-1-j]; \
1221 SUINT tmp1 = ptr[ j]; \
1222 SUINT tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]); \
1223 ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2])); \
1224 ptr[ j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3])); \
1228 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1233 /* we antialias only "long" bands */
1234 if (g->block_type == 2) {
1235 if (!g->switch_point)
1237 /* XXX: check this for 8000Hz case */
1243 ptr = g->sb_hybrid + 18;
1244 for (i = n; i > 0; i--) {
1257 #endif /* compute_antialias */
1259 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1260 INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1262 INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1264 int i, j, mdct_long_end, sblimit;
1266 /* find last non zero block */
1267 ptr = g->sb_hybrid + 576;
1268 ptr1 = g->sb_hybrid + 2 * 18;
1269 while (ptr >= ptr1) {
1273 if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1276 sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1278 if (g->block_type == 2) {
1279 /* XXX: check for 8000 Hz */
1280 if (g->switch_point)
1285 mdct_long_end = sblimit;
1288 s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1289 mdct_long_end, g->switch_point,
1292 buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1293 ptr = g->sb_hybrid + 18 * mdct_long_end;
1295 for (j = mdct_long_end; j < sblimit; j++) {
1296 /* select frequency inversion */
1297 win = RENAME(ff_mdct_win)[2 + (4 & -(j & 1))];
1298 out_ptr = sb_samples + j;
1300 for (i = 0; i < 6; i++) {
1301 *out_ptr = buf[4*i];
1304 imdct12(out2, ptr + 0);
1305 for (i = 0; i < 6; i++) {
1306 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*1)];
1307 buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1310 imdct12(out2, ptr + 1);
1311 for (i = 0; i < 6; i++) {
1312 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*2)];
1313 buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1316 imdct12(out2, ptr + 2);
1317 for (i = 0; i < 6; i++) {
1318 buf[4*(i + 6*0)] = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*0)];
1319 buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1320 buf[4*(i + 6*2)] = 0;
1323 buf += (j&3) != 3 ? 1 : (4*18-3);
1326 for (j = sblimit; j < SBLIMIT; j++) {
1328 out_ptr = sb_samples + j;
1329 for (i = 0; i < 18; i++) {
1330 *out_ptr = buf[4*i];
1334 buf += (j&3) != 3 ? 1 : (4*18-3);
1338 /* main layer3 decoding function */
1339 static int mp_decode_layer3(MPADecodeContext *s)
1341 int nb_granules, main_data_begin;
1342 int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1344 int16_t exponents[576]; //FIXME try INTFLOAT
1347 /* read side info */
1349 ret = handle_crc(s, ((s->nb_channels == 1) ? 8*9 : 8*17));
1350 main_data_begin = get_bits(&s->gb, 8);
1351 skip_bits(&s->gb, s->nb_channels);
1354 ret = handle_crc(s, ((s->nb_channels == 1) ? 8*17 : 8*32));
1355 main_data_begin = get_bits(&s->gb, 9);
1356 if (s->nb_channels == 2)
1357 skip_bits(&s->gb, 3);
1359 skip_bits(&s->gb, 5);
1361 for (ch = 0; ch < s->nb_channels; ch++) {
1362 s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1363 s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1369 for (gr = 0; gr < nb_granules; gr++) {
1370 for (ch = 0; ch < s->nb_channels; ch++) {
1371 ff_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1372 g = &s->granules[ch][gr];
1373 g->part2_3_length = get_bits(&s->gb, 12);
1374 g->big_values = get_bits(&s->gb, 9);
1375 if (g->big_values > 288) {
1376 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1377 return AVERROR_INVALIDDATA;
1380 g->global_gain = get_bits(&s->gb, 8);
1381 /* if MS stereo only is selected, we precompute the
1382 1/sqrt(2) renormalization factor */
1383 if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1385 g->global_gain -= 2;
1387 g->scalefac_compress = get_bits(&s->gb, 9);
1389 g->scalefac_compress = get_bits(&s->gb, 4);
1390 blocksplit_flag = get_bits1(&s->gb);
1391 if (blocksplit_flag) {
1392 g->block_type = get_bits(&s->gb, 2);
1393 if (g->block_type == 0) {
1394 av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1395 return AVERROR_INVALIDDATA;
1397 g->switch_point = get_bits1(&s->gb);
1398 for (i = 0; i < 2; i++)
1399 g->table_select[i] = get_bits(&s->gb, 5);
1400 for (i = 0; i < 3; i++)
1401 g->subblock_gain[i] = get_bits(&s->gb, 3);
1402 init_short_region(s, g);
1404 int region_address1, region_address2;
1406 g->switch_point = 0;
1407 for (i = 0; i < 3; i++)
1408 g->table_select[i] = get_bits(&s->gb, 5);
1409 /* compute huffman coded region sizes */
1410 region_address1 = get_bits(&s->gb, 4);
1411 region_address2 = get_bits(&s->gb, 3);
1412 ff_dlog(s->avctx, "region1=%d region2=%d\n",
1413 region_address1, region_address2);
1414 init_long_region(s, g, region_address1, region_address2);
1416 region_offset2size(g);
1417 compute_band_indexes(s, g);
1421 g->preflag = get_bits1(&s->gb);
1422 g->scalefac_scale = get_bits1(&s->gb);
1423 g->count1table_select = get_bits1(&s->gb);
1424 ff_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1425 g->block_type, g->switch_point);
1431 const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb) >> 3);
1432 s->extrasize = av_clip((get_bits_left(&s->gb) >> 3) - s->extrasize, 0,
1433 FFMAX(0, LAST_BUF_SIZE - s->last_buf_size));
1434 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1435 /* now we get bits from the main_data_begin offset */
1436 ff_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1437 main_data_begin, s->last_buf_size);
1439 memcpy(s->last_buf + s->last_buf_size, ptr, s->extrasize);
1441 init_get_bits(&s->gb, s->last_buf, (s->last_buf_size + s->extrasize) * 8);
1442 s->last_buf_size <<= 3;
1443 for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1444 for (ch = 0; ch < s->nb_channels; ch++) {
1445 g = &s->granules[ch][gr];
1446 s->last_buf_size += g->part2_3_length;
1447 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1448 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1451 skip = s->last_buf_size - 8 * main_data_begin;
1452 if (skip >= s->gb.size_in_bits - s->extrasize * 8 && s->in_gb.buffer) {
1453 skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits + s->extrasize * 8);
1455 s->in_gb.buffer = NULL;
1458 skip_bits_long(&s->gb, skip);
1465 for (; gr < nb_granules; gr++) {
1466 for (ch = 0; ch < s->nb_channels; ch++) {
1467 g = &s->granules[ch][gr];
1468 bits_pos = get_bits_count(&s->gb);
1472 int slen, slen1, slen2;
1474 /* MPEG-1 scale factors */
1475 slen1 = slen_table[0][g->scalefac_compress];
1476 slen2 = slen_table[1][g->scalefac_compress];
1477 ff_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1478 if (g->block_type == 2) {
1479 n = g->switch_point ? 17 : 18;
1482 for (i = 0; i < n; i++)
1483 g->scale_factors[j++] = get_bits(&s->gb, slen1);
1485 for (i = 0; i < n; i++)
1486 g->scale_factors[j++] = 0;
1489 for (i = 0; i < 18; i++)
1490 g->scale_factors[j++] = get_bits(&s->gb, slen2);
1491 for (i = 0; i < 3; i++)
1492 g->scale_factors[j++] = 0;
1494 for (i = 0; i < 21; i++)
1495 g->scale_factors[j++] = 0;
1498 sc = s->granules[ch][0].scale_factors;
1500 for (k = 0; k < 4; k++) {
1502 if ((g->scfsi & (0x8 >> k)) == 0) {
1503 slen = (k < 2) ? slen1 : slen2;
1505 for (i = 0; i < n; i++)
1506 g->scale_factors[j++] = get_bits(&s->gb, slen);
1508 for (i = 0; i < n; i++)
1509 g->scale_factors[j++] = 0;
1512 /* simply copy from last granule */
1513 for (i = 0; i < n; i++) {
1514 g->scale_factors[j] = sc[j];
1519 g->scale_factors[j++] = 0;
1522 int tindex, tindex2, slen[4], sl, sf;
1524 /* LSF scale factors */
1525 if (g->block_type == 2)
1526 tindex = g->switch_point ? 2 : 1;
1530 sf = g->scalefac_compress;
1531 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1532 /* intensity stereo case */
1535 lsf_sf_expand(slen, sf, 6, 6, 0);
1537 } else if (sf < 244) {
1538 lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1541 lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1547 lsf_sf_expand(slen, sf, 5, 4, 4);
1549 } else if (sf < 500) {
1550 lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1553 lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1560 for (k = 0; k < 4; k++) {
1561 n = lsf_nsf_table[tindex2][tindex][k];
1564 for (i = 0; i < n; i++)
1565 g->scale_factors[j++] = get_bits(&s->gb, sl);
1567 for (i = 0; i < n; i++)
1568 g->scale_factors[j++] = 0;
1571 /* XXX: should compute exact size */
1573 g->scale_factors[j] = 0;
1576 exponents_from_scale_factors(s, g, exponents);
1578 /* read Huffman coded residue */
1579 huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1582 if (s->mode == MPA_JSTEREO)
1583 compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1585 for (ch = 0; ch < s->nb_channels; ch++) {
1586 g = &s->granules[ch][gr];
1588 reorder_block(s, g);
1589 compute_antialias(s, g);
1590 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1593 if (get_bits_count(&s->gb) < 0)
1594 skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1595 return nb_granules * 18;
1598 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1599 const uint8_t *buf, int buf_size)
1601 int i, nb_frames, ch, ret;
1602 OUT_INT *samples_ptr;
1604 init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1605 if (s->error_protection)
1606 s->crc = get_bits(&s->gb, 16);
1610 s->avctx->frame_size = 384;
1611 nb_frames = mp_decode_layer1(s);
1614 s->avctx->frame_size = 1152;
1615 nb_frames = mp_decode_layer2(s);
1618 s->avctx->frame_size = s->lsf ? 576 : 1152;
1620 nb_frames = mp_decode_layer3(s);
1623 if (s->in_gb.buffer) {
1624 align_get_bits(&s->gb);
1625 i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1626 if (i >= 0 && i <= BACKSTEP_SIZE) {
1627 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb) >> 3), i);
1630 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1632 s->in_gb.buffer = NULL;
1636 align_get_bits(&s->gb);
1637 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1638 i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1639 if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1641 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1642 i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1644 av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1645 memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1646 s->last_buf_size += i;
1652 /* get output buffer */
1654 av_assert0(s->frame);
1655 s->frame->nb_samples = s->avctx->frame_size;
1656 if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0)
1658 samples = (OUT_INT **)s->frame->extended_data;
1661 /* apply the synthesis filter */
1662 for (ch = 0; ch < s->nb_channels; ch++) {
1664 if (s->avctx->sample_fmt == OUT_FMT_P) {
1665 samples_ptr = samples[ch];
1668 samples_ptr = samples[0] + ch;
1669 sample_stride = s->nb_channels;
1671 for (i = 0; i < nb_frames; i++) {
1672 RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1673 &(s->synth_buf_offset[ch]),
1674 RENAME(ff_mpa_synth_window),
1675 &s->dither_state, samples_ptr,
1676 sample_stride, s->sb_samples[ch][i]);
1677 samples_ptr += 32 * sample_stride;
1681 return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1684 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1687 const uint8_t *buf = avpkt->data;
1688 int buf_size = avpkt->size;
1689 MPADecodeContext *s = avctx->priv_data;
1694 while(buf_size && !*buf){
1700 if (buf_size < HEADER_SIZE)
1701 return AVERROR_INVALIDDATA;
1703 header = AV_RB32(buf);
1704 if (header >> 8 == AV_RB32("TAG") >> 8) {
1705 av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1706 return buf_size + skipped;
1708 ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1710 av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1711 return AVERROR_INVALIDDATA;
1712 } else if (ret == 1) {
1713 /* free format: prepare to compute frame size */
1715 return AVERROR_INVALIDDATA;
1717 /* update codec info */
1718 avctx->channels = s->nb_channels;
1719 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1720 if (!avctx->bit_rate)
1721 avctx->bit_rate = s->bit_rate;
1723 if (s->frame_size <= 0) {
1724 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1725 return AVERROR_INVALIDDATA;
1726 } else if (s->frame_size < buf_size) {
1727 av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1728 buf_size= s->frame_size;
1733 ret = mp_decode_frame(s, NULL, buf, buf_size);
1735 s->frame->nb_samples = avctx->frame_size;
1737 avctx->sample_rate = s->sample_rate;
1738 //FIXME maybe move the other codec info stuff from above here too
1740 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1741 /* Only return an error if the bad frame makes up the whole packet or
1742 * the error is related to buffer management.
1743 * If there is more data in the packet, just consume the bad frame
1744 * instead of returning an error, which would discard the whole
1747 if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1751 return buf_size + skipped;
1754 static void mp_flush(MPADecodeContext *ctx)
1756 memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1757 memset(ctx->mdct_buf, 0, sizeof(ctx->mdct_buf));
1758 ctx->last_buf_size = 0;
1759 ctx->dither_state = 0;
1762 static void flush(AVCodecContext *avctx)
1764 mp_flush(avctx->priv_data);
1767 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1768 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1769 int *got_frame_ptr, AVPacket *avpkt)
1771 const uint8_t *buf = avpkt->data;
1772 int buf_size = avpkt->size;
1773 MPADecodeContext *s = avctx->priv_data;
1776 int av_unused out_size;
1780 // Discard too short frames
1781 if (buf_size < HEADER_SIZE) {
1782 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1783 return AVERROR_INVALIDDATA;
1787 if (len > MPA_MAX_CODED_FRAME_SIZE)
1788 len = MPA_MAX_CODED_FRAME_SIZE;
1790 // Get header and restore sync word
1791 header = AV_RB32(buf) | 0xffe00000;
1793 ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1795 av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1798 /* update codec info */
1799 avctx->sample_rate = s->sample_rate;
1800 avctx->channels = s->nb_channels;
1801 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1802 if (!avctx->bit_rate)
1803 avctx->bit_rate = s->bit_rate;
1805 s->frame_size = len;
1809 ret = mp_decode_frame(s, NULL, buf, buf_size);
1811 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1819 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1821 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1824 * Context for MP3On4 decoder
1826 typedef struct MP3On4DecodeContext {
1827 int frames; ///< number of mp3 frames per block (number of mp3 decoder instances)
1828 int syncword; ///< syncword patch
1829 const uint8_t *coff; ///< channel offsets in output buffer
1830 MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1831 } MP3On4DecodeContext;
1833 #include "mpeg4audio.h"
1835 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1837 /* number of mp3 decoder instances */
1838 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1840 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1841 static const uint8_t chan_offset[8][5] = {
1846 { 2, 0, 3 }, // C FLR BS
1847 { 2, 0, 3 }, // C FLR BLRS
1848 { 2, 0, 4, 3 }, // C FLR BLRS LFE
1849 { 2, 0, 6, 4, 3 }, // C FLR BLRS BLR LFE
1852 /* mp3on4 channel layouts */
1853 static const int16_t chan_layout[8] = {
1856 AV_CH_LAYOUT_STEREO,
1857 AV_CH_LAYOUT_SURROUND,
1858 AV_CH_LAYOUT_4POINT0,
1859 AV_CH_LAYOUT_5POINT0,
1860 AV_CH_LAYOUT_5POINT1,
1861 AV_CH_LAYOUT_7POINT1
1864 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1866 MP3On4DecodeContext *s = avctx->priv_data;
1869 for (i = 0; i < s->frames; i++)
1870 av_freep(&s->mp3decctx[i]);
1876 static av_cold int decode_init_mp3on4(AVCodecContext * avctx)
1878 MP3On4DecodeContext *s = avctx->priv_data;
1879 MPEG4AudioConfig cfg;
1882 if ((avctx->extradata_size < 2) || !avctx->extradata) {
1883 av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1884 return AVERROR_INVALIDDATA;
1887 avpriv_mpeg4audio_get_config2(&cfg, avctx->extradata,
1888 avctx->extradata_size, 1, avctx);
1889 if (!cfg.chan_config || cfg.chan_config > 7) {
1890 av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1891 return AVERROR_INVALIDDATA;
1893 s->frames = mp3Frames[cfg.chan_config];
1894 s->coff = chan_offset[cfg.chan_config];
1895 avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
1896 avctx->channel_layout = chan_layout[cfg.chan_config];
1898 if (cfg.sample_rate < 16000)
1899 s->syncword = 0xffe00000;
1901 s->syncword = 0xfff00000;
1903 /* Init the first mp3 decoder in standard way, so that all tables get builded
1904 * We replace avctx->priv_data with the context of the first decoder so that
1905 * decode_init() does not have to be changed.
1906 * Other decoders will be initialized here copying data from the first context
1908 // Allocate zeroed memory for the first decoder context
1909 s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1910 if (!s->mp3decctx[0])
1911 return AVERROR(ENOMEM);
1912 // Put decoder context in place to make init_decode() happy
1913 avctx->priv_data = s->mp3decctx[0];
1914 ret = decode_init(avctx);
1915 // Restore mp3on4 context pointer
1916 avctx->priv_data = s;
1919 s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1921 /* Create a separate codec/context for each frame (first is already ok).
1922 * Each frame is 1 or 2 channels - up to 5 frames allowed
1924 for (i = 1; i < s->frames; i++) {
1925 s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1926 if (!s->mp3decctx[i])
1927 return AVERROR(ENOMEM);
1928 s->mp3decctx[i]->adu_mode = 1;
1929 s->mp3decctx[i]->avctx = avctx;
1930 s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1931 s->mp3decctx[i]->butterflies_float = s->mp3decctx[0]->butterflies_float;
1938 static void flush_mp3on4(AVCodecContext *avctx)
1941 MP3On4DecodeContext *s = avctx->priv_data;
1943 for (i = 0; i < s->frames; i++)
1944 mp_flush(s->mp3decctx[i]);
1948 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1949 int *got_frame_ptr, AVPacket *avpkt)
1951 AVFrame *frame = data;
1952 const uint8_t *buf = avpkt->data;
1953 int buf_size = avpkt->size;
1954 MP3On4DecodeContext *s = avctx->priv_data;
1955 MPADecodeContext *m;
1956 int fsize, len = buf_size, out_size = 0;
1958 OUT_INT **out_samples;
1962 /* get output buffer */
1963 frame->nb_samples = MPA_FRAME_SIZE;
1964 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1966 out_samples = (OUT_INT **)frame->extended_data;
1968 // Discard too short frames
1969 if (buf_size < HEADER_SIZE)
1970 return AVERROR_INVALIDDATA;
1972 avctx->bit_rate = 0;
1975 for (fr = 0; fr < s->frames; fr++) {
1976 fsize = AV_RB16(buf) >> 4;
1977 fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1978 m = s->mp3decctx[fr];
1981 if (fsize < HEADER_SIZE) {
1982 av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1983 return AVERROR_INVALIDDATA;
1985 header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1987 ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1989 av_log(avctx, AV_LOG_ERROR, "Bad header, discard block\n");
1990 return AVERROR_INVALIDDATA;
1993 if (ch + m->nb_channels > avctx->channels ||
1994 s->coff[fr] + m->nb_channels > avctx->channels) {
1995 av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1997 return AVERROR_INVALIDDATA;
1999 ch += m->nb_channels;
2001 outptr[0] = out_samples[s->coff[fr]];
2002 if (m->nb_channels > 1)
2003 outptr[1] = out_samples[s->coff[fr] + 1];
2005 if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0) {
2006 av_log(avctx, AV_LOG_ERROR, "failed to decode channel %d\n", ch);
2007 memset(outptr[0], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2008 if (m->nb_channels > 1)
2009 memset(outptr[1], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2010 ret = m->nb_channels * MPA_FRAME_SIZE*sizeof(OUT_INT);
2017 avctx->bit_rate += m->bit_rate;
2019 if (ch != avctx->channels) {
2020 av_log(avctx, AV_LOG_ERROR, "failed to decode all channels\n");
2021 return AVERROR_INVALIDDATA;
2024 /* update codec info */
2025 avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2027 frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
2032 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */