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