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/avassert.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/float_dsp.h"
30 #include "libavutil/libm.h"
35 #include "mpegaudiodsp.h"
39 * - test lsf / mpeg25 extensively.
42 #include "mpegaudio.h"
43 #include "mpegaudiodecheader.h"
45 #define BACKSTEP_SIZE 512
47 #define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
49 /* layer 3 "granule" */
50 typedef struct GranuleDef {
55 int scalefac_compress;
60 uint8_t scalefac_scale;
61 uint8_t count1table_select;
62 int region_size[3]; /* number of huffman codes in each region */
64 int short_start, long_end; /* long/short band indexes */
65 uint8_t scale_factors[40];
66 DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
69 typedef struct MPADecodeContext {
71 uint8_t last_buf[LAST_BUF_SIZE];
73 /* next header (used in free format parsing) */
74 uint32_t free_format_next_header;
77 DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
78 int synth_buf_offset[MPA_MAX_CHANNELS];
79 DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
80 INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
81 GranuleDef granules[2][2]; /* Used in Layer 3 */
82 int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
85 AVCodecContext* avctx;
87 AVFloatDSPContext fdsp;
92 # define SHR(a,b) ((a)*(1.0f/(1<<(b))))
93 # define FIXR_OLD(a) ((int)((a) * FRAC_ONE + 0.5))
94 # define FIXR(x) ((float)(x))
95 # define FIXHR(x) ((float)(x))
96 # define MULH3(x, y, s) ((s)*(y)*(x))
97 # define MULLx(x, y, s) ((y)*(x))
98 # define RENAME(a) a ## _float
99 # define OUT_FMT AV_SAMPLE_FMT_FLT
100 # define OUT_FMT_P AV_SAMPLE_FMT_FLTP
102 # define SHR(a,b) ((a)>>(b))
103 /* WARNING: only correct for positive numbers */
104 # define FIXR_OLD(a) ((int)((a) * FRAC_ONE + 0.5))
105 # define FIXR(a) ((int)((a) * FRAC_ONE + 0.5))
106 # define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
107 # define MULH3(x, y, s) MULH((s)*(x), y)
108 # define MULLx(x, y, s) MULL(x,y,s)
109 # define RENAME(a) a ## _fixed
110 # define OUT_FMT AV_SAMPLE_FMT_S16
111 # define OUT_FMT_P AV_SAMPLE_FMT_S16P
116 #define HEADER_SIZE 4
118 #include "mpegaudiodata.h"
119 #include "mpegaudiodectab.h"
121 /* vlc structure for decoding layer 3 huffman tables */
122 static VLC huff_vlc[16];
123 static VLC_TYPE huff_vlc_tables[
124 0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
125 142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
127 static const int huff_vlc_tables_sizes[16] = {
128 0, 128, 128, 128, 130, 128, 154, 166,
129 142, 204, 190, 170, 542, 460, 662, 414
131 static VLC huff_quad_vlc[2];
132 static VLC_TYPE huff_quad_vlc_tables[128+16][2];
133 static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
134 /* computed from band_size_long */
135 static uint16_t band_index_long[9][23];
136 #include "mpegaudio_tablegen.h"
137 /* intensity stereo coef table */
138 static INTFLOAT is_table[2][16];
139 static INTFLOAT is_table_lsf[2][2][16];
140 static INTFLOAT csa_table[8][4];
142 static int16_t division_tab3[1<<6 ];
143 static int16_t division_tab5[1<<8 ];
144 static int16_t division_tab9[1<<11];
146 static int16_t * const division_tabs[4] = {
147 division_tab3, division_tab5, NULL, division_tab9
150 /* lower 2 bits: modulo 3, higher bits: shift */
151 static uint16_t scale_factor_modshift[64];
152 /* [i][j]: 2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
153 static int32_t scale_factor_mult[15][3];
154 /* mult table for layer 2 group quantization */
156 #define SCALE_GEN(v) \
157 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
159 static const int32_t scale_factor_mult2[3][3] = {
160 SCALE_GEN(4.0 / 3.0), /* 3 steps */
161 SCALE_GEN(4.0 / 5.0), /* 5 steps */
162 SCALE_GEN(4.0 / 9.0), /* 9 steps */
166 * Convert region offsets to region sizes and truncate
167 * size to big_values.
169 static void region_offset2size(GranuleDef *g)
172 g->region_size[2] = 576 / 2;
173 for (i = 0; i < 3; i++) {
174 k = FFMIN(g->region_size[i], g->big_values);
175 g->region_size[i] = k - j;
180 static void init_short_region(MPADecodeContext *s, GranuleDef *g)
182 if (g->block_type == 2) {
183 if (s->sample_rate_index != 8)
184 g->region_size[0] = (36 / 2);
186 g->region_size[0] = (72 / 2);
188 if (s->sample_rate_index <= 2)
189 g->region_size[0] = (36 / 2);
190 else if (s->sample_rate_index != 8)
191 g->region_size[0] = (54 / 2);
193 g->region_size[0] = (108 / 2);
195 g->region_size[1] = (576 / 2);
198 static void init_long_region(MPADecodeContext *s, GranuleDef *g,
202 g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
203 /* should not overflow */
204 l = FFMIN(ra1 + ra2 + 2, 22);
205 g->region_size[1] = band_index_long[s->sample_rate_index][ l] >> 1;
208 static void compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
210 if (g->block_type == 2) {
211 if (g->switch_point) {
212 if(s->sample_rate_index == 8)
213 avpriv_request_sample(s->avctx, "switch point in 8khz");
214 /* if switched mode, we handle the 36 first samples as
215 long blocks. For 8000Hz, we handle the 72 first
216 exponents as long blocks */
217 if (s->sample_rate_index <= 2)
233 /* layer 1 unscaling */
234 /* n = number of bits of the mantissa minus 1 */
235 static inline int l1_unscale(int n, int mant, int scale_factor)
240 shift = scale_factor_modshift[scale_factor];
243 val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
245 /* NOTE: at this point, 1 <= shift >= 21 + 15 */
246 return (int)((val + (1LL << (shift - 1))) >> shift);
249 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
253 shift = scale_factor_modshift[scale_factor];
257 val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
258 /* NOTE: at this point, 0 <= shift <= 21 */
260 val = (val + (1 << (shift - 1))) >> shift;
264 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
265 static inline int l3_unscale(int value, int exponent)
270 e = table_4_3_exp [4 * value + (exponent & 3)];
271 m = table_4_3_value[4 * value + (exponent & 3)];
275 av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
279 m = (m + (1 << (e - 1))) >> e;
284 static av_cold void decode_init_static(void)
289 /* scale factors table for layer 1/2 */
290 for (i = 0; i < 64; i++) {
292 /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
295 scale_factor_modshift[i] = mod | (shift << 2);
298 /* scale factor multiply for layer 1 */
299 for (i = 0; i < 15; i++) {
302 norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
303 scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0 * 2.0), FRAC_BITS);
304 scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
305 scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
306 av_dlog(NULL, "%d: norm=%x s=%x %x %x\n", i, norm,
307 scale_factor_mult[i][0],
308 scale_factor_mult[i][1],
309 scale_factor_mult[i][2]);
312 RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
314 /* huffman decode tables */
316 for (i = 1; i < 16; i++) {
317 const HuffTable *h = &mpa_huff_tables[i];
319 uint8_t tmp_bits [512] = { 0 };
320 uint16_t tmp_codes[512] = { 0 };
325 for (x = 0; x < xsize; x++) {
326 for (y = 0; y < xsize; y++) {
327 tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j ];
328 tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
333 huff_vlc[i].table = huff_vlc_tables+offset;
334 huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
335 init_vlc(&huff_vlc[i], 7, 512,
336 tmp_bits, 1, 1, tmp_codes, 2, 2,
337 INIT_VLC_USE_NEW_STATIC);
338 offset += huff_vlc_tables_sizes[i];
340 av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
343 for (i = 0; i < 2; i++) {
344 huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
345 huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
346 init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
347 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
348 INIT_VLC_USE_NEW_STATIC);
349 offset += huff_quad_vlc_tables_sizes[i];
351 av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
353 for (i = 0; i < 9; i++) {
355 for (j = 0; j < 22; j++) {
356 band_index_long[i][j] = k;
357 k += band_size_long[i][j];
359 band_index_long[i][22] = k;
362 /* compute n ^ (4/3) and store it in mantissa/exp format */
364 mpegaudio_tableinit();
366 for (i = 0; i < 4; i++) {
367 if (ff_mpa_quant_bits[i] < 0) {
368 for (j = 0; j < (1 << (-ff_mpa_quant_bits[i]+1)); j++) {
369 int val1, val2, val3, steps;
371 steps = ff_mpa_quant_steps[i];
376 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
382 for (i = 0; i < 7; i++) {
386 f = tan((double)i * M_PI / 12.0);
387 v = FIXR(f / (1.0 + f));
392 is_table[1][6 - i] = v;
395 for (i = 7; i < 16; i++)
396 is_table[0][i] = is_table[1][i] = 0.0;
398 for (i = 0; i < 16; i++) {
402 for (j = 0; j < 2; j++) {
403 e = -(j + 1) * ((i + 1) >> 1);
406 is_table_lsf[j][k ^ 1][i] = FIXR(f);
407 is_table_lsf[j][k ][i] = FIXR(1.0);
408 av_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
409 i, j, (float) is_table_lsf[j][0][i],
410 (float) is_table_lsf[j][1][i]);
414 for (i = 0; i < 8; i++) {
417 cs = 1.0 / sqrt(1.0 + ci * ci);
420 csa_table[i][0] = FIXHR(cs/4);
421 csa_table[i][1] = FIXHR(ca/4);
422 csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
423 csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
425 csa_table[i][0] = cs;
426 csa_table[i][1] = ca;
427 csa_table[i][2] = ca + cs;
428 csa_table[i][3] = ca - cs;
433 static av_cold int decode_init(AVCodecContext * avctx)
435 static int initialized_tables = 0;
436 MPADecodeContext *s = avctx->priv_data;
438 if (!initialized_tables) {
439 decode_init_static();
440 initialized_tables = 1;
445 avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
446 ff_mpadsp_init(&s->mpadsp);
448 if (avctx->request_sample_fmt == OUT_FMT &&
449 avctx->codec_id != AV_CODEC_ID_MP3ON4)
450 avctx->sample_fmt = OUT_FMT;
452 avctx->sample_fmt = OUT_FMT_P;
453 s->err_recognition = avctx->err_recognition;
455 if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
461 #define C3 FIXHR(0.86602540378443864676/2)
462 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
463 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
464 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
466 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
468 static void imdct12(INTFLOAT *out, INTFLOAT *in)
470 INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
473 in1 = in[1*3] + in[0*3];
474 in2 = in[2*3] + in[1*3];
475 in3 = in[3*3] + in[2*3];
476 in4 = in[4*3] + in[3*3];
477 in5 = in[5*3] + in[4*3];
481 in2 = MULH3(in2, C3, 2);
482 in3 = MULH3(in3, C3, 4);
485 t2 = MULH3(in1 - in5, C4, 2);
495 in1 = MULH3(in5 + in3, C5, 1);
502 in5 = MULH3(in5 - in3, C6, 2);
509 /* return the number of decoded frames */
510 static int mp_decode_layer1(MPADecodeContext *s)
512 int bound, i, v, n, ch, j, mant;
513 uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
514 uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
516 if (s->mode == MPA_JSTEREO)
517 bound = (s->mode_ext + 1) * 4;
521 /* allocation bits */
522 for (i = 0; i < bound; i++) {
523 for (ch = 0; ch < s->nb_channels; ch++) {
524 allocation[ch][i] = get_bits(&s->gb, 4);
527 for (i = bound; i < SBLIMIT; i++)
528 allocation[0][i] = get_bits(&s->gb, 4);
531 for (i = 0; i < bound; i++) {
532 for (ch = 0; ch < s->nb_channels; ch++) {
533 if (allocation[ch][i])
534 scale_factors[ch][i] = get_bits(&s->gb, 6);
537 for (i = bound; i < SBLIMIT; i++) {
538 if (allocation[0][i]) {
539 scale_factors[0][i] = get_bits(&s->gb, 6);
540 scale_factors[1][i] = get_bits(&s->gb, 6);
544 /* compute samples */
545 for (j = 0; j < 12; j++) {
546 for (i = 0; i < bound; i++) {
547 for (ch = 0; ch < s->nb_channels; ch++) {
548 n = allocation[ch][i];
550 mant = get_bits(&s->gb, n + 1);
551 v = l1_unscale(n, mant, scale_factors[ch][i]);
555 s->sb_samples[ch][j][i] = v;
558 for (i = bound; i < SBLIMIT; i++) {
559 n = allocation[0][i];
561 mant = get_bits(&s->gb, n + 1);
562 v = l1_unscale(n, mant, scale_factors[0][i]);
563 s->sb_samples[0][j][i] = v;
564 v = l1_unscale(n, mant, scale_factors[1][i]);
565 s->sb_samples[1][j][i] = v;
567 s->sb_samples[0][j][i] = 0;
568 s->sb_samples[1][j][i] = 0;
575 static int mp_decode_layer2(MPADecodeContext *s)
577 int sblimit; /* number of used subbands */
578 const unsigned char *alloc_table;
579 int table, bit_alloc_bits, i, j, ch, bound, v;
580 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
581 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
582 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
583 int scale, qindex, bits, steps, k, l, m, b;
585 /* select decoding table */
586 table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
587 s->sample_rate, s->lsf);
588 sblimit = ff_mpa_sblimit_table[table];
589 alloc_table = ff_mpa_alloc_tables[table];
591 if (s->mode == MPA_JSTEREO)
592 bound = (s->mode_ext + 1) * 4;
596 av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
602 /* parse bit allocation */
604 for (i = 0; i < bound; i++) {
605 bit_alloc_bits = alloc_table[j];
606 for (ch = 0; ch < s->nb_channels; ch++)
607 bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
608 j += 1 << bit_alloc_bits;
610 for (i = bound; i < sblimit; i++) {
611 bit_alloc_bits = alloc_table[j];
612 v = get_bits(&s->gb, bit_alloc_bits);
615 j += 1 << bit_alloc_bits;
619 for (i = 0; i < sblimit; i++) {
620 for (ch = 0; ch < s->nb_channels; ch++) {
621 if (bit_alloc[ch][i])
622 scale_code[ch][i] = get_bits(&s->gb, 2);
627 for (i = 0; i < sblimit; i++) {
628 for (ch = 0; ch < s->nb_channels; ch++) {
629 if (bit_alloc[ch][i]) {
630 sf = scale_factors[ch][i];
631 switch (scale_code[ch][i]) {
634 sf[0] = get_bits(&s->gb, 6);
635 sf[1] = get_bits(&s->gb, 6);
636 sf[2] = get_bits(&s->gb, 6);
639 sf[0] = get_bits(&s->gb, 6);
644 sf[0] = get_bits(&s->gb, 6);
645 sf[2] = get_bits(&s->gb, 6);
649 sf[0] = get_bits(&s->gb, 6);
650 sf[2] = get_bits(&s->gb, 6);
659 for (k = 0; k < 3; k++) {
660 for (l = 0; l < 12; l += 3) {
662 for (i = 0; i < bound; i++) {
663 bit_alloc_bits = alloc_table[j];
664 for (ch = 0; ch < s->nb_channels; ch++) {
665 b = bit_alloc[ch][i];
667 scale = scale_factors[ch][i][k];
668 qindex = alloc_table[j+b];
669 bits = ff_mpa_quant_bits[qindex];
672 /* 3 values at the same time */
673 v = get_bits(&s->gb, -bits);
674 v2 = division_tabs[qindex][v];
675 steps = ff_mpa_quant_steps[qindex];
677 s->sb_samples[ch][k * 12 + l + 0][i] =
678 l2_unscale_group(steps, v2 & 15, scale);
679 s->sb_samples[ch][k * 12 + l + 1][i] =
680 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
681 s->sb_samples[ch][k * 12 + l + 2][i] =
682 l2_unscale_group(steps, v2 >> 8 , scale);
684 for (m = 0; m < 3; m++) {
685 v = get_bits(&s->gb, bits);
686 v = l1_unscale(bits - 1, v, scale);
687 s->sb_samples[ch][k * 12 + l + m][i] = v;
691 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
692 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
693 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
696 /* next subband in alloc table */
697 j += 1 << bit_alloc_bits;
699 /* XXX: find a way to avoid this duplication of code */
700 for (i = bound; i < sblimit; i++) {
701 bit_alloc_bits = alloc_table[j];
704 int mant, scale0, scale1;
705 scale0 = scale_factors[0][i][k];
706 scale1 = scale_factors[1][i][k];
707 qindex = alloc_table[j+b];
708 bits = ff_mpa_quant_bits[qindex];
710 /* 3 values at the same time */
711 v = get_bits(&s->gb, -bits);
712 steps = ff_mpa_quant_steps[qindex];
715 s->sb_samples[0][k * 12 + l + 0][i] =
716 l2_unscale_group(steps, mant, scale0);
717 s->sb_samples[1][k * 12 + l + 0][i] =
718 l2_unscale_group(steps, mant, scale1);
721 s->sb_samples[0][k * 12 + l + 1][i] =
722 l2_unscale_group(steps, mant, scale0);
723 s->sb_samples[1][k * 12 + l + 1][i] =
724 l2_unscale_group(steps, mant, scale1);
725 s->sb_samples[0][k * 12 + l + 2][i] =
726 l2_unscale_group(steps, v, scale0);
727 s->sb_samples[1][k * 12 + l + 2][i] =
728 l2_unscale_group(steps, v, scale1);
730 for (m = 0; m < 3; m++) {
731 mant = get_bits(&s->gb, bits);
732 s->sb_samples[0][k * 12 + l + m][i] =
733 l1_unscale(bits - 1, mant, scale0);
734 s->sb_samples[1][k * 12 + l + m][i] =
735 l1_unscale(bits - 1, mant, scale1);
739 s->sb_samples[0][k * 12 + l + 0][i] = 0;
740 s->sb_samples[0][k * 12 + l + 1][i] = 0;
741 s->sb_samples[0][k * 12 + l + 2][i] = 0;
742 s->sb_samples[1][k * 12 + l + 0][i] = 0;
743 s->sb_samples[1][k * 12 + l + 1][i] = 0;
744 s->sb_samples[1][k * 12 + l + 2][i] = 0;
746 /* next subband in alloc table */
747 j += 1 << bit_alloc_bits;
749 /* fill remaining samples to zero */
750 for (i = sblimit; i < SBLIMIT; i++) {
751 for (ch = 0; ch < s->nb_channels; ch++) {
752 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
753 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
754 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
762 #define SPLIT(dst,sf,n) \
764 int m = (sf * 171) >> 9; \
767 } else if (n == 4) { \
770 } else if (n == 5) { \
771 int m = (sf * 205) >> 10; \
774 } else if (n == 6) { \
775 int m = (sf * 171) >> 10; \
782 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
785 SPLIT(slen[3], sf, n3)
786 SPLIT(slen[2], sf, n2)
787 SPLIT(slen[1], sf, n1)
791 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
794 const uint8_t *bstab, *pretab;
795 int len, i, j, k, l, v0, shift, gain, gains[3];
799 gain = g->global_gain - 210;
800 shift = g->scalefac_scale + 1;
802 bstab = band_size_long[s->sample_rate_index];
803 pretab = mpa_pretab[g->preflag];
804 for (i = 0; i < g->long_end; i++) {
805 v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
807 for (j = len; j > 0; j--)
811 if (g->short_start < 13) {
812 bstab = band_size_short[s->sample_rate_index];
813 gains[0] = gain - (g->subblock_gain[0] << 3);
814 gains[1] = gain - (g->subblock_gain[1] << 3);
815 gains[2] = gain - (g->subblock_gain[2] << 3);
817 for (i = g->short_start; i < 13; i++) {
819 for (l = 0; l < 3; l++) {
820 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
821 for (j = len; j > 0; j--)
828 /* handle n = 0 too */
829 static inline int get_bitsz(GetBitContext *s, int n)
831 return n ? get_bits(s, n) : 0;
835 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
838 if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
840 s->in_gb.buffer = NULL;
841 av_assert2((get_bits_count(&s->gb) & 7) == 0);
842 skip_bits_long(&s->gb, *pos - *end_pos);
844 *end_pos = *end_pos2 + get_bits_count(&s->gb) - *pos;
845 *pos = get_bits_count(&s->gb);
849 /* Following is a optimized code for
851 if(get_bits1(&s->gb))
856 #define READ_FLIP_SIGN(dst,src) \
857 v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31); \
860 #define READ_FLIP_SIGN(dst,src) \
861 v = -get_bits1(&s->gb); \
862 *(dst) = (*(src) ^ v) - v;
865 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
866 int16_t *exponents, int end_pos2)
870 int last_pos, bits_left;
872 int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
874 /* low frequencies (called big values) */
876 for (i = 0; i < 3; i++) {
877 int j, k, l, linbits;
878 j = g->region_size[i];
881 /* select vlc table */
882 k = g->table_select[i];
883 l = mpa_huff_data[k][0];
884 linbits = mpa_huff_data[k][1];
888 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
893 /* read huffcode and compute each couple */
897 int pos = get_bits_count(&s->gb);
900 switch_buffer(s, &pos, &end_pos, &end_pos2);
904 y = get_vlc2(&s->gb, vlc->table, 7, 3);
907 g->sb_hybrid[s_index ] =
908 g->sb_hybrid[s_index+1] = 0;
913 exponent= exponents[s_index];
915 av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
916 i, g->region_size[i] - j, x, y, exponent);
921 READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
923 x += get_bitsz(&s->gb, linbits);
924 v = l3_unscale(x, exponent);
925 if (get_bits1(&s->gb))
927 g->sb_hybrid[s_index] = v;
930 READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
932 y += get_bitsz(&s->gb, linbits);
933 v = l3_unscale(y, exponent);
934 if (get_bits1(&s->gb))
936 g->sb_hybrid[s_index+1] = v;
943 READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
945 x += get_bitsz(&s->gb, linbits);
946 v = l3_unscale(x, exponent);
947 if (get_bits1(&s->gb))
949 g->sb_hybrid[s_index+!!y] = v;
951 g->sb_hybrid[s_index + !y] = 0;
957 /* high frequencies */
958 vlc = &huff_quad_vlc[g->count1table_select];
960 while (s_index <= 572) {
962 pos = get_bits_count(&s->gb);
963 if (pos >= end_pos) {
964 if (pos > end_pos2 && last_pos) {
965 /* some encoders generate an incorrect size for this
966 part. We must go back into the data */
968 skip_bits_long(&s->gb, last_pos - pos);
969 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
970 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
974 switch_buffer(s, &pos, &end_pos, &end_pos2);
980 code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
981 av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
982 g->sb_hybrid[s_index+0] =
983 g->sb_hybrid[s_index+1] =
984 g->sb_hybrid[s_index+2] =
985 g->sb_hybrid[s_index+3] = 0;
987 static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
989 int pos = s_index + idxtab[code];
990 code ^= 8 >> idxtab[code];
991 READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
995 /* skip extension bits */
996 bits_left = end_pos2 - get_bits_count(&s->gb);
997 if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
998 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1000 } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1001 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1004 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1005 skip_bits_long(&s->gb, bits_left);
1007 i = get_bits_count(&s->gb);
1008 switch_buffer(s, &i, &end_pos, &end_pos2);
1013 /* Reorder short blocks from bitstream order to interleaved order. It
1014 would be faster to do it in parsing, but the code would be far more
1016 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1019 INTFLOAT *ptr, *dst, *ptr1;
1022 if (g->block_type != 2)
1025 if (g->switch_point) {
1026 if (s->sample_rate_index != 8)
1027 ptr = g->sb_hybrid + 36;
1029 ptr = g->sb_hybrid + 72;
1034 for (i = g->short_start; i < 13; i++) {
1035 len = band_size_short[s->sample_rate_index][i];
1038 for (j = len; j > 0; j--) {
1039 *dst++ = ptr[0*len];
1040 *dst++ = ptr[1*len];
1041 *dst++ = ptr[2*len];
1045 memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1049 #define ISQRT2 FIXR(0.70710678118654752440)
1051 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1054 int sf_max, sf, len, non_zero_found;
1055 INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1056 int non_zero_found_short[3];
1058 /* intensity stereo */
1059 if (s->mode_ext & MODE_EXT_I_STEREO) {
1064 is_tab = is_table_lsf[g1->scalefac_compress & 1];
1068 tab0 = g0->sb_hybrid + 576;
1069 tab1 = g1->sb_hybrid + 576;
1071 non_zero_found_short[0] = 0;
1072 non_zero_found_short[1] = 0;
1073 non_zero_found_short[2] = 0;
1074 k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1075 for (i = 12; i >= g1->short_start; i--) {
1076 /* for last band, use previous scale factor */
1079 len = band_size_short[s->sample_rate_index][i];
1080 for (l = 2; l >= 0; l--) {
1083 if (!non_zero_found_short[l]) {
1084 /* test if non zero band. if so, stop doing i-stereo */
1085 for (j = 0; j < len; j++) {
1087 non_zero_found_short[l] = 1;
1091 sf = g1->scale_factors[k + l];
1097 for (j = 0; j < len; j++) {
1099 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1100 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1104 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1105 /* lower part of the spectrum : do ms stereo
1107 for (j = 0; j < len; j++) {
1110 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1111 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1118 non_zero_found = non_zero_found_short[0] |
1119 non_zero_found_short[1] |
1120 non_zero_found_short[2];
1122 for (i = g1->long_end - 1;i >= 0;i--) {
1123 len = band_size_long[s->sample_rate_index][i];
1126 /* test if non zero band. if so, stop doing i-stereo */
1127 if (!non_zero_found) {
1128 for (j = 0; j < len; j++) {
1134 /* for last band, use previous scale factor */
1135 k = (i == 21) ? 20 : i;
1136 sf = g1->scale_factors[k];
1141 for (j = 0; j < len; j++) {
1143 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1144 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1148 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1149 /* lower part of the spectrum : do ms stereo
1151 for (j = 0; j < len; j++) {
1154 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1155 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1160 } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1161 /* ms stereo ONLY */
1162 /* NOTE: the 1/sqrt(2) normalization factor is included in the
1165 s->fdsp.butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1167 tab0 = g0->sb_hybrid;
1168 tab1 = g1->sb_hybrid;
1169 for (i = 0; i < 576; i++) {
1172 tab0[i] = tmp0 + tmp1;
1173 tab1[i] = tmp0 - tmp1;
1181 # include "mips/compute_antialias_float.h"
1182 #endif /* HAVE_MIPSFPU */
1185 # include "mips/compute_antialias_fixed.h"
1186 #endif /* HAVE_MIPSDSPR1 */
1187 #endif /* CONFIG_FLOAT */
1189 #ifndef compute_antialias
1191 #define AA(j) do { \
1192 float tmp0 = ptr[-1-j]; \
1193 float tmp1 = ptr[ j]; \
1194 ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1]; \
1195 ptr[ j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0]; \
1198 #define AA(j) do { \
1199 int tmp0 = ptr[-1-j]; \
1200 int tmp1 = ptr[ j]; \
1201 int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]); \
1202 ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2])); \
1203 ptr[ j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3])); \
1207 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1212 /* we antialias only "long" bands */
1213 if (g->block_type == 2) {
1214 if (!g->switch_point)
1216 /* XXX: check this for 8000Hz case */
1222 ptr = g->sb_hybrid + 18;
1223 for (i = n; i > 0; i--) {
1236 #endif /* compute_antialias */
1238 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1239 INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1241 INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1243 int i, j, mdct_long_end, sblimit;
1245 /* find last non zero block */
1246 ptr = g->sb_hybrid + 576;
1247 ptr1 = g->sb_hybrid + 2 * 18;
1248 while (ptr >= ptr1) {
1252 if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1255 sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1257 if (g->block_type == 2) {
1258 /* XXX: check for 8000 Hz */
1259 if (g->switch_point)
1264 mdct_long_end = sblimit;
1267 s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1268 mdct_long_end, g->switch_point,
1271 buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1272 ptr = g->sb_hybrid + 18 * mdct_long_end;
1274 for (j = mdct_long_end; j < sblimit; j++) {
1275 /* select frequency inversion */
1276 win = RENAME(ff_mdct_win)[2 + (4 & -(j & 1))];
1277 out_ptr = sb_samples + j;
1279 for (i = 0; i < 6; i++) {
1280 *out_ptr = buf[4*i];
1283 imdct12(out2, ptr + 0);
1284 for (i = 0; i < 6; i++) {
1285 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*1)];
1286 buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1289 imdct12(out2, ptr + 1);
1290 for (i = 0; i < 6; i++) {
1291 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*2)];
1292 buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1295 imdct12(out2, ptr + 2);
1296 for (i = 0; i < 6; i++) {
1297 buf[4*(i + 6*0)] = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*0)];
1298 buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1299 buf[4*(i + 6*2)] = 0;
1302 buf += (j&3) != 3 ? 1 : (4*18-3);
1305 for (j = sblimit; j < SBLIMIT; j++) {
1307 out_ptr = sb_samples + j;
1308 for (i = 0; i < 18; i++) {
1309 *out_ptr = buf[4*i];
1313 buf += (j&3) != 3 ? 1 : (4*18-3);
1317 /* main layer3 decoding function */
1318 static int mp_decode_layer3(MPADecodeContext *s)
1320 int nb_granules, main_data_begin;
1321 int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1323 int16_t exponents[576]; //FIXME try INTFLOAT
1325 /* read side info */
1327 main_data_begin = get_bits(&s->gb, 8);
1328 skip_bits(&s->gb, s->nb_channels);
1331 main_data_begin = get_bits(&s->gb, 9);
1332 if (s->nb_channels == 2)
1333 skip_bits(&s->gb, 3);
1335 skip_bits(&s->gb, 5);
1337 for (ch = 0; ch < s->nb_channels; ch++) {
1338 s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1339 s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1343 for (gr = 0; gr < nb_granules; gr++) {
1344 for (ch = 0; ch < s->nb_channels; ch++) {
1345 av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1346 g = &s->granules[ch][gr];
1347 g->part2_3_length = get_bits(&s->gb, 12);
1348 g->big_values = get_bits(&s->gb, 9);
1349 if (g->big_values > 288) {
1350 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1351 return AVERROR_INVALIDDATA;
1354 g->global_gain = get_bits(&s->gb, 8);
1355 /* if MS stereo only is selected, we precompute the
1356 1/sqrt(2) renormalization factor */
1357 if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1359 g->global_gain -= 2;
1361 g->scalefac_compress = get_bits(&s->gb, 9);
1363 g->scalefac_compress = get_bits(&s->gb, 4);
1364 blocksplit_flag = get_bits1(&s->gb);
1365 if (blocksplit_flag) {
1366 g->block_type = get_bits(&s->gb, 2);
1367 if (g->block_type == 0) {
1368 av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1369 return AVERROR_INVALIDDATA;
1371 g->switch_point = get_bits1(&s->gb);
1372 for (i = 0; i < 2; i++)
1373 g->table_select[i] = get_bits(&s->gb, 5);
1374 for (i = 0; i < 3; i++)
1375 g->subblock_gain[i] = get_bits(&s->gb, 3);
1376 init_short_region(s, g);
1378 int region_address1, region_address2;
1380 g->switch_point = 0;
1381 for (i = 0; i < 3; i++)
1382 g->table_select[i] = get_bits(&s->gb, 5);
1383 /* compute huffman coded region sizes */
1384 region_address1 = get_bits(&s->gb, 4);
1385 region_address2 = get_bits(&s->gb, 3);
1386 av_dlog(s->avctx, "region1=%d region2=%d\n",
1387 region_address1, region_address2);
1388 init_long_region(s, g, region_address1, region_address2);
1390 region_offset2size(g);
1391 compute_band_indexes(s, g);
1395 g->preflag = get_bits1(&s->gb);
1396 g->scalefac_scale = get_bits1(&s->gb);
1397 g->count1table_select = get_bits1(&s->gb);
1398 av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1399 g->block_type, g->switch_point);
1405 const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1406 int extrasize = av_clip(get_bits_left(&s->gb) >> 3, 0, EXTRABYTES);
1407 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1408 /* now we get bits from the main_data_begin offset */
1409 av_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1410 main_data_begin, s->last_buf_size);
1412 memcpy(s->last_buf + s->last_buf_size, ptr, extrasize);
1414 init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1415 #if !UNCHECKED_BITSTREAM_READER
1416 s->gb.size_in_bits_plus8 += FFMAX(extrasize, LAST_BUF_SIZE - s->last_buf_size) * 8;
1418 s->last_buf_size <<= 3;
1419 for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1420 for (ch = 0; ch < s->nb_channels; ch++) {
1421 g = &s->granules[ch][gr];
1422 s->last_buf_size += g->part2_3_length;
1423 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1424 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1427 skip = s->last_buf_size - 8 * main_data_begin;
1428 if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
1429 skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
1431 s->in_gb.buffer = NULL;
1433 skip_bits_long(&s->gb, skip);
1439 for (; gr < nb_granules; gr++) {
1440 for (ch = 0; ch < s->nb_channels; ch++) {
1441 g = &s->granules[ch][gr];
1442 bits_pos = get_bits_count(&s->gb);
1446 int slen, slen1, slen2;
1448 /* MPEG1 scale factors */
1449 slen1 = slen_table[0][g->scalefac_compress];
1450 slen2 = slen_table[1][g->scalefac_compress];
1451 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1452 if (g->block_type == 2) {
1453 n = g->switch_point ? 17 : 18;
1456 for (i = 0; i < n; i++)
1457 g->scale_factors[j++] = get_bits(&s->gb, slen1);
1459 for (i = 0; i < n; i++)
1460 g->scale_factors[j++] = 0;
1463 for (i = 0; i < 18; i++)
1464 g->scale_factors[j++] = get_bits(&s->gb, slen2);
1465 for (i = 0; i < 3; i++)
1466 g->scale_factors[j++] = 0;
1468 for (i = 0; i < 21; i++)
1469 g->scale_factors[j++] = 0;
1472 sc = s->granules[ch][0].scale_factors;
1474 for (k = 0; k < 4; k++) {
1476 if ((g->scfsi & (0x8 >> k)) == 0) {
1477 slen = (k < 2) ? slen1 : slen2;
1479 for (i = 0; i < n; i++)
1480 g->scale_factors[j++] = get_bits(&s->gb, slen);
1482 for (i = 0; i < n; i++)
1483 g->scale_factors[j++] = 0;
1486 /* simply copy from last granule */
1487 for (i = 0; i < n; i++) {
1488 g->scale_factors[j] = sc[j];
1493 g->scale_factors[j++] = 0;
1496 int tindex, tindex2, slen[4], sl, sf;
1498 /* LSF scale factors */
1499 if (g->block_type == 2)
1500 tindex = g->switch_point ? 2 : 1;
1504 sf = g->scalefac_compress;
1505 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1506 /* intensity stereo case */
1509 lsf_sf_expand(slen, sf, 6, 6, 0);
1511 } else if (sf < 244) {
1512 lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1515 lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1521 lsf_sf_expand(slen, sf, 5, 4, 4);
1523 } else if (sf < 500) {
1524 lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1527 lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1534 for (k = 0; k < 4; k++) {
1535 n = lsf_nsf_table[tindex2][tindex][k];
1538 for (i = 0; i < n; i++)
1539 g->scale_factors[j++] = get_bits(&s->gb, sl);
1541 for (i = 0; i < n; i++)
1542 g->scale_factors[j++] = 0;
1545 /* XXX: should compute exact size */
1547 g->scale_factors[j] = 0;
1550 exponents_from_scale_factors(s, g, exponents);
1552 /* read Huffman coded residue */
1553 huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1556 if (s->mode == MPA_JSTEREO)
1557 compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1559 for (ch = 0; ch < s->nb_channels; ch++) {
1560 g = &s->granules[ch][gr];
1562 reorder_block(s, g);
1563 compute_antialias(s, g);
1564 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1567 if (get_bits_count(&s->gb) < 0)
1568 skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1569 return nb_granules * 18;
1572 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1573 const uint8_t *buf, int buf_size)
1575 int i, nb_frames, ch, ret;
1576 OUT_INT *samples_ptr;
1578 init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1580 /* skip error protection field */
1581 if (s->error_protection)
1582 skip_bits(&s->gb, 16);
1586 s->avctx->frame_size = 384;
1587 nb_frames = mp_decode_layer1(s);
1590 s->avctx->frame_size = 1152;
1591 nb_frames = mp_decode_layer2(s);
1594 s->avctx->frame_size = s->lsf ? 576 : 1152;
1596 nb_frames = mp_decode_layer3(s);
1599 if (s->in_gb.buffer) {
1600 align_get_bits(&s->gb);
1601 i = get_bits_left(&s->gb)>>3;
1602 if (i >= 0 && i <= BACKSTEP_SIZE) {
1603 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1606 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1608 s->in_gb.buffer = NULL;
1611 align_get_bits(&s->gb);
1612 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1613 i = get_bits_left(&s->gb) >> 3;
1615 if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1617 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1618 i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1620 av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1621 memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1622 s->last_buf_size += i;
1628 /* get output buffer */
1630 av_assert0(s->frame != NULL);
1631 s->frame->nb_samples = s->avctx->frame_size;
1632 if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0)
1634 samples = (OUT_INT **)s->frame->extended_data;
1637 /* apply the synthesis filter */
1638 for (ch = 0; ch < s->nb_channels; ch++) {
1640 if (s->avctx->sample_fmt == OUT_FMT_P) {
1641 samples_ptr = samples[ch];
1644 samples_ptr = samples[0] + ch;
1645 sample_stride = s->nb_channels;
1647 for (i = 0; i < nb_frames; i++) {
1648 RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1649 &(s->synth_buf_offset[ch]),
1650 RENAME(ff_mpa_synth_window),
1651 &s->dither_state, samples_ptr,
1652 sample_stride, s->sb_samples[ch][i]);
1653 samples_ptr += 32 * sample_stride;
1657 return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1660 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1663 const uint8_t *buf = avpkt->data;
1664 int buf_size = avpkt->size;
1665 MPADecodeContext *s = avctx->priv_data;
1669 while(buf_size && !*buf){
1674 if (buf_size < HEADER_SIZE)
1675 return AVERROR_INVALIDDATA;
1677 header = AV_RB32(buf);
1678 if (header>>8 == AV_RB32("TAG")>>8) {
1679 av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1682 if (ff_mpa_check_header(header) < 0) {
1683 av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1684 return AVERROR_INVALIDDATA;
1687 if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1688 /* free format: prepare to compute frame size */
1690 return AVERROR_INVALIDDATA;
1692 /* update codec info */
1693 avctx->channels = s->nb_channels;
1694 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1695 if (!avctx->bit_rate)
1696 avctx->bit_rate = s->bit_rate;
1698 if (s->frame_size <= 0 || s->frame_size > buf_size) {
1699 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1700 return AVERROR_INVALIDDATA;
1701 } else if (s->frame_size < buf_size) {
1702 av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1703 buf_size= s->frame_size;
1708 ret = mp_decode_frame(s, NULL, buf, buf_size);
1710 s->frame->nb_samples = avctx->frame_size;
1712 avctx->sample_rate = s->sample_rate;
1713 //FIXME maybe move the other codec info stuff from above here too
1715 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1716 /* Only return an error if the bad frame makes up the whole packet or
1717 * the error is related to buffer management.
1718 * If there is more data in the packet, just consume the bad frame
1719 * instead of returning an error, which would discard the whole
1722 if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1729 static void mp_flush(MPADecodeContext *ctx)
1731 memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1732 ctx->last_buf_size = 0;
1735 static void flush(AVCodecContext *avctx)
1737 mp_flush(avctx->priv_data);
1740 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1741 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1742 int *got_frame_ptr, AVPacket *avpkt)
1744 const uint8_t *buf = avpkt->data;
1745 int buf_size = avpkt->size;
1746 MPADecodeContext *s = avctx->priv_data;
1749 int av_unused out_size;
1753 // Discard too short frames
1754 if (buf_size < HEADER_SIZE) {
1755 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1756 return AVERROR_INVALIDDATA;
1760 if (len > MPA_MAX_CODED_FRAME_SIZE)
1761 len = MPA_MAX_CODED_FRAME_SIZE;
1763 // Get header and restore sync word
1764 header = AV_RB32(buf) | 0xffe00000;
1766 if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
1767 av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1768 return AVERROR_INVALIDDATA;
1771 avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1772 /* update codec info */
1773 avctx->sample_rate = s->sample_rate;
1774 avctx->channels = s->nb_channels;
1775 if (!avctx->bit_rate)
1776 avctx->bit_rate = s->bit_rate;
1778 s->frame_size = len;
1782 ret = mp_decode_frame(s, NULL, buf, buf_size);
1784 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1792 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1794 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1797 * Context for MP3On4 decoder
1799 typedef struct MP3On4DecodeContext {
1800 int frames; ///< number of mp3 frames per block (number of mp3 decoder instances)
1801 int syncword; ///< syncword patch
1802 const uint8_t *coff; ///< channel offsets in output buffer
1803 MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1804 } MP3On4DecodeContext;
1806 #include "mpeg4audio.h"
1808 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1810 /* number of mp3 decoder instances */
1811 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1813 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1814 static const uint8_t chan_offset[8][5] = {
1819 { 2, 0, 3 }, // C FLR BS
1820 { 2, 0, 3 }, // C FLR BLRS
1821 { 2, 0, 4, 3 }, // C FLR BLRS LFE
1822 { 2, 0, 6, 4, 3 }, // C FLR BLRS BLR LFE
1825 /* mp3on4 channel layouts */
1826 static const int16_t chan_layout[8] = {
1829 AV_CH_LAYOUT_STEREO,
1830 AV_CH_LAYOUT_SURROUND,
1831 AV_CH_LAYOUT_4POINT0,
1832 AV_CH_LAYOUT_5POINT0,
1833 AV_CH_LAYOUT_5POINT1,
1834 AV_CH_LAYOUT_7POINT1
1837 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1839 MP3On4DecodeContext *s = avctx->priv_data;
1842 for (i = 0; i < s->frames; i++)
1843 av_free(s->mp3decctx[i]);
1849 static int decode_init_mp3on4(AVCodecContext * avctx)
1851 MP3On4DecodeContext *s = avctx->priv_data;
1852 MPEG4AudioConfig cfg;
1855 if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
1856 av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1857 return AVERROR_INVALIDDATA;
1860 avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
1861 avctx->extradata_size * 8, 1);
1862 if (!cfg.chan_config || cfg.chan_config > 7) {
1863 av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1864 return AVERROR_INVALIDDATA;
1866 s->frames = mp3Frames[cfg.chan_config];
1867 s->coff = chan_offset[cfg.chan_config];
1868 avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
1869 avctx->channel_layout = chan_layout[cfg.chan_config];
1871 if (cfg.sample_rate < 16000)
1872 s->syncword = 0xffe00000;
1874 s->syncword = 0xfff00000;
1876 /* Init the first mp3 decoder in standard way, so that all tables get builded
1877 * We replace avctx->priv_data with the context of the first decoder so that
1878 * decode_init() does not have to be changed.
1879 * Other decoders will be initialized here copying data from the first context
1881 // Allocate zeroed memory for the first decoder context
1882 s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1883 if (!s->mp3decctx[0])
1885 // Put decoder context in place to make init_decode() happy
1886 avctx->priv_data = s->mp3decctx[0];
1888 // Restore mp3on4 context pointer
1889 avctx->priv_data = s;
1890 s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1892 /* Create a separate codec/context for each frame (first is already ok).
1893 * Each frame is 1 or 2 channels - up to 5 frames allowed
1895 for (i = 1; i < s->frames; i++) {
1896 s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1897 if (!s->mp3decctx[i])
1899 s->mp3decctx[i]->adu_mode = 1;
1900 s->mp3decctx[i]->avctx = avctx;
1901 s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1906 decode_close_mp3on4(avctx);
1907 return AVERROR(ENOMEM);
1911 static void flush_mp3on4(AVCodecContext *avctx)
1914 MP3On4DecodeContext *s = avctx->priv_data;
1916 for (i = 0; i < s->frames; i++)
1917 mp_flush(s->mp3decctx[i]);
1921 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1922 int *got_frame_ptr, AVPacket *avpkt)
1924 AVFrame *frame = data;
1925 const uint8_t *buf = avpkt->data;
1926 int buf_size = avpkt->size;
1927 MP3On4DecodeContext *s = avctx->priv_data;
1928 MPADecodeContext *m;
1929 int fsize, len = buf_size, out_size = 0;
1931 OUT_INT **out_samples;
1935 /* get output buffer */
1936 frame->nb_samples = MPA_FRAME_SIZE;
1937 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1939 out_samples = (OUT_INT **)frame->extended_data;
1941 // Discard too short frames
1942 if (buf_size < HEADER_SIZE)
1943 return AVERROR_INVALIDDATA;
1945 avctx->bit_rate = 0;
1948 for (fr = 0; fr < s->frames; fr++) {
1949 fsize = AV_RB16(buf) >> 4;
1950 fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1951 m = s->mp3decctx[fr];
1954 if (fsize < HEADER_SIZE) {
1955 av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1956 return AVERROR_INVALIDDATA;
1958 header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1960 if (ff_mpa_check_header(header) < 0) // Bad header, discard block
1963 avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1965 if (ch + m->nb_channels > avctx->channels || s->coff[fr] + m->nb_channels > avctx->channels) {
1966 av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1968 return AVERROR_INVALIDDATA;
1970 ch += m->nb_channels;
1972 outptr[0] = out_samples[s->coff[fr]];
1973 if (m->nb_channels > 1)
1974 outptr[1] = out_samples[s->coff[fr] + 1];
1976 if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
1983 avctx->bit_rate += m->bit_rate;
1986 /* update codec info */
1987 avctx->sample_rate = s->mp3decctx[0]->sample_rate;
1989 frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
1994 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
1997 #if CONFIG_MP1_DECODER
1998 AVCodec ff_mp1_decoder = {
2000 .type = AVMEDIA_TYPE_AUDIO,
2001 .id = AV_CODEC_ID_MP1,
2002 .priv_data_size = sizeof(MPADecodeContext),
2003 .init = decode_init,
2004 .decode = decode_frame,
2005 .capabilities = CODEC_CAP_DR1,
2007 .long_name = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2008 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2010 AV_SAMPLE_FMT_NONE },
2013 #if CONFIG_MP2_DECODER
2014 AVCodec ff_mp2_decoder = {
2016 .type = AVMEDIA_TYPE_AUDIO,
2017 .id = AV_CODEC_ID_MP2,
2018 .priv_data_size = sizeof(MPADecodeContext),
2019 .init = decode_init,
2020 .decode = decode_frame,
2021 .capabilities = CODEC_CAP_DR1,
2023 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2024 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2026 AV_SAMPLE_FMT_NONE },
2029 #if CONFIG_MP3_DECODER
2030 AVCodec ff_mp3_decoder = {
2032 .type = AVMEDIA_TYPE_AUDIO,
2033 .id = AV_CODEC_ID_MP3,
2034 .priv_data_size = sizeof(MPADecodeContext),
2035 .init = decode_init,
2036 .decode = decode_frame,
2037 .capabilities = CODEC_CAP_DR1,
2039 .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2040 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2042 AV_SAMPLE_FMT_NONE },
2045 #if CONFIG_MP3ADU_DECODER
2046 AVCodec ff_mp3adu_decoder = {
2048 .type = AVMEDIA_TYPE_AUDIO,
2049 .id = AV_CODEC_ID_MP3ADU,
2050 .priv_data_size = sizeof(MPADecodeContext),
2051 .init = decode_init,
2052 .decode = decode_frame_adu,
2053 .capabilities = CODEC_CAP_DR1,
2055 .long_name = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2056 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2058 AV_SAMPLE_FMT_NONE },
2061 #if CONFIG_MP3ON4_DECODER
2062 AVCodec ff_mp3on4_decoder = {
2064 .type = AVMEDIA_TYPE_AUDIO,
2065 .id = AV_CODEC_ID_MP3ON4,
2066 .priv_data_size = sizeof(MP3On4DecodeContext),
2067 .init = decode_init_mp3on4,
2068 .close = decode_close_mp3on4,
2069 .decode = decode_frame_mp3on4,
2070 .capabilities = CODEC_CAP_DR1,
2071 .flush = flush_mp3on4,
2072 .long_name = NULL_IF_CONFIG_SMALL("MP3onMP4"),
2073 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2074 AV_SAMPLE_FMT_NONE },