tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

mpegaudiodec_template.c (64046B)


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