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