Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 0d849074

History | View | Annotate | Download (70.9 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

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

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

    
40
#include "mathops.h"
41

    
42
#if CONFIG_FLOAT
43
#   define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
44
#   define compute_antialias compute_antialias_float
45
#   define FIXR_OLD(a)    ((int)((a) * FRAC_ONE + 0.5))
46
#   define FIXR(x)        ((float)(x))
47
#   define FIXHR(x)       ((float)(x))
48
#   define MULH3(x, y, s) ((s)*(y)*(x))
49
#   define MULLx(x, y, s) ((y)*(x))
50
#   define RENAME(a) a ## _float
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
#endif
62

    
63
/****************/
64

    
65
#define HEADER_SIZE 4
66

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
237
    return m;
238
}
239

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

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

    
248
static int dev_4_3_coefs[DEV_ORDER];
249

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

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

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

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

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

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

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

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

    
307
        RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
308

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

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

    
320
            xsize = h->xsize;
321

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

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

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

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

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

    
362
        int_pow_init();
363
        mpegaudio_tableinit();
364

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

    
378

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

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

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

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

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

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

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

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

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

    
462
        init = 1;
463
    }
464

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

    
470

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

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

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

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

    
487
#else
488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
623

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

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

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

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

    
647
#define C3 FIXHR(0.86602540378443864676/2)
648

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

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

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

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

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

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

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

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

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

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

    
728

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1140

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

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

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

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

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

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

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

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

    
1219
            exponent= exponents[s_index];
1220

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

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

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

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

    
1319
    return 0;
1320
}
1321

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

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

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

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

    
1359
#define ISQRT2 FIXR(0.70710678118654752440)
1360

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1842
            exponents_from_scale_factors(s, g, exponents);
1843

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

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

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

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

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

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

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

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

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

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

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

    
1917
        break;
1918
    }
1919

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

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

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

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

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

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

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

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

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

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

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

    
2012
    len = buf_size;
2013

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

    
2020

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

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

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

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

    
2040
    s->frame_size = len;
2041

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

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

    
2053
#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
2054

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

    
2065
#include "mpeg4audio.h"
2066

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

    
2081

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

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

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

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

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

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

    
2130
    return 0;
2131
}
2132

    
2133

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

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

    
2142
    return 0;
2143
}
2144

    
2145

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

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

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

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

    
2172
    avctx->bit_rate = 0;
2173

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

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

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

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

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

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

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

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