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