libavcodec/mpegaudiodec.c
de6d9b64
 /*
  * MPEG Audio decoder
406792e7
  * Copyright (c) 2001, 2002 Fabrice Bellard
de6d9b64
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
ff4ec49e
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
de6d9b64
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
de6d9b64
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
ff4ec49e
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
de6d9b64
  *
ff4ec49e
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64
  */
983e3246
 
 /**
ba87f080
  * @file
cd816d9b
  * MPEG Audio decoder
115329f1
  */
983e3246
 
a2f91e7b
 #include "libavutil/avassert.h"
a903f8f0
 #include "libavutil/channel_layout.h"
76fac073
 #include "libavutil/libm.h"
de6d9b64
 #include "avcodec.h"
9106a698
 #include "get_bits.h"
594d4d5d
 #include "internal.h"
a88ef93b
 #include "mathops.h"
c4f5c2d6
 #include "mpegaudiodsp.h"
9b4cd586
 #include "dsputil.h"
de6d9b64
 
 /*
239c2f4c
  * TODO:
  *  - test lsf / mpeg25 extensively.
de6d9b64
  */
 
d9b1c197
 #include "mpegaudio.h"
4bd8e17c
 #include "mpegaudiodecheader.h"
a3a5f4d6
 
918d0584
 #define BACKSTEP_SIZE 512
 #define EXTRABYTES 24
b7165426
 #define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
918d0584
 
 /* layer 3 "granule" */
 typedef struct GranuleDef {
     uint8_t scfsi;
     int part2_3_length;
     int big_values;
     int global_gain;
     int scalefac_compress;
     uint8_t block_type;
     uint8_t switch_point;
     int table_select[3];
     int subblock_gain[3];
     uint8_t scalefac_scale;
     uint8_t count1table_select;
     int region_size[3]; /* number of huffman codes in each region */
     int preflag;
     int short_start, long_end; /* long/short band indexes */
     uint8_t scale_factors[40];
e32aaba3
     DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
918d0584
 } GranuleDef;
 
 typedef struct MPADecodeContext {
     MPA_DECODE_HEADER
b7165426
     uint8_t last_buf[LAST_BUF_SIZE];
918d0584
     int last_buf_size;
     /* next header (used in free format parsing) */
     uint32_t free_format_next_header;
     GetBitContext gb;
     GetBitContext in_gb;
6204feb1
     DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
918d0584
     int synth_buf_offset[MPA_MAX_CHANNELS];
6204feb1
     DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
918d0584
     INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
     GranuleDef granules[2][2]; /* Used in Layer 3 */
     int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
     int dither_state;
9abc9873
     int err_recognition;
918d0584
     AVCodecContext* avctx;
     MPADSPContext mpadsp;
9b4cd586
     DSPContext dsp;
0eea2129
     AVFrame frame;
918d0584
 } MPADecodeContext;
 
b91d4661
 #if CONFIG_FLOAT
40914d97
 #   define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
b91d4661
 #   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
0628f3e8
 #   define FIXR(x)        ((float)(x))
 #   define FIXHR(x)       ((float)(x))
b91d4661
 #   define MULH3(x, y, s) ((s)*(y)*(x))
 #   define MULLx(x, y, s) ((y)*(x))
 #   define RENAME(a) a ## _float
3ffed68c
 #   define OUT_FMT   AV_SAMPLE_FMT_FLT
 #   define OUT_FMT_P AV_SAMPLE_FMT_FLTP
b91d4661
 #else
 #   define SHR(a,b)       ((a)>>(b))
cd816d9b
 /* WARNING: only correct for positive numbers */
b91d4661
 #   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
 #   define FIXR(a)        ((int)((a) * FRAC_ONE + 0.5))
 #   define FIXHR(a)       ((int)((a) * (1LL<<32) + 0.5))
 #   define MULH3(x, y, s) MULH((s)*(x), y)
 #   define MULLx(x, y, s) MULL(x,y,s)
4bac1bbc
 #   define RENAME(a)      a ## _fixed
3ffed68c
 #   define OUT_FMT   AV_SAMPLE_FMT_S16
 #   define OUT_FMT_P AV_SAMPLE_FMT_S16P
b91d4661
 #endif
711ae726
 
239c2f4c
 /****************/
 
de6d9b64
 #define HEADER_SIZE 4
 
4991c051
 #include "mpegaudiodata.h"
239c2f4c
 #include "mpegaudiodectab.h"
 
 /* vlc structure for decoding layer 3 huffman tables */
115329f1
 static VLC huff_vlc[16];
bbdf8728
 static VLC_TYPE huff_vlc_tables[
cd816d9b
     0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
   142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
bbdf8728
   ][2];
 static const int huff_vlc_tables_sizes[16] = {
cd816d9b
     0,  128,  128,  128,  130,  128,  154,  166,
   142,  204,  190,  170,  542,  460,  662,  414
bbdf8728
 };
239c2f4c
 static VLC huff_quad_vlc[2];
cd816d9b
 static VLC_TYPE  huff_quad_vlc_tables[128+16][2];
 static const int huff_quad_vlc_tables_sizes[2] = { 128, 16 };
239c2f4c
 /* computed from band_size_long */
0c1a9eda
 static uint16_t band_index_long[9][23];
eadaa00c
 #include "mpegaudio_tablegen.h"
239c2f4c
 /* intensity stereo coef table */
b91d4661
 static INTFLOAT is_table[2][16];
 static INTFLOAT is_table_lsf[2][2][16];
6f1ec38c
 static INTFLOAT csa_table[8][4];
239c2f4c
 
186d0215
 static int16_t division_tab3[1<<6 ];
 static int16_t division_tab5[1<<8 ];
 static int16_t division_tab9[1<<11];
 
 static int16_t * const division_tabs[4] = {
     division_tab3, division_tab5, NULL, division_tab9
 };
 
239c2f4c
 /* lower 2 bits: modulo 3, higher bits: shift */
0c1a9eda
 static uint16_t scale_factor_modshift[64];
239c2f4c
 /* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
0c1a9eda
 static int32_t scale_factor_mult[15][3];
239c2f4c
 /* mult table for layer 2 group quantization */
 
 #define SCALE_GEN(v) \
b91d4661
 { FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
239c2f4c
 
c26ae41d
 static const int32_t scale_factor_mult2[3][3] = {
81552334
     SCALE_GEN(4.0 / 3.0), /* 3 steps */
     SCALE_GEN(4.0 / 5.0), /* 5 steps */
     SCALE_GEN(4.0 / 9.0), /* 9 steps */
239c2f4c
 };
 
9f7458b2
 /**
  * Convert region offsets to region sizes and truncate
  * size to big_values.
  */
cd816d9b
 static void ff_region_offset2size(GranuleDef *g)
 {
     int i, k, j = 0;
     g->region_size[2] = 576 / 2;
     for (i = 0; i < 3; i++) {
9f7458b2
         k = FFMIN(g->region_size[i], g->big_values);
         g->region_size[i] = k - j;
         j = k;
     }
 }
 
cd816d9b
 static void ff_init_short_region(MPADecodeContext *s, GranuleDef *g)
 {
b37d945d
     if (g->block_type == 2) {
         if (s->sample_rate_index != 8)
             g->region_size[0] = (36 / 2);
         else
             g->region_size[0] = (72 / 2);
     } else {
9f7458b2
         if (s->sample_rate_index <= 2)
             g->region_size[0] = (36 / 2);
         else if (s->sample_rate_index != 8)
             g->region_size[0] = (54 / 2);
         else
             g->region_size[0] = (108 / 2);
     }
     g->region_size[1] = (576 / 2);
 }
 
cd816d9b
 static void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2)
 {
9f7458b2
     int l;
cd816d9b
     g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
9f7458b2
     /* should not overflow */
     l = FFMIN(ra1 + ra2 + 2, 22);
cd816d9b
     g->region_size[1] = band_index_long[s->sample_rate_index][      l] >> 1;
9f7458b2
 }
 
cd816d9b
 static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
 {
9f7458b2
     if (g->block_type == 2) {
         if (g->switch_point) {
ac7d0c79
             if(s->sample_rate_index == 8)
                 av_log_ask_for_sample(s->avctx, "switch point in 8khz\n");
9f7458b2
             /* if switched mode, we handle the 36 first samples as
b37d945d
                 long blocks.  For 8000Hz, we handle the 72 first
                 exponents as long blocks */
9f7458b2
             if (s->sample_rate_index <= 2)
                 g->long_end = 8;
             else
b37d945d
                 g->long_end = 6;
9f7458b2
 
94041feb
             g->short_start = 3;
9f7458b2
         } else {
cd816d9b
             g->long_end    = 0;
9f7458b2
             g->short_start = 0;
         }
     } else {
         g->short_start = 13;
cd816d9b
         g->long_end    = 22;
9f7458b2
     }
 }
 
239c2f4c
 /* layer 1 unscaling */
 /* n = number of bits of the mantissa minus 1 */
 static inline int l1_unscale(int n, int mant, int scale_factor)
 {
     int shift, mod;
0c1a9eda
     int64_t val;
239c2f4c
 
cd816d9b
     shift   = scale_factor_modshift[scale_factor];
     mod     = shift & 3;
239c2f4c
     shift >>= 2;
cd816d9b
     val     = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
     shift  += n;
81552334
     /* NOTE: at this point, 1 <= shift >= 21 + 15 */
     return (int)((val + (1LL << (shift - 1))) >> shift);
239c2f4c
 }
 
 static inline int l2_unscale_group(int steps, int mant, int scale_factor)
 {
     int shift, mod, val;
 
cd816d9b
     shift   = scale_factor_modshift[scale_factor];
     mod     = shift & 3;
239c2f4c
     shift >>= 2;
81552334
 
     val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
     /* NOTE: at this point, 0 <= shift <= 21 */
     if (shift > 0)
         val = (val + (1 << (shift - 1))) >> shift;
     return val;
239c2f4c
 }
 
 /* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
 static inline int l3_unscale(int value, int exponent)
 {
     unsigned int m;
     int e;
 
cd816d9b
     e  = table_4_3_exp  [4 * value + (exponent & 3)];
     m  = table_4_3_value[4 * value + (exponent & 3)];
     e -= exponent >> 2;
29d1df66
 #ifdef DEBUG
     if(e < 1)
0efcf16a
         av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
29d1df66
 #endif
239c2f4c
     if (e > 31)
b696d2a6
         return 0;
cd816d9b
     m = (m + (1 << (e - 1))) >> e;
d04728bb
 
239c2f4c
     return m;
 }
 
0df5e869
 static av_cold void decode_init_static(void)
de6d9b64
 {
239c2f4c
     int i, j, k;
f1d1516e
     int offset;
 
     /* scale factors table for layer 1/2 */
     for (i = 0; i < 64; i++) {
         int shift, mod;
         /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
         shift = i / 3;
         mod   = i % 3;
         scale_factor_modshift[i] = mod | (shift << 2);
     }
de6d9b64
 
f1d1516e
     /* scale factor multiply for layer 1 */
     for (i = 0; i < 15; i++) {
         int n, norm;
         n = i + 2;
         norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
         scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
         scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
         scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
c1c836d9
         av_dlog(NULL, "%d: norm=%x s=%x %x %x\n", i, norm,
f1d1516e
                 scale_factor_mult[i][0],
                 scale_factor_mult[i][1],
                 scale_factor_mult[i][2]);
     }
115329f1
 
f1d1516e
     RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
115329f1
 
f1d1516e
     /* huffman decode tables */
     offset = 0;
     for (i = 1; i < 16; i++) {
         const HuffTable *h = &mpa_huff_tables[i];
         int xsize, x, y;
a92be9b8
         uint8_t  tmp_bits [512] = { 0 };
         uint16_t tmp_codes[512] = { 0 };
239c2f4c
 
f1d1516e
         xsize = h->xsize;
115329f1
 
f1d1516e
         j = 0;
         for (x = 0; x < xsize; x++) {
             for (y = 0; y < xsize; y++) {
                 tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
                 tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
239c2f4c
             }
         }
 
f1d1516e
         /* XXX: fail test */
         huff_vlc[i].table = huff_vlc_tables+offset;
         huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
         init_vlc(&huff_vlc[i], 7, 512,
                  tmp_bits, 1, 1, tmp_codes, 2, 2,
                  INIT_VLC_USE_NEW_STATIC);
         offset += huff_vlc_tables_sizes[i];
     }
a2f91e7b
     av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
f1d1516e
 
     offset = 0;
     for (i = 0; i < 2; i++) {
         huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
         huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
         init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
                  mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
                  INIT_VLC_USE_NEW_STATIC);
         offset += huff_quad_vlc_tables_sizes[i];
     }
a2f91e7b
     av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
f1d1516e
 
     for (i = 0; i < 9; i++) {
         k = 0;
         for (j = 0; j < 22; j++) {
             band_index_long[i][j] = k;
             k += band_size_long[i][j];
239c2f4c
         }
f1d1516e
         band_index_long[i][22] = k;
     }
239c2f4c
 
f1d1516e
     /* compute n ^ (4/3) and store it in mantissa/exp format */
 
     mpegaudio_tableinit();
 
     for (i = 0; i < 4; i++) {
         if (ff_mpa_quant_bits[i] < 0) {
             for (j = 0; j < (1 << (-ff_mpa_quant_bits[i]+1)); j++) {
                 int val1, val2, val3, steps;
                 int val = j;
                 steps   = ff_mpa_quant_steps[i];
                 val1    = val % steps;
                 val    /= steps;
                 val2    = val % steps;
                 val3    = val / steps;
                 division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
cd816d9b
             }
         }
f1d1516e
     }
186d0215
 
 
f1d1516e
     for (i = 0; i < 7; i++) {
         float f;
         INTFLOAT v;
         if (i != 6) {
             f = tan((double)i * M_PI / 12.0);
             v = FIXR(f / (1.0 + f));
         } else {
             v = FIXR(1.0);
239c2f4c
         }
f1d1516e
         is_table[0][    i] = v;
         is_table[1][6 - i] = v;
     }
     /* invalid values */
     for (i = 7; i < 16; i++)
         is_table[0][i] = is_table[1][i] = 0.0;
 
     for (i = 0; i < 16; i++) {
         double f;
         int e, k;
 
         for (j = 0; j < 2; j++) {
             e = -(j + 1) * ((i + 1) >> 1);
76fac073
             f = exp2(e / 4.0);
f1d1516e
             k = i & 1;
             is_table_lsf[j][k ^ 1][i] = FIXR(f);
             is_table_lsf[j][k    ][i] = FIXR(1.0);
c1c836d9
             av_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
f1d1516e
                     i, j, (float) is_table_lsf[j][0][i],
                     (float) is_table_lsf[j][1][i]);
239c2f4c
         }
f1d1516e
     }
239c2f4c
 
f1d1516e
     for (i = 0; i < 8; i++) {
         float ci, cs, ca;
         ci = ci_table[i];
         cs = 1.0 / sqrt(1.0 + ci * ci);
         ca = cs * ci;
6f1ec38c
 #if !CONFIG_FLOAT
f1d1516e
         csa_table[i][0] = FIXHR(cs/4);
         csa_table[i][1] = FIXHR(ca/4);
         csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
         csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
6f1ec38c
 #else
f1d1516e
         csa_table[i][0] = cs;
         csa_table[i][1] = ca;
         csa_table[i][2] = ca + cs;
         csa_table[i][3] = ca - cs;
6f1ec38c
 #endif
f1d1516e
     }
1158745a
 }
239c2f4c
 
1158745a
 static av_cold int decode_init(AVCodecContext * avctx)
 {
0df5e869
     static int initialized_tables = 0;
1158745a
     MPADecodeContext *s = avctx->priv_data;
 
0df5e869
     if (!initialized_tables) {
         decode_init_static();
         initialized_tables = 1;
     }
 
1158745a
     s->avctx = avctx;
 
     ff_mpadsp_init(&s->mpadsp);
9b4cd586
     ff_dsputil_init(&s->dsp, avctx);
1158745a
 
3ffed68c
     if (avctx->request_sample_fmt == OUT_FMT &&
         avctx->codec_id != AV_CODEC_ID_MP3ON4)
         avctx->sample_fmt = OUT_FMT;
     else
         avctx->sample_fmt = OUT_FMT_P;
1158745a
     s->err_recognition = avctx->err_recognition;
de6d9b64
 
36ef5369
     if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
1ede228a
         s->adu_mode = 1;
0eea2129
 
     avcodec_get_frame_defaults(&s->frame);
     avctx->coded_frame = &s->frame;
 
de6d9b64
     return 0;
 }
 
125d6246
 #define C3 FIXHR(0.86602540378443864676/2)
e32aaba3
 #define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
 #define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
 #define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
eb644776
 
239c2f4c
 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
    cases. */
b91d4661
 static void imdct12(INTFLOAT *out, INTFLOAT *in)
239c2f4c
 {
b91d4661
     INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
44f1698a
 
cd816d9b
     in0  = in[0*3];
     in1  = in[1*3] + in[0*3];
     in2  = in[2*3] + in[1*3];
     in3  = in[3*3] + in[2*3];
     in4  = in[4*3] + in[3*3];
     in5  = in[5*3] + in[4*3];
125d6246
     in5 += in3;
     in3 += in1;
 
cd816d9b
     in2  = MULH3(in2, C3, 2);
     in3  = MULH3(in3, C3, 4);
 
     t1   = in0 - in4;
e32aaba3
     t2   = MULH3(in1 - in5, C4, 2);
cd816d9b
 
     out[ 7] =
     out[10] = t1 + t2;
     out[ 1] =
     out[ 4] = t1 - t2;
 
     in0    += SHR(in4, 1);
     in4     = in0 + in2;
     in5    += 2*in1;
e32aaba3
     in1     = MULH3(in5 + in3, C5, 1);
cd816d9b
     out[ 8] =
     out[ 9] = in4 + in1;
     out[ 2] =
     out[ 3] = in4 - in1;
 
     in0    -= in2;
e32aaba3
     in5     = MULH3(in5 - in3, C6, 2);
cd816d9b
     out[ 0] =
     out[ 5] = in0 - in5;
     out[ 6] =
     out[11] = in0 + in5;
239c2f4c
 }
 
 /* return the number of decoded frames */
 static int mp_decode_layer1(MPADecodeContext *s)
de6d9b64
 {
239c2f4c
     int bound, i, v, n, ch, j, mant;
0c1a9eda
     uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
     uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
239c2f4c
 
115329f1
     if (s->mode == MPA_JSTEREO)
239c2f4c
         bound = (s->mode_ext + 1) * 4;
     else
         bound = SBLIMIT;
 
     /* allocation bits */
cd816d9b
     for (i = 0; i < bound; i++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
             allocation[ch][i] = get_bits(&s->gb, 4);
         }
     }
cd816d9b
     for (i = bound; i < SBLIMIT; i++)
239c2f4c
         allocation[0][i] = get_bits(&s->gb, 4);
 
     /* scale factors */
cd816d9b
     for (i = 0; i < bound; i++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
             if (allocation[ch][i])
                 scale_factors[ch][i] = get_bits(&s->gb, 6);
         }
     }
cd816d9b
     for (i = bound; i < SBLIMIT; i++) {
239c2f4c
         if (allocation[0][i]) {
             scale_factors[0][i] = get_bits(&s->gb, 6);
             scale_factors[1][i] = get_bits(&s->gb, 6);
         }
     }
115329f1
 
239c2f4c
     /* compute samples */
cd816d9b
     for (j = 0; j < 12; j++) {
         for (i = 0; i < bound; i++) {
             for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
                 n = allocation[ch][i];
                 if (n) {
                     mant = get_bits(&s->gb, n + 1);
                     v = l1_unscale(n, mant, scale_factors[ch][i]);
                 } else {
                     v = 0;
                 }
                 s->sb_samples[ch][j][i] = v;
             }
         }
cd816d9b
         for (i = bound; i < SBLIMIT; i++) {
239c2f4c
             n = allocation[0][i];
             if (n) {
                 mant = get_bits(&s->gb, n + 1);
                 v = l1_unscale(n, mant, scale_factors[0][i]);
                 s->sb_samples[0][j][i] = v;
                 v = l1_unscale(n, mant, scale_factors[1][i]);
                 s->sb_samples[1][j][i] = v;
             } else {
                 s->sb_samples[0][j][i] = 0;
                 s->sb_samples[1][j][i] = 0;
             }
         }
     }
     return 12;
 }
 
 static int mp_decode_layer2(MPADecodeContext *s)
 {
     int sblimit; /* number of used subbands */
     const unsigned char *alloc_table;
     int table, bit_alloc_bits, i, j, ch, bound, v;
     unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
     unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
     unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
     int scale, qindex, bits, steps, k, l, m, b;
de6d9b64
 
239c2f4c
     /* select decoding table */
08aa2c9b
     table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
cd816d9b
                                    s->sample_rate, s->lsf);
     sblimit     = ff_mpa_sblimit_table[table];
677fe2e2
     alloc_table = ff_mpa_alloc_tables[table];
239c2f4c
 
115329f1
     if (s->mode == MPA_JSTEREO)
239c2f4c
         bound = (s->mode_ext + 1) * 4;
     else
         bound = sblimit;
 
9ef5a9de
     av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
2caa92d9
 
     /* sanity check */
cd816d9b
     if (bound > sblimit)
         bound = sblimit;
2caa92d9
 
239c2f4c
     /* parse bit allocation */
     j = 0;
cd816d9b
     for (i = 0; i < bound; i++) {
239c2f4c
         bit_alloc_bits = alloc_table[j];
cd816d9b
         for (ch = 0; ch < s->nb_channels; ch++)
239c2f4c
             bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
         j += 1 << bit_alloc_bits;
     }
cd816d9b
     for (i = bound; i < sblimit; i++) {
239c2f4c
         bit_alloc_bits = alloc_table[j];
         v = get_bits(&s->gb, bit_alloc_bits);
         bit_alloc[0][i] = v;
         bit_alloc[1][i] = v;
         j += 1 << bit_alloc_bits;
de6d9b64
     }
239c2f4c
 
     /* scale codes */
cd816d9b
     for (i = 0; i < sblimit; i++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
115329f1
             if (bit_alloc[ch][i])
239c2f4c
                 scale_code[ch][i] = get_bits(&s->gb, 2);
         }
     }
115329f1
 
239c2f4c
     /* scale factors */
cd816d9b
     for (i = 0; i < sblimit; i++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
             if (bit_alloc[ch][i]) {
                 sf = scale_factors[ch][i];
cd816d9b
                 switch (scale_code[ch][i]) {
239c2f4c
                 default:
                 case 0:
                     sf[0] = get_bits(&s->gb, 6);
                     sf[1] = get_bits(&s->gb, 6);
                     sf[2] = get_bits(&s->gb, 6);
                     break;
                 case 2:
                     sf[0] = get_bits(&s->gb, 6);
                     sf[1] = sf[0];
                     sf[2] = sf[0];
                     break;
                 case 1:
                     sf[0] = get_bits(&s->gb, 6);
                     sf[2] = get_bits(&s->gb, 6);
                     sf[1] = sf[0];
                     break;
                 case 3:
                     sf[0] = get_bits(&s->gb, 6);
                     sf[2] = get_bits(&s->gb, 6);
                     sf[1] = sf[2];
                     break;
                 }
             }
         }
     }
 
     /* samples */
cd816d9b
     for (k = 0; k < 3; k++) {
         for (l = 0; l < 12; l += 3) {
239c2f4c
             j = 0;
cd816d9b
             for (i = 0; i < bound; i++) {
239c2f4c
                 bit_alloc_bits = alloc_table[j];
cd816d9b
                 for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
                     b = bit_alloc[ch][i];
                     if (b) {
                         scale = scale_factors[ch][i][k];
                         qindex = alloc_table[j+b];
677fe2e2
                         bits = ff_mpa_quant_bits[qindex];
239c2f4c
                         if (bits < 0) {
186d0215
                             int v2;
239c2f4c
                             /* 3 values at the same time */
                             v = get_bits(&s->gb, -bits);
186d0215
                             v2 = division_tabs[qindex][v];
                             steps  = ff_mpa_quant_steps[qindex];
 
115329f1
                             s->sb_samples[ch][k * 12 + l + 0][i] =
cd816d9b
                                 l2_unscale_group(steps,  v2       & 15, scale);
115329f1
                             s->sb_samples[ch][k * 12 + l + 1][i] =
186d0215
                                 l2_unscale_group(steps, (v2 >> 4) & 15, scale);
115329f1
                             s->sb_samples[ch][k * 12 + l + 2][i] =
186d0215
                                 l2_unscale_group(steps,  v2 >> 8      , scale);
239c2f4c
                         } else {
cd816d9b
                             for (m = 0; m < 3; m++) {
239c2f4c
                                 v = get_bits(&s->gb, bits);
                                 v = l1_unscale(bits - 1, v, scale);
                                 s->sb_samples[ch][k * 12 + l + m][i] = v;
                             }
                         }
                     } else {
                         s->sb_samples[ch][k * 12 + l + 0][i] = 0;
                         s->sb_samples[ch][k * 12 + l + 1][i] = 0;
                         s->sb_samples[ch][k * 12 + l + 2][i] = 0;
                     }
                 }
                 /* next subband in alloc table */
115329f1
                 j += 1 << bit_alloc_bits;
239c2f4c
             }
             /* XXX: find a way to avoid this duplication of code */
cd816d9b
             for (i = bound; i < sblimit; i++) {
239c2f4c
                 bit_alloc_bits = alloc_table[j];
                 b = bit_alloc[0][i];
                 if (b) {
                     int mant, scale0, scale1;
                     scale0 = scale_factors[0][i][k];
                     scale1 = scale_factors[1][i][k];
                     qindex = alloc_table[j+b];
677fe2e2
                     bits = ff_mpa_quant_bits[qindex];
239c2f4c
                     if (bits < 0) {
                         /* 3 values at the same time */
                         v = get_bits(&s->gb, -bits);
677fe2e2
                         steps = ff_mpa_quant_steps[qindex];
239c2f4c
                         mant = v % steps;
                         v = v / steps;
115329f1
                         s->sb_samples[0][k * 12 + l + 0][i] =
239c2f4c
                             l2_unscale_group(steps, mant, scale0);
115329f1
                         s->sb_samples[1][k * 12 + l + 0][i] =
239c2f4c
                             l2_unscale_group(steps, mant, scale1);
                         mant = v % steps;
                         v = v / steps;
115329f1
                         s->sb_samples[0][k * 12 + l + 1][i] =
239c2f4c
                             l2_unscale_group(steps, mant, scale0);
115329f1
                         s->sb_samples[1][k * 12 + l + 1][i] =
239c2f4c
                             l2_unscale_group(steps, mant, scale1);
115329f1
                         s->sb_samples[0][k * 12 + l + 2][i] =
239c2f4c
                             l2_unscale_group(steps, v, scale0);
115329f1
                         s->sb_samples[1][k * 12 + l + 2][i] =
239c2f4c
                             l2_unscale_group(steps, v, scale1);
                     } else {
cd816d9b
                         for (m = 0; m < 3; m++) {
239c2f4c
                             mant = get_bits(&s->gb, bits);
115329f1
                             s->sb_samples[0][k * 12 + l + m][i] =
239c2f4c
                                 l1_unscale(bits - 1, mant, scale0);
115329f1
                             s->sb_samples[1][k * 12 + l + m][i] =
239c2f4c
                                 l1_unscale(bits - 1, mant, scale1);
                         }
                     }
                 } else {
                     s->sb_samples[0][k * 12 + l + 0][i] = 0;
                     s->sb_samples[0][k * 12 + l + 1][i] = 0;
                     s->sb_samples[0][k * 12 + l + 2][i] = 0;
                     s->sb_samples[1][k * 12 + l + 0][i] = 0;
                     s->sb_samples[1][k * 12 + l + 1][i] = 0;
                     s->sb_samples[1][k * 12 + l + 2][i] = 0;
                 }
                 /* next subband in alloc table */
115329f1
                 j += 1 << bit_alloc_bits;
239c2f4c
             }
             /* fill remaining samples to zero */
cd816d9b
             for (i = sblimit; i < SBLIMIT; i++) {
                 for (ch = 0; ch < s->nb_channels; ch++) {
239c2f4c
                     s->sb_samples[ch][k * 12 + l + 0][i] = 0;
                     s->sb_samples[ch][k * 12 + l + 1][i] = 0;
                     s->sb_samples[ch][k * 12 + l + 2][i] = 0;
                 }
             }
         }
     }
     return 3 * 12;
de6d9b64
 }
 
cd816d9b
 #define SPLIT(dst,sf,n)             \
     if (n == 3) {                   \
         int m = (sf * 171) >> 9;    \
         dst   = sf - 3 * m;         \
         sf    = m;                  \
     } else if (n == 4) {            \
         dst  = sf & 3;              \
         sf >>= 2;                   \
     } else if (n == 5) {            \
         int m = (sf * 205) >> 10;   \
         dst   = sf - 5 * m;         \
         sf    = m;                  \
     } else if (n == 6) {            \
         int m = (sf * 171) >> 10;   \
         dst   = sf - 6 * m;         \
         sf    = m;                  \
     } else {                        \
         dst = 0;                    \
fd9451c6
     }
 
cd816d9b
 static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
                                            int n3)
239c2f4c
 {
fd9451c6
     SPLIT(slen[3], sf, n3)
     SPLIT(slen[2], sf, n2)
     SPLIT(slen[1], sf, n1)
239c2f4c
     slen[0] = sf;
 }
 
cd816d9b
 static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
0c1a9eda
                                          int16_t *exponents)
239c2f4c
 {
0c1a9eda
     const uint8_t *bstab, *pretab;
239c2f4c
     int len, i, j, k, l, v0, shift, gain, gains[3];
0c1a9eda
     int16_t *exp_ptr;
239c2f4c
 
     exp_ptr = exponents;
cd816d9b
     gain    = g->global_gain - 210;
     shift   = g->scalefac_scale + 1;
239c2f4c
 
cd816d9b
     bstab  = band_size_long[s->sample_rate_index];
239c2f4c
     pretab = mpa_pretab[g->preflag];
cd816d9b
     for (i = 0; i < g->long_end; i++) {
bc2d2757
         v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
239c2f4c
         len = bstab[i];
cd816d9b
         for (j = len; j > 0; j--)
239c2f4c
             *exp_ptr++ = v0;
     }
 
     if (g->short_start < 13) {
cd816d9b
         bstab    = band_size_short[s->sample_rate_index];
239c2f4c
         gains[0] = gain - (g->subblock_gain[0] << 3);
         gains[1] = gain - (g->subblock_gain[1] << 3);
         gains[2] = gain - (g->subblock_gain[2] << 3);
cd816d9b
         k        = g->long_end;
         for (i = g->short_start; i < 13; i++) {
239c2f4c
             len = bstab[i];
cd816d9b
             for (l = 0; l < 3; l++) {
bc2d2757
                 v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
cd816d9b
                 for (j = len; j > 0; j--)
                     *exp_ptr++ = v0;
239c2f4c
             }
         }
     }
 }
 
 /* handle n = 0 too */
 static inline int get_bitsz(GetBitContext *s, int n)
 {
cd816d9b
     return n ? get_bits(s, n) : 0;
239c2f4c
 }
 
5773d460
 
cd816d9b
 static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
                           int *end_pos2)
 {
     if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {
         s->gb           = s->in_gb;
         s->in_gb.buffer = NULL;
a2f91e7b
         av_assert2((get_bits_count(&s->gb) & 7) == 0);
5773d460
         skip_bits_long(&s->gb, *pos - *end_pos);
cd816d9b
         *end_pos2 =
         *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;
         *pos      = get_bits_count(&s->gb);
5773d460
     }
 }
 
4b070a7a
 /* Following is a optimized code for
             INTFLOAT v = *src
             if(get_bits1(&s->gb))
                 v = -v;
             *dst = v;
 */
 #if CONFIG_FLOAT
cd816d9b
 #define READ_FLIP_SIGN(dst,src)                     \
     v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31);  \
     AV_WN32A(dst, v);
4b070a7a
 #else
cd816d9b
 #define READ_FLIP_SIGN(dst,src)     \
     v      = -get_bits1(&s->gb);    \
     *(dst) = (*(src) ^ v) - v;
4b070a7a
 #endif
 
239c2f4c
 static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
06e7fb82
                           int16_t *exponents, int end_pos2)
239c2f4c
 {
     int s_index;
14168ddb
     int i;
06e7fb82
     int last_pos, bits_left;
239c2f4c
     VLC *vlc;
cd816d9b
     int end_pos = FFMIN(end_pos2, s->gb.size_in_bits);
239c2f4c
 
     /* low frequencies (called big values) */
     s_index = 0;
cd816d9b
     for (i = 0; i < 3; i++) {
14168ddb
         int j, k, l, linbits;
239c2f4c
         j = g->region_size[i];
         if (j == 0)
             continue;
         /* select vlc table */
cd816d9b
         k       = g->table_select[i];
         l       = mpa_huff_data[k][0];
239c2f4c
         linbits = mpa_huff_data[k][1];
cd816d9b
         vlc     = &huff_vlc[l];
239c2f4c
 
cd816d9b
         if (!l) {
             memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
             s_index += 2 * j;
daf4cd9a
             continue;
         }
 
239c2f4c
         /* read huffcode and compute each couple */
cd816d9b
         for (; j > 0; j--) {
b91d4661
             int exponent, x, y;
3b7117b7
             int v;
cd816d9b
             int pos = get_bits_count(&s->gb);
06e7fb82
 
             if (pos >= end_pos){
5773d460
                 switch_buffer(s, &pos, &end_pos, &end_pos2);
cd816d9b
                 if (pos >= end_pos)
06e7fb82
                     break;
             }
1f1d675b
             y = get_vlc2(&s->gb, vlc->table, 7, 3);
3328ec63
 
cd816d9b
             if (!y) {
3328ec63
                 g->sb_hybrid[s_index  ] =
                 g->sb_hybrid[s_index+1] = 0;
                 s_index += 2;
                 continue;
             }
 
9b49f89c
             exponent= exponents[s_index];
daf4cd9a
 
9ef5a9de
             av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
9b49f89c
                     i, g->region_size[i] - j, x, y, exponent);
cd816d9b
             if (y & 16) {
9bffa9e7
                 x = y >> 5;
                 y = y & 0x0f;
cd816d9b
                 if (x < 15) {
                     READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
                 } else {
55017f35
                     x += get_bitsz(&s->gb, linbits);
cd816d9b
                     v  = l3_unscale(x, exponent);
3b7117b7
                     if (get_bits1(&s->gb))
                         v = -v;
                     g->sb_hybrid[s_index] = v;
55017f35
                 }
cd816d9b
                 if (y < 15) {
                     READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
                 } else {
55017f35
                     y += get_bitsz(&s->gb, linbits);
cd816d9b
                     v  = l3_unscale(y, exponent);
3b7117b7
                     if (get_bits1(&s->gb))
                         v = -v;
                     g->sb_hybrid[s_index+1] = v;
55017f35
                 }
cd816d9b
             } else {
9bffa9e7
                 x = y >> 5;
                 y = y & 0x0f;
                 x += y;
cd816d9b
                 if (x < 15) {
                     READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
                 } else {
9bffa9e7
                     x += get_bitsz(&s->gb, linbits);
cd816d9b
                     v  = l3_unscale(x, exponent);
3b7117b7
                     if (get_bits1(&s->gb))
                         v = -v;
                     g->sb_hybrid[s_index+!!y] = v;
9bffa9e7
                 }
cd816d9b
                 g->sb_hybrid[s_index + !y] = 0;
239c2f4c
             }
cd816d9b
             s_index += 2;
239c2f4c
         }
     }
115329f1
 
239c2f4c
     /* high frequencies */
     vlc = &huff_quad_vlc[g->count1table_select];
cd816d9b
     last_pos = 0;
239c2f4c
     while (s_index <= 572) {
14168ddb
         int pos, code;
239c2f4c
         pos = get_bits_count(&s->gb);
         if (pos >= end_pos) {
cd816d9b
             if (pos > end_pos2 && last_pos) {
1b4f17fa
                 /* some encoders generate an incorrect size for this
                    part. We must go back into the data */
                 s_index -= 4;
                 skip_bits_long(&s->gb, last_pos - pos);
11f63a22
                 av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
85ab33b8
                 if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
8e5606bf
                     s_index=0;
1b4f17fa
                 break;
             }
5773d460
             switch_buffer(s, &pos, &end_pos, &end_pos2);
cd816d9b
             if (pos >= end_pos)
06e7fb82
                 break;
239c2f4c
         }
cd816d9b
         last_pos = pos;
8db1a1dd
 
3c693e77
         code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
9ef5a9de
         av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
cd816d9b
         g->sb_hybrid[s_index+0] =
         g->sb_hybrid[s_index+1] =
         g->sb_hybrid[s_index+2] =
         g->sb_hybrid[s_index+3] = 0;
         while (code) {
             static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
0c0d88ae
             int v;
cd816d9b
             int pos = s_index + idxtab[code];
             code   ^= 8 >> idxtab[code];
             READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
239c2f4c
         }
cd816d9b
         s_index += 4;
239c2f4c
     }
06e7fb82
     /* skip extension bits */
e0cf9204
     bits_left = end_pos2 - get_bits_count(&s->gb);
b5a69e79
     if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
11f63a22
         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
8e5606bf
         s_index=0;
b5a69e79
     } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
11f63a22
         av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
cd816d9b
         s_index = 0;
06e7fb82
     }
cd816d9b
     memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
06e7fb82
     skip_bits_long(&s->gb, bits_left);
 
cd816d9b
     i = get_bits_count(&s->gb);
5773d460
     switch_buffer(s, &i, &end_pos, &end_pos2);
e0cf9204
 
de6d9b64
     return 0;
 }
 
239c2f4c
 /* Reorder short blocks from bitstream order to interleaved order. It
    would be faster to do it in parsing, but the code would be far more
    complicated */
 static void reorder_block(MPADecodeContext *s, GranuleDef *g)
 {
6430ce0f
     int i, j, len;
b91d4661
     INTFLOAT *ptr, *dst, *ptr1;
     INTFLOAT tmp[576];
239c2f4c
 
     if (g->block_type != 2)
         return;
 
     if (g->switch_point) {
cd816d9b
         if (s->sample_rate_index != 8)
239c2f4c
             ptr = g->sb_hybrid + 36;
cd816d9b
         else
b37d945d
             ptr = g->sb_hybrid + 72;
239c2f4c
     } else {
         ptr = g->sb_hybrid;
     }
115329f1
 
cd816d9b
     for (i = g->short_start; i < 13; i++) {
         len  = band_size_short[s->sample_rate_index][i];
239c2f4c
         ptr1 = ptr;
cd816d9b
         dst  = tmp;
         for (j = len; j > 0; j--) {
6430ce0f
             *dst++ = ptr[0*len];
             *dst++ = ptr[1*len];
             *dst++ = ptr[2*len];
             ptr++;
239c2f4c
         }
cd816d9b
         ptr += 2 * len;
6430ce0f
         memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
239c2f4c
     }
 }
 
 #define ISQRT2 FIXR(0.70710678118654752440)
 
cd816d9b
 static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
239c2f4c
 {
     int i, j, k, l;
b91d4661
     int sf_max, sf, len, non_zero_found;
     INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
239c2f4c
     int non_zero_found_short[3];
 
     /* intensity stereo */
     if (s->mode_ext & MODE_EXT_I_STEREO) {
         if (!s->lsf) {
             is_tab = is_table;
             sf_max = 7;
         } else {
             is_tab = is_table_lsf[g1->scalefac_compress & 1];
             sf_max = 16;
         }
115329f1
 
239c2f4c
         tab0 = g0->sb_hybrid + 576;
         tab1 = g1->sb_hybrid + 576;
 
         non_zero_found_short[0] = 0;
         non_zero_found_short[1] = 0;
         non_zero_found_short[2] = 0;
         k = (13 - g1->short_start) * 3 + g1->long_end - 3;
cd816d9b
         for (i = 12; i >= g1->short_start; i--) {
239c2f4c
             /* for last band, use previous scale factor */
             if (i != 11)
                 k -= 3;
             len = band_size_short[s->sample_rate_index][i];
cd816d9b
             for (l = 2; l >= 0; l--) {
239c2f4c
                 tab0 -= len;
                 tab1 -= len;
                 if (!non_zero_found_short[l]) {
                     /* test if non zero band. if so, stop doing i-stereo */
cd816d9b
                     for (j = 0; j < len; j++) {
239c2f4c
                         if (tab1[j] != 0) {
                             non_zero_found_short[l] = 1;
                             goto found1;
                         }
                     }
                     sf = g1->scale_factors[k + l];
                     if (sf >= sf_max)
                         goto found1;
 
                     v1 = is_tab[0][sf];
                     v2 = is_tab[1][sf];
cd816d9b
                     for (j = 0; j < len; j++) {
                         tmp0    = tab0[j];
b91d4661
                         tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
                         tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
239c2f4c
                     }
                 } else {
cd816d9b
 found1:
239c2f4c
                     if (s->mode_ext & MODE_EXT_MS_STEREO) {
                         /* lower part of the spectrum : do ms stereo
                            if enabled */
cd816d9b
                         for (j = 0; j < len; j++) {
                             tmp0    = tab0[j];
                             tmp1    = tab1[j];
b91d4661
                             tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
                             tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
239c2f4c
                         }
                     }
                 }
             }
         }
 
115329f1
         non_zero_found = non_zero_found_short[0] |
cd816d9b
                          non_zero_found_short[1] |
                          non_zero_found_short[2];
239c2f4c
 
cd816d9b
         for (i = g1->long_end - 1;i >= 0;i--) {
             len   = band_size_long[s->sample_rate_index][i];
239c2f4c
             tab0 -= len;
             tab1 -= len;
             /* test if non zero band. if so, stop doing i-stereo */
             if (!non_zero_found) {
cd816d9b
                 for (j = 0; j < len; j++) {
239c2f4c
                     if (tab1[j] != 0) {
                         non_zero_found = 1;
                         goto found2;
                     }
                 }
                 /* for last band, use previous scale factor */
cd816d9b
                 k  = (i == 21) ? 20 : i;
239c2f4c
                 sf = g1->scale_factors[k];
                 if (sf >= sf_max)
                     goto found2;
                 v1 = is_tab[0][sf];
                 v2 = is_tab[1][sf];
cd816d9b
                 for (j = 0; j < len; j++) {
                     tmp0    = tab0[j];
b91d4661
                     tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
                     tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
239c2f4c
                 }
             } else {
cd816d9b
 found2:
239c2f4c
                 if (s->mode_ext & MODE_EXT_MS_STEREO) {
                     /* lower part of the spectrum : do ms stereo
                        if enabled */
cd816d9b
                     for (j = 0; j < len; j++) {
                         tmp0    = tab0[j];
                         tmp1    = tab1[j];
b91d4661
                         tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
                         tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
239c2f4c
                     }
                 }
             }
         }
     } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
         /* ms stereo ONLY */
         /* NOTE: the 1/sqrt(2) normalization factor is included in the
            global gain */
9b4cd586
 #if CONFIG_FLOAT
        s-> dsp.butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
 #else
239c2f4c
         tab0 = g0->sb_hybrid;
         tab1 = g1->sb_hybrid;
cd816d9b
         for (i = 0; i < 576; i++) {
             tmp0    = tab0[i];
             tmp1    = tab1[i];
239c2f4c
             tab0[i] = tmp0 + tmp1;
             tab1[i] = tmp0 - tmp1;
         }
9b4cd586
 #endif
239c2f4c
     }
 }
 
6f1ec38c
 #if CONFIG_FLOAT
6d74e3c6
 #if HAVE_MIPSFPU
 #   include "mips/compute_antialias_float.h"
 #endif /* HAVE_MIPSFPU */
 #else
 #if HAVE_MIPSDSPR1
 #   include "mips/compute_antialias_fixed.h"
 #endif /* HAVE_MIPSDSPR1 */
 #endif /* CONFIG_FLOAT */
 
 #ifndef compute_antialias
 #if CONFIG_FLOAT
6f1ec38c
 #define AA(j) do {                                                      \
         float tmp0 = ptr[-1-j];                                         \
         float tmp1 = ptr[   j];                                         \
         ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1];    \
         ptr[   j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0];    \
     } while (0)
 #else
 #define AA(j) do {                                              \
         int tmp0 = ptr[-1-j];                                   \
         int tmp1 = ptr[   j];                                   \
         int tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]);          \
cd816d9b
         ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2]));   \
         ptr[   j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3]));   \
6f1ec38c
     } while (0)
 #endif
 
 static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
239c2f4c
 {
6f1ec38c
     INTFLOAT *ptr;
ce4a29c0
     int n, i;
239c2f4c
 
     /* we antialias only "long" bands */
     if (g->block_type == 2) {
         if (!g->switch_point)
             return;
         /* XXX: check this for 8000Hz case */
         n = 1;
     } else {
         n = SBLIMIT - 1;
     }
115329f1
 
239c2f4c
     ptr = g->sb_hybrid + 18;
cd816d9b
     for (i = n; i > 0; i--) {
6f1ec38c
         AA(0);
         AA(1);
         AA(2);
         AA(3);
         AA(4);
         AA(5);
         AA(6);
         AA(7);
115329f1
 
         ptr += 18;
a1e257b2
     }
 }
6d74e3c6
 #endif /* compute_antialias */
239c2f4c
 
cd816d9b
 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
                           INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
239c2f4c
 {
e32aaba3
     INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
b91d4661
     INTFLOAT out2[12];
     int i, j, mdct_long_end, sblimit;
239c2f4c
 
     /* find last non zero block */
cd816d9b
     ptr  = g->sb_hybrid + 576;
239c2f4c
     ptr1 = g->sb_hybrid + 2 * 18;
     while (ptr >= ptr1) {
b91d4661
         int32_t *p;
239c2f4c
         ptr -= 6;
cd816d9b
         p    = (int32_t*)ptr;
         if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
239c2f4c
             break;
     }
     sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
 
     if (g->block_type == 2) {
         /* XXX: check for 8000 Hz */
         if (g->switch_point)
             mdct_long_end = 2;
         else
             mdct_long_end = 0;
     } else {
         mdct_long_end = sblimit;
     }
 
6dfcf530
     s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
                                      mdct_long_end, g->switch_point,
                                      g->block_type);
 
     buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
     ptr = g->sb_hybrid + 18 * mdct_long_end;
 
cd816d9b
     for (j = mdct_long_end; j < sblimit; j++) {
239c2f4c
         /* select frequency inversion */
6dfcf530
         win     = RENAME(ff_mdct_win)[2 + (4  & -(j & 1))];
239c2f4c
         out_ptr = sb_samples + j;
115329f1
 
cd816d9b
         for (i = 0; i < 6; i++) {
421c99a4
             *out_ptr = buf[4*i];
125d6246
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 0);
cd816d9b
         for (i = 0; i < 6; i++) {
421c99a4
             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*1)];
             buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
239c2f4c
             out_ptr += SBLIMIT;
         }
125d6246
         imdct12(out2, ptr + 1);
cd816d9b
         for (i = 0; i < 6; i++) {
421c99a4
             *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*2)];
             buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
125d6246
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 2);
cd816d9b
         for (i = 0; i < 6; i++) {
421c99a4
             buf[4*(i + 6*0)] = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*0)];
             buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
             buf[4*(i + 6*2)] = 0;
125d6246
         }
239c2f4c
         ptr += 18;
421c99a4
         buf += (j&3) != 3 ? 1 : (4*18-3);
239c2f4c
     }
     /* zero bands */
cd816d9b
     for (j = sblimit; j < SBLIMIT; j++) {
239c2f4c
         /* overlap */
         out_ptr = sb_samples + j;
cd816d9b
         for (i = 0; i < 18; i++) {
421c99a4
             *out_ptr = buf[4*i];
             buf[4*i]   = 0;
239c2f4c
             out_ptr += SBLIMIT;
         }
421c99a4
         buf += (j&3) != 3 ? 1 : (4*18-3);
239c2f4c
     }
 }
 
 /* main layer3 decoding function */
 static int mp_decode_layer3(MPADecodeContext *s)
 {
fdf18e33
     int nb_granules, main_data_begin;
06e7fb82
     int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
c9023405
     GranuleDef *g;
b91d4661
     int16_t exponents[576]; //FIXME try INTFLOAT
239c2f4c
 
     /* read side info */
     if (s->lsf) {
         main_data_begin = get_bits(&s->gb, 8);
fdf18e33
         skip_bits(&s->gb, s->nb_channels);
239c2f4c
         nb_granules = 1;
     } else {
         main_data_begin = get_bits(&s->gb, 9);
         if (s->nb_channels == 2)
fdf18e33
             skip_bits(&s->gb, 3);
239c2f4c
         else
fdf18e33
             skip_bits(&s->gb, 5);
239c2f4c
         nb_granules = 2;
cd816d9b
         for (ch = 0; ch < s->nb_channels; ch++) {
c9023405
             s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
             s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
239c2f4c
         }
     }
115329f1
 
cd816d9b
     for (gr = 0; gr < nb_granules; gr++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
9ef5a9de
             av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
c9023405
             g = &s->granules[ch][gr];
239c2f4c
             g->part2_3_length = get_bits(&s->gb, 12);
cd816d9b
             g->big_values     = get_bits(&s->gb,  9);
             if (g->big_values > 288) {
318c5e05
                 av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
dac15a03
                 return AVERROR_INVALIDDATA;
bd60e11b
             }
 
239c2f4c
             g->global_gain = get_bits(&s->gb, 8);
             /* if MS stereo only is selected, we precompute the
                1/sqrt(2) renormalization factor */
115329f1
             if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
239c2f4c
                 MODE_EXT_MS_STEREO)
                 g->global_gain -= 2;
             if (s->lsf)
                 g->scalefac_compress = get_bits(&s->gb, 9);
             else
                 g->scalefac_compress = get_bits(&s->gb, 4);
5fc32c27
             blocksplit_flag = get_bits1(&s->gb);
239c2f4c
             if (blocksplit_flag) {
                 g->block_type = get_bits(&s->gb, 2);
cd816d9b
                 if (g->block_type == 0) {
11f63a22
                     av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
dac15a03
                     return AVERROR_INVALIDDATA;
bd60e11b
                 }
5fc32c27
                 g->switch_point = get_bits1(&s->gb);
cd816d9b
                 for (i = 0; i < 2; i++)
239c2f4c
                     g->table_select[i] = get_bits(&s->gb, 5);
cd816d9b
                 for (i = 0; i < 3; i++)
239c2f4c
                     g->subblock_gain[i] = get_bits(&s->gb, 3);
9f7458b2
                 ff_init_short_region(s, g);
239c2f4c
             } else {
9f7458b2
                 int region_address1, region_address2;
239c2f4c
                 g->block_type = 0;
                 g->switch_point = 0;
cd816d9b
                 for (i = 0; i < 3; i++)
239c2f4c
                     g->table_select[i] = get_bits(&s->gb, 5);
                 /* compute huffman coded region sizes */
                 region_address1 = get_bits(&s->gb, 4);
                 region_address2 = get_bits(&s->gb, 3);
9ef5a9de
                 av_dlog(s->avctx, "region1=%d region2=%d\n",
239c2f4c
                         region_address1, region_address2);
9f7458b2
                 ff_init_long_region(s, g, region_address1, region_address2);
239c2f4c
             }
9f7458b2
             ff_region_offset2size(g);
             ff_compute_band_indexes(s, g);
115329f1
 
239c2f4c
             g->preflag = 0;
             if (!s->lsf)
5fc32c27
                 g->preflag = get_bits1(&s->gb);
cd816d9b
             g->scalefac_scale     = get_bits1(&s->gb);
5fc32c27
             g->count1table_select = get_bits1(&s->gb);
9ef5a9de
             av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
239c2f4c
                     g->block_type, g->switch_point);
         }
     }
 
cd816d9b
     if (!s->adu_mode) {
a057ef69
         int skip;
cd816d9b
         const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
8e039121
         int extrasize = av_clip(get_bits_left(&s->gb) >> 3, 0, EXTRABYTES);
a2f91e7b
         av_assert1((get_bits_count(&s->gb) & 7) == 0);
cd816d9b
         /* now we get bits from the main_data_begin offset */
1218777f
         av_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
                 main_data_begin, s->last_buf_size);
06e7fb82
 
f372ce11
         memcpy(s->last_buf + s->last_buf_size, ptr, extrasize);
cd816d9b
         s->in_gb = s->gb;
ee50a7c1
         init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
481a7ff5
 #if !UNCHECKED_BITSTREAM_READER
8e039121
         s->gb.size_in_bits_plus8 += FFMAX(extrasize, LAST_BUF_SIZE - s->last_buf_size) * 8;
ac08f798
 #endif
a057ef69
         s->last_buf_size <<= 3;
         for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
             for (ch = 0; ch < s->nb_channels; ch++) {
                 g = &s->granules[ch][gr];
                 s->last_buf_size += g->part2_3_length;
                 memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
57130918
                 compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
a057ef69
             }
         }
         skip = s->last_buf_size - 8 * main_data_begin;
         if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
             skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
             s->gb           = s->in_gb;
             s->in_gb.buffer = NULL;
         } else {
             skip_bits_long(&s->gb, skip);
         }
     } else {
         gr = 0;
464f2688
     }
115329f1
 
a057ef69
     for (; gr < nb_granules; gr++) {
9c1f0493
         for (ch = 0; ch < s->nb_channels; ch++) {
464f2688
             g = &s->granules[ch][gr];
239c2f4c
             bits_pos = get_bits_count(&s->gb);
115329f1
 
239c2f4c
             if (!s->lsf) {
0c1a9eda
                 uint8_t *sc;
239c2f4c
                 int slen, slen1, slen2;
 
                 /* MPEG1 scale factors */
                 slen1 = slen_table[0][g->scalefac_compress];
                 slen2 = slen_table[1][g->scalefac_compress];
9ef5a9de
                 av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
239c2f4c
                 if (g->block_type == 2) {
                     n = g->switch_point ? 17 : 18;
                     j = 0;
cd816d9b
                     if (slen1) {
                         for (i = 0; i < n; i++)
e90a7270
                             g->scale_factors[j++] = get_bits(&s->gb, slen1);
cd816d9b
                     } else {
                         for (i = 0; i < n; i++)
e90a7270
                             g->scale_factors[j++] = 0;
                     }
cd816d9b
                     if (slen2) {
                         for (i = 0; i < 18; i++)
e90a7270
                             g->scale_factors[j++] = get_bits(&s->gb, slen2);
cd816d9b
                         for (i = 0; i < 3; i++)
e90a7270
                             g->scale_factors[j++] = 0;
cd816d9b
                     } else {
                         for (i = 0; i < 21; i++)
e90a7270
                             g->scale_factors[j++] = 0;
                     }
239c2f4c
                 } else {
c9023405
                     sc = s->granules[ch][0].scale_factors;
239c2f4c
                     j = 0;
cd816d9b
                     for (k = 0; k < 4; k++) {
                         n = k == 0 ? 6 : 5;
239c2f4c
                         if ((g->scfsi & (0x8 >> k)) == 0) {
                             slen = (k < 2) ? slen1 : slen2;
cd816d9b
                             if (slen) {
                                 for (i = 0; i < n; i++)
e90a7270
                                     g->scale_factors[j++] = get_bits(&s->gb, slen);
cd816d9b
                             } else {
                                 for (i = 0; i < n; i++)
e90a7270
                                     g->scale_factors[j++] = 0;
                             }
239c2f4c
                         } else {
                             /* simply copy from last granule */
cd816d9b
                             for (i = 0; i < n; i++) {
239c2f4c
                                 g->scale_factors[j] = sc[j];
                                 j++;
                             }
                         }
                     }
                     g->scale_factors[j++] = 0;
                 }
             } else {
                 int tindex, tindex2, slen[4], sl, sf;
 
                 /* LSF scale factors */
cd816d9b
                 if (g->block_type == 2)
239c2f4c
                     tindex = g->switch_point ? 2 : 1;
cd816d9b
                 else
239c2f4c
                     tindex = 0;
cd816d9b
 
239c2f4c
                 sf = g->scalefac_compress;
                 if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
                     /* intensity stereo case */
                     sf >>= 1;
                     if (sf < 180) {
                         lsf_sf_expand(slen, sf, 6, 6, 0);
                         tindex2 = 3;
                     } else if (sf < 244) {
                         lsf_sf_expand(slen, sf - 180, 4, 4, 0);
                         tindex2 = 4;
                     } else {
                         lsf_sf_expand(slen, sf - 244, 3, 0, 0);
                         tindex2 = 5;
                     }
                 } else {
                     /* normal case */
                     if (sf < 400) {
                         lsf_sf_expand(slen, sf, 5, 4, 4);
                         tindex2 = 0;
                     } else if (sf < 500) {
                         lsf_sf_expand(slen, sf - 400, 5, 4, 0);
                         tindex2 = 1;
                     } else {
                         lsf_sf_expand(slen, sf - 500, 3, 0, 0);
                         tindex2 = 2;
                         g->preflag = 1;
                     }
                 }
 
                 j = 0;
cd816d9b
                 for (k = 0; k < 4; k++) {
                     n  = lsf_nsf_table[tindex2][tindex][k];
239c2f4c
                     sl = slen[k];
cd816d9b
                     if (sl) {
                         for (i = 0; i < n; i++)
e90a7270
                             g->scale_factors[j++] = get_bits(&s->gb, sl);
cd816d9b
                     } else {
                         for (i = 0; i < n; i++)
e90a7270
                             g->scale_factors[j++] = 0;
                     }
239c2f4c
                 }
                 /* XXX: should compute exact size */
cd816d9b
                 for (; j < 40; j++)
239c2f4c
                     g->scale_factors[j] = 0;
             }
 
             exponents_from_scale_factors(s, g, exponents);
 
             /* read Huffman coded residue */
ee50a7c1
             huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
239c2f4c
         } /* ch */
 
a05c41ac
         if (s->mode == MPA_JSTEREO)
c9023405
             compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
239c2f4c
 
cd816d9b
         for (ch = 0; ch < s->nb_channels; ch++) {
c9023405
             g = &s->granules[ch][gr];
239c2f4c
 
             reorder_block(s, g);
6f1ec38c
             compute_antialias(s, g);
115329f1
             compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
239c2f4c
         }
     } /* gr */
cd816d9b
     if (get_bits_count(&s->gb) < 0)
ee50a7c1
         skip_bits_long(&s->gb, -get_bits_count(&s->gb));
239c2f4c
     return nb_granules * 18;
 }
 
3ffed68c
 static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
cd816d9b
                            const uint8_t *buf, int buf_size)
239c2f4c
 {
0eea2129
     int i, nb_frames, ch, ret;
a3a5f4d6
     OUT_INT *samples_ptr;
239c2f4c
 
cd816d9b
     init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
115329f1
 
239c2f4c
     /* skip error protection field */
     if (s->error_protection)
7ae7300e
         skip_bits(&s->gb, 16);
239c2f4c
 
     switch(s->layer) {
     case 1:
6122b733
         s->avctx->frame_size = 384;
239c2f4c
         nb_frames = mp_decode_layer1(s);
         break;
     case 2:
6122b733
         s->avctx->frame_size = 1152;
239c2f4c
         nb_frames = mp_decode_layer2(s);
         break;
     case 3:
6122b733
         s->avctx->frame_size = s->lsf ? 576 : 1152;
239c2f4c
     default:
         nb_frames = mp_decode_layer3(s);
06e7fb82
 
c0c66dd8
         s->last_buf_size=0;
cd816d9b
         if (s->in_gb.buffer) {
c0c66dd8
             align_get_bits(&s->gb);
cd816d9b
             i = get_bits_left(&s->gb)>>3;
             if (i >= 0 && i <= BACKSTEP_SIZE) {
c0c66dd8
                 memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
                 s->last_buf_size=i;
cd816d9b
             } else
11f63a22
                 av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
cd816d9b
             s->gb           = s->in_gb;
             s->in_gb.buffer = NULL;
c0c66dd8
         }
 
06e7fb82
         align_get_bits(&s->gb);
a2f91e7b
         av_assert1((get_bits_count(&s->gb) & 7) == 0);
cd816d9b
         i = get_bits_left(&s->gb) >> 3;
c0c66dd8
 
cd816d9b
         if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
             if (i < 0)
1d4113d0
                 av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
cd816d9b
             i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1b4f17fa
         }
a2f91e7b
         av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1b4f17fa
         memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
c0c66dd8
         s->last_buf_size += i;
0eea2129
     }
06e7fb82
 
7696a392
     if(nb_frames < 0)
         return nb_frames;
 
0eea2129
     /* get output buffer */
     if (!samples) {
         s->frame.nb_samples = s->avctx->frame_size;
594d4d5d
         if ((ret = ff_get_buffer(s->avctx, &s->frame)) < 0) {
0eea2129
             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
             return ret;
         }
3ffed68c
         samples = (OUT_INT **)s->frame.extended_data;
239c2f4c
     }
969c163f
 
239c2f4c
     /* apply the synthesis filter */
cd816d9b
     for (ch = 0; ch < s->nb_channels; ch++) {
3ffed68c
         int sample_stride;
         if (s->avctx->sample_fmt == OUT_FMT_P) {
             samples_ptr   = samples[ch];
             sample_stride = 1;
         } else {
             samples_ptr   = samples[0] + ch;
             sample_stride = s->nb_channels;
         }
cd816d9b
         for (i = 0; i < nb_frames; i++) {
3ffed68c
             RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
                                         &(s->synth_buf_offset[ch]),
                                         RENAME(ff_mpa_synth_window),
                                         &s->dither_state, samples_ptr,
                                         sample_stride, s->sb_samples[ch][i]);
             samples_ptr += 32 * sample_stride;
239c2f4c
         }
     }
969c163f
 
a3a5f4d6
     return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
239c2f4c
 }
 
0eea2129
 static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
7a00bbad
                         AVPacket *avpkt)
de6d9b64
 {
cd816d9b
     const uint8_t *buf  = avpkt->data;
     int buf_size        = avpkt->size;
de6d9b64
     MPADecodeContext *s = avctx->priv_data;
0c1a9eda
     uint32_t header;
9ab0874e
     int ret;
de6d9b64
 
c5371f77
     while(buf_size && !*buf){
43bc5cf9
         buf++;
c5371f77
         buf_size--;
     }
43bc5cf9
 
cd816d9b
     if (buf_size < HEADER_SIZE)
dac15a03
         return AVERROR_INVALIDDATA;
06e7fb82
 
2c124cb6
     header = AV_RB32(buf);
3183c38a
     if (header>>8 == AV_RB32("TAG")>>8) {
         av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
         return buf_size;
     }
cd816d9b
     if (ff_mpa_check_header(header) < 0) {
822d0a6e
         av_log(avctx, AV_LOG_ERROR, "Header missing\n");
dac15a03
         return AVERROR_INVALIDDATA;
06e7fb82
     }
 
82ab61f9
     if (avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
06e7fb82
         /* free format: prepare to compute frame size */
         s->frame_size = -1;
dac15a03
         return AVERROR_INVALIDDATA;
06e7fb82
     }
     /* update codec info */
cd816d9b
     avctx->channels       = s->nb_channels;
e10976eb
     avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
49d7ef28
     if (!avctx->bit_rate)
         avctx->bit_rate = s->bit_rate;
06e7fb82
 
cd816d9b
     if (s->frame_size <= 0 || s->frame_size > buf_size) {
06e7fb82
         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
dac15a03
         return AVERROR_INVALIDDATA;
cd816d9b
     } else if (s->frame_size < buf_size) {
54e1eaef
         av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
d5aa01cd
         buf_size= s->frame_size;
de6d9b64
     }
06e7fb82
 
9ab0874e
     ret = mp_decode_frame(s, NULL, buf, buf_size);
     if (ret >= 0) {
0eea2129
         *got_frame_ptr   = 1;
         *(AVFrame *)data = s->frame;
498c544a
         avctx->sample_rate = s->sample_rate;
         //FIXME maybe move the other codec info stuff from above here too
4be1e1df
     } else {
         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
9ab0874e
         /* Only return an error if the bad frame makes up the whole packet or
          * the error is related to buffer management.
          * If there is more data in the packet, just consume the bad frame
          * instead of returning an error, which would discard the whole
          * packet. */
0eea2129
         *got_frame_ptr = 0;
9ab0874e
         if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
             return ret;
4be1e1df
     }
06e7fb82
     s->frame_size = 0;
822d0a6e
     return buf_size;
de6d9b64
 }
 
2f17f265
 static void mp_flush(MPADecodeContext *ctx)
 {
     memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
     ctx->last_buf_size = 0;
 }
 
cd816d9b
 static void flush(AVCodecContext *avctx)
 {
2f17f265
     mp_flush(avctx->priv_data);
9bb328d3
 }
 
956dae9e
 #if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
0eea2129
 static int decode_frame_adu(AVCodecContext *avctx, void *data,
                             int *got_frame_ptr, AVPacket *avpkt)
1ede228a
 {
cd816d9b
     const uint8_t *buf  = avpkt->data;
     int buf_size        = avpkt->size;
1ede228a
     MPADecodeContext *s = avctx->priv_data;
     uint32_t header;
9ab0874e
     int len, ret;
e2094bd0
     int av_unused out_size;
1ede228a
 
     len = buf_size;
 
     // Discard too short frames
     if (buf_size < HEADER_SIZE) {
99975966
         av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
         return AVERROR_INVALIDDATA;
1ede228a
     }
 
 
     if (len > MPA_MAX_CODED_FRAME_SIZE)
         len = MPA_MAX_CODED_FRAME_SIZE;
 
     // Get header and restore sync word
2c124cb6
     header = AV_RB32(buf) | 0xffe00000;
1ede228a
 
a7a85899
     if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
99975966
         av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
         return AVERROR_INVALIDDATA;
1ede228a
     }
 
82ab61f9
     avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1ede228a
     /* update codec info */
     avctx->sample_rate = s->sample_rate;
cd816d9b
     avctx->channels    = s->nb_channels;
49d7ef28
     if (!avctx->bit_rate)
         avctx->bit_rate = s->bit_rate;
1ede228a
 
d0ed455f
     s->frame_size = len;
1ede228a
 
9ab0874e
     ret = mp_decode_frame(s, NULL, buf, buf_size);
     if (ret < 0) {
aa3f2cb5
         av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
9ab0874e
         return ret;
aa3f2cb5
     }
0eea2129
 
     *got_frame_ptr   = 1;
     *(AVFrame *)data = s->frame;
1ede228a
 
     return buf_size;
 }
956dae9e
 #endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1ede228a
 
956dae9e
 #if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
b61d2782
 
676e26ab
 /**
  * Context for MP3On4 decoder
  */
 typedef struct MP3On4DecodeContext {
0eea2129
     AVFrame *frame;
cd816d9b
     int frames;                     ///< number of mp3 frames per block (number of mp3 decoder instances)
     int syncword;                   ///< syncword patch
     const uint8_t *coff;            ///< channel offsets in output buffer
676e26ab
     MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
 } MP3On4DecodeContext;
 
b61d2782
 #include "mpeg4audio.h"
 
d2a7718d
 /* Next 3 arrays are indexed by channel config number (passed via codecdata) */
cd816d9b
 
 /* number of mp3 decoder instances */
 static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
 
fff0f831
 /* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
60dfa0b8
 static const uint8_t chan_offset[8][5] = {
cd816d9b
     { 0             },
     { 0             },  // C
     { 0             },  // FLR
     { 2, 0          },  // C FLR
     { 2, 0, 3       },  // C FLR BS
     { 2, 0, 3       },  // C FLR BLRS
     { 2, 0, 4, 3    },  // C FLR BLRS LFE
     { 2, 0, 6, 4, 3 },  // C FLR BLRS BLR LFE
d2a7718d
 };
 
1183d6cd
 /* mp3on4 channel layouts */
 static const int16_t chan_layout[8] = {
     0,
     AV_CH_LAYOUT_MONO,
     AV_CH_LAYOUT_STEREO,
     AV_CH_LAYOUT_SURROUND,
     AV_CH_LAYOUT_4POINT0,
     AV_CH_LAYOUT_5POINT0,
     AV_CH_LAYOUT_5POINT1,
     AV_CH_LAYOUT_7POINT1
 };
d2a7718d
 
f507dd06
 static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
 {
     MP3On4DecodeContext *s = avctx->priv_data;
     int i;
 
     for (i = 0; i < s->frames; i++)
         av_free(s->mp3decctx[i]);
 
     return 0;
 }
 
d2a7718d
 
 static int decode_init_mp3on4(AVCodecContext * avctx)
 {
     MP3On4DecodeContext *s = avctx->priv_data;
b61d2782
     MPEG4AudioConfig cfg;
d2a7718d
     int i;
 
     if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
         av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
dac15a03
         return AVERROR_INVALIDDATA;
d2a7718d
     }
 
fd095539
     avpriv_mpeg4audio_get_config(&cfg, avctx->extradata,
                                  avctx->extradata_size * 8, 1);
b61d2782
     if (!cfg.chan_config || cfg.chan_config > 7) {
d2a7718d
         av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
dac15a03
         return AVERROR_INVALIDDATA;
d2a7718d
     }
cd816d9b
     s->frames             = mp3Frames[cfg.chan_config];
     s->coff               = chan_offset[cfg.chan_config];
     avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];
1183d6cd
     avctx->channel_layout = chan_layout[cfg.chan_config];
d2a7718d
 
9f95bfe2
     if (cfg.sample_rate < 16000)
         s->syncword = 0xffe00000;
     else
         s->syncword = 0xfff00000;
 
d2a7718d
     /* Init the first mp3 decoder in standard way, so that all tables get builded
      * We replace avctx->priv_data with the context of the first decoder so that
      * decode_init() does not have to be changed.
5e534865
      * Other decoders will be initialized here copying data from the first context
d2a7718d
      */
     // Allocate zeroed memory for the first decoder context
     s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
95891804
     if (!s->mp3decctx[0])
         goto alloc_fail;
d2a7718d
     // Put decoder context in place to make init_decode() happy
     avctx->priv_data = s->mp3decctx[0];
     decode_init(avctx);
0eea2129
     s->frame = avctx->coded_frame;
d2a7718d
     // Restore mp3on4 context pointer
     avctx->priv_data = s;
     s->mp3decctx[0]->adu_mode = 1; // Set adu mode
 
     /* Create a separate codec/context for each frame (first is already ok).
      * Each frame is 1 or 2 channels - up to 5 frames allowed
      */
     for (i = 1; i < s->frames; i++) {
         s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
95891804
         if (!s->mp3decctx[i])
             goto alloc_fail;
d2a7718d
         s->mp3decctx[i]->adu_mode = 1;
318c5e05
         s->mp3decctx[i]->avctx = avctx;
cb72230d
         s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
d2a7718d
     }
 
     return 0;
f507dd06
 alloc_fail:
     decode_close_mp3on4(avctx);
     return AVERROR(ENOMEM);
d2a7718d
 }
 
 
180bf988
 static void flush_mp3on4(AVCodecContext *avctx)
d2a7718d
 {
     int i;
180bf988
     MP3On4DecodeContext *s = avctx->priv_data;
d2a7718d
 
2f17f265
     for (i = 0; i < s->frames; i++)
         mp_flush(s->mp3decctx[i]);
d2a7718d
 }
 
 
0eea2129
 static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
                                int *got_frame_ptr, AVPacket *avpkt)
d2a7718d
 {
cd816d9b
     const uint8_t *buf     = avpkt->data;
     int buf_size           = avpkt->size;
d2a7718d
     MP3On4DecodeContext *s = avctx->priv_data;
     MPADecodeContext *m;
41b8800f
     int fsize, len = buf_size, out_size = 0;
d2a7718d
     uint32_t header;
3ffed68c
     OUT_INT **out_samples;
     OUT_INT *outptr[2];
     int fr, ch, ret;
d2a7718d
 
0eea2129
     /* get output buffer */
4e0738ce
     s->frame->nb_samples = MPA_FRAME_SIZE;
594d4d5d
     if ((ret = ff_get_buffer(avctx, s->frame)) < 0) {
0eea2129
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
53c8443a
     }
3ffed68c
     out_samples = (OUT_INT **)s->frame->extended_data;
f7304e99
 
d2a7718d
     // Discard too short frames
a82dcdff
     if (buf_size < HEADER_SIZE)
dac15a03
         return AVERROR_INVALIDDATA;
d2a7718d
 
5fd7a9fc
     avctx->bit_rate = 0;
 
53c8443a
     ch = 0;
d2a7718d
     for (fr = 0; fr < s->frames; fr++) {
ec39f7d8
         fsize = AV_RB16(buf) >> 4;
5be25fc1
         fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
cd816d9b
         m     = s->mp3decctx[fr];
a2f91e7b
         av_assert1(m);
d2a7718d
 
3e13005c
         if (fsize < HEADER_SIZE) {
             av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
             return AVERROR_INVALIDDATA;
         }
9f95bfe2
         header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
d2a7718d
 
169203c1
         if (ff_mpa_check_header(header) < 0) // Bad header, discard block
             break;
d2a7718d
 
82ab61f9
         avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
53c8443a
 
bacf5db1
         if (ch + m->nb_channels > avctx->channels ||
             s->coff[fr] + m->nb_channels > avctx->channels) {
53c8443a
             av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
                                         "channel count\n");
             return AVERROR_INVALIDDATA;
         }
         ch += m->nb_channels;
 
3ffed68c
         outptr[0] = out_samples[s->coff[fr]];
         if (m->nb_channels > 1)
             outptr[1] = out_samples[s->coff[fr] + 1];
 
9ab0874e
         if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0)
             return ret;
 
         out_size += ret;
cd816d9b
         buf      += fsize;
         len      -= fsize;
d2a7718d
 
5fd7a9fc
         avctx->bit_rate += m->bit_rate;
d2a7718d
     }
 
     /* update codec info */
     avctx->sample_rate = s->mp3decctx[0]->sample_rate;
 
0eea2129
     s->frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
     *got_frame_ptr   = 1;
     *(AVFrame *)data = *s->frame;
 
d2a7718d
     return buf_size;
 }
956dae9e
 #endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
d2a7718d
 
b91d4661
 #if !CONFIG_FLOAT
b250f9c6
 #if CONFIG_MP1_DECODER
86714887
 AVCodec ff_mp1_decoder = {
     .name           = "mp1",
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_MP1,
86714887
     .priv_data_size = sizeof(MPADecodeContext),
     .init           = decode_init,
     .decode         = decode_frame,
0eea2129
     .capabilities   = CODEC_CAP_DR1,
86714887
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
3ffed68c
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_S16,
                                                       AV_SAMPLE_FMT_NONE },
cb595b7f
 };
 #endif
b250f9c6
 #if CONFIG_MP2_DECODER
86714887
 AVCodec ff_mp2_decoder = {
     .name           = "mp2",
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_MP2,
86714887
     .priv_data_size = sizeof(MPADecodeContext),
     .init           = decode_init,
     .decode         = decode_frame,
0eea2129
     .capabilities   = CODEC_CAP_DR1,
86714887
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
3ffed68c
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_S16,
                                                       AV_SAMPLE_FMT_NONE },
de6d9b64
 };
62bb489b
 #endif
b250f9c6
 #if CONFIG_MP3_DECODER
86714887
 AVCodec ff_mp3_decoder = {
     .name           = "mp3",
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_MP3,
86714887
     .priv_data_size = sizeof(MPADecodeContext),
     .init           = decode_init,
     .decode         = decode_frame,
0eea2129
     .capabilities   = CODEC_CAP_DR1,
86714887
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
3ffed68c
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_S16,
                                                       AV_SAMPLE_FMT_NONE },
4b1f4f23
 };
62bb489b
 #endif
b250f9c6
 #if CONFIG_MP3ADU_DECODER
86714887
 AVCodec ff_mp3adu_decoder = {
     .name           = "mp3adu",
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_MP3ADU,
86714887
     .priv_data_size = sizeof(MPADecodeContext),
     .init           = decode_init,
     .decode         = decode_frame_adu,
0eea2129
     .capabilities   = CODEC_CAP_DR1,
86714887
     .flush          = flush,
     .long_name      = NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
3ffed68c
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_S16,
                                                       AV_SAMPLE_FMT_NONE },
1ede228a
 };
62bb489b
 #endif
b250f9c6
 #if CONFIG_MP3ON4_DECODER
86714887
 AVCodec ff_mp3on4_decoder = {
     .name           = "mp3on4",
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_MP3ON4,
86714887
     .priv_data_size = sizeof(MP3On4DecodeContext),
     .init           = decode_init_mp3on4,
     .close          = decode_close_mp3on4,
     .decode         = decode_frame_mp3on4,
0eea2129
     .capabilities   = CODEC_CAP_DR1,
180bf988
     .flush          = flush_mp3on4,
86714887
     .long_name      = NULL_IF_CONFIG_SMALL("MP3onMP4"),
3ffed68c
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
                                                       AV_SAMPLE_FMT_NONE },
d2a7718d
 };
62bb489b
 #endif
b91d4661
 #endif