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"
40 * - test lsf / mpeg25 extensively.
43 #include "mpegaudio.h"
44 #include "mpegaudiodecheader.h"
46 #define BACKSTEP_SIZE 512
48 #define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
50 /* layer 3 "granule" */
51 typedef struct GranuleDef {
56 int scalefac_compress;
61 uint8_t scalefac_scale;
62 uint8_t count1table_select;
63 int region_size[3]; /* number of huffman codes in each region */
65 int short_start, long_end; /* long/short band indexes */
66 uint8_t scale_factors[40];
67 DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
70 typedef struct MPADecodeContext {
72 uint8_t last_buf[LAST_BUF_SIZE];
74 /* next header (used in free format parsing) */
75 uint32_t free_format_next_header;
78 DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
79 int synth_buf_offset[MPA_MAX_CHANNELS];
80 DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
81 INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
82 GranuleDef granules[2][2]; /* Used in Layer 3 */
83 int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
86 AVCodecContext* avctx;
88 AVFloatDSPContext fdsp;
93 # define SHR(a,b) ((a)*(1.0f/(1<<(b))))
94 # define FIXR_OLD(a) ((int)((a) * FRAC_ONE + 0.5))
95 # define FIXR(x) ((float)(x))
96 # define FIXHR(x) ((float)(x))
97 # define MULH3(x, y, s) ((s)*(y)*(x))
98 # define MULLx(x, y, s) ((y)*(x))
99 # define RENAME(a) a ## _float
100 # define OUT_FMT AV_SAMPLE_FMT_FLT
101 # define OUT_FMT_P AV_SAMPLE_FMT_FLTP
103 # define SHR(a,b) ((a)>>(b))
104 /* WARNING: only correct for positive numbers */
105 # define FIXR_OLD(a) ((int)((a) * FRAC_ONE + 0.5))
106 # define FIXR(a) ((int)((a) * FRAC_ONE + 0.5))
107 # define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
108 # define MULH3(x, y, s) MULH((s)*(x), y)
109 # define MULLx(x, y, s) MULL(x,y,s)
110 # define RENAME(a) a ## _fixed
111 # define OUT_FMT AV_SAMPLE_FMT_S16
112 # define OUT_FMT_P AV_SAMPLE_FMT_S16P
117 #define HEADER_SIZE 4
119 #include "mpegaudiodata.h"
120 #include "mpegaudiodectab.h"
122 /* vlc structure for decoding layer 3 huffman tables */
123 static VLC huff_vlc[16];
124 static VLC_TYPE huff_vlc_tables[
125 0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
126 142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
128 static const int huff_vlc_tables_sizes[16] = {
129 0, 128, 128, 128, 130, 128, 154, 166,
130 142, 204, 190, 170, 542, 460, 662, 414
132 static VLC huff_quad_vlc[2];
133 static VLC_TYPE huff_quad_vlc_tables[128+16][2];
134 static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
135 /* computed from band_size_long */
136 static uint16_t band_index_long[9][23];
137 #include "mpegaudio_tablegen.h"
138 /* intensity stereo coef table */
139 static INTFLOAT is_table[2][16];
140 static INTFLOAT is_table_lsf[2][2][16];
141 static INTFLOAT csa_table[8][4];
143 static int16_t division_tab3[1<<6 ];
144 static int16_t division_tab5[1<<8 ];
145 static int16_t division_tab9[1<<11];
147 static int16_t * const division_tabs[4] = {
148 division_tab3, division_tab5, NULL, division_tab9
151 /* lower 2 bits: modulo 3, higher bits: shift */
152 static uint16_t scale_factor_modshift[64];
153 /* [i][j]: 2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
154 static int32_t scale_factor_mult[15][3];
155 /* mult table for layer 2 group quantization */
157 #define SCALE_GEN(v) \
158 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
160 static const int32_t scale_factor_mult2[3][3] = {
161 SCALE_GEN(4.0 / 3.0), /* 3 steps */
162 SCALE_GEN(4.0 / 5.0), /* 5 steps */
163 SCALE_GEN(4.0 / 9.0), /* 9 steps */
167 * Convert region offsets to region sizes and truncate
168 * size to big_values.
170 static void ff_region_offset2size(GranuleDef *g)
173 g->region_size[2] = 576 / 2;
174 for (i = 0; i < 3; i++) {
175 k = FFMIN(g->region_size[i], g->big_values);
176 g->region_size[i] = k - j;
181 static void ff_init_short_region(MPADecodeContext *s, GranuleDef *g)
183 if (g->block_type == 2) {
184 if (s->sample_rate_index != 8)
185 g->region_size[0] = (36 / 2);
187 g->region_size[0] = (72 / 2);
189 if (s->sample_rate_index <= 2)
190 g->region_size[0] = (36 / 2);
191 else if (s->sample_rate_index != 8)
192 g->region_size[0] = (54 / 2);
194 g->region_size[0] = (108 / 2);
196 g->region_size[1] = (576 / 2);
199 static void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2)
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 ff_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 av_log_ask_for_sample(s->avctx, "switch point in 8khz\n");
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)
458 avcodec_get_frame_defaults(&s->frame);
459 avctx->coded_frame = &s->frame;
464 #define C3 FIXHR(0.86602540378443864676/2)
465 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
466 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
467 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
469 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
471 static void imdct12(INTFLOAT *out, INTFLOAT *in)
473 INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
476 in1 = in[1*3] + in[0*3];
477 in2 = in[2*3] + in[1*3];
478 in3 = in[3*3] + in[2*3];
479 in4 = in[4*3] + in[3*3];
480 in5 = in[5*3] + in[4*3];
484 in2 = MULH3(in2, C3, 2);
485 in3 = MULH3(in3, C3, 4);
488 t2 = MULH3(in1 - in5, C4, 2);
498 in1 = MULH3(in5 + in3, C5, 1);
505 in5 = MULH3(in5 - in3, C6, 2);
512 /* return the number of decoded frames */
513 static int mp_decode_layer1(MPADecodeContext *s)
515 int bound, i, v, n, ch, j, mant;
516 uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
517 uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
519 if (s->mode == MPA_JSTEREO)
520 bound = (s->mode_ext + 1) * 4;
524 /* allocation bits */
525 for (i = 0; i < bound; i++) {
526 for (ch = 0; ch < s->nb_channels; ch++) {
527 allocation[ch][i] = get_bits(&s->gb, 4);
530 for (i = bound; i < SBLIMIT; i++)
531 allocation[0][i] = get_bits(&s->gb, 4);
534 for (i = 0; i < bound; i++) {
535 for (ch = 0; ch < s->nb_channels; ch++) {
536 if (allocation[ch][i])
537 scale_factors[ch][i] = get_bits(&s->gb, 6);
540 for (i = bound; i < SBLIMIT; i++) {
541 if (allocation[0][i]) {
542 scale_factors[0][i] = get_bits(&s->gb, 6);
543 scale_factors[1][i] = get_bits(&s->gb, 6);
547 /* compute samples */
548 for (j = 0; j < 12; j++) {
549 for (i = 0; i < bound; i++) {
550 for (ch = 0; ch < s->nb_channels; ch++) {
551 n = allocation[ch][i];
553 mant = get_bits(&s->gb, n + 1);
554 v = l1_unscale(n, mant, scale_factors[ch][i]);
558 s->sb_samples[ch][j][i] = v;
561 for (i = bound; i < SBLIMIT; i++) {
562 n = allocation[0][i];
564 mant = get_bits(&s->gb, n + 1);
565 v = l1_unscale(n, mant, scale_factors[0][i]);
566 s->sb_samples[0][j][i] = v;
567 v = l1_unscale(n, mant, scale_factors[1][i]);
568 s->sb_samples[1][j][i] = v;
570 s->sb_samples[0][j][i] = 0;
571 s->sb_samples[1][j][i] = 0;
578 static int mp_decode_layer2(MPADecodeContext *s)
580 int sblimit; /* number of used subbands */
581 const unsigned char *alloc_table;
582 int table, bit_alloc_bits, i, j, ch, bound, v;
583 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
584 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
585 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
586 int scale, qindex, bits, steps, k, l, m, b;
588 /* select decoding table */
589 table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
590 s->sample_rate, s->lsf);
591 sblimit = ff_mpa_sblimit_table[table];
592 alloc_table = ff_mpa_alloc_tables[table];
594 if (s->mode == MPA_JSTEREO)
595 bound = (s->mode_ext + 1) * 4;
599 av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
605 /* parse bit allocation */
607 for (i = 0; i < bound; i++) {
608 bit_alloc_bits = alloc_table[j];
609 for (ch = 0; ch < s->nb_channels; ch++)
610 bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
611 j += 1 << bit_alloc_bits;
613 for (i = bound; i < sblimit; i++) {
614 bit_alloc_bits = alloc_table[j];
615 v = get_bits(&s->gb, bit_alloc_bits);
618 j += 1 << bit_alloc_bits;
622 for (i = 0; i < sblimit; i++) {
623 for (ch = 0; ch < s->nb_channels; ch++) {
624 if (bit_alloc[ch][i])
625 scale_code[ch][i] = get_bits(&s->gb, 2);
630 for (i = 0; i < sblimit; i++) {
631 for (ch = 0; ch < s->nb_channels; ch++) {
632 if (bit_alloc[ch][i]) {
633 sf = scale_factors[ch][i];
634 switch (scale_code[ch][i]) {
637 sf[0] = get_bits(&s->gb, 6);
638 sf[1] = get_bits(&s->gb, 6);
639 sf[2] = get_bits(&s->gb, 6);
642 sf[0] = get_bits(&s->gb, 6);
647 sf[0] = get_bits(&s->gb, 6);
648 sf[2] = get_bits(&s->gb, 6);
652 sf[0] = get_bits(&s->gb, 6);
653 sf[2] = get_bits(&s->gb, 6);
662 for (k = 0; k < 3; k++) {
663 for (l = 0; l < 12; l += 3) {
665 for (i = 0; i < bound; i++) {
666 bit_alloc_bits = alloc_table[j];
667 for (ch = 0; ch < s->nb_channels; ch++) {
668 b = bit_alloc[ch][i];
670 scale = scale_factors[ch][i][k];
671 qindex = alloc_table[j+b];
672 bits = ff_mpa_quant_bits[qindex];
675 /* 3 values at the same time */
676 v = get_bits(&s->gb, -bits);
677 v2 = division_tabs[qindex][v];
678 steps = ff_mpa_quant_steps[qindex];
680 s->sb_samples[ch][k * 12 + l + 0][i] =
681 l2_unscale_group(steps, v2 & 15, scale);
682 s->sb_samples[ch][k * 12 + l + 1][i] =
683 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
684 s->sb_samples[ch][k * 12 + l + 2][i] =
685 l2_unscale_group(steps, v2 >> 8 , scale);
687 for (m = 0; m < 3; m++) {
688 v = get_bits(&s->gb, bits);
689 v = l1_unscale(bits - 1, v, scale);
690 s->sb_samples[ch][k * 12 + l + m][i] = v;
694 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
695 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
696 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
699 /* next subband in alloc table */
700 j += 1 << bit_alloc_bits;
702 /* XXX: find a way to avoid this duplication of code */
703 for (i = bound; i < sblimit; i++) {
704 bit_alloc_bits = alloc_table[j];
707 int mant, scale0, scale1;
708 scale0 = scale_factors[0][i][k];
709 scale1 = scale_factors[1][i][k];
710 qindex = alloc_table[j+b];
711 bits = ff_mpa_quant_bits[qindex];
713 /* 3 values at the same time */
714 v = get_bits(&s->gb, -bits);
715 steps = ff_mpa_quant_steps[qindex];
718 s->sb_samples[0][k * 12 + l + 0][i] =
719 l2_unscale_group(steps, mant, scale0);
720 s->sb_samples[1][k * 12 + l + 0][i] =
721 l2_unscale_group(steps, mant, scale1);
724 s->sb_samples[0][k * 12 + l + 1][i] =
725 l2_unscale_group(steps, mant, scale0);
726 s->sb_samples[1][k * 12 + l + 1][i] =
727 l2_unscale_group(steps, mant, scale1);
728 s->sb_samples[0][k * 12 + l + 2][i] =
729 l2_unscale_group(steps, v, scale0);
730 s->sb_samples[1][k * 12 + l + 2][i] =
731 l2_unscale_group(steps, v, scale1);
733 for (m = 0; m < 3; m++) {
734 mant = get_bits(&s->gb, bits);
735 s->sb_samples[0][k * 12 + l + m][i] =
736 l1_unscale(bits - 1, mant, scale0);
737 s->sb_samples[1][k * 12 + l + m][i] =
738 l1_unscale(bits - 1, mant, scale1);
742 s->sb_samples[0][k * 12 + l + 0][i] = 0;
743 s->sb_samples[0][k * 12 + l + 1][i] = 0;
744 s->sb_samples[0][k * 12 + l + 2][i] = 0;
745 s->sb_samples[1][k * 12 + l + 0][i] = 0;
746 s->sb_samples[1][k * 12 + l + 1][i] = 0;
747 s->sb_samples[1][k * 12 + l + 2][i] = 0;
749 /* next subband in alloc table */
750 j += 1 << bit_alloc_bits;
752 /* fill remaining samples to zero */
753 for (i = sblimit; i < SBLIMIT; i++) {
754 for (ch = 0; ch < s->nb_channels; ch++) {
755 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
756 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
757 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
765 #define SPLIT(dst,sf,n) \
767 int m = (sf * 171) >> 9; \
770 } else if (n == 4) { \
773 } else if (n == 5) { \
774 int m = (sf * 205) >> 10; \
777 } else if (n == 6) { \
778 int m = (sf * 171) >> 10; \
785 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
788 SPLIT(slen[3], sf, n3)
789 SPLIT(slen[2], sf, n2)
790 SPLIT(slen[1], sf, n1)
794 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
797 const uint8_t *bstab, *pretab;
798 int len, i, j, k, l, v0, shift, gain, gains[3];
802 gain = g->global_gain - 210;
803 shift = g->scalefac_scale + 1;
805 bstab = band_size_long[s->sample_rate_index];
806 pretab = mpa_pretab[g->preflag];
807 for (i = 0; i < g->long_end; i++) {
808 v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
810 for (j = len; j > 0; j--)
814 if (g->short_start < 13) {
815 bstab = band_size_short[s->sample_rate_index];
816 gains[0] = gain - (g->subblock_gain[0] << 3);
817 gains[1] = gain - (g->subblock_gain[1] << 3);
818 gains[2] = gain - (g->subblock_gain[2] << 3);
820 for (i = g->short_start; i < 13; i++) {
822 for (l = 0; l < 3; l++) {
823 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
824 for (j = len; j > 0; j--)
831 /* handle n = 0 too */
832 static inline int get_bitsz(GetBitContext *s, int n)
834 return n ? get_bits(s, n) : 0;
838 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
841 if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
843 s->in_gb.buffer = NULL;
844 av_assert2((get_bits_count(&s->gb) & 7) == 0);
845 skip_bits_long(&s->gb, *pos - *end_pos);
847 *end_pos = *end_pos2 + get_bits_count(&s->gb) - *pos;
848 *pos = get_bits_count(&s->gb);
852 /* Following is a optimized code for
854 if(get_bits1(&s->gb))
859 #define READ_FLIP_SIGN(dst,src) \
860 v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31); \
863 #define READ_FLIP_SIGN(dst,src) \
864 v = -get_bits1(&s->gb); \
865 *(dst) = (*(src) ^ v) - v;
868 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
869 int16_t *exponents, int end_pos2)
873 int last_pos, bits_left;
875 int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
877 /* low frequencies (called big values) */
879 for (i = 0; i < 3; i++) {
880 int j, k, l, linbits;
881 j = g->region_size[i];
884 /* select vlc table */
885 k = g->table_select[i];
886 l = mpa_huff_data[k][0];
887 linbits = mpa_huff_data[k][1];
891 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
896 /* read huffcode and compute each couple */
900 int pos = get_bits_count(&s->gb);
903 switch_buffer(s, &pos, &end_pos, &end_pos2);
907 y = get_vlc2(&s->gb, vlc->table, 7, 3);
910 g->sb_hybrid[s_index ] =
911 g->sb_hybrid[s_index+1] = 0;
916 exponent= exponents[s_index];
918 av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
919 i, g->region_size[i] - j, x, y, exponent);
924 READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
926 x += get_bitsz(&s->gb, linbits);
927 v = l3_unscale(x, exponent);
928 if (get_bits1(&s->gb))
930 g->sb_hybrid[s_index] = v;
933 READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
935 y += get_bitsz(&s->gb, linbits);
936 v = l3_unscale(y, exponent);
937 if (get_bits1(&s->gb))
939 g->sb_hybrid[s_index+1] = v;
946 READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
948 x += get_bitsz(&s->gb, linbits);
949 v = l3_unscale(x, exponent);
950 if (get_bits1(&s->gb))
952 g->sb_hybrid[s_index+!!y] = v;
954 g->sb_hybrid[s_index + !y] = 0;
960 /* high frequencies */
961 vlc = &huff_quad_vlc[g->count1table_select];
963 while (s_index <= 572) {
965 pos = get_bits_count(&s->gb);
966 if (pos >= end_pos) {
967 if (pos > end_pos2 && last_pos) {
968 /* some encoders generate an incorrect size for this
969 part. We must go back into the data */
971 skip_bits_long(&s->gb, last_pos - pos);
972 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
973 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
977 switch_buffer(s, &pos, &end_pos, &end_pos2);
983 code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
984 av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
985 g->sb_hybrid[s_index+0] =
986 g->sb_hybrid[s_index+1] =
987 g->sb_hybrid[s_index+2] =
988 g->sb_hybrid[s_index+3] = 0;
990 static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
992 int pos = s_index + idxtab[code];
993 code ^= 8 >> idxtab[code];
994 READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
998 /* skip extension bits */
999 bits_left = end_pos2 - get_bits_count(&s->gb);
1000 if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1001 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1003 } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1004 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1007 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1008 skip_bits_long(&s->gb, bits_left);
1010 i = get_bits_count(&s->gb);
1011 switch_buffer(s, &i, &end_pos, &end_pos2);
1016 /* Reorder short blocks from bitstream order to interleaved order. It
1017 would be faster to do it in parsing, but the code would be far more
1019 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1022 INTFLOAT *ptr, *dst, *ptr1;
1025 if (g->block_type != 2)
1028 if (g->switch_point) {
1029 if (s->sample_rate_index != 8)
1030 ptr = g->sb_hybrid + 36;
1032 ptr = g->sb_hybrid + 72;
1037 for (i = g->short_start; i < 13; i++) {
1038 len = band_size_short[s->sample_rate_index][i];
1041 for (j = len; j > 0; j--) {
1042 *dst++ = ptr[0*len];
1043 *dst++ = ptr[1*len];
1044 *dst++ = ptr[2*len];
1048 memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1052 #define ISQRT2 FIXR(0.70710678118654752440)
1054 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1057 int sf_max, sf, len, non_zero_found;
1058 INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1059 int non_zero_found_short[3];
1061 /* intensity stereo */
1062 if (s->mode_ext & MODE_EXT_I_STEREO) {
1067 is_tab = is_table_lsf[g1->scalefac_compress & 1];
1071 tab0 = g0->sb_hybrid + 576;
1072 tab1 = g1->sb_hybrid + 576;
1074 non_zero_found_short[0] = 0;
1075 non_zero_found_short[1] = 0;
1076 non_zero_found_short[2] = 0;
1077 k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1078 for (i = 12; i >= g1->short_start; i--) {
1079 /* for last band, use previous scale factor */
1082 len = band_size_short[s->sample_rate_index][i];
1083 for (l = 2; l >= 0; l--) {
1086 if (!non_zero_found_short[l]) {
1087 /* test if non zero band. if so, stop doing i-stereo */
1088 for (j = 0; j < len; j++) {
1090 non_zero_found_short[l] = 1;
1094 sf = g1->scale_factors[k + l];
1100 for (j = 0; j < len; j++) {
1102 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1103 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1107 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1108 /* lower part of the spectrum : do ms stereo
1110 for (j = 0; j < len; j++) {
1113 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1114 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1121 non_zero_found = non_zero_found_short[0] |
1122 non_zero_found_short[1] |
1123 non_zero_found_short[2];
1125 for (i = g1->long_end - 1;i >= 0;i--) {
1126 len = band_size_long[s->sample_rate_index][i];
1129 /* test if non zero band. if so, stop doing i-stereo */
1130 if (!non_zero_found) {
1131 for (j = 0; j < len; j++) {
1137 /* for last band, use previous scale factor */
1138 k = (i == 21) ? 20 : i;
1139 sf = g1->scale_factors[k];
1144 for (j = 0; j < len; j++) {
1146 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1147 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1151 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1152 /* lower part of the spectrum : do ms stereo
1154 for (j = 0; j < len; j++) {
1157 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1158 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1163 } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1164 /* ms stereo ONLY */
1165 /* NOTE: the 1/sqrt(2) normalization factor is included in the
1168 s->fdsp.butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1170 tab0 = g0->sb_hybrid;
1171 tab1 = g1->sb_hybrid;
1172 for (i = 0; i < 576; i++) {
1175 tab0[i] = tmp0 + tmp1;
1176 tab1[i] = tmp0 - tmp1;
1184 # include "mips/compute_antialias_float.h"
1185 #endif /* HAVE_MIPSFPU */
1188 # include "mips/compute_antialias_fixed.h"
1189 #endif /* HAVE_MIPSDSPR1 */
1190 #endif /* CONFIG_FLOAT */
1192 #ifndef compute_antialias
1194 #define AA(j) do { \
1195 float tmp0 = ptr[-1-j]; \
1196 float tmp1 = ptr[ j]; \
1197 ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1]; \
1198 ptr[ j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0]; \
1201 #define AA(j) do { \
1202 int tmp0 = ptr[-1-j]; \
1203 int tmp1 = ptr[ j]; \
1204 int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]); \
1205 ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2])); \
1206 ptr[ j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3])); \
1210 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1215 /* we antialias only "long" bands */
1216 if (g->block_type == 2) {
1217 if (!g->switch_point)
1219 /* XXX: check this for 8000Hz case */
1225 ptr = g->sb_hybrid + 18;
1226 for (i = n; i > 0; i--) {
1239 #endif /* compute_antialias */
1241 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1242 INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1244 INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1246 int i, j, mdct_long_end, sblimit;
1248 /* find last non zero block */
1249 ptr = g->sb_hybrid + 576;
1250 ptr1 = g->sb_hybrid + 2 * 18;
1251 while (ptr >= ptr1) {
1255 if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1258 sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1260 if (g->block_type == 2) {
1261 /* XXX: check for 8000 Hz */
1262 if (g->switch_point)
1267 mdct_long_end = sblimit;
1270 s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1271 mdct_long_end, g->switch_point,
1274 buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1275 ptr = g->sb_hybrid + 18 * mdct_long_end;
1277 for (j = mdct_long_end; j < sblimit; j++) {
1278 /* select frequency inversion */
1279 win = RENAME(ff_mdct_win)[2 + (4 & -(j & 1))];
1280 out_ptr = sb_samples + j;
1282 for (i = 0; i < 6; i++) {
1283 *out_ptr = buf[4*i];
1286 imdct12(out2, ptr + 0);
1287 for (i = 0; i < 6; i++) {
1288 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*1)];
1289 buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1292 imdct12(out2, ptr + 1);
1293 for (i = 0; i < 6; i++) {
1294 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*2)];
1295 buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1298 imdct12(out2, ptr + 2);
1299 for (i = 0; i < 6; i++) {
1300 buf[4*(i + 6*0)] = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*0)];
1301 buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1302 buf[4*(i + 6*2)] = 0;
1305 buf += (j&3) != 3 ? 1 : (4*18-3);
1308 for (j = sblimit; j < SBLIMIT; j++) {
1310 out_ptr = sb_samples + j;
1311 for (i = 0; i < 18; i++) {
1312 *out_ptr = buf[4*i];
1316 buf += (j&3) != 3 ? 1 : (4*18-3);
1320 /* main layer3 decoding function */
1321 static int mp_decode_layer3(MPADecodeContext *s)
1323 int nb_granules, main_data_begin;
1324 int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1326 int16_t exponents[576]; //FIXME try INTFLOAT
1328 /* read side info */
1330 main_data_begin = get_bits(&s->gb, 8);
1331 skip_bits(&s->gb, s->nb_channels);
1334 main_data_begin = get_bits(&s->gb, 9);
1335 if (s->nb_channels == 2)
1336 skip_bits(&s->gb, 3);
1338 skip_bits(&s->gb, 5);
1340 for (ch = 0; ch < s->nb_channels; ch++) {
1341 s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1342 s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1346 for (gr = 0; gr < nb_granules; gr++) {
1347 for (ch = 0; ch < s->nb_channels; ch++) {
1348 av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1349 g = &s->granules[ch][gr];
1350 g->part2_3_length = get_bits(&s->gb, 12);
1351 g->big_values = get_bits(&s->gb, 9);
1352 if (g->big_values > 288) {
1353 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1354 return AVERROR_INVALIDDATA;
1357 g->global_gain = get_bits(&s->gb, 8);
1358 /* if MS stereo only is selected, we precompute the
1359 1/sqrt(2) renormalization factor */
1360 if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1362 g->global_gain -= 2;
1364 g->scalefac_compress = get_bits(&s->gb, 9);
1366 g->scalefac_compress = get_bits(&s->gb, 4);
1367 blocksplit_flag = get_bits1(&s->gb);
1368 if (blocksplit_flag) {
1369 g->block_type = get_bits(&s->gb, 2);
1370 if (g->block_type == 0) {
1371 av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1372 return AVERROR_INVALIDDATA;
1374 g->switch_point = get_bits1(&s->gb);
1375 for (i = 0; i < 2; i++)
1376 g->table_select[i] = get_bits(&s->gb, 5);
1377 for (i = 0; i < 3; i++)
1378 g->subblock_gain[i] = get_bits(&s->gb, 3);
1379 ff_init_short_region(s, g);
1381 int region_address1, region_address2;
1383 g->switch_point = 0;
1384 for (i = 0; i < 3; i++)
1385 g->table_select[i] = get_bits(&s->gb, 5);
1386 /* compute huffman coded region sizes */
1387 region_address1 = get_bits(&s->gb, 4);
1388 region_address2 = get_bits(&s->gb, 3);
1389 av_dlog(s->avctx, "region1=%d region2=%d\n",
1390 region_address1, region_address2);
1391 ff_init_long_region(s, g, region_address1, region_address2);
1393 ff_region_offset2size(g);
1394 ff_compute_band_indexes(s, g);
1398 g->preflag = get_bits1(&s->gb);
1399 g->scalefac_scale = get_bits1(&s->gb);
1400 g->count1table_select = get_bits1(&s->gb);
1401 av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1402 g->block_type, g->switch_point);
1408 const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1409 int extrasize = av_clip(get_bits_left(&s->gb) >> 3, 0, EXTRABYTES);
1410 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1411 /* now we get bits from the main_data_begin offset */
1412 av_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1413 main_data_begin, s->last_buf_size);
1415 memcpy(s->last_buf + s->last_buf_size, ptr, extrasize);
1417 init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1418 #if !UNCHECKED_BITSTREAM_READER
1419 s->gb.size_in_bits_plus8 += FFMAX(extrasize, LAST_BUF_SIZE - s->last_buf_size) * 8;
1421 s->last_buf_size <<= 3;
1422 for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1423 for (ch = 0; ch < s->nb_channels; ch++) {
1424 g = &s->granules[ch][gr];
1425 s->last_buf_size += g->part2_3_length;
1426 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1427 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1430 skip = s->last_buf_size - 8 * main_data_begin;
1431 if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
1432 skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
1434 s->in_gb.buffer = NULL;
1436 skip_bits_long(&s->gb, skip);
1442 for (; gr < nb_granules; gr++) {
1443 for (ch = 0; ch < s->nb_channels; ch++) {
1444 g = &s->granules[ch][gr];
1445 bits_pos = get_bits_count(&s->gb);
1449 int slen, slen1, slen2;
1451 /* MPEG1 scale factors */
1452 slen1 = slen_table[0][g->scalefac_compress];
1453 slen2 = slen_table[1][g->scalefac_compress];
1454 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1455 if (g->block_type == 2) {
1456 n = g->switch_point ? 17 : 18;
1459 for (i = 0; i < n; i++)
1460 g->scale_factors[j++] = get_bits(&s->gb, slen1);
1462 for (i = 0; i < n; i++)
1463 g->scale_factors[j++] = 0;
1466 for (i = 0; i < 18; i++)
1467 g->scale_factors[j++] = get_bits(&s->gb, slen2);
1468 for (i = 0; i < 3; i++)
1469 g->scale_factors[j++] = 0;
1471 for (i = 0; i < 21; i++)
1472 g->scale_factors[j++] = 0;
1475 sc = s->granules[ch][0].scale_factors;
1477 for (k = 0; k < 4; k++) {
1479 if ((g->scfsi & (0x8 >> k)) == 0) {
1480 slen = (k < 2) ? slen1 : slen2;
1482 for (i = 0; i < n; i++)
1483 g->scale_factors[j++] = get_bits(&s->gb, slen);
1485 for (i = 0; i < n; i++)
1486 g->scale_factors[j++] = 0;
1489 /* simply copy from last granule */
1490 for (i = 0; i < n; i++) {
1491 g->scale_factors[j] = sc[j];
1496 g->scale_factors[j++] = 0;
1499 int tindex, tindex2, slen[4], sl, sf;
1501 /* LSF scale factors */
1502 if (g->block_type == 2)
1503 tindex = g->switch_point ? 2 : 1;
1507 sf = g->scalefac_compress;
1508 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1509 /* intensity stereo case */
1512 lsf_sf_expand(slen, sf, 6, 6, 0);
1514 } else if (sf < 244) {
1515 lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1518 lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1524 lsf_sf_expand(slen, sf, 5, 4, 4);
1526 } else if (sf < 500) {
1527 lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1530 lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1537 for (k = 0; k < 4; k++) {
1538 n = lsf_nsf_table[tindex2][tindex][k];
1541 for (i = 0; i < n; i++)
1542 g->scale_factors[j++] = get_bits(&s->gb, sl);
1544 for (i = 0; i < n; i++)
1545 g->scale_factors[j++] = 0;
1548 /* XXX: should compute exact size */
1550 g->scale_factors[j] = 0;
1553 exponents_from_scale_factors(s, g, exponents);
1555 /* read Huffman coded residue */
1556 huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1559 if (s->mode == MPA_JSTEREO)
1560 compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1562 for (ch = 0; ch < s->nb_channels; ch++) {
1563 g = &s->granules[ch][gr];
1565 reorder_block(s, g);
1566 compute_antialias(s, g);
1567 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1570 if (get_bits_count(&s->gb) < 0)
1571 skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1572 return nb_granules * 18;
1575 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1576 const uint8_t *buf, int buf_size)
1578 int i, nb_frames, ch, ret;
1579 OUT_INT *samples_ptr;
1581 init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1583 /* skip error protection field */
1584 if (s->error_protection)
1585 skip_bits(&s->gb, 16);
1589 s->avctx->frame_size = 384;
1590 nb_frames = mp_decode_layer1(s);
1593 s->avctx->frame_size = 1152;
1594 nb_frames = mp_decode_layer2(s);
1597 s->avctx->frame_size = s->lsf ? 576 : 1152;
1599 nb_frames = mp_decode_layer3(s);
1602 if (s->in_gb.buffer) {
1603 align_get_bits(&s->gb);
1604 i = get_bits_left(&s->gb)>>3;
1605 if (i >= 0 && i <= BACKSTEP_SIZE) {
1606 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1609 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1611 s->in_gb.buffer = NULL;
1614 align_get_bits(&s->gb);
1615 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1616 i = get_bits_left(&s->gb) >> 3;
1618 if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1620 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1621 i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1623 av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1624 memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1625 s->last_buf_size += i;
1631 /* get output buffer */
1633 s->frame.nb_samples = s->avctx->frame_size;
1634 if ((ret = ff_get_buffer(s->avctx, &s->frame)) < 0) {
1635 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1638 samples = (OUT_INT **)s->frame.extended_data;
1641 /* apply the synthesis filter */
1642 for (ch = 0; ch < s->nb_channels; ch++) {
1644 if (s->avctx->sample_fmt == OUT_FMT_P) {
1645 samples_ptr = samples[ch];
1648 samples_ptr = samples[0] + ch;
1649 sample_stride = s->nb_channels;
1651 for (i = 0; i < nb_frames; i++) {
1652 RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1653 &(s->synth_buf_offset[ch]),
1654 RENAME(ff_mpa_synth_window),
1655 &s->dither_state, samples_ptr,
1656 sample_stride, s->sb_samples[ch][i]);
1657 samples_ptr += 32 * sample_stride;
1661 return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1664 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1667 const uint8_t *buf = avpkt->data;
1668 int buf_size = avpkt->size;
1669 MPADecodeContext *s = avctx->priv_data;
1673 while(buf_size && !*buf){
1678 if (buf_size < HEADER_SIZE)
1679 return AVERROR_INVALIDDATA;
1681 header = AV_RB32(buf);
1682 if (header>>8 == AV_RB32("TAG")>>8) {
1683 av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1686 if (ff_mpa_check_header(header) < 0) {
1687 av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1688 return AVERROR_INVALIDDATA;
1691 if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1692 /* free format: prepare to compute frame size */
1694 return AVERROR_INVALIDDATA;
1696 /* update codec info */
1697 avctx->channels = s->nb_channels;
1698 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1699 if (!avctx->bit_rate)
1700 avctx->bit_rate = s->bit_rate;
1702 if (s->frame_size <= 0 || s->frame_size > buf_size) {
1703 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1704 return AVERROR_INVALIDDATA;
1705 } else if (s->frame_size < buf_size) {
1706 av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1707 buf_size= s->frame_size;
1710 ret = mp_decode_frame(s, NULL, buf, buf_size);
1713 *(AVFrame *)data = s->frame;
1714 avctx->sample_rate = s->sample_rate;
1715 //FIXME maybe move the other codec info stuff from above here too
1717 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1718 /* Only return an error if the bad frame makes up the whole packet or
1719 * the error is related to buffer management.
1720 * If there is more data in the packet, just consume the bad frame
1721 * instead of returning an error, which would discard the whole
1724 if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1731 static void mp_flush(MPADecodeContext *ctx)
1733 memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1734 ctx->last_buf_size = 0;
1737 static void flush(AVCodecContext *avctx)
1739 mp_flush(avctx->priv_data);
1742 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1743 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1744 int *got_frame_ptr, AVPacket *avpkt)
1746 const uint8_t *buf = avpkt->data;
1747 int buf_size = avpkt->size;
1748 MPADecodeContext *s = avctx->priv_data;
1751 int av_unused out_size;
1755 // Discard too short frames
1756 if (buf_size < HEADER_SIZE) {
1757 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1758 return AVERROR_INVALIDDATA;
1762 if (len > MPA_MAX_CODED_FRAME_SIZE)
1763 len = MPA_MAX_CODED_FRAME_SIZE;
1765 // Get header and restore sync word
1766 header = AV_RB32(buf) | 0xffe00000;
1768 if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
1769 av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1770 return AVERROR_INVALIDDATA;
1773 avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1774 /* update codec info */
1775 avctx->sample_rate = s->sample_rate;
1776 avctx->channels = s->nb_channels;
1777 if (!avctx->bit_rate)
1778 avctx->bit_rate = s->bit_rate;
1780 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");
1789 *(AVFrame *)data = s->frame;
1793 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1795 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1798 * Context for MP3On4 decoder
1800 typedef struct MP3On4DecodeContext {
1802 int frames; ///< number of mp3 frames per block (number of mp3 decoder instances)
1803 int syncword; ///< syncword patch
1804 const uint8_t *coff; ///< channel offsets in output buffer
1805 MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1806 } MP3On4DecodeContext;
1808 #include "mpeg4audio.h"
1810 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1812 /* number of mp3 decoder instances */
1813 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1815 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1816 static const uint8_t chan_offset[8][5] = {
1821 { 2, 0, 3 }, // C FLR BS
1822 { 2, 0, 3 }, // C FLR BLRS
1823 { 2, 0, 4, 3 }, // C FLR BLRS LFE
1824 { 2, 0, 6, 4, 3 }, // C FLR BLRS BLR LFE
1827 /* mp3on4 channel layouts */
1828 static const int16_t chan_layout[8] = {
1831 AV_CH_LAYOUT_STEREO,
1832 AV_CH_LAYOUT_SURROUND,
1833 AV_CH_LAYOUT_4POINT0,
1834 AV_CH_LAYOUT_5POINT0,
1835 AV_CH_LAYOUT_5POINT1,
1836 AV_CH_LAYOUT_7POINT1
1839 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1841 MP3On4DecodeContext *s = avctx->priv_data;
1844 for (i = 0; i < s->frames; i++)
1845 av_free(s->mp3decctx[i]);
1851 static int decode_init_mp3on4(AVCodecContext * avctx)
1853 MP3On4DecodeContext *s = avctx->priv_data;
1854 MPEG4AudioConfig cfg;
1857 if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
1858 av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1859 return AVERROR_INVALIDDATA;
1862 avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
1863 avctx->extradata_size * 8, 1);
1864 if (!cfg.chan_config || cfg.chan_config > 7) {
1865 av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1866 return AVERROR_INVALIDDATA;
1868 s->frames = mp3Frames[cfg.chan_config];
1869 s->coff = chan_offset[cfg.chan_config];
1870 avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
1871 avctx->channel_layout = chan_layout[cfg.chan_config];
1873 if (cfg.sample_rate < 16000)
1874 s->syncword = 0xffe00000;
1876 s->syncword = 0xfff00000;
1878 /* Init the first mp3 decoder in standard way, so that all tables get builded
1879 * We replace avctx->priv_data with the context of the first decoder so that
1880 * decode_init() does not have to be changed.
1881 * Other decoders will be initialized here copying data from the first context
1883 // Allocate zeroed memory for the first decoder context
1884 s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1885 if (!s->mp3decctx[0])
1887 // Put decoder context in place to make init_decode() happy
1888 avctx->priv_data = s->mp3decctx[0];
1890 s->frame = avctx->coded_frame;
1891 // Restore mp3on4 context pointer
1892 avctx->priv_data = s;
1893 s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1895 /* Create a separate codec/context for each frame (first is already ok).
1896 * Each frame is 1 or 2 channels - up to 5 frames allowed
1898 for (i = 1; i < s->frames; i++) {
1899 s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1900 if (!s->mp3decctx[i])
1902 s->mp3decctx[i]->adu_mode = 1;
1903 s->mp3decctx[i]->avctx = avctx;
1904 s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1909 decode_close_mp3on4(avctx);
1910 return AVERROR(ENOMEM);
1914 static void flush_mp3on4(AVCodecContext *avctx)
1917 MP3On4DecodeContext *s = avctx->priv_data;
1919 for (i = 0; i < s->frames; i++)
1920 mp_flush(s->mp3decctx[i]);
1924 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1925 int *got_frame_ptr, AVPacket *avpkt)
1927 const uint8_t *buf = avpkt->data;
1928 int buf_size = avpkt->size;
1929 MP3On4DecodeContext *s = avctx->priv_data;
1930 MPADecodeContext *m;
1931 int fsize, len = buf_size, out_size = 0;
1933 OUT_INT **out_samples;
1937 /* get output buffer */
1938 s->frame->nb_samples = MPA_FRAME_SIZE;
1939 if ((ret = ff_get_buffer(avctx, s->frame)) < 0) {
1940 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1943 out_samples = (OUT_INT **)s->frame->extended_data;
1945 // Discard too short frames
1946 if (buf_size < HEADER_SIZE)
1947 return AVERROR_INVALIDDATA;
1949 avctx->bit_rate = 0;
1952 for (fr = 0; fr < s->frames; fr++) {
1953 fsize = AV_RB16(buf) >> 4;
1954 fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1955 m = s->mp3decctx[fr];
1958 if (fsize < HEADER_SIZE) {
1959 av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1960 return AVERROR_INVALIDDATA;
1962 header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1964 if (ff_mpa_check_header(header) < 0) // Bad header, discard block
1967 avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1969 if (ch + m->nb_channels > avctx->channels || s->coff[fr] + m->nb_channels > avctx->channels) {
1970 av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1972 return AVERROR_INVALIDDATA;
1974 ch += m->nb_channels;
1976 outptr[0] = out_samples[s->coff[fr]];
1977 if (m->nb_channels > 1)
1978 outptr[1] = out_samples[s->coff[fr] + 1];
1980 if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
1987 avctx->bit_rate += m->bit_rate;
1990 /* update codec info */
1991 avctx->sample_rate = s->mp3decctx[0]->sample_rate;
1993 s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
1995 *(AVFrame *)data = *s->frame;
1999 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
2002 #if CONFIG_MP1_DECODER
2003 AVCodec ff_mp1_decoder = {
2005 .type = AVMEDIA_TYPE_AUDIO,
2006 .id = AV_CODEC_ID_MP1,
2007 .priv_data_size = sizeof(MPADecodeContext),
2008 .init = decode_init,
2009 .decode = decode_frame,
2010 .capabilities = CODEC_CAP_DR1,
2012 .long_name = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2013 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2015 AV_SAMPLE_FMT_NONE },
2018 #if CONFIG_MP2_DECODER
2019 AVCodec ff_mp2_decoder = {
2021 .type = AVMEDIA_TYPE_AUDIO,
2022 .id = AV_CODEC_ID_MP2,
2023 .priv_data_size = sizeof(MPADecodeContext),
2024 .init = decode_init,
2025 .decode = decode_frame,
2026 .capabilities = CODEC_CAP_DR1,
2028 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2029 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2031 AV_SAMPLE_FMT_NONE },
2034 #if CONFIG_MP3_DECODER
2035 AVCodec ff_mp3_decoder = {
2037 .type = AVMEDIA_TYPE_AUDIO,
2038 .id = AV_CODEC_ID_MP3,
2039 .priv_data_size = sizeof(MPADecodeContext),
2040 .init = decode_init,
2041 .decode = decode_frame,
2042 .capabilities = CODEC_CAP_DR1,
2044 .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2045 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2047 AV_SAMPLE_FMT_NONE },
2050 #if CONFIG_MP3ADU_DECODER
2051 AVCodec ff_mp3adu_decoder = {
2053 .type = AVMEDIA_TYPE_AUDIO,
2054 .id = AV_CODEC_ID_MP3ADU,
2055 .priv_data_size = sizeof(MPADecodeContext),
2056 .init = decode_init,
2057 .decode = decode_frame_adu,
2058 .capabilities = CODEC_CAP_DR1,
2060 .long_name = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2061 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2063 AV_SAMPLE_FMT_NONE },
2066 #if CONFIG_MP3ON4_DECODER
2067 AVCodec ff_mp3on4_decoder = {
2069 .type = AVMEDIA_TYPE_AUDIO,
2070 .id = AV_CODEC_ID_MP3ON4,
2071 .priv_data_size = sizeof(MP3On4DecodeContext),
2072 .init = decode_init_mp3on4,
2073 .close = decode_close_mp3on4,
2074 .decode = decode_frame_mp3on4,
2075 .capabilities = CODEC_CAP_DR1,
2076 .flush = flush_mp3on4,
2077 .long_name = NULL_IF_CONFIG_SMALL("MP3onMP4"),
2078 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2079 AV_SAMPLE_FMT_NONE },