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