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/libm.h"
34 #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;
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 ff_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 ff_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 ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2)
201 g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
202 /* should not overflow */
203 l = FFMIN(ra1 + ra2 + 2, 22);
204 g->region_size[1] = band_index_long[s->sample_rate_index][ l] >> 1;
207 static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
209 if (g->block_type == 2) {
210 if (g->switch_point) {
211 if(s->sample_rate_index == 8)
212 av_log_ask_for_sample(s->avctx, "switch point in 8khz\n");
213 /* if switched mode, we handle the 36 first samples as
214 long blocks. For 8000Hz, we handle the 72 first
215 exponents as long blocks */
216 if (s->sample_rate_index <= 2)
232 /* layer 1 unscaling */
233 /* n = number of bits of the mantissa minus 1 */
234 static inline int l1_unscale(int n, int mant, int scale_factor)
239 shift = scale_factor_modshift[scale_factor];
242 val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
244 /* NOTE: at this point, 1 <= shift >= 21 + 15 */
245 return (int)((val + (1LL << (shift - 1))) >> shift);
248 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
252 shift = scale_factor_modshift[scale_factor];
256 val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
257 /* NOTE: at this point, 0 <= shift <= 21 */
259 val = (val + (1 << (shift - 1))) >> shift;
263 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
264 static inline int l3_unscale(int value, int exponent)
269 e = table_4_3_exp [4 * value + (exponent & 3)];
270 m = table_4_3_value[4 * value + (exponent & 3)];
274 av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
278 m = (m + (1 << (e - 1))) >> e;
283 static av_cold void decode_init_static(void)
288 /* scale factors table for layer 1/2 */
289 for (i = 0; i < 64; i++) {
291 /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
294 scale_factor_modshift[i] = mod | (shift << 2);
297 /* scale factor multiply for layer 1 */
298 for (i = 0; i < 15; i++) {
301 norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
302 scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0 * 2.0), FRAC_BITS);
303 scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
304 scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
305 av_dlog(NULL, "%d: norm=%x s=%x %x %x\n", i, norm,
306 scale_factor_mult[i][0],
307 scale_factor_mult[i][1],
308 scale_factor_mult[i][2]);
311 RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
313 /* huffman decode tables */
315 for (i = 1; i < 16; i++) {
316 const HuffTable *h = &mpa_huff_tables[i];
318 uint8_t tmp_bits [512] = { 0 };
319 uint16_t tmp_codes[512] = { 0 };
324 for (x = 0; x < xsize; x++) {
325 for (y = 0; y < xsize; y++) {
326 tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j ];
327 tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
332 huff_vlc[i].table = huff_vlc_tables+offset;
333 huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
334 init_vlc(&huff_vlc[i], 7, 512,
335 tmp_bits, 1, 1, tmp_codes, 2, 2,
336 INIT_VLC_USE_NEW_STATIC);
337 offset += huff_vlc_tables_sizes[i];
339 av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
342 for (i = 0; i < 2; i++) {
343 huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
344 huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
345 init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
346 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
347 INIT_VLC_USE_NEW_STATIC);
348 offset += huff_quad_vlc_tables_sizes[i];
350 av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
352 for (i = 0; i < 9; i++) {
354 for (j = 0; j < 22; j++) {
355 band_index_long[i][j] = k;
356 k += band_size_long[i][j];
358 band_index_long[i][22] = k;
361 /* compute n ^ (4/3) and store it in mantissa/exp format */
363 mpegaudio_tableinit();
365 for (i = 0; i < 4; i++) {
366 if (ff_mpa_quant_bits[i] < 0) {
367 for (j = 0; j < (1 << (-ff_mpa_quant_bits[i]+1)); j++) {
368 int val1, val2, val3, steps;
370 steps = ff_mpa_quant_steps[i];
375 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
381 for (i = 0; i < 7; i++) {
385 f = tan((double)i * M_PI / 12.0);
386 v = FIXR(f / (1.0 + f));
391 is_table[1][6 - i] = v;
394 for (i = 7; i < 16; i++)
395 is_table[0][i] = is_table[1][i] = 0.0;
397 for (i = 0; i < 16; i++) {
401 for (j = 0; j < 2; j++) {
402 e = -(j + 1) * ((i + 1) >> 1);
405 is_table_lsf[j][k ^ 1][i] = FIXR(f);
406 is_table_lsf[j][k ][i] = FIXR(1.0);
407 av_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
408 i, j, (float) is_table_lsf[j][0][i],
409 (float) is_table_lsf[j][1][i]);
413 for (i = 0; i < 8; i++) {
416 cs = 1.0 / sqrt(1.0 + ci * ci);
419 csa_table[i][0] = FIXHR(cs/4);
420 csa_table[i][1] = FIXHR(ca/4);
421 csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
422 csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
424 csa_table[i][0] = cs;
425 csa_table[i][1] = ca;
426 csa_table[i][2] = ca + cs;
427 csa_table[i][3] = ca - cs;
432 static av_cold int decode_init(AVCodecContext * avctx)
434 static int initialized_tables = 0;
435 MPADecodeContext *s = avctx->priv_data;
437 if (!initialized_tables) {
438 decode_init_static();
439 initialized_tables = 1;
444 ff_mpadsp_init(&s->mpadsp);
445 ff_dsputil_init(&s->dsp, avctx);
447 if (avctx->request_sample_fmt == OUT_FMT &&
448 avctx->codec_id != AV_CODEC_ID_MP3ON4)
449 avctx->sample_fmt = OUT_FMT;
451 avctx->sample_fmt = OUT_FMT_P;
452 s->err_recognition = avctx->err_recognition;
454 if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
457 avcodec_get_frame_defaults(&s->frame);
458 avctx->coded_frame = &s->frame;
463 #define C3 FIXHR(0.86602540378443864676/2)
464 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
465 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
466 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
468 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
470 static void imdct12(INTFLOAT *out, INTFLOAT *in)
472 INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
475 in1 = in[1*3] + in[0*3];
476 in2 = in[2*3] + in[1*3];
477 in3 = in[3*3] + in[2*3];
478 in4 = in[4*3] + in[3*3];
479 in5 = in[5*3] + in[4*3];
483 in2 = MULH3(in2, C3, 2);
484 in3 = MULH3(in3, C3, 4);
487 t2 = MULH3(in1 - in5, C4, 2);
497 in1 = MULH3(in5 + in3, C5, 1);
504 in5 = MULH3(in5 - in3, C6, 2);
511 /* return the number of decoded frames */
512 static int mp_decode_layer1(MPADecodeContext *s)
514 int bound, i, v, n, ch, j, mant;
515 uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
516 uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
518 if (s->mode == MPA_JSTEREO)
519 bound = (s->mode_ext + 1) * 4;
523 /* allocation bits */
524 for (i = 0; i < bound; i++) {
525 for (ch = 0; ch < s->nb_channels; ch++) {
526 allocation[ch][i] = get_bits(&s->gb, 4);
529 for (i = bound; i < SBLIMIT; i++)
530 allocation[0][i] = get_bits(&s->gb, 4);
533 for (i = 0; i < bound; i++) {
534 for (ch = 0; ch < s->nb_channels; ch++) {
535 if (allocation[ch][i])
536 scale_factors[ch][i] = get_bits(&s->gb, 6);
539 for (i = bound; i < SBLIMIT; i++) {
540 if (allocation[0][i]) {
541 scale_factors[0][i] = get_bits(&s->gb, 6);
542 scale_factors[1][i] = get_bits(&s->gb, 6);
546 /* compute samples */
547 for (j = 0; j < 12; j++) {
548 for (i = 0; i < bound; i++) {
549 for (ch = 0; ch < s->nb_channels; ch++) {
550 n = allocation[ch][i];
552 mant = get_bits(&s->gb, n + 1);
553 v = l1_unscale(n, mant, scale_factors[ch][i]);
557 s->sb_samples[ch][j][i] = v;
560 for (i = bound; i < SBLIMIT; i++) {
561 n = allocation[0][i];
563 mant = get_bits(&s->gb, n + 1);
564 v = l1_unscale(n, mant, scale_factors[0][i]);
565 s->sb_samples[0][j][i] = v;
566 v = l1_unscale(n, mant, scale_factors[1][i]);
567 s->sb_samples[1][j][i] = v;
569 s->sb_samples[0][j][i] = 0;
570 s->sb_samples[1][j][i] = 0;
577 static int mp_decode_layer2(MPADecodeContext *s)
579 int sblimit; /* number of used subbands */
580 const unsigned char *alloc_table;
581 int table, bit_alloc_bits, i, j, ch, bound, v;
582 unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
583 unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
584 unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
585 int scale, qindex, bits, steps, k, l, m, b;
587 /* select decoding table */
588 table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
589 s->sample_rate, s->lsf);
590 sblimit = ff_mpa_sblimit_table[table];
591 alloc_table = ff_mpa_alloc_tables[table];
593 if (s->mode == MPA_JSTEREO)
594 bound = (s->mode_ext + 1) * 4;
598 av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
604 /* parse bit allocation */
606 for (i = 0; i < bound; i++) {
607 bit_alloc_bits = alloc_table[j];
608 for (ch = 0; ch < s->nb_channels; ch++)
609 bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
610 j += 1 << bit_alloc_bits;
612 for (i = bound; i < sblimit; i++) {
613 bit_alloc_bits = alloc_table[j];
614 v = get_bits(&s->gb, bit_alloc_bits);
617 j += 1 << bit_alloc_bits;
621 for (i = 0; i < sblimit; i++) {
622 for (ch = 0; ch < s->nb_channels; ch++) {
623 if (bit_alloc[ch][i])
624 scale_code[ch][i] = get_bits(&s->gb, 2);
629 for (i = 0; i < sblimit; i++) {
630 for (ch = 0; ch < s->nb_channels; ch++) {
631 if (bit_alloc[ch][i]) {
632 sf = scale_factors[ch][i];
633 switch (scale_code[ch][i]) {
636 sf[0] = get_bits(&s->gb, 6);
637 sf[1] = get_bits(&s->gb, 6);
638 sf[2] = get_bits(&s->gb, 6);
641 sf[0] = get_bits(&s->gb, 6);
646 sf[0] = get_bits(&s->gb, 6);
647 sf[2] = get_bits(&s->gb, 6);
651 sf[0] = get_bits(&s->gb, 6);
652 sf[2] = get_bits(&s->gb, 6);
661 for (k = 0; k < 3; k++) {
662 for (l = 0; l < 12; l += 3) {
664 for (i = 0; i < bound; i++) {
665 bit_alloc_bits = alloc_table[j];
666 for (ch = 0; ch < s->nb_channels; ch++) {
667 b = bit_alloc[ch][i];
669 scale = scale_factors[ch][i][k];
670 qindex = alloc_table[j+b];
671 bits = ff_mpa_quant_bits[qindex];
674 /* 3 values at the same time */
675 v = get_bits(&s->gb, -bits);
676 v2 = division_tabs[qindex][v];
677 steps = ff_mpa_quant_steps[qindex];
679 s->sb_samples[ch][k * 12 + l + 0][i] =
680 l2_unscale_group(steps, v2 & 15, scale);
681 s->sb_samples[ch][k * 12 + l + 1][i] =
682 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
683 s->sb_samples[ch][k * 12 + l + 2][i] =
684 l2_unscale_group(steps, v2 >> 8 , scale);
686 for (m = 0; m < 3; m++) {
687 v = get_bits(&s->gb, bits);
688 v = l1_unscale(bits - 1, v, scale);
689 s->sb_samples[ch][k * 12 + l + m][i] = v;
693 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
694 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
695 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
698 /* next subband in alloc table */
699 j += 1 << bit_alloc_bits;
701 /* XXX: find a way to avoid this duplication of code */
702 for (i = bound; i < sblimit; i++) {
703 bit_alloc_bits = alloc_table[j];
706 int mant, scale0, scale1;
707 scale0 = scale_factors[0][i][k];
708 scale1 = scale_factors[1][i][k];
709 qindex = alloc_table[j+b];
710 bits = ff_mpa_quant_bits[qindex];
712 /* 3 values at the same time */
713 v = get_bits(&s->gb, -bits);
714 steps = ff_mpa_quant_steps[qindex];
717 s->sb_samples[0][k * 12 + l + 0][i] =
718 l2_unscale_group(steps, mant, scale0);
719 s->sb_samples[1][k * 12 + l + 0][i] =
720 l2_unscale_group(steps, mant, scale1);
723 s->sb_samples[0][k * 12 + l + 1][i] =
724 l2_unscale_group(steps, mant, scale0);
725 s->sb_samples[1][k * 12 + l + 1][i] =
726 l2_unscale_group(steps, mant, scale1);
727 s->sb_samples[0][k * 12 + l + 2][i] =
728 l2_unscale_group(steps, v, scale0);
729 s->sb_samples[1][k * 12 + l + 2][i] =
730 l2_unscale_group(steps, v, scale1);
732 for (m = 0; m < 3; m++) {
733 mant = get_bits(&s->gb, bits);
734 s->sb_samples[0][k * 12 + l + m][i] =
735 l1_unscale(bits - 1, mant, scale0);
736 s->sb_samples[1][k * 12 + l + m][i] =
737 l1_unscale(bits - 1, mant, scale1);
741 s->sb_samples[0][k * 12 + l + 0][i] = 0;
742 s->sb_samples[0][k * 12 + l + 1][i] = 0;
743 s->sb_samples[0][k * 12 + l + 2][i] = 0;
744 s->sb_samples[1][k * 12 + l + 0][i] = 0;
745 s->sb_samples[1][k * 12 + l + 1][i] = 0;
746 s->sb_samples[1][k * 12 + l + 2][i] = 0;
748 /* next subband in alloc table */
749 j += 1 << bit_alloc_bits;
751 /* fill remaining samples to zero */
752 for (i = sblimit; i < SBLIMIT; i++) {
753 for (ch = 0; ch < s->nb_channels; ch++) {
754 s->sb_samples[ch][k * 12 + l + 0][i] = 0;
755 s->sb_samples[ch][k * 12 + l + 1][i] = 0;
756 s->sb_samples[ch][k * 12 + l + 2][i] = 0;
764 #define SPLIT(dst,sf,n) \
766 int m = (sf * 171) >> 9; \
769 } else if (n == 4) { \
772 } else if (n == 5) { \
773 int m = (sf * 205) >> 10; \
776 } else if (n == 6) { \
777 int m = (sf * 171) >> 10; \
784 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
787 SPLIT(slen[3], sf, n3)
788 SPLIT(slen[2], sf, n2)
789 SPLIT(slen[1], sf, n1)
793 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
796 const uint8_t *bstab, *pretab;
797 int len, i, j, k, l, v0, shift, gain, gains[3];
801 gain = g->global_gain - 210;
802 shift = g->scalefac_scale + 1;
804 bstab = band_size_long[s->sample_rate_index];
805 pretab = mpa_pretab[g->preflag];
806 for (i = 0; i < g->long_end; i++) {
807 v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
809 for (j = len; j > 0; j--)
813 if (g->short_start < 13) {
814 bstab = band_size_short[s->sample_rate_index];
815 gains[0] = gain - (g->subblock_gain[0] << 3);
816 gains[1] = gain - (g->subblock_gain[1] << 3);
817 gains[2] = gain - (g->subblock_gain[2] << 3);
819 for (i = g->short_start; i < 13; i++) {
821 for (l = 0; l < 3; l++) {
822 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
823 for (j = len; j > 0; j--)
830 /* handle n = 0 too */
831 static inline int get_bitsz(GetBitContext *s, int n)
833 return n ? get_bits(s, n) : 0;
837 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
840 if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
842 s->in_gb.buffer = NULL;
843 av_assert2((get_bits_count(&s->gb) & 7) == 0);
844 skip_bits_long(&s->gb, *pos - *end_pos);
846 *end_pos = *end_pos2 + get_bits_count(&s->gb) - *pos;
847 *pos = get_bits_count(&s->gb);
851 /* Following is a optimized code for
853 if(get_bits1(&s->gb))
858 #define READ_FLIP_SIGN(dst,src) \
859 v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31); \
862 #define READ_FLIP_SIGN(dst,src) \
863 v = -get_bits1(&s->gb); \
864 *(dst) = (*(src) ^ v) - v;
867 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
868 int16_t *exponents, int end_pos2)
872 int last_pos, bits_left;
874 int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
876 /* low frequencies (called big values) */
878 for (i = 0; i < 3; i++) {
879 int j, k, l, linbits;
880 j = g->region_size[i];
883 /* select vlc table */
884 k = g->table_select[i];
885 l = mpa_huff_data[k][0];
886 linbits = mpa_huff_data[k][1];
890 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
895 /* read huffcode and compute each couple */
899 int pos = get_bits_count(&s->gb);
902 switch_buffer(s, &pos, &end_pos, &end_pos2);
906 y = get_vlc2(&s->gb, vlc->table, 7, 3);
909 g->sb_hybrid[s_index ] =
910 g->sb_hybrid[s_index+1] = 0;
915 exponent= exponents[s_index];
917 av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
918 i, g->region_size[i] - j, x, y, exponent);
923 READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
925 x += get_bitsz(&s->gb, linbits);
926 v = l3_unscale(x, exponent);
927 if (get_bits1(&s->gb))
929 g->sb_hybrid[s_index] = v;
932 READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
934 y += get_bitsz(&s->gb, linbits);
935 v = l3_unscale(y, exponent);
936 if (get_bits1(&s->gb))
938 g->sb_hybrid[s_index+1] = v;
945 READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
947 x += get_bitsz(&s->gb, linbits);
948 v = l3_unscale(x, exponent);
949 if (get_bits1(&s->gb))
951 g->sb_hybrid[s_index+!!y] = v;
953 g->sb_hybrid[s_index + !y] = 0;
959 /* high frequencies */
960 vlc = &huff_quad_vlc[g->count1table_select];
962 while (s_index <= 572) {
964 pos = get_bits_count(&s->gb);
965 if (pos >= end_pos) {
966 if (pos > end_pos2 && last_pos) {
967 /* some encoders generate an incorrect size for this
968 part. We must go back into the data */
970 skip_bits_long(&s->gb, last_pos - pos);
971 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
972 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
976 switch_buffer(s, &pos, &end_pos, &end_pos2);
982 code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
983 av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
984 g->sb_hybrid[s_index+0] =
985 g->sb_hybrid[s_index+1] =
986 g->sb_hybrid[s_index+2] =
987 g->sb_hybrid[s_index+3] = 0;
989 static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
991 int pos = s_index + idxtab[code];
992 code ^= 8 >> idxtab[code];
993 READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
997 /* skip extension bits */
998 bits_left = end_pos2 - get_bits_count(&s->gb);
999 if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1000 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1002 } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1003 av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1006 memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1007 skip_bits_long(&s->gb, bits_left);
1009 i = get_bits_count(&s->gb);
1010 switch_buffer(s, &i, &end_pos, &end_pos2);
1015 /* Reorder short blocks from bitstream order to interleaved order. It
1016 would be faster to do it in parsing, but the code would be far more
1018 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1021 INTFLOAT *ptr, *dst, *ptr1;
1024 if (g->block_type != 2)
1027 if (g->switch_point) {
1028 if (s->sample_rate_index != 8)
1029 ptr = g->sb_hybrid + 36;
1031 ptr = g->sb_hybrid + 72;
1036 for (i = g->short_start; i < 13; i++) {
1037 len = band_size_short[s->sample_rate_index][i];
1040 for (j = len; j > 0; j--) {
1041 *dst++ = ptr[0*len];
1042 *dst++ = ptr[1*len];
1043 *dst++ = ptr[2*len];
1047 memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1051 #define ISQRT2 FIXR(0.70710678118654752440)
1053 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1056 int sf_max, sf, len, non_zero_found;
1057 INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1058 int non_zero_found_short[3];
1060 /* intensity stereo */
1061 if (s->mode_ext & MODE_EXT_I_STEREO) {
1066 is_tab = is_table_lsf[g1->scalefac_compress & 1];
1070 tab0 = g0->sb_hybrid + 576;
1071 tab1 = g1->sb_hybrid + 576;
1073 non_zero_found_short[0] = 0;
1074 non_zero_found_short[1] = 0;
1075 non_zero_found_short[2] = 0;
1076 k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1077 for (i = 12; i >= g1->short_start; i--) {
1078 /* for last band, use previous scale factor */
1081 len = band_size_short[s->sample_rate_index][i];
1082 for (l = 2; l >= 0; l--) {
1085 if (!non_zero_found_short[l]) {
1086 /* test if non zero band. if so, stop doing i-stereo */
1087 for (j = 0; j < len; j++) {
1089 non_zero_found_short[l] = 1;
1093 sf = g1->scale_factors[k + l];
1099 for (j = 0; j < len; j++) {
1101 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1102 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1106 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1107 /* lower part of the spectrum : do ms stereo
1109 for (j = 0; j < len; j++) {
1112 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1113 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1120 non_zero_found = non_zero_found_short[0] |
1121 non_zero_found_short[1] |
1122 non_zero_found_short[2];
1124 for (i = g1->long_end - 1;i >= 0;i--) {
1125 len = band_size_long[s->sample_rate_index][i];
1128 /* test if non zero band. if so, stop doing i-stereo */
1129 if (!non_zero_found) {
1130 for (j = 0; j < len; j++) {
1136 /* for last band, use previous scale factor */
1137 k = (i == 21) ? 20 : i;
1138 sf = g1->scale_factors[k];
1143 for (j = 0; j < len; j++) {
1145 tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1146 tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1150 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1151 /* lower part of the spectrum : do ms stereo
1153 for (j = 0; j < len; j++) {
1156 tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1157 tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1162 } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1163 /* ms stereo ONLY */
1164 /* NOTE: the 1/sqrt(2) normalization factor is included in the
1167 s-> dsp.butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1169 tab0 = g0->sb_hybrid;
1170 tab1 = g1->sb_hybrid;
1171 for (i = 0; i < 576; i++) {
1174 tab0[i] = tmp0 + tmp1;
1175 tab1[i] = tmp0 - tmp1;
1183 # include "mips/compute_antialias_float.h"
1184 #endif /* HAVE_MIPSFPU */
1187 # include "mips/compute_antialias_fixed.h"
1188 #endif /* HAVE_MIPSDSPR1 */
1189 #endif /* CONFIG_FLOAT */
1191 #ifndef compute_antialias
1193 #define AA(j) do { \
1194 float tmp0 = ptr[-1-j]; \
1195 float tmp1 = ptr[ j]; \
1196 ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1]; \
1197 ptr[ j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0]; \
1200 #define AA(j) do { \
1201 int tmp0 = ptr[-1-j]; \
1202 int tmp1 = ptr[ j]; \
1203 int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]); \
1204 ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2])); \
1205 ptr[ j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3])); \
1209 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1214 /* we antialias only "long" bands */
1215 if (g->block_type == 2) {
1216 if (!g->switch_point)
1218 /* XXX: check this for 8000Hz case */
1224 ptr = g->sb_hybrid + 18;
1225 for (i = n; i > 0; i--) {
1238 #endif /* compute_antialias */
1240 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1241 INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1243 INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1245 int i, j, mdct_long_end, sblimit;
1247 /* find last non zero block */
1248 ptr = g->sb_hybrid + 576;
1249 ptr1 = g->sb_hybrid + 2 * 18;
1250 while (ptr >= ptr1) {
1254 if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1257 sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1259 if (g->block_type == 2) {
1260 /* XXX: check for 8000 Hz */
1261 if (g->switch_point)
1266 mdct_long_end = sblimit;
1269 s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1270 mdct_long_end, g->switch_point,
1273 buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1274 ptr = g->sb_hybrid + 18 * mdct_long_end;
1276 for (j = mdct_long_end; j < sblimit; j++) {
1277 /* select frequency inversion */
1278 win = RENAME(ff_mdct_win)[2 + (4 & -(j & 1))];
1279 out_ptr = sb_samples + j;
1281 for (i = 0; i < 6; i++) {
1282 *out_ptr = buf[4*i];
1285 imdct12(out2, ptr + 0);
1286 for (i = 0; i < 6; i++) {
1287 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*1)];
1288 buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1291 imdct12(out2, ptr + 1);
1292 for (i = 0; i < 6; i++) {
1293 *out_ptr = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*2)];
1294 buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1297 imdct12(out2, ptr + 2);
1298 for (i = 0; i < 6; i++) {
1299 buf[4*(i + 6*0)] = MULH3(out2[i ], win[i ], 1) + buf[4*(i + 6*0)];
1300 buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1301 buf[4*(i + 6*2)] = 0;
1304 buf += (j&3) != 3 ? 1 : (4*18-3);
1307 for (j = sblimit; j < SBLIMIT; j++) {
1309 out_ptr = sb_samples + j;
1310 for (i = 0; i < 18; i++) {
1311 *out_ptr = buf[4*i];
1315 buf += (j&3) != 3 ? 1 : (4*18-3);
1319 /* main layer3 decoding function */
1320 static int mp_decode_layer3(MPADecodeContext *s)
1322 int nb_granules, main_data_begin;
1323 int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1325 int16_t exponents[576]; //FIXME try INTFLOAT
1327 /* read side info */
1329 main_data_begin = get_bits(&s->gb, 8);
1330 skip_bits(&s->gb, s->nb_channels);
1333 main_data_begin = get_bits(&s->gb, 9);
1334 if (s->nb_channels == 2)
1335 skip_bits(&s->gb, 3);
1337 skip_bits(&s->gb, 5);
1339 for (ch = 0; ch < s->nb_channels; ch++) {
1340 s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1341 s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1345 for (gr = 0; gr < nb_granules; gr++) {
1346 for (ch = 0; ch < s->nb_channels; ch++) {
1347 av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1348 g = &s->granules[ch][gr];
1349 g->part2_3_length = get_bits(&s->gb, 12);
1350 g->big_values = get_bits(&s->gb, 9);
1351 if (g->big_values > 288) {
1352 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1353 return AVERROR_INVALIDDATA;
1356 g->global_gain = get_bits(&s->gb, 8);
1357 /* if MS stereo only is selected, we precompute the
1358 1/sqrt(2) renormalization factor */
1359 if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1361 g->global_gain -= 2;
1363 g->scalefac_compress = get_bits(&s->gb, 9);
1365 g->scalefac_compress = get_bits(&s->gb, 4);
1366 blocksplit_flag = get_bits1(&s->gb);
1367 if (blocksplit_flag) {
1368 g->block_type = get_bits(&s->gb, 2);
1369 if (g->block_type == 0) {
1370 av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1371 return AVERROR_INVALIDDATA;
1373 g->switch_point = get_bits1(&s->gb);
1374 for (i = 0; i < 2; i++)
1375 g->table_select[i] = get_bits(&s->gb, 5);
1376 for (i = 0; i < 3; i++)
1377 g->subblock_gain[i] = get_bits(&s->gb, 3);
1378 ff_init_short_region(s, g);
1380 int region_address1, region_address2;
1382 g->switch_point = 0;
1383 for (i = 0; i < 3; i++)
1384 g->table_select[i] = get_bits(&s->gb, 5);
1385 /* compute huffman coded region sizes */
1386 region_address1 = get_bits(&s->gb, 4);
1387 region_address2 = get_bits(&s->gb, 3);
1388 av_dlog(s->avctx, "region1=%d region2=%d\n",
1389 region_address1, region_address2);
1390 ff_init_long_region(s, g, region_address1, region_address2);
1392 ff_region_offset2size(g);
1393 ff_compute_band_indexes(s, g);
1397 g->preflag = get_bits1(&s->gb);
1398 g->scalefac_scale = get_bits1(&s->gb);
1399 g->count1table_select = get_bits1(&s->gb);
1400 av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1401 g->block_type, g->switch_point);
1407 const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1408 int extrasize = av_clip(get_bits_left(&s->gb) >> 3, 0, EXTRABYTES);
1409 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1410 /* now we get bits from the main_data_begin offset */
1411 av_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1412 main_data_begin, s->last_buf_size);
1414 memcpy(s->last_buf + s->last_buf_size, ptr, extrasize);
1416 init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1417 #if !UNCHECKED_BITSTREAM_READER
1418 s->gb.size_in_bits_plus8 += FFMAX(extrasize, LAST_BUF_SIZE - s->last_buf_size) * 8;
1420 s->last_buf_size <<= 3;
1421 for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1422 for (ch = 0; ch < s->nb_channels; ch++) {
1423 g = &s->granules[ch][gr];
1424 s->last_buf_size += g->part2_3_length;
1425 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1426 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1429 skip = s->last_buf_size - 8 * main_data_begin;
1430 if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
1431 skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
1433 s->in_gb.buffer = NULL;
1435 skip_bits_long(&s->gb, skip);
1441 for (; gr < nb_granules; gr++) {
1442 for (ch = 0; ch < s->nb_channels; ch++) {
1443 g = &s->granules[ch][gr];
1444 bits_pos = get_bits_count(&s->gb);
1448 int slen, slen1, slen2;
1450 /* MPEG1 scale factors */
1451 slen1 = slen_table[0][g->scalefac_compress];
1452 slen2 = slen_table[1][g->scalefac_compress];
1453 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1454 if (g->block_type == 2) {
1455 n = g->switch_point ? 17 : 18;
1458 for (i = 0; i < n; i++)
1459 g->scale_factors[j++] = get_bits(&s->gb, slen1);
1461 for (i = 0; i < n; i++)
1462 g->scale_factors[j++] = 0;
1465 for (i = 0; i < 18; i++)
1466 g->scale_factors[j++] = get_bits(&s->gb, slen2);
1467 for (i = 0; i < 3; i++)
1468 g->scale_factors[j++] = 0;
1470 for (i = 0; i < 21; i++)
1471 g->scale_factors[j++] = 0;
1474 sc = s->granules[ch][0].scale_factors;
1476 for (k = 0; k < 4; k++) {
1478 if ((g->scfsi & (0x8 >> k)) == 0) {
1479 slen = (k < 2) ? slen1 : slen2;
1481 for (i = 0; i < n; i++)
1482 g->scale_factors[j++] = get_bits(&s->gb, slen);
1484 for (i = 0; i < n; i++)
1485 g->scale_factors[j++] = 0;
1488 /* simply copy from last granule */
1489 for (i = 0; i < n; i++) {
1490 g->scale_factors[j] = sc[j];
1495 g->scale_factors[j++] = 0;
1498 int tindex, tindex2, slen[4], sl, sf;
1500 /* LSF scale factors */
1501 if (g->block_type == 2)
1502 tindex = g->switch_point ? 2 : 1;
1506 sf = g->scalefac_compress;
1507 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1508 /* intensity stereo case */
1511 lsf_sf_expand(slen, sf, 6, 6, 0);
1513 } else if (sf < 244) {
1514 lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1517 lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1523 lsf_sf_expand(slen, sf, 5, 4, 4);
1525 } else if (sf < 500) {
1526 lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1529 lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1536 for (k = 0; k < 4; k++) {
1537 n = lsf_nsf_table[tindex2][tindex][k];
1540 for (i = 0; i < n; i++)
1541 g->scale_factors[j++] = get_bits(&s->gb, sl);
1543 for (i = 0; i < n; i++)
1544 g->scale_factors[j++] = 0;
1547 /* XXX: should compute exact size */
1549 g->scale_factors[j] = 0;
1552 exponents_from_scale_factors(s, g, exponents);
1554 /* read Huffman coded residue */
1555 huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1558 if (s->mode == MPA_JSTEREO)
1559 compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1561 for (ch = 0; ch < s->nb_channels; ch++) {
1562 g = &s->granules[ch][gr];
1564 reorder_block(s, g);
1565 compute_antialias(s, g);
1566 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1569 if (get_bits_count(&s->gb) < 0)
1570 skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1571 return nb_granules * 18;
1574 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1575 const uint8_t *buf, int buf_size)
1577 int i, nb_frames, ch, ret;
1578 OUT_INT *samples_ptr;
1580 init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1582 /* skip error protection field */
1583 if (s->error_protection)
1584 skip_bits(&s->gb, 16);
1588 s->avctx->frame_size = 384;
1589 nb_frames = mp_decode_layer1(s);
1592 s->avctx->frame_size = 1152;
1593 nb_frames = mp_decode_layer2(s);
1596 s->avctx->frame_size = s->lsf ? 576 : 1152;
1598 nb_frames = mp_decode_layer3(s);
1601 if (s->in_gb.buffer) {
1602 align_get_bits(&s->gb);
1603 i = get_bits_left(&s->gb)>>3;
1604 if (i >= 0 && i <= BACKSTEP_SIZE) {
1605 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1608 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1610 s->in_gb.buffer = NULL;
1613 align_get_bits(&s->gb);
1614 av_assert1((get_bits_count(&s->gb) & 7) == 0);
1615 i = get_bits_left(&s->gb) >> 3;
1617 if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1619 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1620 i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1622 av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1623 memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1624 s->last_buf_size += i;
1630 /* get output buffer */
1632 s->frame.nb_samples = s->avctx->frame_size;
1633 if ((ret = ff_get_buffer(s->avctx, &s->frame)) < 0) {
1634 av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1637 samples = (OUT_INT **)s->frame.extended_data;
1640 /* apply the synthesis filter */
1641 for (ch = 0; ch < s->nb_channels; ch++) {
1643 if (s->avctx->sample_fmt == OUT_FMT_P) {
1644 samples_ptr = samples[ch];
1647 samples_ptr = samples[0] + ch;
1648 sample_stride = s->nb_channels;
1650 for (i = 0; i < nb_frames; i++) {
1651 RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1652 &(s->synth_buf_offset[ch]),
1653 RENAME(ff_mpa_synth_window),
1654 &s->dither_state, samples_ptr,
1655 sample_stride, s->sb_samples[ch][i]);
1656 samples_ptr += 32 * sample_stride;
1660 return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1663 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1666 const uint8_t *buf = avpkt->data;
1667 int buf_size = avpkt->size;
1668 MPADecodeContext *s = avctx->priv_data;
1672 while(buf_size && !*buf){
1677 if (buf_size < HEADER_SIZE)
1678 return AVERROR_INVALIDDATA;
1680 header = AV_RB32(buf);
1681 if (header>>8 == AV_RB32("TAG")>>8) {
1682 av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1685 if (ff_mpa_check_header(header) < 0) {
1686 av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1687 return AVERROR_INVALIDDATA;
1690 if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1691 /* free format: prepare to compute frame size */
1693 return AVERROR_INVALIDDATA;
1695 /* update codec info */
1696 avctx->channels = s->nb_channels;
1697 avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1698 if (!avctx->bit_rate)
1699 avctx->bit_rate = s->bit_rate;
1701 if (s->frame_size <= 0 || s->frame_size > buf_size) {
1702 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1703 return AVERROR_INVALIDDATA;
1704 } else if (s->frame_size < buf_size) {
1705 av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1706 buf_size= s->frame_size;
1709 ret = mp_decode_frame(s, NULL, buf, buf_size);
1712 *(AVFrame *)data = s->frame;
1713 avctx->sample_rate = s->sample_rate;
1714 //FIXME maybe move the other codec info stuff from above here too
1716 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1717 /* Only return an error if the bad frame makes up the whole packet or
1718 * the error is related to buffer management.
1719 * If there is more data in the packet, just consume the bad frame
1720 * instead of returning an error, which would discard the whole
1723 if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1730 static void mp_flush(MPADecodeContext *ctx)
1732 memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1733 ctx->last_buf_size = 0;
1736 static void flush(AVCodecContext *avctx)
1738 mp_flush(avctx->priv_data);
1741 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1742 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1743 int *got_frame_ptr, AVPacket *avpkt)
1745 const uint8_t *buf = avpkt->data;
1746 int buf_size = avpkt->size;
1747 MPADecodeContext *s = avctx->priv_data;
1750 int av_unused out_size;
1754 // Discard too short frames
1755 if (buf_size < HEADER_SIZE) {
1756 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1757 return AVERROR_INVALIDDATA;
1761 if (len > MPA_MAX_CODED_FRAME_SIZE)
1762 len = MPA_MAX_CODED_FRAME_SIZE;
1764 // Get header and restore sync word
1765 header = AV_RB32(buf) | 0xffe00000;
1767 if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
1768 av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1769 return AVERROR_INVALIDDATA;
1772 avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1773 /* update codec info */
1774 avctx->sample_rate = s->sample_rate;
1775 avctx->channels = s->nb_channels;
1776 if (!avctx->bit_rate)
1777 avctx->bit_rate = s->bit_rate;
1779 s->frame_size = len;
1781 ret = mp_decode_frame(s, NULL, buf, buf_size);
1783 av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1788 *(AVFrame *)data = s->frame;
1792 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1794 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1797 * Context for MP3On4 decoder
1799 typedef struct MP3On4DecodeContext {
1801 int frames; ///< number of mp3 frames per block (number of mp3 decoder instances)
1802 int syncword; ///< syncword patch
1803 const uint8_t *coff; ///< channel offsets in output buffer
1804 MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1805 } MP3On4DecodeContext;
1807 #include "mpeg4audio.h"
1809 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1811 /* number of mp3 decoder instances */
1812 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1814 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1815 static const uint8_t chan_offset[8][5] = {
1820 { 2, 0, 3 }, // C FLR BS
1821 { 2, 0, 3 }, // C FLR BLRS
1822 { 2, 0, 4, 3 }, // C FLR BLRS LFE
1823 { 2, 0, 6, 4, 3 }, // C FLR BLRS BLR LFE
1826 /* mp3on4 channel layouts */
1827 static const int16_t chan_layout[8] = {
1830 AV_CH_LAYOUT_STEREO,
1831 AV_CH_LAYOUT_SURROUND,
1832 AV_CH_LAYOUT_4POINT0,
1833 AV_CH_LAYOUT_5POINT0,
1834 AV_CH_LAYOUT_5POINT1,
1835 AV_CH_LAYOUT_7POINT1
1838 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1840 MP3On4DecodeContext *s = avctx->priv_data;
1843 for (i = 0; i < s->frames; i++)
1844 av_free(s->mp3decctx[i]);
1850 static int decode_init_mp3on4(AVCodecContext * avctx)
1852 MP3On4DecodeContext *s = avctx->priv_data;
1853 MPEG4AudioConfig cfg;
1856 if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
1857 av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1858 return AVERROR_INVALIDDATA;
1861 avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
1862 avctx->extradata_size * 8, 1);
1863 if (!cfg.chan_config || cfg.chan_config > 7) {
1864 av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1865 return AVERROR_INVALIDDATA;
1867 s->frames = mp3Frames[cfg.chan_config];
1868 s->coff = chan_offset[cfg.chan_config];
1869 avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
1870 avctx->channel_layout = chan_layout[cfg.chan_config];
1872 if (cfg.sample_rate < 16000)
1873 s->syncword = 0xffe00000;
1875 s->syncword = 0xfff00000;
1877 /* Init the first mp3 decoder in standard way, so that all tables get builded
1878 * We replace avctx->priv_data with the context of the first decoder so that
1879 * decode_init() does not have to be changed.
1880 * Other decoders will be initialized here copying data from the first context
1882 // Allocate zeroed memory for the first decoder context
1883 s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1884 if (!s->mp3decctx[0])
1886 // Put decoder context in place to make init_decode() happy
1887 avctx->priv_data = s->mp3decctx[0];
1889 s->frame = avctx->coded_frame;
1890 // Restore mp3on4 context pointer
1891 avctx->priv_data = s;
1892 s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1894 /* Create a separate codec/context for each frame (first is already ok).
1895 * Each frame is 1 or 2 channels - up to 5 frames allowed
1897 for (i = 1; i < s->frames; i++) {
1898 s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1899 if (!s->mp3decctx[i])
1901 s->mp3decctx[i]->adu_mode = 1;
1902 s->mp3decctx[i]->avctx = avctx;
1903 s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1908 decode_close_mp3on4(avctx);
1909 return AVERROR(ENOMEM);
1913 static void flush_mp3on4(AVCodecContext *avctx)
1916 MP3On4DecodeContext *s = avctx->priv_data;
1918 for (i = 0; i < s->frames; i++)
1919 mp_flush(s->mp3decctx[i]);
1923 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1924 int *got_frame_ptr, AVPacket *avpkt)
1926 const uint8_t *buf = avpkt->data;
1927 int buf_size = avpkt->size;
1928 MP3On4DecodeContext *s = avctx->priv_data;
1929 MPADecodeContext *m;
1930 int fsize, len = buf_size, out_size = 0;
1932 OUT_INT **out_samples;
1936 /* get output buffer */
1937 s->frame->nb_samples = s->frames * MPA_FRAME_SIZE;
1938 if ((ret = ff_get_buffer(avctx, s->frame)) < 0) {
1939 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1942 out_samples = (OUT_INT **)s->frame->extended_data;
1944 // Discard too short frames
1945 if (buf_size < HEADER_SIZE)
1946 return AVERROR_INVALIDDATA;
1948 avctx->bit_rate = 0;
1951 for (fr = 0; fr < s->frames; fr++) {
1952 fsize = AV_RB16(buf) >> 4;
1953 fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1954 m = s->mp3decctx[fr];
1957 if (fsize < HEADER_SIZE) {
1958 av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1959 return AVERROR_INVALIDDATA;
1961 header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1963 if (ff_mpa_check_header(header) < 0) // Bad header, discard block
1966 avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1968 if (ch + m->nb_channels > avctx->channels || s->coff[fr] + m->nb_channels > avctx->channels) {
1969 av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1971 return AVERROR_INVALIDDATA;
1973 ch += m->nb_channels;
1975 outptr[0] = out_samples[s->coff[fr]];
1976 if (m->nb_channels > 1)
1977 outptr[1] = out_samples[s->coff[fr] + 1];
1979 if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
1986 avctx->bit_rate += m->bit_rate;
1989 /* update codec info */
1990 avctx->sample_rate = s->mp3decctx[0]->sample_rate;
1992 s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
1994 *(AVFrame *)data = *s->frame;
1998 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
2001 #if CONFIG_MP1_DECODER
2002 AVCodec ff_mp1_decoder = {
2004 .type = AVMEDIA_TYPE_AUDIO,
2005 .id = AV_CODEC_ID_MP1,
2006 .priv_data_size = sizeof(MPADecodeContext),
2007 .init = decode_init,
2008 .decode = decode_frame,
2009 .capabilities = CODEC_CAP_DR1,
2011 .long_name = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2012 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2014 AV_SAMPLE_FMT_NONE },
2017 #if CONFIG_MP2_DECODER
2018 AVCodec ff_mp2_decoder = {
2020 .type = AVMEDIA_TYPE_AUDIO,
2021 .id = AV_CODEC_ID_MP2,
2022 .priv_data_size = sizeof(MPADecodeContext),
2023 .init = decode_init,
2024 .decode = decode_frame,
2025 .capabilities = CODEC_CAP_DR1,
2027 .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2028 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2030 AV_SAMPLE_FMT_NONE },
2033 #if CONFIG_MP3_DECODER
2034 AVCodec ff_mp3_decoder = {
2036 .type = AVMEDIA_TYPE_AUDIO,
2037 .id = AV_CODEC_ID_MP3,
2038 .priv_data_size = sizeof(MPADecodeContext),
2039 .init = decode_init,
2040 .decode = decode_frame,
2041 .capabilities = CODEC_CAP_DR1,
2043 .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2044 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2046 AV_SAMPLE_FMT_NONE },
2049 #if CONFIG_MP3ADU_DECODER
2050 AVCodec ff_mp3adu_decoder = {
2052 .type = AVMEDIA_TYPE_AUDIO,
2053 .id = AV_CODEC_ID_MP3ADU,
2054 .priv_data_size = sizeof(MPADecodeContext),
2055 .init = decode_init,
2056 .decode = decode_frame_adu,
2057 .capabilities = CODEC_CAP_DR1,
2059 .long_name = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2060 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2062 AV_SAMPLE_FMT_NONE },
2065 #if CONFIG_MP3ON4_DECODER
2066 AVCodec ff_mp3on4_decoder = {
2068 .type = AVMEDIA_TYPE_AUDIO,
2069 .id = AV_CODEC_ID_MP3ON4,
2070 .priv_data_size = sizeof(MP3On4DecodeContext),
2071 .init = decode_init_mp3on4,
2072 .close = decode_close_mp3on4,
2073 .decode = decode_frame_mp3on4,
2074 .capabilities = CODEC_CAP_DR1,
2075 .flush = flush_mp3on4,
2076 .long_name = NULL_IF_CONFIG_SMALL("MP3onMP4"),
2077 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
2078 AV_SAMPLE_FMT_NONE },