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