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