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