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