Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ bdefbf3e

History | View | Annotate | Download (71 KB)

1
/*
2
 * MPEG Audio decoder
3
 * Copyright (c) 2001, 2002 Fabrice Bellard
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * Libav is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/**
23
 * @file
24
 * MPEG Audio decoder.
25
 */
26

    
27
#include "libavutil/audioconvert.h"
28
#include "avcodec.h"
29
#include "get_bits.h"
30
#include "dsputil.h"
31
#include "mathops.h"
32

    
33
/*
34
 * TODO:
35
 *  - test lsf / mpeg25 extensively.
36
 */
37

    
38
#include "mpegaudio.h"
39
#include "mpegaudiodecheader.h"
40

    
41
#if CONFIG_FLOAT
42
#   define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
43
#   define compute_antialias compute_antialias_float
44
#   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
45
#   define FIXR(x)        ((float)(x))
46
#   define FIXHR(x)       ((float)(x))
47
#   define MULH3(x, y, s) ((s)*(y)*(x))
48
#   define MULLx(x, y, s) ((y)*(x))
49
#   define RENAME(a) a ## _float
50
#   define OUT_FMT AV_SAMPLE_FMT_FLT
51
#else
52
#   define SHR(a,b)       ((a)>>(b))
53
#   define compute_antialias compute_antialias_integer
54
/* WARNING: only correct for posititive numbers */
55
#   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
56
#   define FIXR(a)        ((int)((a) * FRAC_ONE + 0.5))
57
#   define FIXHR(a)       ((int)((a) * (1LL<<32) + 0.5))
58
#   define MULH3(x, y, s) MULH((s)*(x), y)
59
#   define MULLx(x, y, s) MULL(x,y,s)
60
#   define RENAME(a)      a
61
#   define OUT_FMT AV_SAMPLE_FMT_S16
62
#endif
63

    
64
/****************/
65

    
66
#define HEADER_SIZE 4
67

    
68
#include "mpegaudiodata.h"
69
#include "mpegaudiodectab.h"
70

    
71
#if CONFIG_FLOAT
72
#    include "fft.h"
73
#else
74
#    include "dct32.c"
75
#endif
76

    
77
static void compute_antialias(MPADecodeContext *s, GranuleDef *g);
78
static void apply_window_mp3_c(MPA_INT *synth_buf, MPA_INT *window,
79
                               int *dither_state, OUT_INT *samples, int incr);
80

    
81
/* vlc structure for decoding layer 3 huffman tables */
82
static VLC huff_vlc[16];
83
static VLC_TYPE huff_vlc_tables[
84
  0+128+128+128+130+128+154+166+
85
  142+204+190+170+542+460+662+414
86
  ][2];
87
static const int huff_vlc_tables_sizes[16] = {
88
  0, 128, 128, 128, 130, 128, 154, 166,
89
  142, 204, 190, 170, 542, 460, 662, 414
90
};
91
static VLC huff_quad_vlc[2];
92
static VLC_TYPE huff_quad_vlc_tables[128+16][2];
93
static const int huff_quad_vlc_tables_sizes[2] = {
94
  128, 16
95
};
96
/* computed from band_size_long */
97
static uint16_t band_index_long[9][23];
98
#include "mpegaudio_tablegen.h"
99
/* intensity stereo coef table */
100
static INTFLOAT is_table[2][16];
101
static INTFLOAT is_table_lsf[2][2][16];
102
static int32_t csa_table[8][4];
103
static float csa_table_float[8][4];
104
static INTFLOAT mdct_win[8][36];
105

    
106
static int16_t division_tab3[1<<6 ];
107
static int16_t division_tab5[1<<8 ];
108
static int16_t division_tab9[1<<11];
109

    
110
static int16_t * const division_tabs[4] = {
111
    division_tab3, division_tab5, NULL, division_tab9
112
};
113

    
114
/* lower 2 bits: modulo 3, higher bits: shift */
115
static uint16_t scale_factor_modshift[64];
116
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
117
static int32_t scale_factor_mult[15][3];
118
/* mult table for layer 2 group quantization */
119

    
120
#define SCALE_GEN(v) \
121
{ FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
122

    
123
static const int32_t scale_factor_mult2[3][3] = {
124
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
125
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
126
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
127
};
128

    
129
DECLARE_ALIGNED(16, MPA_INT, RENAME(ff_mpa_synth_window))[512+256];
130

    
131
/**
132
 * Convert region offsets to region sizes and truncate
133
 * size to big_values.
134
 */
135
static void ff_region_offset2size(GranuleDef *g){
136
    int i, k, j=0;
137
    g->region_size[2] = (576 / 2);
138
    for(i=0;i<3;i++) {
139
        k = FFMIN(g->region_size[i], g->big_values);
140
        g->region_size[i] = k - j;
141
        j = k;
142
    }
143
}
144

    
145
static void ff_init_short_region(MPADecodeContext *s, GranuleDef *g){
146
    if (g->block_type == 2)
147
        g->region_size[0] = (36 / 2);
148
    else {
149
        if (s->sample_rate_index <= 2)
150
            g->region_size[0] = (36 / 2);
151
        else if (s->sample_rate_index != 8)
152
            g->region_size[0] = (54 / 2);
153
        else
154
            g->region_size[0] = (108 / 2);
155
    }
156
    g->region_size[1] = (576 / 2);
157
}
158

    
159
static void ff_init_long_region(MPADecodeContext *s, GranuleDef *g, int ra1, int ra2){
160
    int l;
161
    g->region_size[0] =
162
        band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
163
    /* should not overflow */
164
    l = FFMIN(ra1 + ra2 + 2, 22);
165
    g->region_size[1] =
166
        band_index_long[s->sample_rate_index][l] >> 1;
167
}
168

    
169
static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g){
170
    if (g->block_type == 2) {
171
        if (g->switch_point) {
172
            /* if switched mode, we handle the 36 first samples as
173
                long blocks.  For 8000Hz, we handle the 48 first
174
                exponents as long blocks (XXX: check this!) */
175
            if (s->sample_rate_index <= 2)
176
                g->long_end = 8;
177
            else if (s->sample_rate_index != 8)
178
                g->long_end = 6;
179
            else
180
                g->long_end = 4; /* 8000 Hz */
181

    
182
            g->short_start = 2 + (s->sample_rate_index != 8);
183
        } else {
184
            g->long_end = 0;
185
            g->short_start = 0;
186
        }
187
    } else {
188
        g->short_start = 13;
189
        g->long_end = 22;
190
    }
191
}
192

    
193
/* layer 1 unscaling */
194
/* n = number of bits of the mantissa minus 1 */
195
static inline int l1_unscale(int n, int mant, int scale_factor)
196
{
197
    int shift, mod;
198
    int64_t val;
199

    
200
    shift = scale_factor_modshift[scale_factor];
201
    mod = shift & 3;
202
    shift >>= 2;
203
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
204
    shift += n;
205
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
206
    return (int)((val + (1LL << (shift - 1))) >> shift);
207
}
208

    
209
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
210
{
211
    int shift, mod, val;
212

    
213
    shift = scale_factor_modshift[scale_factor];
214
    mod = shift & 3;
215
    shift >>= 2;
216

    
217
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
218
    /* NOTE: at this point, 0 <= shift <= 21 */
219
    if (shift > 0)
220
        val = (val + (1 << (shift - 1))) >> shift;
221
    return val;
222
}
223

    
224
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
225
static inline int l3_unscale(int value, int exponent)
226
{
227
    unsigned int m;
228
    int e;
229

    
230
    e = table_4_3_exp  [4*value + (exponent&3)];
231
    m = table_4_3_value[4*value + (exponent&3)];
232
    e -= (exponent >> 2);
233
    assert(e>=1);
234
    if (e > 31)
235
        return 0;
236
    m = (m + (1 << (e-1))) >> e;
237

    
238
    return m;
239
}
240

    
241
/* all integer n^(4/3) computation code */
242
#define DEV_ORDER 13
243

    
244
#define POW_FRAC_BITS 24
245
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
246
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
247
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
248

    
249
static int dev_4_3_coefs[DEV_ORDER];
250

    
251
static av_cold void int_pow_init(void)
252
{
253
    int i, a;
254

    
255
    a = POW_FIX(1.0);
256
    for(i=0;i<DEV_ORDER;i++) {
257
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
258
        dev_4_3_coefs[i] = a;
259
    }
260
}
261

    
262
static av_cold int decode_init(AVCodecContext * avctx)
263
{
264
    MPADecodeContext *s = avctx->priv_data;
265
    static int init=0;
266
    int i, j, k;
267

    
268
    s->avctx = avctx;
269
    s->apply_window_mp3 = apply_window_mp3_c;
270
#if HAVE_MMX && CONFIG_FLOAT
271
    ff_mpegaudiodec_init_mmx(s);
272
#endif
273
#if CONFIG_FLOAT
274
    ff_dct_init(&s->dct, 5, DCT_II);
275
#endif
276
    if (HAVE_ALTIVEC && CONFIG_FLOAT) ff_mpegaudiodec_init_altivec(s);
277

    
278
    avctx->sample_fmt= OUT_FMT;
279
    s->error_recognition= avctx->error_recognition;
280

    
281
    if (!init && !avctx->parse_only) {
282
        int offset;
283

    
284
        /* scale factors table for layer 1/2 */
285
        for(i=0;i<64;i++) {
286
            int shift, mod;
287
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
288
            shift = (i / 3);
289
            mod = i % 3;
290
            scale_factor_modshift[i] = mod | (shift << 2);
291
        }
292

    
293
        /* scale factor multiply for layer 1 */
294
        for(i=0;i<15;i++) {
295
            int n, norm;
296
            n = i + 2;
297
            norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
298
            scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
299
            scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
300
            scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
301
            av_dlog(avctx, "%d: norm=%x s=%x %x %x\n",
302
                    i, norm,
303
                    scale_factor_mult[i][0],
304
                    scale_factor_mult[i][1],
305
                    scale_factor_mult[i][2]);
306
        }
307

    
308
        RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
309

    
310
        /* huffman decode tables */
311
        offset = 0;
312
        for(i=1;i<16;i++) {
313
            const HuffTable *h = &mpa_huff_tables[i];
314
            int xsize, x, y;
315
            uint8_t  tmp_bits [512];
316
            uint16_t tmp_codes[512];
317

    
318
            memset(tmp_bits , 0, sizeof(tmp_bits ));
319
            memset(tmp_codes, 0, sizeof(tmp_codes));
320

    
321
            xsize = h->xsize;
322

    
323
            j = 0;
324
            for(x=0;x<xsize;x++) {
325
                for(y=0;y<xsize;y++){
326
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
327
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
328
                }
329
            }
330

    
331
            /* XXX: fail test */
332
            huff_vlc[i].table = huff_vlc_tables+offset;
333
            huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
334
            init_vlc(&huff_vlc[i], 7, 512,
335
                     tmp_bits, 1, 1, tmp_codes, 2, 2,
336
                     INIT_VLC_USE_NEW_STATIC);
337
            offset += huff_vlc_tables_sizes[i];
338
        }
339
        assert(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
340

    
341
        offset = 0;
342
        for(i=0;i<2;i++) {
343
            huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
344
            huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
345
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
346
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
347
                     INIT_VLC_USE_NEW_STATIC);
348
            offset += huff_quad_vlc_tables_sizes[i];
349
        }
350
        assert(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
351

    
352
        for(i=0;i<9;i++) {
353
            k = 0;
354
            for(j=0;j<22;j++) {
355
                band_index_long[i][j] = k;
356
                k += band_size_long[i][j];
357
            }
358
            band_index_long[i][22] = k;
359
        }
360

    
361
        /* compute n ^ (4/3) and store it in mantissa/exp format */
362

    
363
        int_pow_init();
364
        mpegaudio_tableinit();
365

    
366
        for (i = 0; i < 4; i++)
367
            if (ff_mpa_quant_bits[i] < 0)
368
                for (j = 0; j < (1<<(-ff_mpa_quant_bits[i]+1)); j++) {
369
                    int val1, val2, val3, steps;
370
                    int val = j;
371
                    steps  = ff_mpa_quant_steps[i];
372
                    val1 = val % steps;
373
                    val /= steps;
374
                    val2 = val % steps;
375
                    val3 = val / steps;
376
                    division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
377
                }
378

    
379

    
380
        for(i=0;i<7;i++) {
381
            float f;
382
            INTFLOAT v;
383
            if (i != 6) {
384
                f = tan((double)i * M_PI / 12.0);
385
                v = FIXR(f / (1.0 + f));
386
            } else {
387
                v = FIXR(1.0);
388
            }
389
            is_table[0][i] = v;
390
            is_table[1][6 - i] = v;
391
        }
392
        /* invalid values */
393
        for(i=7;i<16;i++)
394
            is_table[0][i] = is_table[1][i] = 0.0;
395

    
396
        for(i=0;i<16;i++) {
397
            double f;
398
            int e, k;
399

    
400
            for(j=0;j<2;j++) {
401
                e = -(j + 1) * ((i + 1) >> 1);
402
                f = pow(2.0, e / 4.0);
403
                k = i & 1;
404
                is_table_lsf[j][k ^ 1][i] = FIXR(f);
405
                is_table_lsf[j][k][i] = FIXR(1.0);
406
                av_dlog(avctx, "is_table_lsf %d %d: %x %x\n",
407
                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
408
            }
409
        }
410

    
411
        for(i=0;i<8;i++) {
412
            float ci, cs, ca;
413
            ci = ci_table[i];
414
            cs = 1.0 / sqrt(1.0 + ci * ci);
415
            ca = cs * ci;
416
            csa_table[i][0] = FIXHR(cs/4);
417
            csa_table[i][1] = FIXHR(ca/4);
418
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
419
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
420
            csa_table_float[i][0] = cs;
421
            csa_table_float[i][1] = ca;
422
            csa_table_float[i][2] = ca + cs;
423
            csa_table_float[i][3] = ca - cs;
424
        }
425

    
426
        /* compute mdct windows */
427
        for(i=0;i<36;i++) {
428
            for(j=0; j<4; j++){
429
                double d;
430

    
431
                if(j==2 && i%3 != 1)
432
                    continue;
433

    
434
                d= sin(M_PI * (i + 0.5) / 36.0);
435
                if(j==1){
436
                    if     (i>=30) d= 0;
437
                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
438
                    else if(i>=18) d= 1;
439
                }else if(j==3){
440
                    if     (i<  6) d= 0;
441
                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
442
                    else if(i< 18) d= 1;
443
                }
444
                //merge last stage of imdct into the window coefficients
445
                d*= 0.5 / cos(M_PI*(2*i + 19)/72);
446

    
447
                if(j==2)
448
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
449
                else
450
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
451
            }
452
        }
453

    
454
        /* NOTE: we do frequency inversion adter the MDCT by changing
455
           the sign of the right window coefs */
456
        for(j=0;j<4;j++) {
457
            for(i=0;i<36;i+=2) {
458
                mdct_win[j + 4][i] = mdct_win[j][i];
459
                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
460
            }
461
        }
462

    
463
        init = 1;
464
    }
465

    
466
    if (avctx->codec_id == CODEC_ID_MP3ADU)
467
        s->adu_mode = 1;
468
    return 0;
469
}
470

    
471

    
472
#if CONFIG_FLOAT
473
static inline float round_sample(float *sum)
474
{
475
    float sum1=*sum;
476
    *sum = 0;
477
    return sum1;
478
}
479

    
480
/* signed 16x16 -> 32 multiply add accumulate */
481
#define MACS(rt, ra, rb) rt+=(ra)*(rb)
482

    
483
/* signed 16x16 -> 32 multiply */
484
#define MULS(ra, rb) ((ra)*(rb))
485

    
486
#define MLSS(rt, ra, rb) rt-=(ra)*(rb)
487

    
488
#else
489

    
490
static inline int round_sample(int64_t *sum)
491
{
492
    int sum1;
493
    sum1 = (int)((*sum) >> OUT_SHIFT);
494
    *sum &= (1<<OUT_SHIFT)-1;
495
    return av_clip_int16(sum1);
496
}
497

    
498
#   define MULS(ra, rb) MUL64(ra, rb)
499
#   define MACS(rt, ra, rb) MAC64(rt, ra, rb)
500
#   define MLSS(rt, ra, rb) MLS64(rt, ra, rb)
501
#endif
502

    
503
#define SUM8(op, sum, w, p)               \
504
{                                         \
505
    op(sum, (w)[0 * 64], (p)[0 * 64]);    \
506
    op(sum, (w)[1 * 64], (p)[1 * 64]);    \
507
    op(sum, (w)[2 * 64], (p)[2 * 64]);    \
508
    op(sum, (w)[3 * 64], (p)[3 * 64]);    \
509
    op(sum, (w)[4 * 64], (p)[4 * 64]);    \
510
    op(sum, (w)[5 * 64], (p)[5 * 64]);    \
511
    op(sum, (w)[6 * 64], (p)[6 * 64]);    \
512
    op(sum, (w)[7 * 64], (p)[7 * 64]);    \
513
}
514

    
515
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
516
{                                               \
517
    INTFLOAT tmp;\
518
    tmp = p[0 * 64];\
519
    op1(sum1, (w1)[0 * 64], tmp);\
520
    op2(sum2, (w2)[0 * 64], tmp);\
521
    tmp = p[1 * 64];\
522
    op1(sum1, (w1)[1 * 64], tmp);\
523
    op2(sum2, (w2)[1 * 64], tmp);\
524
    tmp = p[2 * 64];\
525
    op1(sum1, (w1)[2 * 64], tmp);\
526
    op2(sum2, (w2)[2 * 64], tmp);\
527
    tmp = p[3 * 64];\
528
    op1(sum1, (w1)[3 * 64], tmp);\
529
    op2(sum2, (w2)[3 * 64], tmp);\
530
    tmp = p[4 * 64];\
531
    op1(sum1, (w1)[4 * 64], tmp);\
532
    op2(sum2, (w2)[4 * 64], tmp);\
533
    tmp = p[5 * 64];\
534
    op1(sum1, (w1)[5 * 64], tmp);\
535
    op2(sum2, (w2)[5 * 64], tmp);\
536
    tmp = p[6 * 64];\
537
    op1(sum1, (w1)[6 * 64], tmp);\
538
    op2(sum2, (w2)[6 * 64], tmp);\
539
    tmp = p[7 * 64];\
540
    op1(sum1, (w1)[7 * 64], tmp);\
541
    op2(sum2, (w2)[7 * 64], tmp);\
542
}
543

    
544
void av_cold RENAME(ff_mpa_synth_init)(MPA_INT *window)
545
{
546
    int i, j;
547

    
548
    /* max = 18760, max sum over all 16 coefs : 44736 */
549
    for(i=0;i<257;i++) {
550
        INTFLOAT v;
551
        v = ff_mpa_enwindow[i];
552
#if CONFIG_FLOAT
553
        v *= 1.0 / (1LL<<(16 + FRAC_BITS));
554
#endif
555
        window[i] = v;
556
        if ((i & 63) != 0)
557
            v = -v;
558
        if (i != 0)
559
            window[512 - i] = v;
560
    }
561

    
562
    // Needed for avoiding shuffles in ASM implementations
563
    for(i=0; i < 8; i++)
564
        for(j=0; j < 16; j++)
565
            window[512+16*i+j] = window[64*i+32-j];
566

    
567
    for(i=0; i < 8; i++)
568
        for(j=0; j < 16; j++)
569
            window[512+128+16*i+j] = window[64*i+48-j];
570
}
571

    
572
static void apply_window_mp3_c(MPA_INT *synth_buf, MPA_INT *window,
573
                               int *dither_state, OUT_INT *samples, int incr)
574
{
575
    register const MPA_INT *w, *w2, *p;
576
    int j;
577
    OUT_INT *samples2;
578
#if CONFIG_FLOAT
579
    float sum, sum2;
580
#else
581
    int64_t sum, sum2;
582
#endif
583

    
584
    /* copy to avoid wrap */
585
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(*synth_buf));
586

    
587
    samples2 = samples + 31 * incr;
588
    w = window;
589
    w2 = window + 31;
590

    
591
    sum = *dither_state;
592
    p = synth_buf + 16;
593
    SUM8(MACS, sum, w, p);
594
    p = synth_buf + 48;
595
    SUM8(MLSS, sum, w + 32, p);
596
    *samples = round_sample(&sum);
597
    samples += incr;
598
    w++;
599

    
600
    /* we calculate two samples at the same time to avoid one memory
601
       access per two sample */
602
    for(j=1;j<16;j++) {
603
        sum2 = 0;
604
        p = synth_buf + 16 + j;
605
        SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
606
        p = synth_buf + 48 - j;
607
        SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
608

    
609
        *samples = round_sample(&sum);
610
        samples += incr;
611
        sum += sum2;
612
        *samples2 = round_sample(&sum);
613
        samples2 -= incr;
614
        w++;
615
        w2--;
616
    }
617

    
618
    p = synth_buf + 32;
619
    SUM8(MLSS, sum, w + 32, p);
620
    *samples = round_sample(&sum);
621
    *dither_state= sum;
622
}
623

    
624

    
625
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
626
   32 samples. */
627
/* XXX: optimize by avoiding ring buffer usage */
628
#if !CONFIG_FLOAT
629
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
630
                         MPA_INT *window, int *dither_state,
631
                         OUT_INT *samples, int incr,
632
                         INTFLOAT sb_samples[SBLIMIT])
633
{
634
    register MPA_INT *synth_buf;
635
    int offset;
636

    
637
    offset = *synth_buf_offset;
638
    synth_buf = synth_buf_ptr + offset;
639

    
640
    dct32(synth_buf, sb_samples);
641
    apply_window_mp3_c(synth_buf, window, dither_state, samples, incr);
642

    
643
    offset = (offset - 32) & 511;
644
    *synth_buf_offset = offset;
645
}
646
#endif
647

    
648
#define C3 FIXHR(0.86602540378443864676/2)
649

    
650
/* 0.5 / cos(pi*(2*i+1)/36) */
651
static const INTFLOAT icos36[9] = {
652
    FIXR(0.50190991877167369479),
653
    FIXR(0.51763809020504152469), //0
654
    FIXR(0.55168895948124587824),
655
    FIXR(0.61038729438072803416),
656
    FIXR(0.70710678118654752439), //1
657
    FIXR(0.87172339781054900991),
658
    FIXR(1.18310079157624925896),
659
    FIXR(1.93185165257813657349), //2
660
    FIXR(5.73685662283492756461),
661
};
662

    
663
/* 0.5 / cos(pi*(2*i+1)/36) */
664
static const INTFLOAT icos36h[9] = {
665
    FIXHR(0.50190991877167369479/2),
666
    FIXHR(0.51763809020504152469/2), //0
667
    FIXHR(0.55168895948124587824/2),
668
    FIXHR(0.61038729438072803416/2),
669
    FIXHR(0.70710678118654752439/2), //1
670
    FIXHR(0.87172339781054900991/2),
671
    FIXHR(1.18310079157624925896/4),
672
    FIXHR(1.93185165257813657349/4), //2
673
//    FIXHR(5.73685662283492756461),
674
};
675

    
676
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
677
   cases. */
678
static void imdct12(INTFLOAT *out, INTFLOAT *in)
679
{
680
    INTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
681

    
682
    in0= in[0*3];
683
    in1= in[1*3] + in[0*3];
684
    in2= in[2*3] + in[1*3];
685
    in3= in[3*3] + in[2*3];
686
    in4= in[4*3] + in[3*3];
687
    in5= in[5*3] + in[4*3];
688
    in5 += in3;
689
    in3 += in1;
690

    
691
    in2= MULH3(in2, C3, 2);
692
    in3= MULH3(in3, C3, 4);
693

    
694
    t1 = in0 - in4;
695
    t2 = MULH3(in1 - in5, icos36h[4], 2);
696

    
697
    out[ 7]=
698
    out[10]= t1 + t2;
699
    out[ 1]=
700
    out[ 4]= t1 - t2;
701

    
702
    in0 += SHR(in4, 1);
703
    in4 = in0 + in2;
704
    in5 += 2*in1;
705
    in1 = MULH3(in5 + in3, icos36h[1], 1);
706
    out[ 8]=
707
    out[ 9]= in4 + in1;
708
    out[ 2]=
709
    out[ 3]= in4 - in1;
710

    
711
    in0 -= in2;
712
    in5 = MULH3(in5 - in3, icos36h[7], 2);
713
    out[ 0]=
714
    out[ 5]= in0 - in5;
715
    out[ 6]=
716
    out[11]= in0 + in5;
717
}
718

    
719
/* cos(pi*i/18) */
720
#define C1 FIXHR(0.98480775301220805936/2)
721
#define C2 FIXHR(0.93969262078590838405/2)
722
#define C3 FIXHR(0.86602540378443864676/2)
723
#define C4 FIXHR(0.76604444311897803520/2)
724
#define C5 FIXHR(0.64278760968653932632/2)
725
#define C6 FIXHR(0.5/2)
726
#define C7 FIXHR(0.34202014332566873304/2)
727
#define C8 FIXHR(0.17364817766693034885/2)
728

    
729

    
730
/* using Lee like decomposition followed by hand coded 9 points DCT */
731
static void imdct36(INTFLOAT *out, INTFLOAT *buf, INTFLOAT *in, INTFLOAT *win)
732
{
733
    int i, j;
734
    INTFLOAT t0, t1, t2, t3, s0, s1, s2, s3;
735
    INTFLOAT tmp[18], *tmp1, *in1;
736

    
737
    for(i=17;i>=1;i--)
738
        in[i] += in[i-1];
739
    for(i=17;i>=3;i-=2)
740
        in[i] += in[i-2];
741

    
742
    for(j=0;j<2;j++) {
743
        tmp1 = tmp + j;
744
        in1 = in + j;
745

    
746
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
747

    
748
        t3 = in1[2*0] + SHR(in1[2*6],1);
749
        t1 = in1[2*0] - in1[2*6];
750
        tmp1[ 6] = t1 - SHR(t2,1);
751
        tmp1[16] = t1 + t2;
752

    
753
        t0 = MULH3(in1[2*2] + in1[2*4] ,    C2, 2);
754
        t1 = MULH3(in1[2*4] - in1[2*8] , -2*C8, 1);
755
        t2 = MULH3(in1[2*2] + in1[2*8] ,   -C4, 2);
756

    
757
        tmp1[10] = t3 - t0 - t2;
758
        tmp1[ 2] = t3 + t0 + t1;
759
        tmp1[14] = t3 + t2 - t1;
760

    
761
        tmp1[ 4] = MULH3(in1[2*5] + in1[2*7] - in1[2*1], -C3, 2);
762
        t2 = MULH3(in1[2*1] + in1[2*5],    C1, 2);
763
        t3 = MULH3(in1[2*5] - in1[2*7], -2*C7, 1);
764
        t0 = MULH3(in1[2*3], C3, 2);
765

    
766
        t1 = MULH3(in1[2*1] + in1[2*7],   -C5, 2);
767

    
768
        tmp1[ 0] = t2 + t3 + t0;
769
        tmp1[12] = t2 + t1 - t0;
770
        tmp1[ 8] = t3 - t1 - t0;
771
    }
772

    
773
    i = 0;
774
    for(j=0;j<4;j++) {
775
        t0 = tmp[i];
776
        t1 = tmp[i + 2];
777
        s0 = t1 + t0;
778
        s2 = t1 - t0;
779

    
780
        t2 = tmp[i + 1];
781
        t3 = tmp[i + 3];
782
        s1 = MULH3(t3 + t2, icos36h[j], 2);
783
        s3 = MULLx(t3 - t2, icos36[8 - j], FRAC_BITS);
784

    
785
        t0 = s0 + s1;
786
        t1 = s0 - s1;
787
        out[(9 + j)*SBLIMIT] =  MULH3(t1, win[9 + j], 1) + buf[9 + j];
788
        out[(8 - j)*SBLIMIT] =  MULH3(t1, win[8 - j], 1) + buf[8 - j];
789
        buf[9 + j] = MULH3(t0, win[18 + 9 + j], 1);
790
        buf[8 - j] = MULH3(t0, win[18 + 8 - j], 1);
791

    
792
        t0 = s2 + s3;
793
        t1 = s2 - s3;
794
        out[(9 + 8 - j)*SBLIMIT] =  MULH3(t1, win[9 + 8 - j], 1) + buf[9 + 8 - j];
795
        out[(        j)*SBLIMIT] =  MULH3(t1, win[        j], 1) + buf[        j];
796
        buf[9 + 8 - j] = MULH3(t0, win[18 + 9 + 8 - j], 1);
797
        buf[      + j] = MULH3(t0, win[18         + j], 1);
798
        i += 4;
799
    }
800

    
801
    s0 = tmp[16];
802
    s1 = MULH3(tmp[17], icos36h[4], 2);
803
    t0 = s0 + s1;
804
    t1 = s0 - s1;
805
    out[(9 + 4)*SBLIMIT] =  MULH3(t1, win[9 + 4], 1) + buf[9 + 4];
806
    out[(8 - 4)*SBLIMIT] =  MULH3(t1, win[8 - 4], 1) + buf[8 - 4];
807
    buf[9 + 4] = MULH3(t0, win[18 + 9 + 4], 1);
808
    buf[8 - 4] = MULH3(t0, win[18 + 8 - 4], 1);
809
}
810

    
811
/* return the number of decoded frames */
812
static int mp_decode_layer1(MPADecodeContext *s)
813
{
814
    int bound, i, v, n, ch, j, mant;
815
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
816
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
817

    
818
    if (s->mode == MPA_JSTEREO)
819
        bound = (s->mode_ext + 1) * 4;
820
    else
821
        bound = SBLIMIT;
822

    
823
    /* allocation bits */
824
    for(i=0;i<bound;i++) {
825
        for(ch=0;ch<s->nb_channels;ch++) {
826
            allocation[ch][i] = get_bits(&s->gb, 4);
827
        }
828
    }
829
    for(i=bound;i<SBLIMIT;i++) {
830
        allocation[0][i] = get_bits(&s->gb, 4);
831
    }
832

    
833
    /* scale factors */
834
    for(i=0;i<bound;i++) {
835
        for(ch=0;ch<s->nb_channels;ch++) {
836
            if (allocation[ch][i])
837
                scale_factors[ch][i] = get_bits(&s->gb, 6);
838
        }
839
    }
840
    for(i=bound;i<SBLIMIT;i++) {
841
        if (allocation[0][i]) {
842
            scale_factors[0][i] = get_bits(&s->gb, 6);
843
            scale_factors[1][i] = get_bits(&s->gb, 6);
844
        }
845
    }
846

    
847
    /* compute samples */
848
    for(j=0;j<12;j++) {
849
        for(i=0;i<bound;i++) {
850
            for(ch=0;ch<s->nb_channels;ch++) {
851
                n = allocation[ch][i];
852
                if (n) {
853
                    mant = get_bits(&s->gb, n + 1);
854
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
855
                } else {
856
                    v = 0;
857
                }
858
                s->sb_samples[ch][j][i] = v;
859
            }
860
        }
861
        for(i=bound;i<SBLIMIT;i++) {
862
            n = allocation[0][i];
863
            if (n) {
864
                mant = get_bits(&s->gb, n + 1);
865
                v = l1_unscale(n, mant, scale_factors[0][i]);
866
                s->sb_samples[0][j][i] = v;
867
                v = l1_unscale(n, mant, scale_factors[1][i]);
868
                s->sb_samples[1][j][i] = v;
869
            } else {
870
                s->sb_samples[0][j][i] = 0;
871
                s->sb_samples[1][j][i] = 0;
872
            }
873
        }
874
    }
875
    return 12;
876
}
877

    
878
static int mp_decode_layer2(MPADecodeContext *s)
879
{
880
    int sblimit; /* number of used subbands */
881
    const unsigned char *alloc_table;
882
    int table, bit_alloc_bits, i, j, ch, bound, v;
883
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
884
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
885
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
886
    int scale, qindex, bits, steps, k, l, m, b;
887

    
888
    /* select decoding table */
889
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
890
                            s->sample_rate, s->lsf);
891
    sblimit = ff_mpa_sblimit_table[table];
892
    alloc_table = ff_mpa_alloc_tables[table];
893

    
894
    if (s->mode == MPA_JSTEREO)
895
        bound = (s->mode_ext + 1) * 4;
896
    else
897
        bound = sblimit;
898

    
899
    av_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
900

    
901
    /* sanity check */
902
    if( bound > sblimit ) bound = sblimit;
903

    
904
    /* parse bit allocation */
905
    j = 0;
906
    for(i=0;i<bound;i++) {
907
        bit_alloc_bits = alloc_table[j];
908
        for(ch=0;ch<s->nb_channels;ch++) {
909
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
910
        }
911
        j += 1 << bit_alloc_bits;
912
    }
913
    for(i=bound;i<sblimit;i++) {
914
        bit_alloc_bits = alloc_table[j];
915
        v = get_bits(&s->gb, bit_alloc_bits);
916
        bit_alloc[0][i] = v;
917
        bit_alloc[1][i] = v;
918
        j += 1 << bit_alloc_bits;
919
    }
920

    
921
    /* scale codes */
922
    for(i=0;i<sblimit;i++) {
923
        for(ch=0;ch<s->nb_channels;ch++) {
924
            if (bit_alloc[ch][i])
925
                scale_code[ch][i] = get_bits(&s->gb, 2);
926
        }
927
    }
928

    
929
    /* scale factors */
930
    for(i=0;i<sblimit;i++) {
931
        for(ch=0;ch<s->nb_channels;ch++) {
932
            if (bit_alloc[ch][i]) {
933
                sf = scale_factors[ch][i];
934
                switch(scale_code[ch][i]) {
935
                default:
936
                case 0:
937
                    sf[0] = get_bits(&s->gb, 6);
938
                    sf[1] = get_bits(&s->gb, 6);
939
                    sf[2] = get_bits(&s->gb, 6);
940
                    break;
941
                case 2:
942
                    sf[0] = get_bits(&s->gb, 6);
943
                    sf[1] = sf[0];
944
                    sf[2] = sf[0];
945
                    break;
946
                case 1:
947
                    sf[0] = get_bits(&s->gb, 6);
948
                    sf[2] = get_bits(&s->gb, 6);
949
                    sf[1] = sf[0];
950
                    break;
951
                case 3:
952
                    sf[0] = get_bits(&s->gb, 6);
953
                    sf[2] = get_bits(&s->gb, 6);
954
                    sf[1] = sf[2];
955
                    break;
956
                }
957
            }
958
        }
959
    }
960

    
961
    /* samples */
962
    for(k=0;k<3;k++) {
963
        for(l=0;l<12;l+=3) {
964
            j = 0;
965
            for(i=0;i<bound;i++) {
966
                bit_alloc_bits = alloc_table[j];
967
                for(ch=0;ch<s->nb_channels;ch++) {
968
                    b = bit_alloc[ch][i];
969
                    if (b) {
970
                        scale = scale_factors[ch][i][k];
971
                        qindex = alloc_table[j+b];
972
                        bits = ff_mpa_quant_bits[qindex];
973
                        if (bits < 0) {
974
                            int v2;
975
                            /* 3 values at the same time */
976
                            v = get_bits(&s->gb, -bits);
977
                            v2 = division_tabs[qindex][v];
978
                            steps  = ff_mpa_quant_steps[qindex];
979

    
980
                            s->sb_samples[ch][k * 12 + l + 0][i] =
981
                                l2_unscale_group(steps, v2        & 15, scale);
982
                            s->sb_samples[ch][k * 12 + l + 1][i] =
983
                                l2_unscale_group(steps, (v2 >> 4) & 15, scale);
984
                            s->sb_samples[ch][k * 12 + l + 2][i] =
985
                                l2_unscale_group(steps,  v2 >> 8      , scale);
986
                        } else {
987
                            for(m=0;m<3;m++) {
988
                                v = get_bits(&s->gb, bits);
989
                                v = l1_unscale(bits - 1, v, scale);
990
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
991
                            }
992
                        }
993
                    } else {
994
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
995
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
996
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
997
                    }
998
                }
999
                /* next subband in alloc table */
1000
                j += 1 << bit_alloc_bits;
1001
            }
1002
            /* XXX: find a way to avoid this duplication of code */
1003
            for(i=bound;i<sblimit;i++) {
1004
                bit_alloc_bits = alloc_table[j];
1005
                b = bit_alloc[0][i];
1006
                if (b) {
1007
                    int mant, scale0, scale1;
1008
                    scale0 = scale_factors[0][i][k];
1009
                    scale1 = scale_factors[1][i][k];
1010
                    qindex = alloc_table[j+b];
1011
                    bits = ff_mpa_quant_bits[qindex];
1012
                    if (bits < 0) {
1013
                        /* 3 values at the same time */
1014
                        v = get_bits(&s->gb, -bits);
1015
                        steps = ff_mpa_quant_steps[qindex];
1016
                        mant = v % steps;
1017
                        v = v / steps;
1018
                        s->sb_samples[0][k * 12 + l + 0][i] =
1019
                            l2_unscale_group(steps, mant, scale0);
1020
                        s->sb_samples[1][k * 12 + l + 0][i] =
1021
                            l2_unscale_group(steps, mant, scale1);
1022
                        mant = v % steps;
1023
                        v = v / steps;
1024
                        s->sb_samples[0][k * 12 + l + 1][i] =
1025
                            l2_unscale_group(steps, mant, scale0);
1026
                        s->sb_samples[1][k * 12 + l + 1][i] =
1027
                            l2_unscale_group(steps, mant, scale1);
1028
                        s->sb_samples[0][k * 12 + l + 2][i] =
1029
                            l2_unscale_group(steps, v, scale0);
1030
                        s->sb_samples[1][k * 12 + l + 2][i] =
1031
                            l2_unscale_group(steps, v, scale1);
1032
                    } else {
1033
                        for(m=0;m<3;m++) {
1034
                            mant = get_bits(&s->gb, bits);
1035
                            s->sb_samples[0][k * 12 + l + m][i] =
1036
                                l1_unscale(bits - 1, mant, scale0);
1037
                            s->sb_samples[1][k * 12 + l + m][i] =
1038
                                l1_unscale(bits - 1, mant, scale1);
1039
                        }
1040
                    }
1041
                } else {
1042
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1043
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1044
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1045
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1046
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1047
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1048
                }
1049
                /* next subband in alloc table */
1050
                j += 1 << bit_alloc_bits;
1051
            }
1052
            /* fill remaining samples to zero */
1053
            for(i=sblimit;i<SBLIMIT;i++) {
1054
                for(ch=0;ch<s->nb_channels;ch++) {
1055
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1056
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1057
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1058
                }
1059
            }
1060
        }
1061
    }
1062
    return 3 * 12;
1063
}
1064

    
1065
#define SPLIT(dst,sf,n)\
1066
    if(n==3){\
1067
        int m= (sf*171)>>9;\
1068
        dst= sf - 3*m;\
1069
        sf=m;\
1070
    }else if(n==4){\
1071
        dst= sf&3;\
1072
        sf>>=2;\
1073
    }else if(n==5){\
1074
        int m= (sf*205)>>10;\
1075
        dst= sf - 5*m;\
1076
        sf=m;\
1077
    }else if(n==6){\
1078
        int m= (sf*171)>>10;\
1079
        dst= sf - 6*m;\
1080
        sf=m;\
1081
    }else{\
1082
        dst=0;\
1083
    }
1084

    
1085
static av_always_inline void lsf_sf_expand(int *slen,
1086
                                 int sf, int n1, int n2, int n3)
1087
{
1088
    SPLIT(slen[3], sf, n3)
1089
    SPLIT(slen[2], sf, n2)
1090
    SPLIT(slen[1], sf, n1)
1091
    slen[0] = sf;
1092
}
1093

    
1094
static void exponents_from_scale_factors(MPADecodeContext *s,
1095
                                         GranuleDef *g,
1096
                                         int16_t *exponents)
1097
{
1098
    const uint8_t *bstab, *pretab;
1099
    int len, i, j, k, l, v0, shift, gain, gains[3];
1100
    int16_t *exp_ptr;
1101

    
1102
    exp_ptr = exponents;
1103
    gain = g->global_gain - 210;
1104
    shift = g->scalefac_scale + 1;
1105

    
1106
    bstab = band_size_long[s->sample_rate_index];
1107
    pretab = mpa_pretab[g->preflag];
1108
    for(i=0;i<g->long_end;i++) {
1109
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1110
        len = bstab[i];
1111
        for(j=len;j>0;j--)
1112
            *exp_ptr++ = v0;
1113
    }
1114

    
1115
    if (g->short_start < 13) {
1116
        bstab = band_size_short[s->sample_rate_index];
1117
        gains[0] = gain - (g->subblock_gain[0] << 3);
1118
        gains[1] = gain - (g->subblock_gain[1] << 3);
1119
        gains[2] = gain - (g->subblock_gain[2] << 3);
1120
        k = g->long_end;
1121
        for(i=g->short_start;i<13;i++) {
1122
            len = bstab[i];
1123
            for(l=0;l<3;l++) {
1124
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1125
                for(j=len;j>0;j--)
1126
                *exp_ptr++ = v0;
1127
            }
1128
        }
1129
    }
1130
}
1131

    
1132
/* handle n = 0 too */
1133
static inline int get_bitsz(GetBitContext *s, int n)
1134
{
1135
    if (n == 0)
1136
        return 0;
1137
    else
1138
        return get_bits(s, n);
1139
}
1140

    
1141

    
1142
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1143
    if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1144
        s->gb= s->in_gb;
1145
        s->in_gb.buffer=NULL;
1146
        assert((get_bits_count(&s->gb) & 7) == 0);
1147
        skip_bits_long(&s->gb, *pos - *end_pos);
1148
        *end_pos2=
1149
        *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1150
        *pos= get_bits_count(&s->gb);
1151
    }
1152
}
1153

    
1154
/* Following is a optimized code for
1155
            INTFLOAT v = *src
1156
            if(get_bits1(&s->gb))
1157
                v = -v;
1158
            *dst = v;
1159
*/
1160
#if CONFIG_FLOAT
1161
#define READ_FLIP_SIGN(dst,src)\
1162
            v = AV_RN32A(src) ^ (get_bits1(&s->gb)<<31);\
1163
            AV_WN32A(dst, v);
1164
#else
1165
#define READ_FLIP_SIGN(dst,src)\
1166
            v= -get_bits1(&s->gb);\
1167
            *(dst) = (*(src) ^ v) - v;
1168
#endif
1169

    
1170
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1171
                          int16_t *exponents, int end_pos2)
1172
{
1173
    int s_index;
1174
    int i;
1175
    int last_pos, bits_left;
1176
    VLC *vlc;
1177
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1178

    
1179
    /* low frequencies (called big values) */
1180
    s_index = 0;
1181
    for(i=0;i<3;i++) {
1182
        int j, k, l, linbits;
1183
        j = g->region_size[i];
1184
        if (j == 0)
1185
            continue;
1186
        /* select vlc table */
1187
        k = g->table_select[i];
1188
        l = mpa_huff_data[k][0];
1189
        linbits = mpa_huff_data[k][1];
1190
        vlc = &huff_vlc[l];
1191

    
1192
        if(!l){
1193
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1194
            s_index += 2*j;
1195
            continue;
1196
        }
1197

    
1198
        /* read huffcode and compute each couple */
1199
        for(;j>0;j--) {
1200
            int exponent, x, y;
1201
            int v;
1202
            int pos= get_bits_count(&s->gb);
1203

    
1204
            if (pos >= end_pos){
1205
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1206
                switch_buffer(s, &pos, &end_pos, &end_pos2);
1207
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1208
                if(pos >= end_pos)
1209
                    break;
1210
            }
1211
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1212

    
1213
            if(!y){
1214
                g->sb_hybrid[s_index  ] =
1215
                g->sb_hybrid[s_index+1] = 0;
1216
                s_index += 2;
1217
                continue;
1218
            }
1219

    
1220
            exponent= exponents[s_index];
1221

    
1222
            av_dlog(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1223
                    i, g->region_size[i] - j, x, y, exponent);
1224
            if(y&16){
1225
                x = y >> 5;
1226
                y = y & 0x0f;
1227
                if (x < 15){
1228
                    READ_FLIP_SIGN(g->sb_hybrid+s_index, RENAME(expval_table)[ exponent ]+x)
1229
                }else{
1230
                    x += get_bitsz(&s->gb, linbits);
1231
                    v = l3_unscale(x, exponent);
1232
                    if (get_bits1(&s->gb))
1233
                        v = -v;
1234
                    g->sb_hybrid[s_index] = v;
1235
                }
1236
                if (y < 15){
1237
                    READ_FLIP_SIGN(g->sb_hybrid+s_index+1, RENAME(expval_table)[ exponent ]+y)
1238
                }else{
1239
                    y += get_bitsz(&s->gb, linbits);
1240
                    v = l3_unscale(y, exponent);
1241
                    if (get_bits1(&s->gb))
1242
                        v = -v;
1243
                    g->sb_hybrid[s_index+1] = v;
1244
                }
1245
            }else{
1246
                x = y >> 5;
1247
                y = y & 0x0f;
1248
                x += y;
1249
                if (x < 15){
1250
                    READ_FLIP_SIGN(g->sb_hybrid+s_index+!!y, RENAME(expval_table)[ exponent ]+x)
1251
                }else{
1252
                    x += get_bitsz(&s->gb, linbits);
1253
                    v = l3_unscale(x, exponent);
1254
                    if (get_bits1(&s->gb))
1255
                        v = -v;
1256
                    g->sb_hybrid[s_index+!!y] = v;
1257
                }
1258
                g->sb_hybrid[s_index+ !y] = 0;
1259
            }
1260
            s_index+=2;
1261
        }
1262
    }
1263

    
1264
    /* high frequencies */
1265
    vlc = &huff_quad_vlc[g->count1table_select];
1266
    last_pos=0;
1267
    while (s_index <= 572) {
1268
        int pos, code;
1269
        pos = get_bits_count(&s->gb);
1270
        if (pos >= end_pos) {
1271
            if (pos > end_pos2 && last_pos){
1272
                /* some encoders generate an incorrect size for this
1273
                   part. We must go back into the data */
1274
                s_index -= 4;
1275
                skip_bits_long(&s->gb, last_pos - pos);
1276
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1277
                if(s->error_recognition >= FF_ER_COMPLIANT)
1278
                    s_index=0;
1279
                break;
1280
            }
1281
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1282
            switch_buffer(s, &pos, &end_pos, &end_pos2);
1283
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1284
            if(pos >= end_pos)
1285
                break;
1286
        }
1287
        last_pos= pos;
1288

    
1289
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1290
        av_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1291
        g->sb_hybrid[s_index+0]=
1292
        g->sb_hybrid[s_index+1]=
1293
        g->sb_hybrid[s_index+2]=
1294
        g->sb_hybrid[s_index+3]= 0;
1295
        while(code){
1296
            static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1297
            int v;
1298
            int pos= s_index+idxtab[code];
1299
            code ^= 8>>idxtab[code];
1300
            READ_FLIP_SIGN(g->sb_hybrid+pos, RENAME(exp_table)+exponents[pos])
1301
        }
1302
        s_index+=4;
1303
    }
1304
    /* skip extension bits */
1305
    bits_left = end_pos2 - get_bits_count(&s->gb);
1306
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1307
    if (bits_left < 0 && s->error_recognition >= FF_ER_COMPLIANT) {
1308
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1309
        s_index=0;
1310
    }else if(bits_left > 0 && s->error_recognition >= FF_ER_AGGRESSIVE){
1311
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1312
        s_index=0;
1313
    }
1314
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1315
    skip_bits_long(&s->gb, bits_left);
1316

    
1317
    i= get_bits_count(&s->gb);
1318
    switch_buffer(s, &i, &end_pos, &end_pos2);
1319

    
1320
    return 0;
1321
}
1322

    
1323
/* Reorder short blocks from bitstream order to interleaved order. It
1324
   would be faster to do it in parsing, but the code would be far more
1325
   complicated */
1326
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1327
{
1328
    int i, j, len;
1329
    INTFLOAT *ptr, *dst, *ptr1;
1330
    INTFLOAT tmp[576];
1331

    
1332
    if (g->block_type != 2)
1333
        return;
1334

    
1335
    if (g->switch_point) {
1336
        if (s->sample_rate_index != 8) {
1337
            ptr = g->sb_hybrid + 36;
1338
        } else {
1339
            ptr = g->sb_hybrid + 48;
1340
        }
1341
    } else {
1342
        ptr = g->sb_hybrid;
1343
    }
1344

    
1345
    for(i=g->short_start;i<13;i++) {
1346
        len = band_size_short[s->sample_rate_index][i];
1347
        ptr1 = ptr;
1348
        dst = tmp;
1349
        for(j=len;j>0;j--) {
1350
            *dst++ = ptr[0*len];
1351
            *dst++ = ptr[1*len];
1352
            *dst++ = ptr[2*len];
1353
            ptr++;
1354
        }
1355
        ptr+=2*len;
1356
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1357
    }
1358
}
1359

    
1360
#define ISQRT2 FIXR(0.70710678118654752440)
1361

    
1362
static void compute_stereo(MPADecodeContext *s,
1363
                           GranuleDef *g0, GranuleDef *g1)
1364
{
1365
    int i, j, k, l;
1366
    int sf_max, sf, len, non_zero_found;
1367
    INTFLOAT (*is_tab)[16], *tab0, *tab1, tmp0, tmp1, v1, v2;
1368
    int non_zero_found_short[3];
1369

    
1370
    /* intensity stereo */
1371
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1372
        if (!s->lsf) {
1373
            is_tab = is_table;
1374
            sf_max = 7;
1375
        } else {
1376
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1377
            sf_max = 16;
1378
        }
1379

    
1380
        tab0 = g0->sb_hybrid + 576;
1381
        tab1 = g1->sb_hybrid + 576;
1382

    
1383
        non_zero_found_short[0] = 0;
1384
        non_zero_found_short[1] = 0;
1385
        non_zero_found_short[2] = 0;
1386
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1387
        for(i = 12;i >= g1->short_start;i--) {
1388
            /* for last band, use previous scale factor */
1389
            if (i != 11)
1390
                k -= 3;
1391
            len = band_size_short[s->sample_rate_index][i];
1392
            for(l=2;l>=0;l--) {
1393
                tab0 -= len;
1394
                tab1 -= len;
1395
                if (!non_zero_found_short[l]) {
1396
                    /* test if non zero band. if so, stop doing i-stereo */
1397
                    for(j=0;j<len;j++) {
1398
                        if (tab1[j] != 0) {
1399
                            non_zero_found_short[l] = 1;
1400
                            goto found1;
1401
                        }
1402
                    }
1403
                    sf = g1->scale_factors[k + l];
1404
                    if (sf >= sf_max)
1405
                        goto found1;
1406

    
1407
                    v1 = is_tab[0][sf];
1408
                    v2 = is_tab[1][sf];
1409
                    for(j=0;j<len;j++) {
1410
                        tmp0 = tab0[j];
1411
                        tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1412
                        tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1413
                    }
1414
                } else {
1415
                found1:
1416
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1417
                        /* lower part of the spectrum : do ms stereo
1418
                           if enabled */
1419
                        for(j=0;j<len;j++) {
1420
                            tmp0 = tab0[j];
1421
                            tmp1 = tab1[j];
1422
                            tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1423
                            tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1424
                        }
1425
                    }
1426
                }
1427
            }
1428
        }
1429

    
1430
        non_zero_found = non_zero_found_short[0] |
1431
            non_zero_found_short[1] |
1432
            non_zero_found_short[2];
1433

    
1434
        for(i = g1->long_end - 1;i >= 0;i--) {
1435
            len = band_size_long[s->sample_rate_index][i];
1436
            tab0 -= len;
1437
            tab1 -= len;
1438
            /* test if non zero band. if so, stop doing i-stereo */
1439
            if (!non_zero_found) {
1440
                for(j=0;j<len;j++) {
1441
                    if (tab1[j] != 0) {
1442
                        non_zero_found = 1;
1443
                        goto found2;
1444
                    }
1445
                }
1446
                /* for last band, use previous scale factor */
1447
                k = (i == 21) ? 20 : i;
1448
                sf = g1->scale_factors[k];
1449
                if (sf >= sf_max)
1450
                    goto found2;
1451
                v1 = is_tab[0][sf];
1452
                v2 = is_tab[1][sf];
1453
                for(j=0;j<len;j++) {
1454
                    tmp0 = tab0[j];
1455
                    tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1456
                    tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1457
                }
1458
            } else {
1459
            found2:
1460
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1461
                    /* lower part of the spectrum : do ms stereo
1462
                       if enabled */
1463
                    for(j=0;j<len;j++) {
1464
                        tmp0 = tab0[j];
1465
                        tmp1 = tab1[j];
1466
                        tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1467
                        tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1468
                    }
1469
                }
1470
            }
1471
        }
1472
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1473
        /* ms stereo ONLY */
1474
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1475
           global gain */
1476
        tab0 = g0->sb_hybrid;
1477
        tab1 = g1->sb_hybrid;
1478
        for(i=0;i<576;i++) {
1479
            tmp0 = tab0[i];
1480
            tmp1 = tab1[i];
1481
            tab0[i] = tmp0 + tmp1;
1482
            tab1[i] = tmp0 - tmp1;
1483
        }
1484
    }
1485
}
1486

    
1487
#if !CONFIG_FLOAT
1488
static void compute_antialias_integer(MPADecodeContext *s,
1489
                              GranuleDef *g)
1490
{
1491
    int32_t *ptr, *csa;
1492
    int n, i;
1493

    
1494
    /* we antialias only "long" bands */
1495
    if (g->block_type == 2) {
1496
        if (!g->switch_point)
1497
            return;
1498
        /* XXX: check this for 8000Hz case */
1499
        n = 1;
1500
    } else {
1501
        n = SBLIMIT - 1;
1502
    }
1503

    
1504
    ptr = g->sb_hybrid + 18;
1505
    for(i = n;i > 0;i--) {
1506
        int tmp0, tmp1, tmp2;
1507
        csa = &csa_table[0][0];
1508
#define INT_AA(j) \
1509
            tmp0 = ptr[-1-j];\
1510
            tmp1 = ptr[   j];\
1511
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1512
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1513
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1514

    
1515
        INT_AA(0)
1516
        INT_AA(1)
1517
        INT_AA(2)
1518
        INT_AA(3)
1519
        INT_AA(4)
1520
        INT_AA(5)
1521
        INT_AA(6)
1522
        INT_AA(7)
1523

    
1524
        ptr += 18;
1525
    }
1526
}
1527
#endif
1528

    
1529
static void compute_imdct(MPADecodeContext *s,
1530
                          GranuleDef *g,
1531
                          INTFLOAT *sb_samples,
1532
                          INTFLOAT *mdct_buf)
1533
{
1534
    INTFLOAT *win, *win1, *out_ptr, *ptr, *buf, *ptr1;
1535
    INTFLOAT out2[12];
1536
    int i, j, mdct_long_end, sblimit;
1537

    
1538
    /* find last non zero block */
1539
    ptr = g->sb_hybrid + 576;
1540
    ptr1 = g->sb_hybrid + 2 * 18;
1541
    while (ptr >= ptr1) {
1542
        int32_t *p;
1543
        ptr -= 6;
1544
        p= (int32_t*)ptr;
1545
        if(p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1546
            break;
1547
    }
1548
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1549

    
1550
    if (g->block_type == 2) {
1551
        /* XXX: check for 8000 Hz */
1552
        if (g->switch_point)
1553
            mdct_long_end = 2;
1554
        else
1555
            mdct_long_end = 0;
1556
    } else {
1557
        mdct_long_end = sblimit;
1558
    }
1559

    
1560
    buf = mdct_buf;
1561
    ptr = g->sb_hybrid;
1562
    for(j=0;j<mdct_long_end;j++) {
1563
        /* apply window & overlap with previous buffer */
1564
        out_ptr = sb_samples + j;
1565
        /* select window */
1566
        if (g->switch_point && j < 2)
1567
            win1 = mdct_win[0];
1568
        else
1569
            win1 = mdct_win[g->block_type];
1570
        /* select frequency inversion */
1571
        win = win1 + ((4 * 36) & -(j & 1));
1572
        imdct36(out_ptr, buf, ptr, win);
1573
        out_ptr += 18*SBLIMIT;
1574
        ptr += 18;
1575
        buf += 18;
1576
    }
1577
    for(j=mdct_long_end;j<sblimit;j++) {
1578
        /* select frequency inversion */
1579
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
1580
        out_ptr = sb_samples + j;
1581

    
1582
        for(i=0; i<6; i++){
1583
            *out_ptr = buf[i];
1584
            out_ptr += SBLIMIT;
1585
        }
1586
        imdct12(out2, ptr + 0);
1587
        for(i=0;i<6;i++) {
1588
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*1];
1589
            buf[i + 6*2] = MULH3(out2[i + 6], win[i + 6], 1);
1590
            out_ptr += SBLIMIT;
1591
        }
1592
        imdct12(out2, ptr + 1);
1593
        for(i=0;i<6;i++) {
1594
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*2];
1595
            buf[i + 6*0] = MULH3(out2[i + 6], win[i + 6], 1);
1596
            out_ptr += SBLIMIT;
1597
        }
1598
        imdct12(out2, ptr + 2);
1599
        for(i=0;i<6;i++) {
1600
            buf[i + 6*0] = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*0];
1601
            buf[i + 6*1] = MULH3(out2[i + 6], win[i + 6], 1);
1602
            buf[i + 6*2] = 0;
1603
        }
1604
        ptr += 18;
1605
        buf += 18;
1606
    }
1607
    /* zero bands */
1608
    for(j=sblimit;j<SBLIMIT;j++) {
1609
        /* overlap */
1610
        out_ptr = sb_samples + j;
1611
        for(i=0;i<18;i++) {
1612
            *out_ptr = buf[i];
1613
            buf[i] = 0;
1614
            out_ptr += SBLIMIT;
1615
        }
1616
        buf += 18;
1617
    }
1618
}
1619

    
1620
/* main layer3 decoding function */
1621
static int mp_decode_layer3(MPADecodeContext *s)
1622
{
1623
    int nb_granules, main_data_begin, private_bits;
1624
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1625
    GranuleDef *g;
1626
    int16_t exponents[576]; //FIXME try INTFLOAT
1627

    
1628
    /* read side info */
1629
    if (s->lsf) {
1630
        main_data_begin = get_bits(&s->gb, 8);
1631
        private_bits = get_bits(&s->gb, s->nb_channels);
1632
        nb_granules = 1;
1633
    } else {
1634
        main_data_begin = get_bits(&s->gb, 9);
1635
        if (s->nb_channels == 2)
1636
            private_bits = get_bits(&s->gb, 3);
1637
        else
1638
            private_bits = get_bits(&s->gb, 5);
1639
        nb_granules = 2;
1640
        for(ch=0;ch<s->nb_channels;ch++) {
1641
            s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1642
            s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1643
        }
1644
    }
1645

    
1646
    for(gr=0;gr<nb_granules;gr++) {
1647
        for(ch=0;ch<s->nb_channels;ch++) {
1648
            av_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1649
            g = &s->granules[ch][gr];
1650
            g->part2_3_length = get_bits(&s->gb, 12);
1651
            g->big_values = get_bits(&s->gb, 9);
1652
            if(g->big_values > 288){
1653
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1654
                return -1;
1655
            }
1656

    
1657
            g->global_gain = get_bits(&s->gb, 8);
1658
            /* if MS stereo only is selected, we precompute the
1659
               1/sqrt(2) renormalization factor */
1660
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1661
                MODE_EXT_MS_STEREO)
1662
                g->global_gain -= 2;
1663
            if (s->lsf)
1664
                g->scalefac_compress = get_bits(&s->gb, 9);
1665
            else
1666
                g->scalefac_compress = get_bits(&s->gb, 4);
1667
            blocksplit_flag = get_bits1(&s->gb);
1668
            if (blocksplit_flag) {
1669
                g->block_type = get_bits(&s->gb, 2);
1670
                if (g->block_type == 0){
1671
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1672
                    return -1;
1673
                }
1674
                g->switch_point = get_bits1(&s->gb);
1675
                for(i=0;i<2;i++)
1676
                    g->table_select[i] = get_bits(&s->gb, 5);
1677
                for(i=0;i<3;i++)
1678
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
1679
                ff_init_short_region(s, g);
1680
            } else {
1681
                int region_address1, region_address2;
1682
                g->block_type = 0;
1683
                g->switch_point = 0;
1684
                for(i=0;i<3;i++)
1685
                    g->table_select[i] = get_bits(&s->gb, 5);
1686
                /* compute huffman coded region sizes */
1687
                region_address1 = get_bits(&s->gb, 4);
1688
                region_address2 = get_bits(&s->gb, 3);
1689
                av_dlog(s->avctx, "region1=%d region2=%d\n",
1690
                        region_address1, region_address2);
1691
                ff_init_long_region(s, g, region_address1, region_address2);
1692
            }
1693
            ff_region_offset2size(g);
1694
            ff_compute_band_indexes(s, g);
1695

    
1696
            g->preflag = 0;
1697
            if (!s->lsf)
1698
                g->preflag = get_bits1(&s->gb);
1699
            g->scalefac_scale = get_bits1(&s->gb);
1700
            g->count1table_select = get_bits1(&s->gb);
1701
            av_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1702
                    g->block_type, g->switch_point);
1703
        }
1704
    }
1705

    
1706
  if (!s->adu_mode) {
1707
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
1708
    assert((get_bits_count(&s->gb) & 7) == 0);
1709
    /* now we get bits from the main_data_begin offset */
1710
    av_dlog(s->avctx, "seekback: %d\n", main_data_begin);
1711
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
1712

    
1713
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
1714
    s->in_gb= s->gb;
1715
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
1716
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
1717
  }
1718

    
1719
    for(gr=0;gr<nb_granules;gr++) {
1720
        for(ch=0;ch<s->nb_channels;ch++) {
1721
            g = &s->granules[ch][gr];
1722
            if(get_bits_count(&s->gb)<0){
1723
                av_log(s->avctx, AV_LOG_DEBUG, "mdb:%d, lastbuf:%d skipping granule %d\n",
1724
                                            main_data_begin, s->last_buf_size, gr);
1725
                skip_bits_long(&s->gb, g->part2_3_length);
1726
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1727
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
1728
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
1729
                    s->gb= s->in_gb;
1730
                    s->in_gb.buffer=NULL;
1731
                }
1732
                continue;
1733
            }
1734

    
1735
            bits_pos = get_bits_count(&s->gb);
1736

    
1737
            if (!s->lsf) {
1738
                uint8_t *sc;
1739
                int slen, slen1, slen2;
1740

    
1741
                /* MPEG1 scale factors */
1742
                slen1 = slen_table[0][g->scalefac_compress];
1743
                slen2 = slen_table[1][g->scalefac_compress];
1744
                av_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1745
                if (g->block_type == 2) {
1746
                    n = g->switch_point ? 17 : 18;
1747
                    j = 0;
1748
                    if(slen1){
1749
                        for(i=0;i<n;i++)
1750
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
1751
                    }else{
1752
                        for(i=0;i<n;i++)
1753
                            g->scale_factors[j++] = 0;
1754
                    }
1755
                    if(slen2){
1756
                        for(i=0;i<18;i++)
1757
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
1758
                        for(i=0;i<3;i++)
1759
                            g->scale_factors[j++] = 0;
1760
                    }else{
1761
                        for(i=0;i<21;i++)
1762
                            g->scale_factors[j++] = 0;
1763
                    }
1764
                } else {
1765
                    sc = s->granules[ch][0].scale_factors;
1766
                    j = 0;
1767
                    for(k=0;k<4;k++) {
1768
                        n = (k == 0 ? 6 : 5);
1769
                        if ((g->scfsi & (0x8 >> k)) == 0) {
1770
                            slen = (k < 2) ? slen1 : slen2;
1771
                            if(slen){
1772
                                for(i=0;i<n;i++)
1773
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
1774
                            }else{
1775
                                for(i=0;i<n;i++)
1776
                                    g->scale_factors[j++] = 0;
1777
                            }
1778
                        } else {
1779
                            /* simply copy from last granule */
1780
                            for(i=0;i<n;i++) {
1781
                                g->scale_factors[j] = sc[j];
1782
                                j++;
1783
                            }
1784
                        }
1785
                    }
1786
                    g->scale_factors[j++] = 0;
1787
                }
1788
            } else {
1789
                int tindex, tindex2, slen[4], sl, sf;
1790

    
1791
                /* LSF scale factors */
1792
                if (g->block_type == 2) {
1793
                    tindex = g->switch_point ? 2 : 1;
1794
                } else {
1795
                    tindex = 0;
1796
                }
1797
                sf = g->scalefac_compress;
1798
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1799
                    /* intensity stereo case */
1800
                    sf >>= 1;
1801
                    if (sf < 180) {
1802
                        lsf_sf_expand(slen, sf, 6, 6, 0);
1803
                        tindex2 = 3;
1804
                    } else if (sf < 244) {
1805
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1806
                        tindex2 = 4;
1807
                    } else {
1808
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1809
                        tindex2 = 5;
1810
                    }
1811
                } else {
1812
                    /* normal case */
1813
                    if (sf < 400) {
1814
                        lsf_sf_expand(slen, sf, 5, 4, 4);
1815
                        tindex2 = 0;
1816
                    } else if (sf < 500) {
1817
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1818
                        tindex2 = 1;
1819
                    } else {
1820
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1821
                        tindex2 = 2;
1822
                        g->preflag = 1;
1823
                    }
1824
                }
1825

    
1826
                j = 0;
1827
                for(k=0;k<4;k++) {
1828
                    n = lsf_nsf_table[tindex2][tindex][k];
1829
                    sl = slen[k];
1830
                    if(sl){
1831
                        for(i=0;i<n;i++)
1832
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
1833
                    }else{
1834
                        for(i=0;i<n;i++)
1835
                            g->scale_factors[j++] = 0;
1836
                    }
1837
                }
1838
                /* XXX: should compute exact size */
1839
                for(;j<40;j++)
1840
                    g->scale_factors[j] = 0;
1841
            }
1842

    
1843
            exponents_from_scale_factors(s, g, exponents);
1844

    
1845
            /* read Huffman coded residue */
1846
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1847
        } /* ch */
1848

    
1849
        if (s->nb_channels == 2)
1850
            compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1851

    
1852
        for(ch=0;ch<s->nb_channels;ch++) {
1853
            g = &s->granules[ch][gr];
1854

    
1855
            reorder_block(s, g);
1856
            compute_antialias(s, g);
1857
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1858
        }
1859
    } /* gr */
1860
    if(get_bits_count(&s->gb)<0)
1861
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1862
    return nb_granules * 18;
1863
}
1864

    
1865
static int mp_decode_frame(MPADecodeContext *s,
1866
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
1867
{
1868
    int i, nb_frames, ch;
1869
    OUT_INT *samples_ptr;
1870

    
1871
    init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE)*8);
1872

    
1873
    /* skip error protection field */
1874
    if (s->error_protection)
1875
        skip_bits(&s->gb, 16);
1876

    
1877
    av_dlog(s->avctx, "frame %d:\n", s->frame_count);
1878
    switch(s->layer) {
1879
    case 1:
1880
        s->avctx->frame_size = 384;
1881
        nb_frames = mp_decode_layer1(s);
1882
        break;
1883
    case 2:
1884
        s->avctx->frame_size = 1152;
1885
        nb_frames = mp_decode_layer2(s);
1886
        break;
1887
    case 3:
1888
        s->avctx->frame_size = s->lsf ? 576 : 1152;
1889
    default:
1890
        nb_frames = mp_decode_layer3(s);
1891

    
1892
        s->last_buf_size=0;
1893
        if(s->in_gb.buffer){
1894
            align_get_bits(&s->gb);
1895
            i= get_bits_left(&s->gb)>>3;
1896
            if(i >= 0 && i <= BACKSTEP_SIZE){
1897
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
1898
                s->last_buf_size=i;
1899
            }else
1900
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1901
            s->gb= s->in_gb;
1902
            s->in_gb.buffer= NULL;
1903
        }
1904

    
1905
        align_get_bits(&s->gb);
1906
        assert((get_bits_count(&s->gb) & 7) == 0);
1907
        i= get_bits_left(&s->gb)>>3;
1908

    
1909
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
1910
            if(i<0)
1911
                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1912
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1913
        }
1914
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
1915
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1916
        s->last_buf_size += i;
1917

    
1918
        break;
1919
    }
1920

    
1921
    /* apply the synthesis filter */
1922
    for(ch=0;ch<s->nb_channels;ch++) {
1923
        samples_ptr = samples + ch;
1924
        for(i=0;i<nb_frames;i++) {
1925
            RENAME(ff_mpa_synth_filter)(
1926
#if CONFIG_FLOAT
1927
                         s,
1928
#endif
1929
                         s->synth_buf[ch], &(s->synth_buf_offset[ch]),
1930
                         RENAME(ff_mpa_synth_window), &s->dither_state,
1931
                         samples_ptr, s->nb_channels,
1932
                         s->sb_samples[ch][i]);
1933
            samples_ptr += 32 * s->nb_channels;
1934
        }
1935
    }
1936

    
1937
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1938
}
1939

    
1940
static int decode_frame(AVCodecContext * avctx,
1941
                        void *data, int *data_size,
1942
                        AVPacket *avpkt)
1943
{
1944
    const uint8_t *buf = avpkt->data;
1945
    int buf_size = avpkt->size;
1946
    MPADecodeContext *s = avctx->priv_data;
1947
    uint32_t header;
1948
    int out_size;
1949
    OUT_INT *out_samples = data;
1950

    
1951
    if(buf_size < HEADER_SIZE)
1952
        return -1;
1953

    
1954
    header = AV_RB32(buf);
1955
    if(ff_mpa_check_header(header) < 0){
1956
        av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1957
        return -1;
1958
    }
1959

    
1960
    if (ff_mpegaudio_decode_header((MPADecodeHeader *)s, header) == 1) {
1961
        /* free format: prepare to compute frame size */
1962
        s->frame_size = -1;
1963
        return -1;
1964
    }
1965
    /* update codec info */
1966
    avctx->channels = s->nb_channels;
1967
    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1968
    if (!avctx->bit_rate)
1969
        avctx->bit_rate = s->bit_rate;
1970
    avctx->sub_id = s->layer;
1971

    
1972
    if(*data_size < 1152*avctx->channels*sizeof(OUT_INT))
1973
        return -1;
1974
    *data_size = 0;
1975

    
1976
    if(s->frame_size<=0 || s->frame_size > buf_size){
1977
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1978
        return -1;
1979
    }else if(s->frame_size < buf_size){
1980
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
1981
        buf_size= s->frame_size;
1982
    }
1983

    
1984
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
1985
    if(out_size>=0){
1986
        *data_size = out_size;
1987
        avctx->sample_rate = s->sample_rate;
1988
        //FIXME maybe move the other codec info stuff from above here too
1989
    }else
1990
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
1991
    s->frame_size = 0;
1992
    return buf_size;
1993
}
1994

    
1995
static void flush(AVCodecContext *avctx){
1996
    MPADecodeContext *s = avctx->priv_data;
1997
    memset(s->synth_buf, 0, sizeof(s->synth_buf));
1998
    s->last_buf_size= 0;
1999
}
2000

    
2001
#if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
2002
static int decode_frame_adu(AVCodecContext * avctx,
2003
                        void *data, int *data_size,
2004
                        AVPacket *avpkt)
2005
{
2006
    const uint8_t *buf = avpkt->data;
2007
    int buf_size = avpkt->size;
2008
    MPADecodeContext *s = avctx->priv_data;
2009
    uint32_t header;
2010
    int len, out_size;
2011
    OUT_INT *out_samples = data;
2012

    
2013
    len = buf_size;
2014

    
2015
    // Discard too short frames
2016
    if (buf_size < HEADER_SIZE) {
2017
        *data_size = 0;
2018
        return buf_size;
2019
    }
2020

    
2021

    
2022
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2023
        len = MPA_MAX_CODED_FRAME_SIZE;
2024

    
2025
    // Get header and restore sync word
2026
    header = AV_RB32(buf) | 0xffe00000;
2027

    
2028
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2029
        *data_size = 0;
2030
        return buf_size;
2031
    }
2032

    
2033
    ff_mpegaudio_decode_header((MPADecodeHeader *)s, header);
2034
    /* update codec info */
2035
    avctx->sample_rate = s->sample_rate;
2036
    avctx->channels = s->nb_channels;
2037
    if (!avctx->bit_rate)
2038
        avctx->bit_rate = s->bit_rate;
2039
    avctx->sub_id = s->layer;
2040

    
2041
    s->frame_size = len;
2042

    
2043
    if (avctx->parse_only) {
2044
        out_size = buf_size;
2045
    } else {
2046
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2047
    }
2048

    
2049
    *data_size = out_size;
2050
    return buf_size;
2051
}
2052
#endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
2053

    
2054
#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
2055

    
2056
/**
2057
 * Context for MP3On4 decoder
2058
 */
2059
typedef struct MP3On4DecodeContext {
2060
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
2061
    int syncword; ///< syncword patch
2062
    const uint8_t *coff; ///< channels offsets in output buffer
2063
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
2064
} MP3On4DecodeContext;
2065

    
2066
#include "mpeg4audio.h"
2067

    
2068
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2069
static const uint8_t mp3Frames[8] = {0,1,1,2,3,3,4,5};   /* number of mp3 decoder instances */
2070
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2071
static const uint8_t chan_offset[8][5] = {
2072
    {0},
2073
    {0},            // C
2074
    {0},            // FLR
2075
    {2,0},          // C FLR
2076
    {2,0,3},        // C FLR BS
2077
    {4,0,2},        // C FLR BLRS
2078
    {4,0,2,5},      // C FLR BLRS LFE
2079
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2080
};
2081

    
2082

    
2083
static int decode_init_mp3on4(AVCodecContext * avctx)
2084
{
2085
    MP3On4DecodeContext *s = avctx->priv_data;
2086
    MPEG4AudioConfig cfg;
2087
    int i;
2088

    
2089
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2090
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2091
        return -1;
2092
    }
2093

    
2094
    ff_mpeg4audio_get_config(&cfg, avctx->extradata, avctx->extradata_size);
2095
    if (!cfg.chan_config || cfg.chan_config > 7) {
2096
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2097
        return -1;
2098
    }
2099
    s->frames = mp3Frames[cfg.chan_config];
2100
    s->coff = chan_offset[cfg.chan_config];
2101
    avctx->channels = ff_mpeg4audio_channels[cfg.chan_config];
2102

    
2103
    if (cfg.sample_rate < 16000)
2104
        s->syncword = 0xffe00000;
2105
    else
2106
        s->syncword = 0xfff00000;
2107

    
2108
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2109
     * We replace avctx->priv_data with the context of the first decoder so that
2110
     * decode_init() does not have to be changed.
2111
     * Other decoders will be initialized here copying data from the first context
2112
     */
2113
    // Allocate zeroed memory for the first decoder context
2114
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2115
    // Put decoder context in place to make init_decode() happy
2116
    avctx->priv_data = s->mp3decctx[0];
2117
    decode_init(avctx);
2118
    // Restore mp3on4 context pointer
2119
    avctx->priv_data = s;
2120
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2121

    
2122
    /* Create a separate codec/context for each frame (first is already ok).
2123
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2124
     */
2125
    for (i = 1; i < s->frames; i++) {
2126
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2127
        s->mp3decctx[i]->adu_mode = 1;
2128
        s->mp3decctx[i]->avctx = avctx;
2129
    }
2130

    
2131
    return 0;
2132
}
2133

    
2134

    
2135
static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
2136
{
2137
    MP3On4DecodeContext *s = avctx->priv_data;
2138
    int i;
2139

    
2140
    for (i = 0; i < s->frames; i++)
2141
        av_free(s->mp3decctx[i]);
2142

    
2143
    return 0;
2144
}
2145

    
2146

    
2147
static int decode_frame_mp3on4(AVCodecContext * avctx,
2148
                        void *data, int *data_size,
2149
                        AVPacket *avpkt)
2150
{
2151
    const uint8_t *buf = avpkt->data;
2152
    int buf_size = avpkt->size;
2153
    MP3On4DecodeContext *s = avctx->priv_data;
2154
    MPADecodeContext *m;
2155
    int fsize, len = buf_size, out_size = 0;
2156
    uint32_t header;
2157
    OUT_INT *out_samples = data;
2158
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2159
    OUT_INT *outptr, *bp;
2160
    int fr, j, n;
2161

    
2162
    if(*data_size < MPA_FRAME_SIZE * MPA_MAX_CHANNELS * s->frames * sizeof(OUT_INT))
2163
        return -1;
2164

    
2165
    *data_size = 0;
2166
    // Discard too short frames
2167
    if (buf_size < HEADER_SIZE)
2168
        return -1;
2169

    
2170
    // If only one decoder interleave is not needed
2171
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2172

    
2173
    avctx->bit_rate = 0;
2174

    
2175
    for (fr = 0; fr < s->frames; fr++) {
2176
        fsize = AV_RB16(buf) >> 4;
2177
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
2178
        m = s->mp3decctx[fr];
2179
        assert (m != NULL);
2180

    
2181
        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
2182

    
2183
        if (ff_mpa_check_header(header) < 0) // Bad header, discard block
2184
            break;
2185

    
2186
        ff_mpegaudio_decode_header((MPADecodeHeader *)m, header);
2187
        out_size += mp_decode_frame(m, outptr, buf, fsize);
2188
        buf += fsize;
2189
        len -= fsize;
2190

    
2191
        if(s->frames > 1) {
2192
            n = m->avctx->frame_size*m->nb_channels;
2193
            /* interleave output data */
2194
            bp = out_samples + s->coff[fr];
2195
            if(m->nb_channels == 1) {
2196
                for(j = 0; j < n; j++) {
2197
                    *bp = decoded_buf[j];
2198
                    bp += avctx->channels;
2199
                }
2200
            } else {
2201
                for(j = 0; j < n; j++) {
2202
                    bp[0] = decoded_buf[j++];
2203
                    bp[1] = decoded_buf[j];
2204
                    bp += avctx->channels;
2205
                }
2206
            }
2207
        }
2208
        avctx->bit_rate += m->bit_rate;
2209
    }
2210

    
2211
    /* update codec info */
2212
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2213

    
2214
    *data_size = out_size;
2215
    return buf_size;
2216
}
2217
#endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */
2218

    
2219
#if !CONFIG_FLOAT
2220
#if CONFIG_MP1_DECODER
2221
AVCodec ff_mp1_decoder =
2222
{
2223
    "mp1",
2224
    AVMEDIA_TYPE_AUDIO,
2225
    CODEC_ID_MP1,
2226
    sizeof(MPADecodeContext),
2227
    decode_init,
2228
    NULL,
2229
    NULL,
2230
    decode_frame,
2231
    CODEC_CAP_PARSE_ONLY,
2232
    .flush= flush,
2233
    .long_name= NULL_IF_CONFIG_SMALL("MP1 (MPEG audio layer 1)"),
2234
};
2235
#endif
2236
#if CONFIG_MP2_DECODER
2237
AVCodec ff_mp2_decoder =
2238
{
2239
    "mp2",
2240
    AVMEDIA_TYPE_AUDIO,
2241
    CODEC_ID_MP2,
2242
    sizeof(MPADecodeContext),
2243
    decode_init,
2244
    NULL,
2245
    NULL,
2246
    decode_frame,
2247
    CODEC_CAP_PARSE_ONLY,
2248
    .flush= flush,
2249
    .long_name= NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
2250
};
2251
#endif
2252
#if CONFIG_MP3_DECODER
2253
AVCodec ff_mp3_decoder =
2254
{
2255
    "mp3",
2256
    AVMEDIA_TYPE_AUDIO,
2257
    CODEC_ID_MP3,
2258
    sizeof(MPADecodeContext),
2259
    decode_init,
2260
    NULL,
2261
    NULL,
2262
    decode_frame,
2263
    CODEC_CAP_PARSE_ONLY,
2264
    .flush= flush,
2265
    .long_name= NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
2266
};
2267
#endif
2268
#if CONFIG_MP3ADU_DECODER
2269
AVCodec ff_mp3adu_decoder =
2270
{
2271
    "mp3adu",
2272
    AVMEDIA_TYPE_AUDIO,
2273
    CODEC_ID_MP3ADU,
2274
    sizeof(MPADecodeContext),
2275
    decode_init,
2276
    NULL,
2277
    NULL,
2278
    decode_frame_adu,
2279
    CODEC_CAP_PARSE_ONLY,
2280
    .flush= flush,
2281
    .long_name= NULL_IF_CONFIG_SMALL("ADU (Application Data Unit) MP3 (MPEG audio layer 3)"),
2282
};
2283
#endif
2284
#if CONFIG_MP3ON4_DECODER
2285
AVCodec ff_mp3on4_decoder =
2286
{
2287
    "mp3on4",
2288
    AVMEDIA_TYPE_AUDIO,
2289
    CODEC_ID_MP3ON4,
2290
    sizeof(MP3On4DecodeContext),
2291
    decode_init_mp3on4,
2292
    NULL,
2293
    decode_close_mp3on4,
2294
    decode_frame_mp3on4,
2295
    .flush= flush,
2296
    .long_name= NULL_IF_CONFIG_SMALL("MP3onMP4"),
2297
};
2298
#endif
2299
#endif