3 * Copyright (c) 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/attributes.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/float_dsp.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 switched mode, we handle the 36 first samples as
213 long blocks. For 8000Hz, we handle the 72 first
214 exponents as long blocks */
215 if (s->sample_rate_index <= 2)
231 /* layer 1 unscaling */
232 /* n = number of bits of the mantissa minus 1 */
233 static inline int l1_unscale(int n, int mant, int scale_factor)
238 shift = scale_factor_modshift[scale_factor];
241 val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
243 /* NOTE: at this point, 1 <= shift >= 21 + 15 */
244 return (int)((val + (1LL << (shift - 1))) >> shift);
247 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
251 shift = scale_factor_modshift[scale_factor];
255 val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
256 /* NOTE: at this point, 0 <= shift <= 21 */
258 val = (val + (1 << (shift - 1))) >> shift;
262 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
263 static inline int l3_unscale(int value, int exponent)
268 e = table_4_3_exp [4 * value + (exponent & 3)];
269 m = table_4_3_value[4 * value + (exponent & 3)];
274 m = (m + (1 << (e - 1))) >> e;
279 static av_cold void decode_init_static(void)
284 /* scale factors table for layer 1/2 */
285 for (i = 0; i < 64; i++) {
287 /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
290 scale_factor_modshift[i] = mod | (shift << 2);
293 /* scale factor multiply for layer 1 */
294 for (i = 0; i < 15; i++) {
297 norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
298 scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0 * 2.0), FRAC_BITS);
299 scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
300 scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
301 av_dlog(NULL, "%d: norm=%x s=%x %x %x\n", i, norm,
302 scale_factor_mult[i][0],
303 scale_factor_mult[i][1],
304 scale_factor_mult[i][2]);
307 RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
309 /* huffman decode tables */
311 for (i = 1; i < 16; i++) {
312 const HuffTable *h = &mpa_huff_tables[i];
314 uint8_t tmp_bits [512] = { 0 };
315 uint16_t tmp_codes[512] = { 0 };
320 for (x = 0; x < xsize; x++) {
321 for (y = 0; y < xsize; y++) {
322 tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j ];
323 tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
328 huff_vlc[i].table = huff_vlc_tables+offset;
329 huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
330 init_vlc(&huff_vlc[i], 7, 512,
331 tmp_bits, 1, 1, tmp_codes, 2, 2,
332 INIT_VLC_USE_NEW_STATIC);
333 offset += huff_vlc_tables_sizes[i];
335 assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
338 for (i = 0; i < 2; i++) {
339 huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
340 huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
341 init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
342 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
343 INIT_VLC_USE_NEW_STATIC);
344 offset += huff_quad_vlc_tables_sizes[i];
346 assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
348 for (i = 0; i < 9; i++) {
350 for (j = 0; j < 22; j++) {
351 band_index_long[i][j] = k;
352 k += band_size_long[i][j];
354 band_index_long[i][22] = k;
357 /* compute n ^ (4/3) and store it in mantissa/exp format */
359 mpegaudio_tableinit();
361 for (i = 0; i < 4; i++) {
362 if (ff_mpa_quant_bits[i] < 0) {
363 for (j = 0; j < (1 << (-ff_mpa_quant_bits[i]+1)); j++) {
364 int val1, val2, val3, steps;
366 steps = ff_mpa_quant_steps[i];
371 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
377 for (i = 0; i < 7; i++) {
381 f = tan((double)i * M_PI / 12.0);
382 v = FIXR(f / (1.0 + f));
387 is_table[1][6 - i] = v;
390 for (i = 7; i < 16; i++)
391 is_table[0][i] = is_table[1][i] = 0.0;
393 for (i = 0; i < 16; i++) {
397 for (j = 0; j < 2; j++) {
398 e = -(j + 1) * ((i + 1) >> 1);
399 f = pow(2.0, e / 4.0);
401 is_table_lsf[j][k ^ 1][i] = FIXR(f);
402 is_table_lsf[j][k ][i] = FIXR(1.0);
403 av_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
404 i, j, (float) is_table_lsf[j][0][i],
405 (float) is_table_lsf[j][1][i]);
409 for (i = 0; i < 8; i++) {
412 cs = 1.0 / sqrt(1.0 + ci * ci);
415 csa_table[i][0] = FIXHR(cs/4);
416 csa_table[i][1] = FIXHR(ca/4);
417 csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
418 csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
420 csa_table[i][0] = cs;
421 csa_table[i][1] = ca;
422 csa_table[i][2] = ca + cs;
423 csa_table[i][3] = ca - cs;
428 static av_cold int decode_init(AVCodecContext * avctx)
430 static int initialized_tables = 0;
431 MPADecodeContext *s = avctx->priv_data;
433 if (!initialized_tables) {
434 decode_init_static();
435 initialized_tables = 1;
440 avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
441 ff_mpadsp_init(&s->mpadsp);
443 if (avctx->request_sample_fmt == OUT_FMT &&
444 avctx->codec_id != AV_CODEC_ID_MP3ON4)
445 avctx->sample_fmt = OUT_FMT;
447 avctx->sample_fmt = OUT_FMT_P;
448 s->err_recognition = avctx->err_recognition;
450 if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
456 #define C3 FIXHR(0.86602540378443864676/2)
457 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
458 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
459 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
461 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
463 static void imdct12(INTFLOAT *out, INTFLOAT *in)
465 INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
468 in1 = in[1*3] + in[0*3];
469 in2 = in[2*3] + in[1*3];
470 in3 = in[3*3] + in[2*3];
471 in4 = in[4*3] + in[3*3];
472 in5 = in[5*3] + in[4*3];
476 in2 = MULH3(in2, C3, 2);
477 in3 = MULH3(in3, C3, 4);
480 t2 = MULH3(in1 - in5, C4, 2);
490 in1 = MULH3(in5 + in3, C5, 1);
497 in5 = MULH3(in5 - in3, C6, 2);
504 /* return the number of decoded frames */
505 static int mp_decode_layer1(MPADecodeContext *s)
507 int bound, i, v, n, ch, j, mant;
508 uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
509 uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
511 if (s->mode == MPA_JSTEREO)
512 bound = (s->mode_ext + 1) * 4;
516 /* allocation bits */
517 for (i = 0; i < bound; i++) {
518 for (ch = 0; ch < s->nb_channels; ch++) {
519 allocation[ch][i] = get_bits(&s->gb, 4);
522 for (i = bound; i < SBLIMIT; i++)
523 allocation[0][i] = get_bits(&s->gb, 4);
526 for (i = 0; i < bound; i++) {
527 for (ch = 0; ch < s->nb_channels; ch++) {
528 if (allocation[ch][i])
529 scale_factors[ch][i] = get_bits(&s->gb, 6);
532 for (i = bound; i < SBLIMIT; i++) {
533 if (allocation[0][i]) {
534 scale_factors[0][i] = get_bits(&s->gb, 6);
535 scale_factors[1][i] = get_bits(&s->gb, 6);
539 /* compute samples */
540 for (j = 0; j < 12; j++) {
541 for (i = 0; i < bound; i++) {
542 for (ch = 0; ch < s->nb_channels; ch++) {
543 n = allocation[ch][i];
545 mant = get_bits(&s->gb, n + 1);
546 v = l1_unscale(n, mant, scale_factors[ch][i]);
550 s->sb_samples[ch][j][i] = v;
553 for (i = bound; i < SBLIMIT; i++) {
554 n = allocation[0][i];
556 mant = get_bits(&s->gb, n + 1);
557 v = l1_unscale(n, mant, scale_factors[0][i]);
558 s->sb_samples[0][j][i] = v;
559 v = l1_unscale(n, mant, scale_factors[1][i]);
560 s->sb_samples[1][j][i] = v;
562 s->sb_samples[0][j][i] = 0;
563 s->sb_samples[1][j][i] = 0;
570 static int mp_decode_layer2(MPADecodeContext *s)
572 int sblimit; /* number of used subbands */
573 const unsigned char *alloc_table;
574 int table, bit_alloc_bits, i, j, ch, bound, v;
575 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
576 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
577 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
578 int scale, qindex, bits, steps, k, l, m, b;
580 /* select decoding table */
581 table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
582 s->sample_rate, s->lsf);
583 sblimit = ff_mpa_sblimit_table[table];
584 alloc_table = ff_mpa_alloc_tables[table];
586 if (s->mode == MPA_JSTEREO)
587 bound = (s->mode_ext + 1) * 4;
591 av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
597 /* parse bit allocation */
599 for (i = 0; i < bound; i++) {
600 bit_alloc_bits = alloc_table[j];
601 for (ch = 0; ch < s->nb_channels; ch++)
602 bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
603 j += 1 << bit_alloc_bits;
605 for (i = bound; i < sblimit; i++) {
606 bit_alloc_bits = alloc_table[j];
607 v = get_bits(&s->gb, bit_alloc_bits);
610 j += 1 << bit_alloc_bits;
614 for (i = 0; i < sblimit; i++) {
615 for (ch = 0; ch < s->nb_channels; ch++) {
616 if (bit_alloc[ch][i])
617 scale_code[ch][i] = get_bits(&s->gb, 2);
622 for (i = 0; i < sblimit; i++) {
623 for (ch = 0; ch < s->nb_channels; ch++) {
624 if (bit_alloc[ch][i]) {
625 sf = scale_factors[ch][i];
626 switch (scale_code[ch][i]) {
629 sf[0] = get_bits(&s->gb, 6);
630 sf[1] = get_bits(&s->gb, 6);
631 sf[2] = get_bits(&s->gb, 6);
634 sf[0] = get_bits(&s->gb, 6);
639 sf[0] = get_bits(&s->gb, 6);
640 sf[2] = get_bits(&s->gb, 6);
644 sf[0] = get_bits(&s->gb, 6);
645 sf[2] = get_bits(&s->gb, 6);
654 for (k = 0; k < 3; k++) {
655 for (l = 0; l < 12; l += 3) {
657 for (i = 0; i < bound; i++) {
658 bit_alloc_bits = alloc_table[j];
659 for (ch = 0; ch < s->nb_channels; ch++) {
660 b = bit_alloc[ch][i];
662 scale = scale_factors[ch][i][k];
663 qindex = alloc_table[j+b];
664 bits = ff_mpa_quant_bits[qindex];
667 /* 3 values at the same time */
668 v = get_bits(&s->gb, -bits);
669 v2 = division_tabs[qindex][v];
670 steps = ff_mpa_quant_steps[qindex];
672 s->sb_samples[ch][k * 12 + l + 0][i] =
673 l2_unscale_group(steps, v2 & 15, scale);
674 s->sb_samples[ch][k * 12 + l + 1][i] =
675 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
676 s->sb_samples[ch][k * 12 + l + 2][i] =
677 l2_unscale_group(steps, v2 >> 8 , scale);
679 for (m = 0; m < 3; m++) {
680 v = get_bits(&s->gb, bits);
681 v = l1_unscale(bits - 1, v, scale);
682 s->sb_samples[ch][k * 12 + l + m][i] = v;
686 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
687 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
688 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
691 /* next subband in alloc table */
692 j += 1 << bit_alloc_bits;
694 /* XXX: find a way to avoid this duplication of code */
695 for (i = bound; i < sblimit; i++) {
696 bit_alloc_bits = alloc_table[j];
699 int mant, scale0, scale1;
700 scale0 = scale_factors[0][i][k];
701 scale1 = scale_factors[1][i][k];
702 qindex = alloc_table[j+b];
703 bits = ff_mpa_quant_bits[qindex];
705 /* 3 values at the same time */
706 v = get_bits(&s->gb, -bits);
707 steps = ff_mpa_quant_steps[qindex];
710 s->sb_samples[0][k * 12 + l + 0][i] =
711 l2_unscale_group(steps, mant, scale0);
712 s->sb_samples[1][k * 12 + l + 0][i] =
713 l2_unscale_group(steps, mant, scale1);
716 s->sb_samples[0][k * 12 + l + 1][i] =
717 l2_unscale_group(steps, mant, scale0);
718 s->sb_samples[1][k * 12 + l + 1][i] =
719 l2_unscale_group(steps, mant, scale1);
720 s->sb_samples[0][k * 12 + l + 2][i] =
721 l2_unscale_group(steps, v, scale0);
722 s->sb_samples[1][k * 12 + l + 2][i] =
723 l2_unscale_group(steps, v, scale1);
725 for (m = 0; m < 3; m++) {
726 mant = get_bits(&s->gb, bits);
727 s->sb_samples[0][k * 12 + l + m][i] =
728 l1_unscale(bits - 1, mant, scale0);
729 s->sb_samples[1][k * 12 + l + m][i] =
730 l1_unscale(bits - 1, mant, scale1);
734 s->sb_samples[0][k * 12 + l + 0][i] = 0;
735 s->sb_samples[0][k * 12 + l + 1][i] = 0;
736 s->sb_samples[0][k * 12 + l + 2][i] = 0;
737 s->sb_samples[1][k * 12 + l + 0][i] = 0;
738 s->sb_samples[1][k * 12 + l + 1][i] = 0;
739 s->sb_samples[1][k * 12 + l + 2][i] = 0;
741 /* next subband in alloc table */
742 j += 1 << bit_alloc_bits;
744 /* fill remaining samples to zero */
745 for (i = sblimit; i < SBLIMIT; i++) {
746 for (ch = 0; ch < s->nb_channels; ch++) {
747 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
748 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
749 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
757 #define SPLIT(dst,sf,n) \
759 int m = (sf * 171) >> 9; \
762 } else if (n == 4) { \
765 } else if (n == 5) { \
766 int m = (sf * 205) >> 10; \
769 } else if (n == 6) { \
770 int m = (sf * 171) >> 10; \
777 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
780 SPLIT(slen[3], sf, n3)
781 SPLIT(slen[2], sf, n2)
782 SPLIT(slen[1], sf, n1)
786 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
789 const uint8_t *bstab, *pretab;
790 int len, i, j, k, l, v0, shift, gain, gains[3];
794 gain = g->global_gain - 210;
795 shift = g->scalefac_scale + 1;
797 bstab = band_size_long[s->sample_rate_index];
798 pretab = mpa_pretab[g->preflag];
799 for (i = 0; i < g->long_end; i++) {
800 v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
802 for (j = len; j > 0; j--)
806 if (g->short_start < 13) {
807 bstab = band_size_short[s->sample_rate_index];
808 gains[0] = gain - (g->subblock_gain[0] << 3);
809 gains[1] = gain - (g->subblock_gain[1] << 3);
810 gains[2] = gain - (g->subblock_gain[2] << 3);
812 for (i = g->short_start; i < 13; i++) {
814 for (l = 0; l < 3; l++) {
815 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
816 for (j = len; j > 0; j--)
823 /* handle n = 0 too */
824 static inline int get_bitsz(GetBitContext *s, int n)
826 return n ? get_bits(s, n) : 0;
830 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
833 if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
835 s->in_gb.buffer = NULL;
836 assert((get_bits_count(&s->gb) & 7) == 0);
837 skip_bits_long(&s->gb, *pos - *end_pos);
839 *end_pos = *end_pos2 + get_bits_count(&s->gb) - *pos;
840 *pos = get_bits_count(&s->gb);
844 /* Following is a optimized code for
846 if(get_bits1(&s->gb))
851 #define READ_FLIP_SIGN(dst,src) \
852 v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31); \
855 #define READ_FLIP_SIGN(dst,src) \
856 v = -get_bits1(&s->gb); \
857 *(dst) = (*(src) ^ v) - v;
860 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
861 int16_t *exponents, int end_pos2)
865 int last_pos, bits_left;
867 int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
869 /* low frequencies (called big values) */
871 for (i = 0; i < 3; i++) {
872 int j, k, l, linbits;
873 j = g->region_size[i];
876 /* select vlc table */
877 k = g->table_select[i];
878 l = mpa_huff_data[k][0];
879 linbits = mpa_huff_data[k][1];
883 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
888 /* read huffcode and compute each couple */
892 int pos = get_bits_count(&s->gb);
895 switch_buffer(s, &pos, &end_pos, &end_pos2);
899 y = get_vlc2(&s->gb, vlc->table, 7, 3);
902 g->sb_hybrid[s_index ] =
903 g->sb_hybrid[s_index+1] = 0;
908 exponent= exponents[s_index];
910 av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
911 i, g->region_size[i] - j, x, y, exponent);
916 READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
918 x += get_bitsz(&s->gb, linbits);
919 v = l3_unscale(x, exponent);
920 if (get_bits1(&s->gb))
922 g->sb_hybrid[s_index] = v;
925 READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
927 y += get_bitsz(&s->gb, linbits);
928 v = l3_unscale(y, exponent);
929 if (get_bits1(&s->gb))
931 g->sb_hybrid[s_index+1] = v;
938 READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
940 x += get_bitsz(&s->gb, linbits);
941 v = l3_unscale(x, exponent);
942 if (get_bits1(&s->gb))
944 g->sb_hybrid[s_index+!!y] = v;
946 g->sb_hybrid[s_index + !y] = 0;
952 /* high frequencies */
953 vlc = &huff_quad_vlc[g->count1table_select];
955 while (s_index <= 572) {
957 pos = get_bits_count(&s->gb);
958 if (pos >= end_pos) {
959 if (pos > end_pos2 && last_pos) {
960 /* some encoders generate an incorrect size for this
961 part. We must go back into the data */
963 skip_bits_long(&s->gb, last_pos - pos);
964 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
965 if(s->err_recognition & AV_EF_BITSTREAM)
969 switch_buffer(s, &pos, &end_pos, &end_pos2);
975 code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
976 av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
977 g->sb_hybrid[s_index+0] =
978 g->sb_hybrid[s_index+1] =
979 g->sb_hybrid[s_index+2] =
980 g->sb_hybrid[s_index+3] = 0;
982 static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
984 int pos = s_index + idxtab[code];
985 code ^= 8 >> idxtab[code];
986 READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
990 /* skip extension bits */
991 bits_left = end_pos2 - get_bits_count(&s->gb);
992 if (bits_left < 0 && (s->err_recognition & AV_EF_BUFFER)) {
993 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
995 } else if (bits_left > 0 && (s->err_recognition & AV_EF_BUFFER)) {
996 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
999 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1000 skip_bits_long(&s->gb, bits_left);
1002 i = get_bits_count(&s->gb);
1003 switch_buffer(s, &i, &end_pos, &end_pos2);
1008 /* Reorder short blocks from bitstream order to interleaved order. It
1009 would be faster to do it in parsing, but the code would be far more
1011 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1014 INTFLOAT *ptr, *dst, *ptr1;
1017 if (g->block_type != 2)
1020 if (g->switch_point) {
1021 if (s->sample_rate_index != 8)
1022 ptr = g->sb_hybrid + 36;
1024 ptr = g->sb_hybrid + 72;
1029 for (i = g->short_start; i < 13; i++) {
1030 len = band_size_short[s->sample_rate_index][i];
1033 for (j = len; j > 0; j--) {
1034 *dst++ = ptr[0*len];
1035 *dst++ = ptr[1*len];
1036 *dst++ = ptr[2*len];
1040 memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1044 #define ISQRT2 FIXR(0.70710678118654752440)
1046 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1049 int sf_max, sf, len, non_zero_found;
1050 INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1051 int non_zero_found_short[3];
1053 /* intensity stereo */
1054 if (s->mode_ext & MODE_EXT_I_STEREO) {
1059 is_tab = is_table_lsf[g1->scalefac_compress & 1];
1063 tab0 = g0->sb_hybrid + 576;
1064 tab1 = g1->sb_hybrid + 576;
1066 non_zero_found_short[0] = 0;
1067 non_zero_found_short[1] = 0;
1068 non_zero_found_short[2] = 0;
1069 k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1070 for (i = 12; i >= g1->short_start; i--) {
1071 /* for last band, use previous scale factor */
1074 len = band_size_short[s->sample_rate_index][i];
1075 for (l = 2; l >= 0; l--) {
1078 if (!non_zero_found_short[l]) {
1079 /* test if non zero band. if so, stop doing i-stereo */
1080 for (j = 0; j < len; j++) {
1082 non_zero_found_short[l] = 1;
1086 sf = g1->scale_factors[k + l];
1092 for (j = 0; j < len; j++) {
1094 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1095 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1099 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1100 /* lower part of the spectrum : do ms stereo
1102 for (j = 0; j < len; j++) {
1105 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1106 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1113 non_zero_found = non_zero_found_short[0] |
1114 non_zero_found_short[1] |
1115 non_zero_found_short[2];
1117 for (i = g1->long_end - 1;i >= 0;i--) {
1118 len = band_size_long[s->sample_rate_index][i];
1121 /* test if non zero band. if so, stop doing i-stereo */
1122 if (!non_zero_found) {
1123 for (j = 0; j < len; j++) {
1129 /* for last band, use previous scale factor */
1130 k = (i == 21) ? 20 : i;
1131 sf = g1->scale_factors[k];
1136 for (j = 0; j < len; j++) {
1138 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1139 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1143 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1144 /* lower part of the spectrum : do ms stereo
1146 for (j = 0; j < len; j++) {
1149 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1150 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1155 } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1156 /* ms stereo ONLY */
1157 /* NOTE: the 1/sqrt(2) normalization factor is included in the
1160 s->fdsp.butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1162 tab0 = g0->sb_hybrid;
1163 tab1 = g1->sb_hybrid;
1164 for (i = 0; i < 576; i++) {
1167 tab0[i] = tmp0 + tmp1;
1168 tab1[i] = tmp0 - tmp1;
1175 #define AA(j) do { \
1176 float tmp0 = ptr[-1-j]; \
1177 float tmp1 = ptr[ j]; \
1178 ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1]; \
1179 ptr[ j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0]; \
1182 #define AA(j) do { \
1183 int tmp0 = ptr[-1-j]; \
1184 int tmp1 = ptr[ j]; \
1185 int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]); \
1186 ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2])); \
1187 ptr[ j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3])); \
1191 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1196 /* we antialias only "long" bands */
1197 if (g->block_type == 2) {
1198 if (!g->switch_point)
1200 /* XXX: check this for 8000Hz case */
1206 ptr = g->sb_hybrid + 18;
1207 for (i = n; i > 0; i--) {
1221 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1222 INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1224 INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1226 int i, j, mdct_long_end, sblimit;
1228 /* find last non zero block */
1229 ptr = g->sb_hybrid + 576;
1230 ptr1 = g->sb_hybrid + 2 * 18;
1231 while (ptr >= ptr1) {
1235 if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1238 sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1240 if (g->block_type == 2) {
1241 /* XXX: check for 8000 Hz */
1242 if (g->switch_point)
1247 mdct_long_end = sblimit;
1250 s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1251 mdct_long_end, g->switch_point,
1254 buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1255 ptr = g->sb_hybrid + 18 * mdct_long_end;
1257 for (j = mdct_long_end; j < sblimit; j++) {
1258 /* select frequency inversion */
1259 win = RENAME(ff_mdct_win)[2 + (4 & -(j & 1))];
1260 out_ptr = sb_samples + j;
1262 for (i = 0; i < 6; i++) {
1263 *out_ptr = buf[4*i];
1266 imdct12(out2, ptr + 0);
1267 for (i = 0; i < 6; i++) {
1268 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*1)];
1269 buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1272 imdct12(out2, ptr + 1);
1273 for (i = 0; i < 6; i++) {
1274 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*2)];
1275 buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1278 imdct12(out2, ptr + 2);
1279 for (i = 0; i < 6; i++) {
1280 buf[4*(i + 6*0)] = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*0)];
1281 buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1282 buf[4*(i + 6*2)] = 0;
1285 buf += (j&3) != 3 ? 1 : (4*18-3);
1288 for (j = sblimit; j < SBLIMIT; j++) {
1290 out_ptr = sb_samples + j;
1291 for (i = 0; i < 18; i++) {
1292 *out_ptr = buf[4*i];
1296 buf += (j&3) != 3 ? 1 : (4*18-3);
1300 /* main layer3 decoding function */
1301 static int mp_decode_layer3(MPADecodeContext *s)
1303 int nb_granules, main_data_begin;
1304 int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1306 int16_t exponents[576]; //FIXME try INTFLOAT
1308 /* read side info */
1310 main_data_begin = get_bits(&s->gb, 8);
1311 skip_bits(&s->gb, s->nb_channels);
1314 main_data_begin = get_bits(&s->gb, 9);
1315 if (s->nb_channels == 2)
1316 skip_bits(&s->gb, 3);
1318 skip_bits(&s->gb, 5);
1320 for (ch = 0; ch < s->nb_channels; ch++) {
1321 s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1322 s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1326 for (gr = 0; gr < nb_granules; gr++) {
1327 for (ch = 0; ch < s->nb_channels; ch++) {
1328 av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1329 g = &s->granules[ch][gr];
1330 g->part2_3_length = get_bits(&s->gb, 12);
1331 g->big_values = get_bits(&s->gb, 9);
1332 if (g->big_values > 288) {
1333 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1334 return AVERROR_INVALIDDATA;
1337 g->global_gain = get_bits(&s->gb, 8);
1338 /* if MS stereo only is selected, we precompute the
1339 1/sqrt(2) renormalization factor */
1340 if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1342 g->global_gain -= 2;
1344 g->scalefac_compress = get_bits(&s->gb, 9);
1346 g->scalefac_compress = get_bits(&s->gb, 4);
1347 blocksplit_flag = get_bits1(&s->gb);
1348 if (blocksplit_flag) {
1349 g->block_type = get_bits(&s->gb, 2);
1350 if (g->block_type == 0) {
1351 av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1352 return AVERROR_INVALIDDATA;
1354 g->switch_point = get_bits1(&s->gb);
1355 for (i = 0; i < 2; i++)
1356 g->table_select[i] = get_bits(&s->gb, 5);
1357 for (i = 0; i < 3; i++)
1358 g->subblock_gain[i] = get_bits(&s->gb, 3);
1359 init_short_region(s, g);
1361 int region_address1, region_address2;
1363 g->switch_point = 0;
1364 for (i = 0; i < 3; i++)
1365 g->table_select[i] = get_bits(&s->gb, 5);
1366 /* compute huffman coded region sizes */
1367 region_address1 = get_bits(&s->gb, 4);
1368 region_address2 = get_bits(&s->gb, 3);
1369 av_dlog(s->avctx, "region1=%d region2=%d\n",
1370 region_address1, region_address2);
1371 init_long_region(s, g, region_address1, region_address2);
1373 region_offset2size(g);
1374 compute_band_indexes(s, g);
1378 g->preflag = get_bits1(&s->gb);
1379 g->scalefac_scale = get_bits1(&s->gb);
1380 g->count1table_select = get_bits1(&s->gb);
1381 av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1382 g->block_type, g->switch_point);
1388 const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1389 int extrasize = av_clip(get_bits_left(&s->gb) >> 3, 0,
1390 FFMAX(0, LAST_BUF_SIZE - s->last_buf_size));
1391 assert((get_bits_count(&s->gb) & 7) == 0);
1392 /* now we get bits from the main_data_begin offset */
1393 av_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1394 main_data_begin, s->last_buf_size);
1396 memcpy(s->last_buf + s->last_buf_size, ptr, extrasize);
1398 init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1399 #if !UNCHECKED_BITSTREAM_READER
1400 s->gb.size_in_bits_plus8 += extrasize * 8;
1402 s->last_buf_size <<= 3;
1403 for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1404 for (ch = 0; ch < s->nb_channels; ch++) {
1405 g = &s->granules[ch][gr];
1406 s->last_buf_size += g->part2_3_length;
1407 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1408 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1411 skip = s->last_buf_size - 8 * main_data_begin;
1412 if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
1413 skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
1415 s->in_gb.buffer = NULL;
1417 skip_bits_long(&s->gb, skip);
1423 for (; gr < nb_granules; gr++) {
1424 for (ch = 0; ch < s->nb_channels; ch++) {
1425 g = &s->granules[ch][gr];
1426 bits_pos = get_bits_count(&s->gb);
1430 int slen, slen1, slen2;
1432 /* MPEG1 scale factors */
1433 slen1 = slen_table[0][g->scalefac_compress];
1434 slen2 = slen_table[1][g->scalefac_compress];
1435 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1436 if (g->block_type == 2) {
1437 n = g->switch_point ? 17 : 18;
1440 for (i = 0; i < n; i++)
1441 g->scale_factors[j++] = get_bits(&s->gb, slen1);
1443 for (i = 0; i < n; i++)
1444 g->scale_factors[j++] = 0;
1447 for (i = 0; i < 18; i++)
1448 g->scale_factors[j++] = get_bits(&s->gb, slen2);
1449 for (i = 0; i < 3; i++)
1450 g->scale_factors[j++] = 0;
1452 for (i = 0; i < 21; i++)
1453 g->scale_factors[j++] = 0;
1456 sc = s->granules[ch][0].scale_factors;
1458 for (k = 0; k < 4; k++) {
1460 if ((g->scfsi & (0x8 >> k)) == 0) {
1461 slen = (k < 2) ? slen1 : slen2;
1463 for (i = 0; i < n; i++)
1464 g->scale_factors[j++] = get_bits(&s->gb, slen);
1466 for (i = 0; i < n; i++)
1467 g->scale_factors[j++] = 0;
1470 /* simply copy from last granule */
1471 for (i = 0; i < n; i++) {
1472 g->scale_factors[j] = sc[j];
1477 g->scale_factors[j++] = 0;
1480 int tindex, tindex2, slen[4], sl, sf;
1482 /* LSF scale factors */
1483 if (g->block_type == 2)
1484 tindex = g->switch_point ? 2 : 1;
1488 sf = g->scalefac_compress;
1489 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1490 /* intensity stereo case */
1493 lsf_sf_expand(slen, sf, 6, 6, 0);
1495 } else if (sf < 244) {
1496 lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1499 lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1505 lsf_sf_expand(slen, sf, 5, 4, 4);
1507 } else if (sf < 500) {
1508 lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1511 lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1518 for (k = 0; k < 4; k++) {
1519 n = lsf_nsf_table[tindex2][tindex][k];
1522 for (i = 0; i < n; i++)
1523 g->scale_factors[j++] = get_bits(&s->gb, sl);
1525 for (i = 0; i < n; i++)
1526 g->scale_factors[j++] = 0;
1529 /* XXX: should compute exact size */
1531 g->scale_factors[j] = 0;
1534 exponents_from_scale_factors(s, g, exponents);
1536 /* read Huffman coded residue */
1537 huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1540 if (s->mode == MPA_JSTEREO)
1541 compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1543 for (ch = 0; ch < s->nb_channels; ch++) {
1544 g = &s->granules[ch][gr];
1546 reorder_block(s, g);
1547 compute_antialias(s, g);
1548 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1551 if (get_bits_count(&s->gb) < 0)
1552 skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1553 return nb_granules * 18;
1556 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1557 const uint8_t *buf, int buf_size)
1559 int i, nb_frames, ch, ret;
1560 OUT_INT *samples_ptr;
1562 init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1564 /* skip error protection field */
1565 if (s->error_protection)
1566 skip_bits(&s->gb, 16);
1570 s->avctx->frame_size = 384;
1571 nb_frames = mp_decode_layer1(s);
1574 s->avctx->frame_size = 1152;
1575 nb_frames = mp_decode_layer2(s);
1578 s->avctx->frame_size = s->lsf ? 576 : 1152;
1580 nb_frames = mp_decode_layer3(s);
1586 if (s->in_gb.buffer) {
1587 align_get_bits(&s->gb);
1588 i = get_bits_left(&s->gb)>>3;
1589 if (i >= 0 && i <= BACKSTEP_SIZE) {
1590 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1593 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1595 s->in_gb.buffer = NULL;
1598 align_get_bits(&s->gb);
1599 assert((get_bits_count(&s->gb) & 7) == 0);
1600 i = get_bits_left(&s->gb) >> 3;
1602 if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1604 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1605 i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1607 assert(i <= buf_size - HEADER_SIZE && i >= 0);
1608 memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1609 s->last_buf_size += i;
1612 /* get output buffer */
1614 av_assert0(s->frame != NULL);
1615 s->frame->nb_samples = s->avctx->frame_size;
1616 if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0) {
1617 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1620 samples = (OUT_INT **)s->frame->extended_data;
1623 /* apply the synthesis filter */
1624 for (ch = 0; ch < s->nb_channels; ch++) {
1626 if (s->avctx->sample_fmt == OUT_FMT_P) {
1627 samples_ptr = samples[ch];
1630 samples_ptr = samples[0] + ch;
1631 sample_stride = s->nb_channels;
1633 for (i = 0; i < nb_frames; i++) {
1634 RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1635 &(s->synth_buf_offset[ch]),
1636 RENAME(ff_mpa_synth_window),
1637 &s->dither_state, samples_ptr,
1638 sample_stride, s->sb_samples[ch][i]);
1639 samples_ptr += 32 * sample_stride;
1643 return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1646 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1649 const uint8_t *buf = avpkt->data;
1650 int buf_size = avpkt->size;
1651 MPADecodeContext *s = avctx->priv_data;
1655 if (buf_size < HEADER_SIZE)
1656 return AVERROR_INVALIDDATA;
1658 header = AV_RB32(buf);
1659 if (ff_mpa_check_header(header) < 0) {
1660 av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1661 return AVERROR_INVALIDDATA;
1664 if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1665 /* free format: prepare to compute frame size */
1667 return AVERROR_INVALIDDATA;
1669 /* update codec info */
1670 avctx->channels = s->nb_channels;
1671 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1672 if (!avctx->bit_rate)
1673 avctx->bit_rate = s->bit_rate;
1675 if (s->frame_size <= 0 || s->frame_size > buf_size) {
1676 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1677 return AVERROR_INVALIDDATA;
1678 } else if (s->frame_size < buf_size) {
1679 buf_size= s->frame_size;
1684 ret = mp_decode_frame(s, NULL, buf, buf_size);
1686 s->frame->nb_samples = avctx->frame_size;
1688 avctx->sample_rate = s->sample_rate;
1689 //FIXME maybe move the other codec info stuff from above here too
1691 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1692 /* Only return an error if the bad frame makes up the whole packet or
1693 * the error is related to buffer management.
1694 * If there is more data in the packet, just consume the bad frame
1695 * instead of returning an error, which would discard the whole
1698 if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1705 static void mp_flush(MPADecodeContext *ctx)
1707 memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1708 ctx->last_buf_size = 0;
1711 static void flush(AVCodecContext *avctx)
1713 mp_flush(avctx->priv_data);
1716 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1717 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1718 int *got_frame_ptr, AVPacket *avpkt)
1720 const uint8_t *buf = avpkt->data;
1721 int buf_size = avpkt->size;
1722 MPADecodeContext *s = avctx->priv_data;
1728 // Discard too short frames
1729 if (buf_size < HEADER_SIZE) {
1730 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1731 return AVERROR_INVALIDDATA;
1735 if (len > MPA_MAX_CODED_FRAME_SIZE)
1736 len = MPA_MAX_CODED_FRAME_SIZE;
1738 // Get header and restore sync word
1739 header = AV_RB32(buf) | 0xffe00000;
1741 if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
1742 av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1743 return AVERROR_INVALIDDATA;
1746 avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1747 /* update codec info */
1748 avctx->sample_rate = s->sample_rate;
1749 avctx->channels = s->nb_channels;
1750 if (!avctx->bit_rate)
1751 avctx->bit_rate = s->bit_rate;
1753 s->frame_size = len;
1757 ret = mp_decode_frame(s, NULL, buf, buf_size);
1759 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1767 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1769 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1772 * Context for MP3On4 decoder
1774 typedef struct MP3On4DecodeContext {
1775 int frames; ///< number of mp3 frames per block (number of mp3 decoder instances)
1776 int syncword; ///< syncword patch
1777 const uint8_t *coff; ///< channel offsets in output buffer
1778 MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1779 } MP3On4DecodeContext;
1781 #include "mpeg4audio.h"
1783 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1785 /* number of mp3 decoder instances */
1786 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1788 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1789 static const uint8_t chan_offset[8][5] = {
1794 { 2, 0, 3 }, // C FLR BS
1795 { 2, 0, 3 }, // C FLR BLRS
1796 { 2, 0, 4, 3 }, // C FLR BLRS LFE
1797 { 2, 0, 6, 4, 3 }, // C FLR BLRS BLR LFE
1800 /* mp3on4 channel layouts */
1801 static const int16_t chan_layout[8] = {
1804 AV_CH_LAYOUT_STEREO,
1805 AV_CH_LAYOUT_SURROUND,
1806 AV_CH_LAYOUT_4POINT0,
1807 AV_CH_LAYOUT_5POINT0,
1808 AV_CH_LAYOUT_5POINT1,
1809 AV_CH_LAYOUT_7POINT1
1812 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1814 MP3On4DecodeContext *s = avctx->priv_data;
1817 for (i = 0; i < s->frames; i++)
1818 av_free(s->mp3decctx[i]);
1824 static av_cold int decode_init_mp3on4(AVCodecContext * avctx)
1826 MP3On4DecodeContext *s = avctx->priv_data;
1827 MPEG4AudioConfig cfg;
1830 if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
1831 av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1832 return AVERROR_INVALIDDATA;
1835 avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
1836 avctx->extradata_size * 8, 1);
1837 if (!cfg.chan_config || cfg.chan_config > 7) {
1838 av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1839 return AVERROR_INVALIDDATA;
1841 s->frames = mp3Frames[cfg.chan_config];
1842 s->coff = chan_offset[cfg.chan_config];
1843 avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
1844 avctx->channel_layout = chan_layout[cfg.chan_config];
1846 if (cfg.sample_rate < 16000)
1847 s->syncword = 0xffe00000;
1849 s->syncword = 0xfff00000;
1851 /* Init the first mp3 decoder in standard way, so that all tables get builded
1852 * We replace avctx->priv_data with the context of the first decoder so that
1853 * decode_init() does not have to be changed.
1854 * Other decoders will be initialized here copying data from the first context
1856 // Allocate zeroed memory for the first decoder context
1857 s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1858 if (!s->mp3decctx[0])
1860 // Put decoder context in place to make init_decode() happy
1861 avctx->priv_data = s->mp3decctx[0];
1863 // Restore mp3on4 context pointer
1864 avctx->priv_data = s;
1865 s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1867 /* Create a separate codec/context for each frame (first is already ok).
1868 * Each frame is 1 or 2 channels - up to 5 frames allowed
1870 for (i = 1; i < s->frames; i++) {
1871 s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1872 if (!s->mp3decctx[i])
1874 s->mp3decctx[i]->adu_mode = 1;
1875 s->mp3decctx[i]->avctx = avctx;
1876 s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1881 decode_close_mp3on4(avctx);
1882 return AVERROR(ENOMEM);
1886 static void flush_mp3on4(AVCodecContext *avctx)
1889 MP3On4DecodeContext *s = avctx->priv_data;
1891 for (i = 0; i < s->frames; i++)
1892 mp_flush(s->mp3decctx[i]);
1896 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1897 int *got_frame_ptr, AVPacket *avpkt)
1899 AVFrame *frame = data;
1900 const uint8_t *buf = avpkt->data;
1901 int buf_size = avpkt->size;
1902 MP3On4DecodeContext *s = avctx->priv_data;
1903 MPADecodeContext *m;
1904 int fsize, len = buf_size, out_size = 0;
1906 OUT_INT **out_samples;
1910 /* get output buffer */
1911 frame->nb_samples = MPA_FRAME_SIZE;
1912 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1913 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1916 out_samples = (OUT_INT **)frame->extended_data;
1918 // Discard too short frames
1919 if (buf_size < HEADER_SIZE)
1920 return AVERROR_INVALIDDATA;
1922 avctx->bit_rate = 0;
1925 for (fr = 0; fr < s->frames; fr++) {
1926 fsize = AV_RB16(buf) >> 4;
1927 fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1928 m = s->mp3decctx[fr];
1931 if (fsize < HEADER_SIZE) {
1932 av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1933 return AVERROR_INVALIDDATA;
1935 header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1937 if (ff_mpa_check_header(header) < 0) // Bad header, discard block
1940 avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1942 if (ch + m->nb_channels > avctx->channels) {
1943 av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1945 return AVERROR_INVALIDDATA;
1947 ch += m->nb_channels;
1949 outptr[0] = out_samples[s->coff[fr]];
1950 if (m->nb_channels > 1)
1951 outptr[1] = out_samples[s->coff[fr] + 1];
1953 if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
1960 avctx->bit_rate += m->bit_rate;
1963 /* update codec info */
1964 avctx->sample_rate = s->mp3decctx[0]->sample_rate;
1966 frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
1971 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
1974 #if CONFIG_MP1_DECODER
1975 AVCodec ff_mp1_decoder = {
1977 .type = AVMEDIA_TYPE_AUDIO,
1978 .id = AV_CODEC_ID_MP1,
1979 .priv_data_size = sizeof(MPADecodeContext),
1980 .init = decode_init,
1981 .decode = decode_frame,
1982 .capabilities = CODEC_CAP_DR1,
1984 .long_name = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
1985 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
1987 AV_SAMPLE_FMT_NONE },
1990 #if CONFIG_MP2_DECODER
1991 AVCodec ff_mp2_decoder = {
1993 .type = AVMEDIA_TYPE_AUDIO,
1994 .id = AV_CODEC_ID_MP2,
1995 .priv_data_size = sizeof(MPADecodeContext),
1996 .init = decode_init,
1997 .decode = decode_frame,
1998 .capabilities = CODEC_CAP_DR1,
2000 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2001 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2003 AV_SAMPLE_FMT_NONE },
2006 #if CONFIG_MP3_DECODER
2007 AVCodec ff_mp3_decoder = {
2009 .type = AVMEDIA_TYPE_AUDIO,
2010 .id = AV_CODEC_ID_MP3,
2011 .priv_data_size = sizeof(MPADecodeContext),
2012 .init = decode_init,
2013 .decode = decode_frame,
2014 .capabilities = CODEC_CAP_DR1,
2016 .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2017 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2019 AV_SAMPLE_FMT_NONE },
2022 #if CONFIG_MP3ADU_DECODER
2023 AVCodec ff_mp3adu_decoder = {
2025 .type = AVMEDIA_TYPE_AUDIO,
2026 .id = AV_CODEC_ID_MP3ADU,
2027 .priv_data_size = sizeof(MPADecodeContext),
2028 .init = decode_init,
2029 .decode = decode_frame_adu,
2030 .capabilities = CODEC_CAP_DR1,
2032 .long_name = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2033 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2035 AV_SAMPLE_FMT_NONE },
2038 #if CONFIG_MP3ON4_DECODER
2039 AVCodec ff_mp3on4_decoder = {
2041 .type = AVMEDIA_TYPE_AUDIO,
2042 .id = AV_CODEC_ID_MP3ON4,
2043 .priv_data_size = sizeof(MP3On4DecodeContext),
2044 .init = decode_init_mp3on4,
2045 .close = decode_close_mp3on4,
2046 .decode = decode_frame_mp3on4,
2047 .capabilities = CODEC_CAP_DR1,
2048 .flush = flush_mp3on4,
2049 .long_name = NULL_IF_CONFIG_SMALL("MP3onMP4"),
2050 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2051 AV_SAMPLE_FMT_NONE },