]> git.sesse.net Git - ffmpeg/blob - libavcodec/mpegaudiodec.c
Merge remote-tracking branch 'shariman/wmall'
[ffmpeg] / libavcodec / mpegaudiodec.c
1 /*
2  * MPEG Audio decoder
3  * Copyright (c) 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * MPEG Audio decoder
25  */
26
27 #include "libavutil/audioconvert.h"
28 #include "avcodec.h"
29 #include "get_bits.h"
30 #include "mathops.h"
31 #include "mpegaudiodsp.h"
32
33 /*
34  * TODO:
35  *  - test lsf / mpeg25 extensively.
36  */
37
38 #include "mpegaudio.h"
39 #include "mpegaudiodecheader.h"
40
41 #define BACKSTEP_SIZE 512
42 #define EXTRABYTES 24
43
44 /* layer 3 "granule" */
45 typedef struct GranuleDef {
46     uint8_t scfsi;
47     int part2_3_length;
48     int big_values;
49     int global_gain;
50     int scalefac_compress;
51     uint8_t block_type;
52     uint8_t switch_point;
53     int table_select[3];
54     int subblock_gain[3];
55     uint8_t scalefac_scale;
56     uint8_t count1table_select;
57     int region_size[3]; /* number of huffman codes in each region */
58     int preflag;
59     int short_start, long_end; /* long/short band indexes */
60     uint8_t scale_factors[40];
61     DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
62 } GranuleDef;
63
64 typedef struct MPADecodeContext {
65     MPA_DECODE_HEADER
66     uint8_t last_buf[2 * BACKSTEP_SIZE + EXTRABYTES];
67     int last_buf_size;
68     /* next header (used in free format parsing) */
69     uint32_t free_format_next_header;
70     GetBitContext gb;
71     GetBitContext in_gb;
72     DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
73     int synth_buf_offset[MPA_MAX_CHANNELS];
74     DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
75     INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
76     GranuleDef granules[2][2]; /* Used in Layer 3 */
77     int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
78     int dither_state;
79     int err_recognition;
80     AVCodecContext* avctx;
81     MPADSPContext mpadsp;
82     AVFrame frame;
83 } MPADecodeContext;
84
85 #if CONFIG_FLOAT
86 #   define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
87 #   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
88 #   define FIXR(x)        ((float)(x))
89 #   define FIXHR(x)       ((float)(x))
90 #   define MULH3(x, y, s) ((s)*(y)*(x))
91 #   define MULLx(x, y, s) ((y)*(x))
92 #   define RENAME(a) a ## _float
93 #   define OUT_FMT AV_SAMPLE_FMT_FLT
94 #else
95 #   define SHR(a,b)       ((a)>>(b))
96 /* WARNING: only correct for positive numbers */
97 #   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
98 #   define FIXR(a)        ((int)((a) * FRAC_ONE + 0.5))
99 #   define FIXHR(a)       ((int)((a) * (1LL<<32) + 0.5))
100 #   define MULH3(x, y, s) MULH((s)*(x), y)
101 #   define MULLx(x, y, s) MULL(x,y,s)
102 #   define RENAME(a)      a ## _fixed
103 #   define OUT_FMT AV_SAMPLE_FMT_S16
104 #endif
105
106 /****************/
107
108 #define HEADER_SIZE 4
109
110 #include "mpegaudiodata.h"
111 #include "mpegaudiodectab.h"
112
113 /* vlc structure for decoding layer 3 huffman tables */
114 static VLC huff_vlc[16];
115 static VLC_TYPE huff_vlc_tables[
116     0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
117   142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
118   ][2];
119 static const int huff_vlc_tables_sizes[16] = {
120     0,  128,  128,  128,  130,  128,  154,  166,
121   142,  204,  190,  170,  542,  460,  662,  414
122 };
123 static VLC huff_quad_vlc[2];
124 static VLC_TYPE  huff_quad_vlc_tables[128+16][2];
125 static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
126 /* computed from band_size_long */
127 static uint16_t band_index_long[9][23];
128 #include "mpegaudio_tablegen.h"
129 /* intensity stereo coef table */
130 static INTFLOAT is_table[2][16];
131 static INTFLOAT is_table_lsf[2][2][16];
132 static INTFLOAT csa_table[8][4];
133 /** Window for MDCT. Note that only the component [0,17] and [20,37] are used,
134     the components 18 and 19 are there only to assure 128-bit alignment for asm
135  */
136 DECLARE_ALIGNED(16, static INTFLOAT, mdct_win)[8][40];
137
138 static int16_t division_tab3[1<<6 ];
139 static int16_t division_tab5[1<<8 ];
140 static int16_t division_tab9[1<<11];
141
142 static int16_t * const division_tabs[4] = {
143     division_tab3, division_tab5, NULL, division_tab9
144 };
145
146 /* lower 2 bits: modulo 3, higher bits: shift */
147 static uint16_t scale_factor_modshift[64];
148 /* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
149 static int32_t scale_factor_mult[15][3];
150 /* mult table for layer 2 group quantization */
151
152 #define SCALE_GEN(v) \
153 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
154
155 static const int32_t scale_factor_mult2[3][3] = {
156     SCALE_GEN(4.0 / 3.0), /* 3 steps */
157     SCALE_GEN(4.0 / 5.0), /* 5 steps */
158     SCALE_GEN(4.0 / 9.0), /* 9 steps */
159 };
160
161 /**
162  * Convert region offsets to region sizes and truncate
163  * size to big_values.
164  */
165 static void ff_region_offset2size(GranuleDef *g)
166 {
167     int i, k, j = 0;
168     g->region_size[2] = 576 / 2;
169     for (i = 0; i < 3; i++) {
170         k = FFMIN(g->region_size[i], g->big_values);
171         g->region_size[i] = k - j;
172         j = k;
173     }
174 }
175
176 static void ff_init_short_region(MPADecodeContext *s, GranuleDef *g)
177 {
178     if (g->block_type == 2)
179         g->region_size[0] = (36 / 2);
180     else {
181         if (s->sample_rate_index <= 2)
182             g->region_size[0] = (36 / 2);
183         else if (s->sample_rate_index != 8)
184             g->region_size[0] = (54 / 2);
185         else
186             g->region_size[0] = (108 / 2);
187     }
188     g->region_size[1] = (576 / 2);
189 }
190
191 static void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2)
192 {
193     int l;
194     g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
195     /* should not overflow */
196     l = FFMIN(ra1 + ra2 + 2, 22);
197     g->region_size[1] = band_index_long[s->sample_rate_index][      l] >> 1;
198 }
199
200 static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
201 {
202     if (g->block_type == 2) {
203         if (g->switch_point) {
204             /* if switched mode, we handle the 36 first samples as
205                 long blocks.  For 8000Hz, we handle the 48 first
206                 exponents as long blocks (XXX: check this!) */
207             if (s->sample_rate_index <= 2)
208                 g->long_end = 8;
209             else if (s->sample_rate_index != 8)
210                 g->long_end = 6;
211             else
212                 g->long_end = 4; /* 8000 Hz */
213
214             g->short_start = 2 + (s->sample_rate_index != 8);
215         } else {
216             g->long_end    = 0;
217             g->short_start = 0;
218         }
219     } else {
220         g->short_start = 13;
221         g->long_end    = 22;
222     }
223 }
224
225 /* layer 1 unscaling */
226 /* n = number of bits of the mantissa minus 1 */
227 static inline int l1_unscale(int n, int mant, int scale_factor)
228 {
229     int shift, mod;
230     int64_t val;
231
232     shift   = scale_factor_modshift[scale_factor];
233     mod     = shift & 3;
234     shift >>= 2;
235     val     = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
236     shift  += n;
237     /* NOTE: at this point, 1 <= shift >= 21 + 15 */
238     return (int)((val + (1LL << (shift - 1))) >> shift);
239 }
240
241 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
242 {
243     int shift, mod, val;
244
245     shift   = scale_factor_modshift[scale_factor];
246     mod     = shift & 3;
247     shift >>= 2;
248
249     val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
250     /* NOTE: at this point, 0 <= shift <= 21 */
251     if (shift > 0)
252         val = (val + (1 << (shift - 1))) >> shift;
253     return val;
254 }
255
256 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
257 static inline int l3_unscale(int value, int exponent)
258 {
259     unsigned int m;
260     int e;
261
262     e  = table_4_3_exp  [4 * value + (exponent & 3)];
263     m  = table_4_3_value[4 * value + (exponent & 3)];
264     e -= exponent >> 2;
265     assert(e >= 1);
266     if (e > 31)
267         return 0;
268     m = (m + (1 << (e - 1))) >> e;
269
270     return m;
271 }
272
273 static av_cold void decode_init_static(void)
274 {
275     int i, j, k;
276     int offset;
277
278     /* scale factors table for layer 1/2 */
279     for (i = 0; i < 64; i++) {
280         int shift, mod;
281         /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
282         shift = i / 3;
283         mod   = i % 3;
284         scale_factor_modshift[i] = mod | (shift << 2);
285     }
286
287     /* scale factor multiply for layer 1 */
288     for (i = 0; i < 15; i++) {
289         int n, norm;
290         n = i + 2;
291         norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
292         scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
293         scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
294         scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
295         av_dlog(NULL, "%d: norm=%x s=%x %x %x\n", i, norm,
296                 scale_factor_mult[i][0],
297                 scale_factor_mult[i][1],
298                 scale_factor_mult[i][2]);
299     }
300
301     RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
302
303     /* huffman decode tables */
304     offset = 0;
305     for (i = 1; i < 16; i++) {
306         const HuffTable *h = &mpa_huff_tables[i];
307         int xsize, x, y;
308         uint8_t  tmp_bits [512];
309         uint16_t tmp_codes[512];
310
311         memset(tmp_bits , 0, sizeof(tmp_bits ));
312         memset(tmp_codes, 0, sizeof(tmp_codes));
313
314         xsize = h->xsize;
315
316         j = 0;
317         for (x = 0; x < xsize; x++) {
318             for (y = 0; y < xsize; y++) {
319                 tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
320                 tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
321             }
322         }
323
324         /* XXX: fail test */
325         huff_vlc[i].table = huff_vlc_tables+offset;
326         huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
327         init_vlc(&huff_vlc[i], 7, 512,
328                  tmp_bits, 1, 1, tmp_codes, 2, 2,
329                  INIT_VLC_USE_NEW_STATIC);
330         offset += huff_vlc_tables_sizes[i];
331     }
332     assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
333
334     offset = 0;
335     for (i = 0; i < 2; i++) {
336         huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
337         huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
338         init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
339                  mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
340                  INIT_VLC_USE_NEW_STATIC);
341         offset += huff_quad_vlc_tables_sizes[i];
342     }
343     assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
344
345     for (i = 0; i < 9; i++) {
346         k = 0;
347         for (j = 0; j < 22; j++) {
348             band_index_long[i][j] = k;
349             k += band_size_long[i][j];
350         }
351         band_index_long[i][22] = k;
352     }
353
354     /* compute n ^ (4/3) and store it in mantissa/exp format */
355
356     mpegaudio_tableinit();
357
358     for (i = 0; i < 4; i++) {
359         if (ff_mpa_quant_bits[i] < 0) {
360             for (j = 0; j < (1 << (-ff_mpa_quant_bits[i]+1)); j++) {
361                 int val1, val2, val3, steps;
362                 int val = j;
363                 steps   = ff_mpa_quant_steps[i];
364                 val1    = val % steps;
365                 val    /= steps;
366                 val2    = val % steps;
367                 val3    = val / steps;
368                 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
369             }
370         }
371     }
372
373
374     for (i = 0; i < 7; i++) {
375         float f;
376         INTFLOAT v;
377         if (i != 6) {
378             f = tan((double)i * M_PI / 12.0);
379             v = FIXR(f / (1.0 + f));
380         } else {
381             v = FIXR(1.0);
382         }
383         is_table[0][    i] = v;
384         is_table[1][6 - i] = v;
385     }
386     /* invalid values */
387     for (i = 7; i < 16; i++)
388         is_table[0][i] = is_table[1][i] = 0.0;
389
390     for (i = 0; i < 16; i++) {
391         double f;
392         int e, k;
393
394         for (j = 0; j < 2; j++) {
395             e = -(j + 1) * ((i + 1) >> 1);
396             f = pow(2.0, e / 4.0);
397             k = i & 1;
398             is_table_lsf[j][k ^ 1][i] = FIXR(f);
399             is_table_lsf[j][k    ][i] = FIXR(1.0);
400             av_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
401                     i, j, (float) is_table_lsf[j][0][i],
402                     (float) is_table_lsf[j][1][i]);
403         }
404     }
405
406     for (i = 0; i < 8; i++) {
407         float ci, cs, ca;
408         ci = ci_table[i];
409         cs = 1.0 / sqrt(1.0 + ci * ci);
410         ca = cs * ci;
411 #if !CONFIG_FLOAT
412         csa_table[i][0] = FIXHR(cs/4);
413         csa_table[i][1] = FIXHR(ca/4);
414         csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
415         csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
416 #else
417         csa_table[i][0] = cs;
418         csa_table[i][1] = ca;
419         csa_table[i][2] = ca + cs;
420         csa_table[i][3] = ca - cs;
421 #endif
422     }
423
424     /* compute mdct windows */
425     for (i = 0; i < 36; i++) {
426         for (j = 0; j < 4; j++) {
427             double d;
428
429             if (j == 2 && i % 3 != 1)
430                 continue;
431
432             d = sin(M_PI * (i + 0.5) / 36.0);
433             if (j == 1) {
434                 if      (i >= 30) d = 0;
435                 else if (i >= 24) d = sin(M_PI * (i - 18 + 0.5) / 12.0);
436                 else if (i >= 18) d = 1;
437             } else if (j == 3) {
438                 if      (i <   6) d = 0;
439                 else if (i <  12) d = sin(M_PI * (i -  6 + 0.5) / 12.0);
440                 else if (i <  18) d = 1;
441             }
442             //merge last stage of imdct into the window coefficients
443             d *= 0.5 / cos(M_PI * (2 * i + 19) / 72);
444
445             if (j == 2)
446                 mdct_win[j][i/3] = FIXHR((d / (1<<5)));
447             else {
448                 int idx = i < 18 ? i : i + 2;
449                 mdct_win[j][idx] = FIXHR((d / (1<<5)));
450             }
451         }
452     }
453
454     /* NOTE: we do frequency inversion adter the MDCT by changing
455         the sign of the right window coefs */
456     for (j = 0; j < 4; j++) {
457         for (i = 0; i < 40; i += 2) {
458             mdct_win[j + 4][i    ] =  mdct_win[j][i    ];
459             mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
460         }
461     }
462 }
463
464 static av_cold int decode_init(AVCodecContext * avctx)
465 {
466     static int initialized_tables = 0;
467     MPADecodeContext *s = avctx->priv_data;
468
469     if (!initialized_tables) {
470         decode_init_static();
471         initialized_tables = 1;
472     }
473
474     s->avctx = avctx;
475
476     ff_mpadsp_init(&s->mpadsp);
477
478     avctx->sample_fmt= OUT_FMT;
479     s->err_recognition = avctx->err_recognition;
480
481     if (avctx->codec_id == CODEC_ID_MP3ADU)
482         s->adu_mode = 1;
483
484     avcodec_get_frame_defaults(&s->frame);
485     avctx->coded_frame = &s->frame;
486
487     return 0;
488 }
489
490 #define C3 FIXHR(0.86602540378443864676/2)
491 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
492 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
493 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
494
495 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
496    cases. */
497 static void imdct12(INTFLOAT *out, INTFLOAT *in)
498 {
499     INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
500
501     in0  = in[0*3];
502     in1  = in[1*3] + in[0*3];
503     in2  = in[2*3] + in[1*3];
504     in3  = in[3*3] + in[2*3];
505     in4  = in[4*3] + in[3*3];
506     in5  = in[5*3] + in[4*3];
507     in5 += in3;
508     in3 += in1;
509
510     in2  = MULH3(in2, C3, 2);
511     in3  = MULH3(in3, C3, 4);
512
513     t1   = in0 - in4;
514     t2   = MULH3(in1 - in5, C4, 2);
515
516     out[ 7] =
517     out[10] = t1 + t2;
518     out[ 1] =
519     out[ 4] = t1 - t2;
520
521     in0    += SHR(in4, 1);
522     in4     = in0 + in2;
523     in5    += 2*in1;
524     in1     = MULH3(in5 + in3, C5, 1);
525     out[ 8] =
526     out[ 9] = in4 + in1;
527     out[ 2] =
528     out[ 3] = in4 - in1;
529
530     in0    -= in2;
531     in5     = MULH3(in5 - in3, C6, 2);
532     out[ 0] =
533     out[ 5] = in0 - in5;
534     out[ 6] =
535     out[11] = in0 + in5;
536 }
537
538 /* return the number of decoded frames */
539 static int mp_decode_layer1(MPADecodeContext *s)
540 {
541     int bound, i, v, n, ch, j, mant;
542     uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
543     uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
544
545     if (s->mode == MPA_JSTEREO)
546         bound = (s->mode_ext + 1) * 4;
547     else
548         bound = SBLIMIT;
549
550     /* allocation bits */
551     for (i = 0; i < bound; i++) {
552         for (ch = 0; ch < s->nb_channels; ch++) {
553             allocation[ch][i] = get_bits(&s->gb, 4);
554         }
555     }
556     for (i = bound; i < SBLIMIT; i++)
557         allocation[0][i] = get_bits(&s->gb, 4);
558
559     /* scale factors */
560     for (i = 0; i < bound; i++) {
561         for (ch = 0; ch < s->nb_channels; ch++) {
562             if (allocation[ch][i])
563                 scale_factors[ch][i] = get_bits(&s->gb, 6);
564         }
565     }
566     for (i = bound; i < SBLIMIT; i++) {
567         if (allocation[0][i]) {
568             scale_factors[0][i] = get_bits(&s->gb, 6);
569             scale_factors[1][i] = get_bits(&s->gb, 6);
570         }
571     }
572
573     /* compute samples */
574     for (j = 0; j < 12; j++) {
575         for (i = 0; i < bound; i++) {
576             for (ch = 0; ch < s->nb_channels; ch++) {
577                 n = allocation[ch][i];
578                 if (n) {
579                     mant = get_bits(&s->gb, n + 1);
580                     v = l1_unscale(n, mant, scale_factors[ch][i]);
581                 } else {
582                     v = 0;
583                 }
584                 s->sb_samples[ch][j][i] = v;
585             }
586         }
587         for (i = bound; i < SBLIMIT; i++) {
588             n = allocation[0][i];
589             if (n) {
590                 mant = get_bits(&s->gb, n + 1);
591                 v = l1_unscale(n, mant, scale_factors[0][i]);
592                 s->sb_samples[0][j][i] = v;
593                 v = l1_unscale(n, mant, scale_factors[1][i]);
594                 s->sb_samples[1][j][i] = v;
595             } else {
596                 s->sb_samples[0][j][i] = 0;
597                 s->sb_samples[1][j][i] = 0;
598             }
599         }
600     }
601     return 12;
602 }
603
604 static int mp_decode_layer2(MPADecodeContext *s)
605 {
606     int sblimit; /* number of used subbands */
607     const unsigned char *alloc_table;
608     int table, bit_alloc_bits, i, j, ch, bound, v;
609     unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
610     unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
611     unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
612     int scale, qindex, bits, steps, k, l, m, b;
613
614     /* select decoding table */
615     table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
616                                    s->sample_rate, s->lsf);
617     sblimit     = ff_mpa_sblimit_table[table];
618     alloc_table = ff_mpa_alloc_tables[table];
619
620     if (s->mode == MPA_JSTEREO)
621         bound = (s->mode_ext + 1) * 4;
622     else
623         bound = sblimit;
624
625     av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
626
627     /* sanity check */
628     if (bound > sblimit)
629         bound = sblimit;
630
631     /* parse bit allocation */
632     j = 0;
633     for (i = 0; i < bound; i++) {
634         bit_alloc_bits = alloc_table[j];
635         for (ch = 0; ch < s->nb_channels; ch++)
636             bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
637         j += 1 << bit_alloc_bits;
638     }
639     for (i = bound; i < sblimit; i++) {
640         bit_alloc_bits = alloc_table[j];
641         v = get_bits(&s->gb, bit_alloc_bits);
642         bit_alloc[0][i] = v;
643         bit_alloc[1][i] = v;
644         j += 1 << bit_alloc_bits;
645     }
646
647     /* scale codes */
648     for (i = 0; i < sblimit; i++) {
649         for (ch = 0; ch < s->nb_channels; ch++) {
650             if (bit_alloc[ch][i])
651                 scale_code[ch][i] = get_bits(&s->gb, 2);
652         }
653     }
654
655     /* scale factors */
656     for (i = 0; i < sblimit; i++) {
657         for (ch = 0; ch < s->nb_channels; ch++) {
658             if (bit_alloc[ch][i]) {
659                 sf = scale_factors[ch][i];
660                 switch (scale_code[ch][i]) {
661                 default:
662                 case 0:
663                     sf[0] = get_bits(&s->gb, 6);
664                     sf[1] = get_bits(&s->gb, 6);
665                     sf[2] = get_bits(&s->gb, 6);
666                     break;
667                 case 2:
668                     sf[0] = get_bits(&s->gb, 6);
669                     sf[1] = sf[0];
670                     sf[2] = sf[0];
671                     break;
672                 case 1:
673                     sf[0] = get_bits(&s->gb, 6);
674                     sf[2] = get_bits(&s->gb, 6);
675                     sf[1] = sf[0];
676                     break;
677                 case 3:
678                     sf[0] = get_bits(&s->gb, 6);
679                     sf[2] = get_bits(&s->gb, 6);
680                     sf[1] = sf[2];
681                     break;
682                 }
683             }
684         }
685     }
686
687     /* samples */
688     for (k = 0; k < 3; k++) {
689         for (l = 0; l < 12; l += 3) {
690             j = 0;
691             for (i = 0; i < bound; i++) {
692                 bit_alloc_bits = alloc_table[j];
693                 for (ch = 0; ch < s->nb_channels; ch++) {
694                     b = bit_alloc[ch][i];
695                     if (b) {
696                         scale = scale_factors[ch][i][k];
697                         qindex = alloc_table[j+b];
698                         bits = ff_mpa_quant_bits[qindex];
699                         if (bits < 0) {
700                             int v2;
701                             /* 3 values at the same time */
702                             v = get_bits(&s->gb, -bits);
703                             v2 = division_tabs[qindex][v];
704                             steps  = ff_mpa_quant_steps[qindex];
705
706                             s->sb_samples[ch][k * 12 + l + 0][i] =
707                                 l2_unscale_group(steps,  v2       & 15, scale);
708                             s->sb_samples[ch][k * 12 + l + 1][i] =
709                                 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
710                             s->sb_samples[ch][k * 12 + l + 2][i] =
711                                 l2_unscale_group(steps,  v2 >> 8      , scale);
712                         } else {
713                             for (m = 0; m < 3; m++) {
714                                 v = get_bits(&s->gb, bits);
715                                 v = l1_unscale(bits - 1, v, scale);
716                                 s->sb_samples[ch][k * 12 + l + m][i] = v;
717                             }
718                         }
719                     } else {
720                         s->sb_samples[ch][k * 12 + l + 0][i] = 0;
721                         s->sb_samples[ch][k * 12 + l + 1][i] = 0;
722                         s->sb_samples[ch][k * 12 + l + 2][i] = 0;
723                     }
724                 }
725                 /* next subband in alloc table */
726                 j += 1 << bit_alloc_bits;
727             }
728             /* XXX: find a way to avoid this duplication of code */
729             for (i = bound; i < sblimit; i++) {
730                 bit_alloc_bits = alloc_table[j];
731                 b = bit_alloc[0][i];
732                 if (b) {
733                     int mant, scale0, scale1;
734                     scale0 = scale_factors[0][i][k];
735                     scale1 = scale_factors[1][i][k];
736                     qindex = alloc_table[j+b];
737                     bits = ff_mpa_quant_bits[qindex];
738                     if (bits < 0) {
739                         /* 3 values at the same time */
740                         v = get_bits(&s->gb, -bits);
741                         steps = ff_mpa_quant_steps[qindex];
742                         mant = v % steps;
743                         v = v / steps;
744                         s->sb_samples[0][k * 12 + l + 0][i] =
745                             l2_unscale_group(steps, mant, scale0);
746                         s->sb_samples[1][k * 12 + l + 0][i] =
747                             l2_unscale_group(steps, mant, scale1);
748                         mant = v % steps;
749                         v = v / steps;
750                         s->sb_samples[0][k * 12 + l + 1][i] =
751                             l2_unscale_group(steps, mant, scale0);
752                         s->sb_samples[1][k * 12 + l + 1][i] =
753                             l2_unscale_group(steps, mant, scale1);
754                         s->sb_samples[0][k * 12 + l + 2][i] =
755                             l2_unscale_group(steps, v, scale0);
756                         s->sb_samples[1][k * 12 + l + 2][i] =
757                             l2_unscale_group(steps, v, scale1);
758                     } else {
759                         for (m = 0; m < 3; m++) {
760                             mant = get_bits(&s->gb, bits);
761                             s->sb_samples[0][k * 12 + l + m][i] =
762                                 l1_unscale(bits - 1, mant, scale0);
763                             s->sb_samples[1][k * 12 + l + m][i] =
764                                 l1_unscale(bits - 1, mant, scale1);
765                         }
766                     }
767                 } else {
768                     s->sb_samples[0][k * 12 + l + 0][i] = 0;
769                     s->sb_samples[0][k * 12 + l + 1][i] = 0;
770                     s->sb_samples[0][k * 12 + l + 2][i] = 0;
771                     s->sb_samples[1][k * 12 + l + 0][i] = 0;
772                     s->sb_samples[1][k * 12 + l + 1][i] = 0;
773                     s->sb_samples[1][k * 12 + l + 2][i] = 0;
774                 }
775                 /* next subband in alloc table */
776                 j += 1 << bit_alloc_bits;
777             }
778             /* fill remaining samples to zero */
779             for (i = sblimit; i < SBLIMIT; i++) {
780                 for (ch = 0; ch < s->nb_channels; ch++) {
781                     s->sb_samples[ch][k * 12 + l + 0][i] = 0;
782                     s->sb_samples[ch][k * 12 + l + 1][i] = 0;
783                     s->sb_samples[ch][k * 12 + l + 2][i] = 0;
784                 }
785             }
786         }
787     }
788     return 3 * 12;
789 }
790
791 #define SPLIT(dst,sf,n)             \
792     if (n == 3) {                   \
793         int m = (sf * 171) >> 9;    \
794         dst   = sf - 3 * m;         \
795         sf    = m;                  \
796     } else if (n == 4) {            \
797         dst  = sf & 3;              \
798         sf >>= 2;                   \
799     } else if (n == 5) {            \
800         int m = (sf * 205) >> 10;   \
801         dst   = sf - 5 * m;         \
802         sf    = m;                  \
803     } else if (n == 6) {            \
804         int m = (sf * 171) >> 10;   \
805         dst   = sf - 6 * m;         \
806         sf    = m;                  \
807     } else {                        \
808         dst = 0;                    \
809     }
810
811 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
812                                            int n3)
813 {
814     SPLIT(slen[3], sf, n3)
815     SPLIT(slen[2], sf, n2)
816     SPLIT(slen[1], sf, n1)
817     slen[0] = sf;
818 }
819
820 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
821                                          int16_t *exponents)
822 {
823     const uint8_t *bstab, *pretab;
824     int len, i, j, k, l, v0, shift, gain, gains[3];
825     int16_t *exp_ptr;
826
827     exp_ptr = exponents;
828     gain    = g->global_gain - 210;
829     shift   = g->scalefac_scale + 1;
830
831     bstab  = band_size_long[s->sample_rate_index];
832     pretab = mpa_pretab[g->preflag];
833     for (i = 0; i < g->long_end; i++) {
834         v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
835         len = bstab[i];
836         for (j = len; j > 0; j--)
837             *exp_ptr++ = v0;
838     }
839
840     if (g->short_start < 13) {
841         bstab    = band_size_short[s->sample_rate_index];
842         gains[0] = gain - (g->subblock_gain[0] << 3);
843         gains[1] = gain - (g->subblock_gain[1] << 3);
844         gains[2] = gain - (g->subblock_gain[2] << 3);
845         k        = g->long_end;
846         for (i = g->short_start; i < 13; i++) {
847             len = bstab[i];
848             for (l = 0; l < 3; l++) {
849                 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
850                 for (j = len; j > 0; j--)
851                     *exp_ptr++ = v0;
852             }
853         }
854     }
855 }
856
857 /* handle n = 0 too */
858 static inline int get_bitsz(GetBitContext *s, int n)
859 {
860     return n ? get_bits(s, n) : 0;
861 }
862
863
864 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
865                           int *end_pos2)
866 {
867     if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
868         s->gb           = s->in_gb;
869         s->in_gb.buffer = NULL;
870         assert((get_bits_count(&s->gb) & 7) == 0);
871         skip_bits_long(&s->gb, *pos - *end_pos);
872         *end_pos2 =
873         *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;
874         *pos      = get_bits_count(&s->gb);
875     }
876 }
877
878 /* Following is a optimized code for
879             INTFLOAT v = *src
880             if(get_bits1(&s->gb))
881                 v = -v;
882             *dst = v;
883 */
884 #if CONFIG_FLOAT
885 #define READ_FLIP_SIGN(dst,src)                     \
886     v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31);  \
887     AV_WN32A(dst, v);
888 #else
889 #define READ_FLIP_SIGN(dst,src)     \
890     v      = -get_bits1(&s->gb);    \
891     *(dst) = (*(src) ^ v) - v;
892 #endif
893
894 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
895                           int16_t *exponents, int end_pos2)
896 {
897     int s_index;
898     int i;
899     int last_pos, bits_left;
900     VLC *vlc;
901     int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
902
903     /* low frequencies (called big values) */
904     s_index = 0;
905     for (i = 0; i < 3; i++) {
906         int j, k, l, linbits;
907         j = g->region_size[i];
908         if (j == 0)
909             continue;
910         /* select vlc table */
911         k       = g->table_select[i];
912         l       = mpa_huff_data[k][0];
913         linbits = mpa_huff_data[k][1];
914         vlc     = &huff_vlc[l];
915
916         if (!l) {
917             memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
918             s_index += 2 * j;
919             continue;
920         }
921
922         /* read huffcode and compute each couple */
923         for (; j > 0; j--) {
924             int exponent, x, y;
925             int v;
926             int pos = get_bits_count(&s->gb);
927
928             if (pos >= end_pos){
929 //                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
930                 switch_buffer(s, &pos, &end_pos, &end_pos2);
931 //                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
932                 if (pos >= end_pos)
933                     break;
934             }
935             y = get_vlc2(&s->gb, vlc->table, 7, 3);
936
937             if (!y) {
938                 g->sb_hybrid[s_index  ] =
939                 g->sb_hybrid[s_index+1] = 0;
940                 s_index += 2;
941                 continue;
942             }
943
944             exponent= exponents[s_index];
945
946             av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
947                     i, g->region_size[i] - j, x, y, exponent);
948             if (y & 16) {
949                 x = y >> 5;
950                 y = y & 0x0f;
951                 if (x < 15) {
952                     READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
953                 } else {
954                     x += get_bitsz(&s->gb, linbits);
955                     v  = l3_unscale(x, exponent);
956                     if (get_bits1(&s->gb))
957                         v = -v;
958                     g->sb_hybrid[s_index] = v;
959                 }
960                 if (y < 15) {
961                     READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
962                 } else {
963                     y += get_bitsz(&s->gb, linbits);
964                     v  = l3_unscale(y, exponent);
965                     if (get_bits1(&s->gb))
966                         v = -v;
967                     g->sb_hybrid[s_index+1] = v;
968                 }
969             } else {
970                 x = y >> 5;
971                 y = y & 0x0f;
972                 x += y;
973                 if (x < 15) {
974                     READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
975                 } else {
976                     x += get_bitsz(&s->gb, linbits);
977                     v  = l3_unscale(x, exponent);
978                     if (get_bits1(&s->gb))
979                         v = -v;
980                     g->sb_hybrid[s_index+!!y] = v;
981                 }
982                 g->sb_hybrid[s_index + !y] = 0;
983             }
984             s_index += 2;
985         }
986     }
987
988     /* high frequencies */
989     vlc = &huff_quad_vlc[g->count1table_select];
990     last_pos = 0;
991     while (s_index <= 572) {
992         int pos, code;
993         pos = get_bits_count(&s->gb);
994         if (pos >= end_pos) {
995             if (pos > end_pos2 && last_pos) {
996                 /* some encoders generate an incorrect size for this
997                    part. We must go back into the data */
998                 s_index -= 4;
999                 skip_bits_long(&s->gb, last_pos - pos);
1000                 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1001                 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
1002                     s_index=0;
1003                 break;
1004             }
1005 //                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1006             switch_buffer(s, &pos, &end_pos, &end_pos2);
1007 //                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1008             if (pos >= end_pos)
1009                 break;
1010         }
1011         last_pos = pos;
1012
1013         code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1014         av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1015         g->sb_hybrid[s_index+0] =
1016         g->sb_hybrid[s_index+1] =
1017         g->sb_hybrid[s_index+2] =
1018         g->sb_hybrid[s_index+3] = 0;
1019         while (code) {
1020             static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
1021             int v;
1022             int pos = s_index + idxtab[code];
1023             code   ^= 8 >> idxtab[code];
1024             READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
1025         }
1026         s_index += 4;
1027     }
1028     /* skip extension bits */
1029     bits_left = end_pos2 - get_bits_count(&s->gb);
1030 //av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1031     if (bits_left < 0 && (s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))) {
1032         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1033         s_index=0;
1034     } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE))) {
1035         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1036         s_index = 0;
1037     }
1038     memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1039     skip_bits_long(&s->gb, bits_left);
1040
1041     i = get_bits_count(&s->gb);
1042     switch_buffer(s, &i, &end_pos, &end_pos2);
1043
1044     return 0;
1045 }
1046
1047 /* Reorder short blocks from bitstream order to interleaved order. It
1048    would be faster to do it in parsing, but the code would be far more
1049    complicated */
1050 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1051 {
1052     int i, j, len;
1053     INTFLOAT *ptr, *dst, *ptr1;
1054     INTFLOAT tmp[576];
1055
1056     if (g->block_type != 2)
1057         return;
1058
1059     if (g->switch_point) {
1060         if (s->sample_rate_index != 8)
1061             ptr = g->sb_hybrid + 36;
1062         else
1063             ptr = g->sb_hybrid + 48;
1064     } else {
1065         ptr = g->sb_hybrid;
1066     }
1067
1068     for (i = g->short_start; i < 13; i++) {
1069         len  = band_size_short[s->sample_rate_index][i];
1070         ptr1 = ptr;
1071         dst  = tmp;
1072         for (j = len; j > 0; j--) {
1073             *dst++ = ptr[0*len];
1074             *dst++ = ptr[1*len];
1075             *dst++ = ptr[2*len];
1076             ptr++;
1077         }
1078         ptr += 2 * len;
1079         memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1080     }
1081 }
1082
1083 #define ISQRT2 FIXR(0.70710678118654752440)
1084
1085 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1086 {
1087     int i, j, k, l;
1088     int sf_max, sf, len, non_zero_found;
1089     INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1090     int non_zero_found_short[3];
1091
1092     /* intensity stereo */
1093     if (s->mode_ext & MODE_EXT_I_STEREO) {
1094         if (!s->lsf) {
1095             is_tab = is_table;
1096             sf_max = 7;
1097         } else {
1098             is_tab = is_table_lsf[g1->scalefac_compress & 1];
1099             sf_max = 16;
1100         }
1101
1102         tab0 = g0->sb_hybrid + 576;
1103         tab1 = g1->sb_hybrid + 576;
1104
1105         non_zero_found_short[0] = 0;
1106         non_zero_found_short[1] = 0;
1107         non_zero_found_short[2] = 0;
1108         k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1109         for (i = 12; i >= g1->short_start; i--) {
1110             /* for last band, use previous scale factor */
1111             if (i != 11)
1112                 k -= 3;
1113             len = band_size_short[s->sample_rate_index][i];
1114             for (l = 2; l >= 0; l--) {
1115                 tab0 -= len;
1116                 tab1 -= len;
1117                 if (!non_zero_found_short[l]) {
1118                     /* test if non zero band. if so, stop doing i-stereo */
1119                     for (j = 0; j < len; j++) {
1120                         if (tab1[j] != 0) {
1121                             non_zero_found_short[l] = 1;
1122                             goto found1;
1123                         }
1124                     }
1125                     sf = g1->scale_factors[k + l];
1126                     if (sf >= sf_max)
1127                         goto found1;
1128
1129                     v1 = is_tab[0][sf];
1130                     v2 = is_tab[1][sf];
1131                     for (j = 0; j < len; j++) {
1132                         tmp0    = tab0[j];
1133                         tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1134                         tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1135                     }
1136                 } else {
1137 found1:
1138                     if (s->mode_ext & MODE_EXT_MS_STEREO) {
1139                         /* lower part of the spectrum : do ms stereo
1140                            if enabled */
1141                         for (j = 0; j < len; j++) {
1142                             tmp0    = tab0[j];
1143                             tmp1    = tab1[j];
1144                             tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1145                             tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1146                         }
1147                     }
1148                 }
1149             }
1150         }
1151
1152         non_zero_found = non_zero_found_short[0] |
1153                          non_zero_found_short[1] |
1154                          non_zero_found_short[2];
1155
1156         for (i = g1->long_end - 1;i >= 0;i--) {
1157             len   = band_size_long[s->sample_rate_index][i];
1158             tab0 -= len;
1159             tab1 -= len;
1160             /* test if non zero band. if so, stop doing i-stereo */
1161             if (!non_zero_found) {
1162                 for (j = 0; j < len; j++) {
1163                     if (tab1[j] != 0) {
1164                         non_zero_found = 1;
1165                         goto found2;
1166                     }
1167                 }
1168                 /* for last band, use previous scale factor */
1169                 k  = (i == 21) ? 20 : i;
1170                 sf = g1->scale_factors[k];
1171                 if (sf >= sf_max)
1172                     goto found2;
1173                 v1 = is_tab[0][sf];
1174                 v2 = is_tab[1][sf];
1175                 for (j = 0; j < len; j++) {
1176                     tmp0    = tab0[j];
1177                     tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1178                     tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1179                 }
1180             } else {
1181 found2:
1182                 if (s->mode_ext & MODE_EXT_MS_STEREO) {
1183                     /* lower part of the spectrum : do ms stereo
1184                        if enabled */
1185                     for (j = 0; j < len; j++) {
1186                         tmp0    = tab0[j];
1187                         tmp1    = tab1[j];
1188                         tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1189                         tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1190                     }
1191                 }
1192             }
1193         }
1194     } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1195         /* ms stereo ONLY */
1196         /* NOTE: the 1/sqrt(2) normalization factor is included in the
1197            global gain */
1198         tab0 = g0->sb_hybrid;
1199         tab1 = g1->sb_hybrid;
1200         for (i = 0; i < 576; i++) {
1201             tmp0    = tab0[i];
1202             tmp1    = tab1[i];
1203             tab0[i] = tmp0 + tmp1;
1204             tab1[i] = tmp0 - tmp1;
1205         }
1206     }
1207 }
1208
1209 #if CONFIG_FLOAT
1210 #define AA(j) do {                                                      \
1211         float tmp0 = ptr[-1-j];                                         \
1212         float tmp1 = ptr[   j];                                         \
1213         ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1];    \
1214         ptr[   j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0];    \
1215     } while (0)
1216 #else
1217 #define AA(j) do {                                              \
1218         int tmp0 = ptr[-1-j];                                   \
1219         int tmp1 = ptr[   j];                                   \
1220         int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]);          \
1221         ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2]));   \
1222         ptr[   j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3]));   \
1223     } while (0)
1224 #endif
1225
1226 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1227 {
1228     INTFLOAT *ptr;
1229     int n, i;
1230
1231     /* we antialias only "long" bands */
1232     if (g->block_type == 2) {
1233         if (!g->switch_point)
1234             return;
1235         /* XXX: check this for 8000Hz case */
1236         n = 1;
1237     } else {
1238         n = SBLIMIT - 1;
1239     }
1240
1241     ptr = g->sb_hybrid + 18;
1242     for (i = n; i > 0; i--) {
1243         AA(0);
1244         AA(1);
1245         AA(2);
1246         AA(3);
1247         AA(4);
1248         AA(5);
1249         AA(6);
1250         AA(7);
1251
1252         ptr += 18;
1253     }
1254 }
1255
1256 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1257                           INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1258 {
1259     INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1260     INTFLOAT out2[12];
1261     int i, j, mdct_long_end, sblimit;
1262
1263     /* find last non zero block */
1264     ptr  = g->sb_hybrid + 576;
1265     ptr1 = g->sb_hybrid + 2 * 18;
1266     while (ptr >= ptr1) {
1267         int32_t *p;
1268         ptr -= 6;
1269         p    = (int32_t*)ptr;
1270         if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1271             break;
1272     }
1273     sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1274
1275     if (g->block_type == 2) {
1276         /* XXX: check for 8000 Hz */
1277         if (g->switch_point)
1278             mdct_long_end = 2;
1279         else
1280             mdct_long_end = 0;
1281     } else {
1282         mdct_long_end = sblimit;
1283     }
1284
1285     buf = mdct_buf;
1286     ptr = g->sb_hybrid;
1287     for (j = 0; j < mdct_long_end; j++) {
1288         int win_idx = (g->switch_point && j < 2) ? 0 : g->block_type;
1289         /* apply window & overlap with previous buffer */
1290         out_ptr = sb_samples + j;
1291         /* select window */
1292         win = mdct_win[win_idx + (4 & -(j & 1))];
1293         s->mpadsp.RENAME(imdct36)(out_ptr, buf, ptr, win);
1294         out_ptr += 18 * SBLIMIT;
1295         ptr     += 18;
1296         buf     += 18;
1297     }
1298     for (j = mdct_long_end; j < sblimit; j++) {
1299         /* select frequency inversion */
1300         win     = mdct_win[2 + (4  & -(j & 1))];
1301         out_ptr = sb_samples + j;
1302
1303         for (i = 0; i < 6; i++) {
1304             *out_ptr = buf[i];
1305             out_ptr += SBLIMIT;
1306         }
1307         imdct12(out2, ptr + 0);
1308         for (i = 0; i < 6; i++) {
1309             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*1];
1310             buf[i + 6*2] = MULH3(out2[i + 6], win[i + 6], 1);
1311             out_ptr += SBLIMIT;
1312         }
1313         imdct12(out2, ptr + 1);
1314         for (i = 0; i < 6; i++) {
1315             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*2];
1316             buf[i + 6*0] = MULH3(out2[i + 6], win[i + 6], 1);
1317             out_ptr += SBLIMIT;
1318         }
1319         imdct12(out2, ptr + 2);
1320         for (i = 0; i < 6; i++) {
1321             buf[i + 6*0] = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*0];
1322             buf[i + 6*1] = MULH3(out2[i + 6], win[i + 6], 1);
1323             buf[i + 6*2] = 0;
1324         }
1325         ptr += 18;
1326         buf += 18;
1327     }
1328     /* zero bands */
1329     for (j = sblimit; j < SBLIMIT; j++) {
1330         /* overlap */
1331         out_ptr = sb_samples + j;
1332         for (i = 0; i < 18; i++) {
1333             *out_ptr = buf[i];
1334             buf[i]   = 0;
1335             out_ptr += SBLIMIT;
1336         }
1337         buf += 18;
1338     }
1339 }
1340
1341 /* main layer3 decoding function */
1342 static int mp_decode_layer3(MPADecodeContext *s)
1343 {
1344     int nb_granules, main_data_begin;
1345     int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1346     GranuleDef *g;
1347     int16_t exponents[576]; //FIXME try INTFLOAT
1348
1349     /* read side info */
1350     if (s->lsf) {
1351         main_data_begin = get_bits(&s->gb, 8);
1352         skip_bits(&s->gb, s->nb_channels);
1353         nb_granules = 1;
1354     } else {
1355         main_data_begin = get_bits(&s->gb, 9);
1356         if (s->nb_channels == 2)
1357             skip_bits(&s->gb, 3);
1358         else
1359             skip_bits(&s->gb, 5);
1360         nb_granules = 2;
1361         for (ch = 0; ch < s->nb_channels; ch++) {
1362             s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1363             s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1364         }
1365     }
1366
1367     for (gr = 0; gr < nb_granules; gr++) {
1368         for (ch = 0; ch < s->nb_channels; ch++) {
1369             av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1370             g = &s->granules[ch][gr];
1371             g->part2_3_length = get_bits(&s->gb, 12);
1372             g->big_values     = get_bits(&s->gb,  9);
1373             if (g->big_values > 288) {
1374                 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1375                 return AVERROR_INVALIDDATA;
1376             }
1377
1378             g->global_gain = get_bits(&s->gb, 8);
1379             /* if MS stereo only is selected, we precompute the
1380                1/sqrt(2) renormalization factor */
1381             if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1382                 MODE_EXT_MS_STEREO)
1383                 g->global_gain -= 2;
1384             if (s->lsf)
1385                 g->scalefac_compress = get_bits(&s->gb, 9);
1386             else
1387                 g->scalefac_compress = get_bits(&s->gb, 4);
1388             blocksplit_flag = get_bits1(&s->gb);
1389             if (blocksplit_flag) {
1390                 g->block_type = get_bits(&s->gb, 2);
1391                 if (g->block_type == 0) {
1392                     av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1393                     return AVERROR_INVALIDDATA;
1394                 }
1395                 g->switch_point = get_bits1(&s->gb);
1396                 for (i = 0; i < 2; i++)
1397                     g->table_select[i] = get_bits(&s->gb, 5);
1398                 for (i = 0; i < 3; i++)
1399                     g->subblock_gain[i] = get_bits(&s->gb, 3);
1400                 ff_init_short_region(s, g);
1401             } else {
1402                 int region_address1, region_address2;
1403                 g->block_type = 0;
1404                 g->switch_point = 0;
1405                 for (i = 0; i < 3; i++)
1406                     g->table_select[i] = get_bits(&s->gb, 5);
1407                 /* compute huffman coded region sizes */
1408                 region_address1 = get_bits(&s->gb, 4);
1409                 region_address2 = get_bits(&s->gb, 3);
1410                 av_dlog(s->avctx, "region1=%d region2=%d\n",
1411                         region_address1, region_address2);
1412                 ff_init_long_region(s, g, region_address1, region_address2);
1413             }
1414             ff_region_offset2size(g);
1415             ff_compute_band_indexes(s, g);
1416
1417             g->preflag = 0;
1418             if (!s->lsf)
1419                 g->preflag = get_bits1(&s->gb);
1420             g->scalefac_scale     = get_bits1(&s->gb);
1421             g->count1table_select = get_bits1(&s->gb);
1422             av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1423                     g->block_type, g->switch_point);
1424         }
1425     }
1426
1427     if (!s->adu_mode) {
1428         const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1429         assert((get_bits_count(&s->gb) & 7) == 0);
1430         /* now we get bits from the main_data_begin offset */
1431         av_dlog(s->avctx, "seekback: %d\n", main_data_begin);
1432     //av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
1433
1434         memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
1435         s->in_gb = s->gb;
1436         init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1437         skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
1438     }
1439
1440     for (gr = 0; gr < nb_granules; gr++) {
1441         for (ch = 0; ch < s->nb_channels; ch++) {
1442             g = &s->granules[ch][gr];
1443             if (get_bits_count(&s->gb) < 0) {
1444                 av_log(s->avctx, AV_LOG_DEBUG, "mdb:%d, lastbuf:%d skipping granule %d\n",
1445                        main_data_begin, s->last_buf_size, gr);
1446                 skip_bits_long(&s->gb, g->part2_3_length);
1447                 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1448                 if (get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer) {
1449                     skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
1450                     s->gb           = s->in_gb;
1451                     s->in_gb.buffer = NULL;
1452                 }
1453                 continue;
1454             }
1455
1456             bits_pos = get_bits_count(&s->gb);
1457
1458             if (!s->lsf) {
1459                 uint8_t *sc;
1460                 int slen, slen1, slen2;
1461
1462                 /* MPEG1 scale factors */
1463                 slen1 = slen_table[0][g->scalefac_compress];
1464                 slen2 = slen_table[1][g->scalefac_compress];
1465                 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1466                 if (g->block_type == 2) {
1467                     n = g->switch_point ? 17 : 18;
1468                     j = 0;
1469                     if (slen1) {
1470                         for (i = 0; i < n; i++)
1471                             g->scale_factors[j++] = get_bits(&s->gb, slen1);
1472                     } else {
1473                         for (i = 0; i < n; i++)
1474                             g->scale_factors[j++] = 0;
1475                     }
1476                     if (slen2) {
1477                         for (i = 0; i < 18; i++)
1478                             g->scale_factors[j++] = get_bits(&s->gb, slen2);
1479                         for (i = 0; i < 3; i++)
1480                             g->scale_factors[j++] = 0;
1481                     } else {
1482                         for (i = 0; i < 21; i++)
1483                             g->scale_factors[j++] = 0;
1484                     }
1485                 } else {
1486                     sc = s->granules[ch][0].scale_factors;
1487                     j = 0;
1488                     for (k = 0; k < 4; k++) {
1489                         n = k == 0 ? 6 : 5;
1490                         if ((g->scfsi & (0x8 >> k)) == 0) {
1491                             slen = (k < 2) ? slen1 : slen2;
1492                             if (slen) {
1493                                 for (i = 0; i < n; i++)
1494                                     g->scale_factors[j++] = get_bits(&s->gb, slen);
1495                             } else {
1496                                 for (i = 0; i < n; i++)
1497                                     g->scale_factors[j++] = 0;
1498                             }
1499                         } else {
1500                             /* simply copy from last granule */
1501                             for (i = 0; i < n; i++) {
1502                                 g->scale_factors[j] = sc[j];
1503                                 j++;
1504                             }
1505                         }
1506                     }
1507                     g->scale_factors[j++] = 0;
1508                 }
1509             } else {
1510                 int tindex, tindex2, slen[4], sl, sf;
1511
1512                 /* LSF scale factors */
1513                 if (g->block_type == 2)
1514                     tindex = g->switch_point ? 2 : 1;
1515                 else
1516                     tindex = 0;
1517
1518                 sf = g->scalefac_compress;
1519                 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1520                     /* intensity stereo case */
1521                     sf >>= 1;
1522                     if (sf < 180) {
1523                         lsf_sf_expand(slen, sf, 6, 6, 0);
1524                         tindex2 = 3;
1525                     } else if (sf < 244) {
1526                         lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1527                         tindex2 = 4;
1528                     } else {
1529                         lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1530                         tindex2 = 5;
1531                     }
1532                 } else {
1533                     /* normal case */
1534                     if (sf < 400) {
1535                         lsf_sf_expand(slen, sf, 5, 4, 4);
1536                         tindex2 = 0;
1537                     } else if (sf < 500) {
1538                         lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1539                         tindex2 = 1;
1540                     } else {
1541                         lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1542                         tindex2 = 2;
1543                         g->preflag = 1;
1544                     }
1545                 }
1546
1547                 j = 0;
1548                 for (k = 0; k < 4; k++) {
1549                     n  = lsf_nsf_table[tindex2][tindex][k];
1550                     sl = slen[k];
1551                     if (sl) {
1552                         for (i = 0; i < n; i++)
1553                             g->scale_factors[j++] = get_bits(&s->gb, sl);
1554                     } else {
1555                         for (i = 0; i < n; i++)
1556                             g->scale_factors[j++] = 0;
1557                     }
1558                 }
1559                 /* XXX: should compute exact size */
1560                 for (; j < 40; j++)
1561                     g->scale_factors[j] = 0;
1562             }
1563
1564             exponents_from_scale_factors(s, g, exponents);
1565
1566             /* read Huffman coded residue */
1567             huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1568         } /* ch */
1569
1570         if (s->nb_channels == 2)
1571             compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1572
1573         for (ch = 0; ch < s->nb_channels; ch++) {
1574             g = &s->granules[ch][gr];
1575
1576             reorder_block(s, g);
1577             compute_antialias(s, g);
1578             compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1579         }
1580     } /* gr */
1581     if (get_bits_count(&s->gb) < 0)
1582         skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1583     return nb_granules * 18;
1584 }
1585
1586 static int mp_decode_frame(MPADecodeContext *s, OUT_INT *samples,
1587                            const uint8_t *buf, int buf_size)
1588 {
1589     int i, nb_frames, ch, ret;
1590     OUT_INT *samples_ptr;
1591
1592     init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1593
1594     /* skip error protection field */
1595     if (s->error_protection)
1596         skip_bits(&s->gb, 16);
1597
1598     switch(s->layer) {
1599     case 1:
1600         s->avctx->frame_size = 384;
1601         nb_frames = mp_decode_layer1(s);
1602         break;
1603     case 2:
1604         s->avctx->frame_size = 1152;
1605         nb_frames = mp_decode_layer2(s);
1606         break;
1607     case 3:
1608         s->avctx->frame_size = s->lsf ? 576 : 1152;
1609     default:
1610         nb_frames = mp_decode_layer3(s);
1611
1612         s->last_buf_size=0;
1613         if (s->in_gb.buffer) {
1614             align_get_bits(&s->gb);
1615             i = get_bits_left(&s->gb)>>3;
1616             if (i >= 0 && i <= BACKSTEP_SIZE) {
1617                 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1618                 s->last_buf_size=i;
1619             } else
1620                 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1621             s->gb           = s->in_gb;
1622             s->in_gb.buffer = NULL;
1623         }
1624
1625         align_get_bits(&s->gb);
1626         assert((get_bits_count(&s->gb) & 7) == 0);
1627         i = get_bits_left(&s->gb) >> 3;
1628
1629         if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1630             if (i < 0)
1631                 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1632             i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1633         }
1634         assert(i <= buf_size - HEADER_SIZE && i >= 0);
1635         memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1636         s->last_buf_size += i;
1637     }
1638
1639     /* get output buffer */
1640     if (!samples) {
1641         s->frame.nb_samples = s->avctx->frame_size;
1642         if ((ret = s->avctx->get_buffer(s->avctx, &s->frame)) < 0) {
1643             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1644             return ret;
1645         }
1646         samples = (OUT_INT *)s->frame.data[0];
1647     }
1648
1649     /* apply the synthesis filter */
1650     for (ch = 0; ch < s->nb_channels; ch++) {
1651         samples_ptr = samples + ch;
1652         for (i = 0; i < nb_frames; i++) {
1653             RENAME(ff_mpa_synth_filter)(
1654                          &s->mpadsp,
1655                          s->synth_buf[ch], &(s->synth_buf_offset[ch]),
1656                          RENAME(ff_mpa_synth_window), &s->dither_state,
1657                          samples_ptr, s->nb_channels,
1658                          s->sb_samples[ch][i]);
1659             samples_ptr += 32 * s->nb_channels;
1660         }
1661     }
1662
1663     return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1664 }
1665
1666 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1667                         AVPacket *avpkt)
1668 {
1669     const uint8_t *buf  = avpkt->data;
1670     int buf_size        = avpkt->size;
1671     MPADecodeContext *s = avctx->priv_data;
1672     uint32_t header;
1673     int out_size;
1674
1675     if (buf_size < HEADER_SIZE)
1676         return AVERROR_INVALIDDATA;
1677
1678     header = AV_RB32(buf);
1679     if (ff_mpa_check_header(header) < 0) {
1680         av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1681         return AVERROR_INVALIDDATA;
1682     }
1683
1684     if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1685         /* free format: prepare to compute frame size */
1686         s->frame_size = -1;
1687         return AVERROR_INVALIDDATA;
1688     }
1689     /* update codec info */
1690     avctx->channels       = s->nb_channels;
1691     avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1692     if (!avctx->bit_rate)
1693         avctx->bit_rate = s->bit_rate;
1694     avctx->sub_id = s->layer;
1695
1696     if (s->frame_size <= 0 || s->frame_size > buf_size) {
1697         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1698         return AVERROR_INVALIDDATA;
1699     }else if(s->frame_size < buf_size){
1700         av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1701         buf_size= s->frame_size;
1702     }
1703
1704     out_size = mp_decode_frame(s, NULL, buf, buf_size);
1705     if (out_size >= 0) {
1706         *got_frame_ptr   = 1;
1707         *(AVFrame *)data = s->frame;
1708         avctx->sample_rate = s->sample_rate;
1709         //FIXME maybe move the other codec info stuff from above here too
1710     } else {
1711         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1712         /* Only return an error if the bad frame makes up the whole packet.
1713            If there is more data in the packet, just consume the bad frame
1714            instead of returning an error, which would discard the whole
1715            packet. */
1716         *got_frame_ptr = 0;
1717         if (buf_size == avpkt->size)
1718             return out_size;
1719     }
1720     s->frame_size = 0;
1721     return buf_size;
1722 }
1723
1724 static void flush(AVCodecContext *avctx)
1725 {
1726     MPADecodeContext *s = avctx->priv_data;
1727     memset(s->synth_buf, 0, sizeof(s->synth_buf));
1728     s->last_buf_size = 0;
1729 }
1730
1731 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1732 static int decode_frame_adu(AVCodecContext *avctx, void *data,
1733                             int *got_frame_ptr, AVPacket *avpkt)
1734 {
1735     const uint8_t *buf  = avpkt->data;
1736     int buf_size        = avpkt->size;
1737     MPADecodeContext *s = avctx->priv_data;
1738     uint32_t header;
1739     int len, out_size;
1740
1741     len = buf_size;
1742
1743     // Discard too short frames
1744     if (buf_size < HEADER_SIZE) {
1745         av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1746         return AVERROR_INVALIDDATA;
1747     }
1748
1749
1750     if (len > MPA_MAX_CODED_FRAME_SIZE)
1751         len = MPA_MAX_CODED_FRAME_SIZE;
1752
1753     // Get header and restore sync word
1754     header = AV_RB32(buf) | 0xffe00000;
1755
1756     if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
1757         av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1758         return AVERROR_INVALIDDATA;
1759     }
1760
1761     avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1762     /* update codec info */
1763     avctx->sample_rate = s->sample_rate;
1764     avctx->channels    = s->nb_channels;
1765     if (!avctx->bit_rate)
1766         avctx->bit_rate = s->bit_rate;
1767     avctx->sub_id = s->layer;
1768
1769     s->frame_size = len;
1770
1771 #if FF_API_PARSE_FRAME
1772     if (avctx->parse_only)
1773         out_size = buf_size;
1774     else
1775 #endif
1776     out_size = mp_decode_frame(s, NULL, buf, buf_size);
1777
1778     *got_frame_ptr   = 1;
1779     *(AVFrame *)data = s->frame;
1780
1781     return buf_size;
1782 }
1783 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1784
1785 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1786
1787 /**
1788  * Context for MP3On4 decoder
1789  */
1790 typedef struct MP3On4DecodeContext {
1791     AVFrame *frame;
1792     int frames;                     ///< number of mp3 frames per block (number of mp3 decoder instances)
1793     int syncword;                   ///< syncword patch
1794     const uint8_t *coff;            ///< channel offsets in output buffer
1795     MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1796     OUT_INT *decoded_buf;           ///< output buffer for decoded samples
1797 } MP3On4DecodeContext;
1798
1799 #include "mpeg4audio.h"
1800
1801 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1802
1803 /* number of mp3 decoder instances */
1804 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1805
1806 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1807 static const uint8_t chan_offset[8][5] = {
1808     { 0             },
1809     { 0             },  // C
1810     { 0             },  // FLR
1811     { 2, 0          },  // C FLR
1812     { 2, 0, 3       },  // C FLR BS
1813     { 2, 0, 3       },  // C FLR BLRS
1814     { 2, 0, 4, 3    },  // C FLR BLRS LFE
1815     { 2, 0, 6, 4, 3 },  // C FLR BLRS BLR LFE
1816 };
1817
1818 /* mp3on4 channel layouts */
1819 static const int16_t chan_layout[8] = {
1820     0,
1821     AV_CH_LAYOUT_MONO,
1822     AV_CH_LAYOUT_STEREO,
1823     AV_CH_LAYOUT_SURROUND,
1824     AV_CH_LAYOUT_4POINT0,
1825     AV_CH_LAYOUT_5POINT0,
1826     AV_CH_LAYOUT_5POINT1,
1827     AV_CH_LAYOUT_7POINT1
1828 };
1829
1830 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1831 {
1832     MP3On4DecodeContext *s = avctx->priv_data;
1833     int i;
1834
1835     for (i = 0; i < s->frames; i++)
1836         av_free(s->mp3decctx[i]);
1837
1838     av_freep(&s->decoded_buf);
1839
1840     return 0;
1841 }
1842
1843
1844 static int decode_init_mp3on4(AVCodecContext * avctx)
1845 {
1846     MP3On4DecodeContext *s = avctx->priv_data;
1847     MPEG4AudioConfig cfg;
1848     int i;
1849
1850     if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
1851         av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1852         return AVERROR_INVALIDDATA;
1853     }
1854
1855     avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
1856                                  avctx->extradata_size * 8, 1);
1857     if (!cfg.chan_config || cfg.chan_config > 7) {
1858         av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1859         return AVERROR_INVALIDDATA;
1860     }
1861     s->frames             = mp3Frames[cfg.chan_config];
1862     s->coff               = chan_offset[cfg.chan_config];
1863     avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];
1864     avctx->channel_layout = chan_layout[cfg.chan_config];
1865
1866     if (cfg.sample_rate < 16000)
1867         s->syncword = 0xffe00000;
1868     else
1869         s->syncword = 0xfff00000;
1870
1871     /* Init the first mp3 decoder in standard way, so that all tables get builded
1872      * We replace avctx->priv_data with the context of the first decoder so that
1873      * decode_init() does not have to be changed.
1874      * Other decoders will be initialized here copying data from the first context
1875      */
1876     // Allocate zeroed memory for the first decoder context
1877     s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1878     if (!s->mp3decctx[0])
1879         goto alloc_fail;
1880     // Put decoder context in place to make init_decode() happy
1881     avctx->priv_data = s->mp3decctx[0];
1882     decode_init(avctx);
1883     s->frame = avctx->coded_frame;
1884     // Restore mp3on4 context pointer
1885     avctx->priv_data = s;
1886     s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1887
1888     /* Create a separate codec/context for each frame (first is already ok).
1889      * Each frame is 1 or 2 channels - up to 5 frames allowed
1890      */
1891     for (i = 1; i < s->frames; i++) {
1892         s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1893         if (!s->mp3decctx[i])
1894             goto alloc_fail;
1895         s->mp3decctx[i]->adu_mode = 1;
1896         s->mp3decctx[i]->avctx = avctx;
1897         s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1898     }
1899
1900     /* Allocate buffer for multi-channel output if needed */
1901     if (s->frames > 1) {
1902         s->decoded_buf = av_malloc(MPA_FRAME_SIZE * MPA_MAX_CHANNELS *
1903                                    sizeof(*s->decoded_buf));
1904         if (!s->decoded_buf)
1905             goto alloc_fail;
1906     }
1907
1908     return 0;
1909 alloc_fail:
1910     decode_close_mp3on4(avctx);
1911     return AVERROR(ENOMEM);
1912 }
1913
1914
1915 static void flush_mp3on4(AVCodecContext *avctx)
1916 {
1917     int i;
1918     MP3On4DecodeContext *s = avctx->priv_data;
1919
1920     for (i = 0; i < s->frames; i++) {
1921         MPADecodeContext *m = s->mp3decctx[i];
1922         memset(m->synth_buf, 0, sizeof(m->synth_buf));
1923         m->last_buf_size = 0;
1924     }
1925 }
1926
1927
1928 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1929                                int *got_frame_ptr, AVPacket *avpkt)
1930 {
1931     const uint8_t *buf     = avpkt->data;
1932     int buf_size           = avpkt->size;
1933     MP3On4DecodeContext *s = avctx->priv_data;
1934     MPADecodeContext *m;
1935     int fsize, len = buf_size, out_size = 0;
1936     uint32_t header;
1937     OUT_INT *out_samples;
1938     OUT_INT *outptr, *bp;
1939     int fr, j, n, ch, ret;
1940
1941     /* get output buffer */
1942     s->frame->nb_samples = MPA_FRAME_SIZE;
1943     if ((ret = avctx->get_buffer(avctx, s->frame)) < 0) {
1944         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1945         return ret;
1946     }
1947     out_samples = (OUT_INT *)s->frame->data[0];
1948
1949     // Discard too short frames
1950     if (buf_size < HEADER_SIZE)
1951         return AVERROR_INVALIDDATA;
1952
1953     // If only one decoder interleave is not needed
1954     outptr = s->frames == 1 ? out_samples : s->decoded_buf;
1955
1956     avctx->bit_rate = 0;
1957
1958     ch = 0;
1959     for (fr = 0; fr < s->frames; fr++) {
1960         fsize = AV_RB16(buf) >> 4;
1961         fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1962         m     = s->mp3decctx[fr];
1963         assert(m != NULL);
1964
1965         header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1966
1967         if (ff_mpa_check_header(header) < 0) // Bad header, discard block
1968             break;
1969
1970         avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1971
1972         if (ch + m->nb_channels > avctx->channels) {
1973             av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1974                                         "channel count\n");
1975             return AVERROR_INVALIDDATA;
1976         }
1977         ch += m->nb_channels;
1978
1979         out_size += mp_decode_frame(m, outptr, buf, fsize);
1980         buf      += fsize;
1981         len      -= fsize;
1982
1983         if (s->frames > 1) {
1984             n = m->avctx->frame_size*m->nb_channels;
1985             /* interleave output data */
1986             bp = out_samples + s->coff[fr];
1987             if (m->nb_channels == 1) {
1988                 for (j = 0; j < n; j++) {
1989                     *bp = s->decoded_buf[j];
1990                     bp += avctx->channels;
1991                 }
1992             } else {
1993                 for (j = 0; j < n; j++) {
1994                     bp[0] = s->decoded_buf[j++];
1995                     bp[1] = s->decoded_buf[j];
1996                     bp   += avctx->channels;
1997                 }
1998             }
1999         }
2000         avctx->bit_rate += m->bit_rate;
2001     }
2002
2003     /* update codec info */
2004     avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2005
2006     s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
2007     *got_frame_ptr   = 1;
2008     *(AVFrame *)data = *s->frame;
2009
2010     return buf_size;
2011 }
2012 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
2013
2014 #if !CONFIG_FLOAT
2015 #if CONFIG_MP1_DECODER
2016 AVCodec ff_mp1_decoder = {
2017     .name           = "mp1",
2018     .type           = AVMEDIA_TYPE_AUDIO,
2019     .id             = CODEC_ID_MP1,
2020     .priv_data_size = sizeof(MPADecodeContext),
2021     .init           = decode_init,
2022     .decode         = decode_frame,
2023 #if FF_API_PARSE_FRAME
2024     .capabilities   = CODEC_CAP_PARSE_ONLY | CODEC_CAP_DR1,
2025 #else
2026     .capabilities   = CODEC_CAP_DR1,
2027 #endif
2028     .flush          = flush,
2029     .long_name      = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2030 };
2031 #endif
2032 #if CONFIG_MP2_DECODER
2033 AVCodec ff_mp2_decoder = {
2034     .name           = "mp2",
2035     .type           = AVMEDIA_TYPE_AUDIO,
2036     .id             = CODEC_ID_MP2,
2037     .priv_data_size = sizeof(MPADecodeContext),
2038     .init           = decode_init,
2039     .decode         = decode_frame,
2040 #if FF_API_PARSE_FRAME
2041     .capabilities   = CODEC_CAP_PARSE_ONLY | CODEC_CAP_DR1,
2042 #else
2043     .capabilities   = CODEC_CAP_DR1,
2044 #endif
2045     .flush          = flush,
2046     .long_name      = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2047 };
2048 #endif
2049 #if CONFIG_MP3_DECODER
2050 AVCodec ff_mp3_decoder = {
2051     .name           = "mp3",
2052     .type           = AVMEDIA_TYPE_AUDIO,
2053     .id             = CODEC_ID_MP3,
2054     .priv_data_size = sizeof(MPADecodeContext),
2055     .init           = decode_init,
2056     .decode         = decode_frame,
2057 #if FF_API_PARSE_FRAME
2058     .capabilities   = CODEC_CAP_PARSE_ONLY | CODEC_CAP_DR1,
2059 #else
2060     .capabilities   = CODEC_CAP_DR1,
2061 #endif
2062     .flush          = flush,
2063     .long_name      = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2064 };
2065 #endif
2066 #if CONFIG_MP3ADU_DECODER
2067 AVCodec ff_mp3adu_decoder = {
2068     .name           = "mp3adu",
2069     .type           = AVMEDIA_TYPE_AUDIO,
2070     .id             = CODEC_ID_MP3ADU,
2071     .priv_data_size = sizeof(MPADecodeContext),
2072     .init           = decode_init,
2073     .decode         = decode_frame_adu,
2074 #if FF_API_PARSE_FRAME
2075     .capabilities   = CODEC_CAP_PARSE_ONLY | CODEC_CAP_DR1,
2076 #else
2077     .capabilities   = CODEC_CAP_DR1,
2078 #endif
2079     .flush          = flush,
2080     .long_name      = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2081 };
2082 #endif
2083 #if CONFIG_MP3ON4_DECODER
2084 AVCodec ff_mp3on4_decoder = {
2085     .name           = "mp3on4",
2086     .type           = AVMEDIA_TYPE_AUDIO,
2087     .id             = CODEC_ID_MP3ON4,
2088     .priv_data_size = sizeof(MP3On4DecodeContext),
2089     .init           = decode_init_mp3on4,
2090     .close          = decode_close_mp3on4,
2091     .decode         = decode_frame_mp3on4,
2092     .capabilities   = CODEC_CAP_DR1,
2093     .flush          = flush_mp3on4,
2094     .long_name      = NULL_IF_CONFIG_SMALL("MP3onMP4"),
2095 };
2096 #endif
2097 #endif