Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 7ae7300e

History | View | Annotate | Download (80.3 KB)

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

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

    
27
//#define DEBUG
28
#include "avcodec.h"
29
#include "bitstream.h"
30
#include "dsputil.h"
31

    
32
/*
33
 * TODO:
34
 *  - in low precision mode, use more 16 bit multiplies in synth filter
35
 *  - test lsf / mpeg25 extensively.
36
 */
37

    
38
/* define USE_HIGHPRECISION to have a bit exact (but slower) mpeg
39
   audio decoder */
40
#ifdef CONFIG_MPEGAUDIO_HP
41
#   define USE_HIGHPRECISION
42
#endif
43

    
44
#include "mpegaudio.h"
45
#include "mpegaudiodecheader.h"
46

    
47
#include "mathops.h"
48

    
49
/* WARNING: only correct for posititive numbers */
50
#define FIXR(a)   ((int)((a) * FRAC_ONE + 0.5))
51
#define FRAC_RND(a) (((a) + (FRAC_ONE/2)) >> FRAC_BITS)
52

    
53
#define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
54

    
55
/****************/
56

    
57
#define HEADER_SIZE 4
58

    
59
/**
60
 * Context for MP3On4 decoder
61
 */
62
typedef struct MP3On4DecodeContext {
63
    int frames;   ///< number of mp3 frames per block (number of mp3 decoder instances)
64
    int chan_cfg; ///< channel config number
65
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
66
} MP3On4DecodeContext;
67

    
68
/* layer 3 "granule" */
69
typedef struct GranuleDef {
70
    uint8_t scfsi;
71
    int part2_3_length;
72
    int big_values;
73
    int global_gain;
74
    int scalefac_compress;
75
    uint8_t block_type;
76
    uint8_t switch_point;
77
    int table_select[3];
78
    int subblock_gain[3];
79
    uint8_t scalefac_scale;
80
    uint8_t count1table_select;
81
    int region_size[3]; /* number of huffman codes in each region */
82
    int preflag;
83
    int short_start, long_end; /* long/short band indexes */
84
    uint8_t scale_factors[40];
85
    int32_t sb_hybrid[SBLIMIT * 18]; /* 576 samples */
86
} GranuleDef;
87

    
88
#define MODE_EXT_MS_STEREO 2
89
#define MODE_EXT_I_STEREO  1
90

    
91
#include "mpegaudiodata.h"
92
#include "mpegaudiodectab.h"
93

    
94
static void compute_antialias_integer(MPADecodeContext *s, GranuleDef *g);
95
static void compute_antialias_float(MPADecodeContext *s, GranuleDef *g);
96

    
97
/* vlc structure for decoding layer 3 huffman tables */
98
static VLC huff_vlc[16];
99
static VLC huff_quad_vlc[2];
100
/* computed from band_size_long */
101
static uint16_t band_index_long[9][23];
102
/* XXX: free when all decoders are closed */
103
#define TABLE_4_3_SIZE (8191 + 16)*4
104
static int8_t  table_4_3_exp[TABLE_4_3_SIZE];
105
static uint32_t table_4_3_value[TABLE_4_3_SIZE];
106
static uint32_t exp_table[512];
107
static uint32_t expval_table[512][16];
108
/* intensity stereo coef table */
109
static int32_t is_table[2][16];
110
static int32_t is_table_lsf[2][2][16];
111
static int32_t csa_table[8][4];
112
static float csa_table_float[8][4];
113
static int32_t mdct_win[8][36];
114

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

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

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

    
130
static DECLARE_ALIGNED_16(MPA_INT, window[512]);
131

    
132
/* layer 1 unscaling */
133
/* n = number of bits of the mantissa minus 1 */
134
static inline int l1_unscale(int n, int mant, int scale_factor)
135
{
136
    int shift, mod;
137
    int64_t val;
138

    
139
    shift = scale_factor_modshift[scale_factor];
140
    mod = shift & 3;
141
    shift >>= 2;
142
    val = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);
143
    shift += n;
144
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
145
    return (int)((val + (1LL << (shift - 1))) >> shift);
146
}
147

    
148
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
149
{
150
    int shift, mod, val;
151

    
152
    shift = scale_factor_modshift[scale_factor];
153
    mod = shift & 3;
154
    shift >>= 2;
155

    
156
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
157
    /* NOTE: at this point, 0 <= shift <= 21 */
158
    if (shift > 0)
159
        val = (val + (1 << (shift - 1))) >> shift;
160
    return val;
161
}
162

    
163
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
164
static inline int l3_unscale(int value, int exponent)
165
{
166
    unsigned int m;
167
    int e;
168

    
169
    e = table_4_3_exp  [4*value + (exponent&3)];
170
    m = table_4_3_value[4*value + (exponent&3)];
171
    e -= (exponent >> 2);
172
    assert(e>=1);
173
    if (e > 31)
174
        return 0;
175
    m = (m + (1 << (e-1))) >> e;
176

    
177
    return m;
178
}
179

    
180
/* all integer n^(4/3) computation code */
181
#define DEV_ORDER 13
182

    
183
#define POW_FRAC_BITS 24
184
#define POW_FRAC_ONE    (1 << POW_FRAC_BITS)
185
#define POW_FIX(a)   ((int)((a) * POW_FRAC_ONE))
186
#define POW_MULL(a,b) (((int64_t)(a) * (int64_t)(b)) >> POW_FRAC_BITS)
187

    
188
static int dev_4_3_coefs[DEV_ORDER];
189

    
190
#if 0 /* unused */
191
static int pow_mult3[3] = {
192
    POW_FIX(1.0),
193
    POW_FIX(1.25992104989487316476),
194
    POW_FIX(1.58740105196819947474),
195
};
196
#endif
197

    
198
static void int_pow_init(void)
199
{
200
    int i, a;
201

    
202
    a = POW_FIX(1.0);
203
    for(i=0;i<DEV_ORDER;i++) {
204
        a = POW_MULL(a, POW_FIX(4.0 / 3.0) - i * POW_FIX(1.0)) / (i + 1);
205
        dev_4_3_coefs[i] = a;
206
    }
207
}
208

    
209
#if 0 /* unused, remove? */
210
/* return the mantissa and the binary exponent */
211
static int int_pow(int i, int *exp_ptr)
212
{
213
    int e, er, eq, j;
214
    int a, a1;
215

216
    /* renormalize */
217
    a = i;
218
    e = POW_FRAC_BITS;
219
    while (a < (1 << (POW_FRAC_BITS - 1))) {
220
        a = a << 1;
221
        e--;
222
    }
223
    a -= (1 << POW_FRAC_BITS);
224
    a1 = 0;
225
    for(j = DEV_ORDER - 1; j >= 0; j--)
226
        a1 = POW_MULL(a, dev_4_3_coefs[j] + a1);
227
    a = (1 << POW_FRAC_BITS) + a1;
228
    /* exponent compute (exact) */
229
    e = e * 4;
230
    er = e % 3;
231
    eq = e / 3;
232
    a = POW_MULL(a, pow_mult3[er]);
233
    while (a >= 2 * POW_FRAC_ONE) {
234
        a = a >> 1;
235
        eq++;
236
    }
237
    /* convert to float */
238
    while (a < POW_FRAC_ONE) {
239
        a = a << 1;
240
        eq--;
241
    }
242
    /* now POW_FRAC_ONE <= a < 2 * POW_FRAC_ONE */
243
#if POW_FRAC_BITS > FRAC_BITS
244
    a = (a + (1 << (POW_FRAC_BITS - FRAC_BITS - 1))) >> (POW_FRAC_BITS - FRAC_BITS);
245
    /* correct overflow */
246
    if (a >= 2 * (1 << FRAC_BITS)) {
247
        a = a >> 1;
248
        eq++;
249
    }
250
#endif
251
    *exp_ptr = eq;
252
    return a;
253
}
254
#endif
255

    
256
static int decode_init(AVCodecContext * avctx)
257
{
258
    MPADecodeContext *s = avctx->priv_data;
259
    static int init=0;
260
    int i, j, k;
261

    
262
    s->avctx = avctx;
263

    
264
#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)
265
    avctx->sample_fmt= SAMPLE_FMT_S32;
266
#else
267
    avctx->sample_fmt= SAMPLE_FMT_S16;
268
#endif
269
    s->error_resilience= avctx->error_resilience;
270

    
271
    if(avctx->antialias_algo != FF_AA_FLOAT)
272
        s->compute_antialias= compute_antialias_integer;
273
    else
274
        s->compute_antialias= compute_antialias_float;
275

    
276
    if (!init && !avctx->parse_only) {
277
        /* scale factors table for layer 1/2 */
278
        for(i=0;i<64;i++) {
279
            int shift, mod;
280
            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
281
            shift = (i / 3);
282
            mod = i % 3;
283
            scale_factor_modshift[i] = mod | (shift << 2);
284
        }
285

    
286
        /* scale factor multiply for layer 1 */
287
        for(i=0;i<15;i++) {
288
            int n, norm;
289
            n = i + 2;
290
            norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
291
            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);
292
            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);
293
            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);
294
            dprintf(avctx, "%d: norm=%x s=%x %x %x\n",
295
                    i, norm,
296
                    scale_factor_mult[i][0],
297
                    scale_factor_mult[i][1],
298
                    scale_factor_mult[i][2]);
299
        }
300

    
301
        ff_mpa_synth_init(window);
302

    
303
        /* huffman decode tables */
304
        for(i=1;i<16;i++) {
305
            const HuffTable *h = &mpa_huff_tables[i];
306
            int xsize, x, y;
307
            unsigned int n;
308
            uint8_t  tmp_bits [512];
309
            uint16_t tmp_codes[512];
310

    
311
            memset(tmp_bits , 0, sizeof(tmp_bits ));
312
            memset(tmp_codes, 0, sizeof(tmp_codes));
313

    
314
            xsize = h->xsize;
315
            n = xsize * xsize;
316

    
317
            j = 0;
318
            for(x=0;x<xsize;x++) {
319
                for(y=0;y<xsize;y++){
320
                    tmp_bits [(x << 5) | y | ((x&&y)<<4)]= h->bits [j  ];
321
                    tmp_codes[(x << 5) | y | ((x&&y)<<4)]= h->codes[j++];
322
                }
323
            }
324

    
325
            /* XXX: fail test */
326
            init_vlc(&huff_vlc[i], 7, 512,
327
                     tmp_bits, 1, 1, tmp_codes, 2, 2, 1);
328
        }
329
        for(i=0;i<2;i++) {
330
            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,
331
                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);
332
        }
333

    
334
        for(i=0;i<9;i++) {
335
            k = 0;
336
            for(j=0;j<22;j++) {
337
                band_index_long[i][j] = k;
338
                k += band_size_long[i][j];
339
            }
340
            band_index_long[i][22] = k;
341
        }
342

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

    
345
        int_pow_init();
346
        for(i=1;i<TABLE_4_3_SIZE;i++) {
347
            double f, fm;
348
            int e, m;
349
            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);
350
            fm = frexp(f, &e);
351
            m = (uint32_t)(fm*(1LL<<31) + 0.5);
352
            e+= FRAC_BITS - 31 + 5 - 100;
353

    
354
            /* normalized to FRAC_BITS */
355
            table_4_3_value[i] = m;
356
//            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));
357
            table_4_3_exp[i] = -e;
358
        }
359
        for(i=0; i<512*16; i++){
360
            int exponent= (i>>4);
361
            double f= pow(i&15, 4.0 / 3.0) * pow(2, (exponent-400)*0.25 + FRAC_BITS + 5);
362
            expval_table[exponent][i&15]= llrint(f);
363
            if((i&15)==1)
364
                exp_table[exponent]= llrint(f);
365
        }
366

    
367
        for(i=0;i<7;i++) {
368
            float f;
369
            int v;
370
            if (i != 6) {
371
                f = tan((double)i * M_PI / 12.0);
372
                v = FIXR(f / (1.0 + f));
373
            } else {
374
                v = FIXR(1.0);
375
            }
376
            is_table[0][i] = v;
377
            is_table[1][6 - i] = v;
378
        }
379
        /* invalid values */
380
        for(i=7;i<16;i++)
381
            is_table[0][i] = is_table[1][i] = 0.0;
382

    
383
        for(i=0;i<16;i++) {
384
            double f;
385
            int e, k;
386

    
387
            for(j=0;j<2;j++) {
388
                e = -(j + 1) * ((i + 1) >> 1);
389
                f = pow(2.0, e / 4.0);
390
                k = i & 1;
391
                is_table_lsf[j][k ^ 1][i] = FIXR(f);
392
                is_table_lsf[j][k][i] = FIXR(1.0);
393
                dprintf(avctx, "is_table_lsf %d %d: %x %x\n",
394
                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);
395
            }
396
        }
397

    
398
        for(i=0;i<8;i++) {
399
            float ci, cs, ca;
400
            ci = ci_table[i];
401
            cs = 1.0 / sqrt(1.0 + ci * ci);
402
            ca = cs * ci;
403
            csa_table[i][0] = FIXHR(cs/4);
404
            csa_table[i][1] = FIXHR(ca/4);
405
            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
406
            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
407
            csa_table_float[i][0] = cs;
408
            csa_table_float[i][1] = ca;
409
            csa_table_float[i][2] = ca + cs;
410
            csa_table_float[i][3] = ca - cs;
411
//            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));
412
//            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);
413
        }
414

    
415
        /* compute mdct windows */
416
        for(i=0;i<36;i++) {
417
            for(j=0; j<4; j++){
418
                double d;
419

    
420
                if(j==2 && i%3 != 1)
421
                    continue;
422

    
423
                d= sin(M_PI * (i + 0.5) / 36.0);
424
                if(j==1){
425
                    if     (i>=30) d= 0;
426
                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);
427
                    else if(i>=18) d= 1;
428
                }else if(j==3){
429
                    if     (i<  6) d= 0;
430
                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);
431
                    else if(i< 18) d= 1;
432
                }
433
                //merge last stage of imdct into the window coefficients
434
                d*= 0.5 / cos(M_PI*(2*i + 19)/72);
435

    
436
                if(j==2)
437
                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));
438
                else
439
                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));
440
//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));
441
            }
442
        }
443

    
444
        /* NOTE: we do frequency inversion adter the MDCT by changing
445
           the sign of the right window coefs */
446
        for(j=0;j<4;j++) {
447
            for(i=0;i<36;i+=2) {
448
                mdct_win[j + 4][i] = mdct_win[j][i];
449
                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
450
            }
451
        }
452

    
453
#if defined(DEBUG)
454
        for(j=0;j<8;j++) {
455
            av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);
456
            for(i=0;i<36;i++)
457
                av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);
458
            av_log(avctx, AV_LOG_DEBUG, "\n");
459
        }
460
#endif
461
        init = 1;
462
    }
463

    
464
#ifdef DEBUG
465
    s->frame_count = 0;
466
#endif
467
    if (avctx->codec_id == CODEC_ID_MP3ADU)
468
        s->adu_mode = 1;
469
    return 0;
470
}
471

    
472
/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
473

    
474
/* cos(i*pi/64) */
475

    
476
#define COS0_0  FIXHR(0.50060299823519630134/2)
477
#define COS0_1  FIXHR(0.50547095989754365998/2)
478
#define COS0_2  FIXHR(0.51544730992262454697/2)
479
#define COS0_3  FIXHR(0.53104259108978417447/2)
480
#define COS0_4  FIXHR(0.55310389603444452782/2)
481
#define COS0_5  FIXHR(0.58293496820613387367/2)
482
#define COS0_6  FIXHR(0.62250412303566481615/2)
483
#define COS0_7  FIXHR(0.67480834145500574602/2)
484
#define COS0_8  FIXHR(0.74453627100229844977/2)
485
#define COS0_9  FIXHR(0.83934964541552703873/2)
486
#define COS0_10 FIXHR(0.97256823786196069369/2)
487
#define COS0_11 FIXHR(1.16943993343288495515/4)
488
#define COS0_12 FIXHR(1.48416461631416627724/4)
489
#define COS0_13 FIXHR(2.05778100995341155085/8)
490
#define COS0_14 FIXHR(3.40760841846871878570/8)
491
#define COS0_15 FIXHR(10.19000812354805681150/32)
492

    
493
#define COS1_0 FIXHR(0.50241928618815570551/2)
494
#define COS1_1 FIXHR(0.52249861493968888062/2)
495
#define COS1_2 FIXHR(0.56694403481635770368/2)
496
#define COS1_3 FIXHR(0.64682178335999012954/2)
497
#define COS1_4 FIXHR(0.78815462345125022473/2)
498
#define COS1_5 FIXHR(1.06067768599034747134/4)
499
#define COS1_6 FIXHR(1.72244709823833392782/4)
500
#define COS1_7 FIXHR(5.10114861868916385802/16)
501

    
502
#define COS2_0 FIXHR(0.50979557910415916894/2)
503
#define COS2_1 FIXHR(0.60134488693504528054/2)
504
#define COS2_2 FIXHR(0.89997622313641570463/2)
505
#define COS2_3 FIXHR(2.56291544774150617881/8)
506

    
507
#define COS3_0 FIXHR(0.54119610014619698439/2)
508
#define COS3_1 FIXHR(1.30656296487637652785/4)
509

    
510
#define COS4_0 FIXHR(0.70710678118654752439/2)
511

    
512
/* butterfly operator */
513
#define BF(a, b, c, s)\
514
{\
515
    tmp0 = tab[a] + tab[b];\
516
    tmp1 = tab[a] - tab[b];\
517
    tab[a] = tmp0;\
518
    tab[b] = MULH(tmp1<<(s), c);\
519
}
520

    
521
#define BF1(a, b, c, d)\
522
{\
523
    BF(a, b, COS4_0, 1);\
524
    BF(c, d,-COS4_0, 1);\
525
    tab[c] += tab[d];\
526
}
527

    
528
#define BF2(a, b, c, d)\
529
{\
530
    BF(a, b, COS4_0, 1);\
531
    BF(c, d,-COS4_0, 1);\
532
    tab[c] += tab[d];\
533
    tab[a] += tab[c];\
534
    tab[c] += tab[b];\
535
    tab[b] += tab[d];\
536
}
537

    
538
#define ADD(a, b) tab[a] += tab[b]
539

    
540
/* DCT32 without 1/sqrt(2) coef zero scaling. */
541
static void dct32(int32_t *out, int32_t *tab)
542
{
543
    int tmp0, tmp1;
544

    
545
    /* pass 1 */
546
    BF( 0, 31, COS0_0 , 1);
547
    BF(15, 16, COS0_15, 5);
548
    /* pass 2 */
549
    BF( 0, 15, COS1_0 , 1);
550
    BF(16, 31,-COS1_0 , 1);
551
    /* pass 1 */
552
    BF( 7, 24, COS0_7 , 1);
553
    BF( 8, 23, COS0_8 , 1);
554
    /* pass 2 */
555
    BF( 7,  8, COS1_7 , 4);
556
    BF(23, 24,-COS1_7 , 4);
557
    /* pass 3 */
558
    BF( 0,  7, COS2_0 , 1);
559
    BF( 8, 15,-COS2_0 , 1);
560
    BF(16, 23, COS2_0 , 1);
561
    BF(24, 31,-COS2_0 , 1);
562
    /* pass 1 */
563
    BF( 3, 28, COS0_3 , 1);
564
    BF(12, 19, COS0_12, 2);
565
    /* pass 2 */
566
    BF( 3, 12, COS1_3 , 1);
567
    BF(19, 28,-COS1_3 , 1);
568
    /* pass 1 */
569
    BF( 4, 27, COS0_4 , 1);
570
    BF(11, 20, COS0_11, 2);
571
    /* pass 2 */
572
    BF( 4, 11, COS1_4 , 1);
573
    BF(20, 27,-COS1_4 , 1);
574
    /* pass 3 */
575
    BF( 3,  4, COS2_3 , 3);
576
    BF(11, 12,-COS2_3 , 3);
577
    BF(19, 20, COS2_3 , 3);
578
    BF(27, 28,-COS2_3 , 3);
579
    /* pass 4 */
580
    BF( 0,  3, COS3_0 , 1);
581
    BF( 4,  7,-COS3_0 , 1);
582
    BF( 8, 11, COS3_0 , 1);
583
    BF(12, 15,-COS3_0 , 1);
584
    BF(16, 19, COS3_0 , 1);
585
    BF(20, 23,-COS3_0 , 1);
586
    BF(24, 27, COS3_0 , 1);
587
    BF(28, 31,-COS3_0 , 1);
588

    
589

    
590

    
591
    /* pass 1 */
592
    BF( 1, 30, COS0_1 , 1);
593
    BF(14, 17, COS0_14, 3);
594
    /* pass 2 */
595
    BF( 1, 14, COS1_1 , 1);
596
    BF(17, 30,-COS1_1 , 1);
597
    /* pass 1 */
598
    BF( 6, 25, COS0_6 , 1);
599
    BF( 9, 22, COS0_9 , 1);
600
    /* pass 2 */
601
    BF( 6,  9, COS1_6 , 2);
602
    BF(22, 25,-COS1_6 , 2);
603
    /* pass 3 */
604
    BF( 1,  6, COS2_1 , 1);
605
    BF( 9, 14,-COS2_1 , 1);
606
    BF(17, 22, COS2_1 , 1);
607
    BF(25, 30,-COS2_1 , 1);
608

    
609
    /* pass 1 */
610
    BF( 2, 29, COS0_2 , 1);
611
    BF(13, 18, COS0_13, 3);
612
    /* pass 2 */
613
    BF( 2, 13, COS1_2 , 1);
614
    BF(18, 29,-COS1_2 , 1);
615
    /* pass 1 */
616
    BF( 5, 26, COS0_5 , 1);
617
    BF(10, 21, COS0_10, 1);
618
    /* pass 2 */
619
    BF( 5, 10, COS1_5 , 2);
620
    BF(21, 26,-COS1_5 , 2);
621
    /* pass 3 */
622
    BF( 2,  5, COS2_2 , 1);
623
    BF(10, 13,-COS2_2 , 1);
624
    BF(18, 21, COS2_2 , 1);
625
    BF(26, 29,-COS2_2 , 1);
626
    /* pass 4 */
627
    BF( 1,  2, COS3_1 , 2);
628
    BF( 5,  6,-COS3_1 , 2);
629
    BF( 9, 10, COS3_1 , 2);
630
    BF(13, 14,-COS3_1 , 2);
631
    BF(17, 18, COS3_1 , 2);
632
    BF(21, 22,-COS3_1 , 2);
633
    BF(25, 26, COS3_1 , 2);
634
    BF(29, 30,-COS3_1 , 2);
635

    
636
    /* pass 5 */
637
    BF1( 0,  1,  2,  3);
638
    BF2( 4,  5,  6,  7);
639
    BF1( 8,  9, 10, 11);
640
    BF2(12, 13, 14, 15);
641
    BF1(16, 17, 18, 19);
642
    BF2(20, 21, 22, 23);
643
    BF1(24, 25, 26, 27);
644
    BF2(28, 29, 30, 31);
645

    
646
    /* pass 6 */
647

    
648
    ADD( 8, 12);
649
    ADD(12, 10);
650
    ADD(10, 14);
651
    ADD(14,  9);
652
    ADD( 9, 13);
653
    ADD(13, 11);
654
    ADD(11, 15);
655

    
656
    out[ 0] = tab[0];
657
    out[16] = tab[1];
658
    out[ 8] = tab[2];
659
    out[24] = tab[3];
660
    out[ 4] = tab[4];
661
    out[20] = tab[5];
662
    out[12] = tab[6];
663
    out[28] = tab[7];
664
    out[ 2] = tab[8];
665
    out[18] = tab[9];
666
    out[10] = tab[10];
667
    out[26] = tab[11];
668
    out[ 6] = tab[12];
669
    out[22] = tab[13];
670
    out[14] = tab[14];
671
    out[30] = tab[15];
672

    
673
    ADD(24, 28);
674
    ADD(28, 26);
675
    ADD(26, 30);
676
    ADD(30, 25);
677
    ADD(25, 29);
678
    ADD(29, 27);
679
    ADD(27, 31);
680

    
681
    out[ 1] = tab[16] + tab[24];
682
    out[17] = tab[17] + tab[25];
683
    out[ 9] = tab[18] + tab[26];
684
    out[25] = tab[19] + tab[27];
685
    out[ 5] = tab[20] + tab[28];
686
    out[21] = tab[21] + tab[29];
687
    out[13] = tab[22] + tab[30];
688
    out[29] = tab[23] + tab[31];
689
    out[ 3] = tab[24] + tab[20];
690
    out[19] = tab[25] + tab[21];
691
    out[11] = tab[26] + tab[22];
692
    out[27] = tab[27] + tab[23];
693
    out[ 7] = tab[28] + tab[18];
694
    out[23] = tab[29] + tab[19];
695
    out[15] = tab[30] + tab[17];
696
    out[31] = tab[31];
697
}
698

    
699
#if FRAC_BITS <= 15
700

    
701
static inline int round_sample(int *sum)
702
{
703
    int sum1;
704
    sum1 = (*sum) >> OUT_SHIFT;
705
    *sum &= (1<<OUT_SHIFT)-1;
706
    if (sum1 < OUT_MIN)
707
        sum1 = OUT_MIN;
708
    else if (sum1 > OUT_MAX)
709
        sum1 = OUT_MAX;
710
    return sum1;
711
}
712

    
713
/* signed 16x16 -> 32 multiply add accumulate */
714
#define MACS(rt, ra, rb) MAC16(rt, ra, rb)
715

    
716
/* signed 16x16 -> 32 multiply */
717
#define MULS(ra, rb) MUL16(ra, rb)
718

    
719
#else
720

    
721
static inline int round_sample(int64_t *sum)
722
{
723
    int sum1;
724
    sum1 = (int)((*sum) >> OUT_SHIFT);
725
    *sum &= (1<<OUT_SHIFT)-1;
726
    if (sum1 < OUT_MIN)
727
        sum1 = OUT_MIN;
728
    else if (sum1 > OUT_MAX)
729
        sum1 = OUT_MAX;
730
    return sum1;
731
}
732

    
733
#   define MULS(ra, rb) MUL64(ra, rb)
734
#endif
735

    
736
#define SUM8(sum, op, w, p) \
737
{                                               \
738
    sum op MULS((w)[0 * 64], p[0 * 64]);\
739
    sum op MULS((w)[1 * 64], p[1 * 64]);\
740
    sum op MULS((w)[2 * 64], p[2 * 64]);\
741
    sum op MULS((w)[3 * 64], p[3 * 64]);\
742
    sum op MULS((w)[4 * 64], p[4 * 64]);\
743
    sum op MULS((w)[5 * 64], p[5 * 64]);\
744
    sum op MULS((w)[6 * 64], p[6 * 64]);\
745
    sum op MULS((w)[7 * 64], p[7 * 64]);\
746
}
747

    
748
#define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
749
{                                               \
750
    int tmp;\
751
    tmp = p[0 * 64];\
752
    sum1 op1 MULS((w1)[0 * 64], tmp);\
753
    sum2 op2 MULS((w2)[0 * 64], tmp);\
754
    tmp = p[1 * 64];\
755
    sum1 op1 MULS((w1)[1 * 64], tmp);\
756
    sum2 op2 MULS((w2)[1 * 64], tmp);\
757
    tmp = p[2 * 64];\
758
    sum1 op1 MULS((w1)[2 * 64], tmp);\
759
    sum2 op2 MULS((w2)[2 * 64], tmp);\
760
    tmp = p[3 * 64];\
761
    sum1 op1 MULS((w1)[3 * 64], tmp);\
762
    sum2 op2 MULS((w2)[3 * 64], tmp);\
763
    tmp = p[4 * 64];\
764
    sum1 op1 MULS((w1)[4 * 64], tmp);\
765
    sum2 op2 MULS((w2)[4 * 64], tmp);\
766
    tmp = p[5 * 64];\
767
    sum1 op1 MULS((w1)[5 * 64], tmp);\
768
    sum2 op2 MULS((w2)[5 * 64], tmp);\
769
    tmp = p[6 * 64];\
770
    sum1 op1 MULS((w1)[6 * 64], tmp);\
771
    sum2 op2 MULS((w2)[6 * 64], tmp);\
772
    tmp = p[7 * 64];\
773
    sum1 op1 MULS((w1)[7 * 64], tmp);\
774
    sum2 op2 MULS((w2)[7 * 64], tmp);\
775
}
776

    
777
void ff_mpa_synth_init(MPA_INT *window)
778
{
779
    int i;
780

    
781
    /* max = 18760, max sum over all 16 coefs : 44736 */
782
    for(i=0;i<257;i++) {
783
        int v;
784
        v = ff_mpa_enwindow[i];
785
#if WFRAC_BITS < 16
786
        v = (v + (1 << (16 - WFRAC_BITS - 1))) >> (16 - WFRAC_BITS);
787
#endif
788
        window[i] = v;
789
        if ((i & 63) != 0)
790
            v = -v;
791
        if (i != 0)
792
            window[512 - i] = v;
793
    }
794
}
795

    
796
/* 32 sub band synthesis filter. Input: 32 sub band samples, Output:
797
   32 samples. */
798
/* XXX: optimize by avoiding ring buffer usage */
799
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
800
                         MPA_INT *window, int *dither_state,
801
                         OUT_INT *samples, int incr,
802
                         int32_t sb_samples[SBLIMIT])
803
{
804
    int32_t tmp[32];
805
    register MPA_INT *synth_buf;
806
    register const MPA_INT *w, *w2, *p;
807
    int j, offset, v;
808
    OUT_INT *samples2;
809
#if FRAC_BITS <= 15
810
    int sum, sum2;
811
#else
812
    int64_t sum, sum2;
813
#endif
814

    
815
    dct32(tmp, sb_samples);
816

    
817
    offset = *synth_buf_offset;
818
    synth_buf = synth_buf_ptr + offset;
819

    
820
    for(j=0;j<32;j++) {
821
        v = tmp[j];
822
#if FRAC_BITS <= 15
823
        /* NOTE: can cause a loss in precision if very high amplitude
824
           sound */
825
        if (v > 32767)
826
            v = 32767;
827
        else if (v < -32768)
828
            v = -32768;
829
#endif
830
        synth_buf[j] = v;
831
    }
832
    /* copy to avoid wrap */
833
    memcpy(synth_buf + 512, synth_buf, 32 * sizeof(MPA_INT));
834

    
835
    samples2 = samples + 31 * incr;
836
    w = window;
837
    w2 = window + 31;
838

    
839
    sum = *dither_state;
840
    p = synth_buf + 16;
841
    SUM8(sum, +=, w, p);
842
    p = synth_buf + 48;
843
    SUM8(sum, -=, w + 32, p);
844
    *samples = round_sample(&sum);
845
    samples += incr;
846
    w++;
847

    
848
    /* we calculate two samples at the same time to avoid one memory
849
       access per two sample */
850
    for(j=1;j<16;j++) {
851
        sum2 = 0;
852
        p = synth_buf + 16 + j;
853
        SUM8P2(sum, +=, sum2, -=, w, w2, p);
854
        p = synth_buf + 48 - j;
855
        SUM8P2(sum, -=, sum2, -=, w + 32, w2 + 32, p);
856

    
857
        *samples = round_sample(&sum);
858
        samples += incr;
859
        sum += sum2;
860
        *samples2 = round_sample(&sum);
861
        samples2 -= incr;
862
        w++;
863
        w2--;
864
    }
865

    
866
    p = synth_buf + 32;
867
    SUM8(sum, -=, w + 32, p);
868
    *samples = round_sample(&sum);
869
    *dither_state= sum;
870

    
871
    offset = (offset - 32) & 511;
872
    *synth_buf_offset = offset;
873
}
874

    
875
#define C3 FIXHR(0.86602540378443864676/2)
876

    
877
/* 0.5 / cos(pi*(2*i+1)/36) */
878
static const int icos36[9] = {
879
    FIXR(0.50190991877167369479),
880
    FIXR(0.51763809020504152469), //0
881
    FIXR(0.55168895948124587824),
882
    FIXR(0.61038729438072803416),
883
    FIXR(0.70710678118654752439), //1
884
    FIXR(0.87172339781054900991),
885
    FIXR(1.18310079157624925896),
886
    FIXR(1.93185165257813657349), //2
887
    FIXR(5.73685662283492756461),
888
};
889

    
890
/* 0.5 / cos(pi*(2*i+1)/36) */
891
static const int icos36h[9] = {
892
    FIXHR(0.50190991877167369479/2),
893
    FIXHR(0.51763809020504152469/2), //0
894
    FIXHR(0.55168895948124587824/2),
895
    FIXHR(0.61038729438072803416/2),
896
    FIXHR(0.70710678118654752439/2), //1
897
    FIXHR(0.87172339781054900991/2),
898
    FIXHR(1.18310079157624925896/4),
899
    FIXHR(1.93185165257813657349/4), //2
900
//    FIXHR(5.73685662283492756461),
901
};
902

    
903
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
904
   cases. */
905
static void imdct12(int *out, int *in)
906
{
907
    int in0, in1, in2, in3, in4, in5, t1, t2;
908

    
909
    in0= in[0*3];
910
    in1= in[1*3] + in[0*3];
911
    in2= in[2*3] + in[1*3];
912
    in3= in[3*3] + in[2*3];
913
    in4= in[4*3] + in[3*3];
914
    in5= in[5*3] + in[4*3];
915
    in5 += in3;
916
    in3 += in1;
917

    
918
    in2= MULH(2*in2, C3);
919
    in3= MULH(4*in3, C3);
920

    
921
    t1 = in0 - in4;
922
    t2 = MULH(2*(in1 - in5), icos36h[4]);
923

    
924
    out[ 7]=
925
    out[10]= t1 + t2;
926
    out[ 1]=
927
    out[ 4]= t1 - t2;
928

    
929
    in0 += in4>>1;
930
    in4 = in0 + in2;
931
    in5 += 2*in1;
932
    in1 = MULH(in5 + in3, icos36h[1]);
933
    out[ 8]=
934
    out[ 9]= in4 + in1;
935
    out[ 2]=
936
    out[ 3]= in4 - in1;
937

    
938
    in0 -= in2;
939
    in5 = MULH(2*(in5 - in3), icos36h[7]);
940
    out[ 0]=
941
    out[ 5]= in0 - in5;
942
    out[ 6]=
943
    out[11]= in0 + in5;
944
}
945

    
946
/* cos(pi*i/18) */
947
#define C1 FIXHR(0.98480775301220805936/2)
948
#define C2 FIXHR(0.93969262078590838405/2)
949
#define C3 FIXHR(0.86602540378443864676/2)
950
#define C4 FIXHR(0.76604444311897803520/2)
951
#define C5 FIXHR(0.64278760968653932632/2)
952
#define C6 FIXHR(0.5/2)
953
#define C7 FIXHR(0.34202014332566873304/2)
954
#define C8 FIXHR(0.17364817766693034885/2)
955

    
956

    
957
/* using Lee like decomposition followed by hand coded 9 points DCT */
958
static void imdct36(int *out, int *buf, int *in, int *win)
959
{
960
    int i, j, t0, t1, t2, t3, s0, s1, s2, s3;
961
    int tmp[18], *tmp1, *in1;
962

    
963
    for(i=17;i>=1;i--)
964
        in[i] += in[i-1];
965
    for(i=17;i>=3;i-=2)
966
        in[i] += in[i-2];
967

    
968
    for(j=0;j<2;j++) {
969
        tmp1 = tmp + j;
970
        in1 = in + j;
971
#if 0
972
//more accurate but slower
973
        int64_t t0, t1, t2, t3;
974
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
975

976
        t3 = (in1[2*0] + (int64_t)(in1[2*6]>>1))<<32;
977
        t1 = in1[2*0] - in1[2*6];
978
        tmp1[ 6] = t1 - (t2>>1);
979
        tmp1[16] = t1 + t2;
980

981
        t0 = MUL64(2*(in1[2*2] + in1[2*4]),    C2);
982
        t1 = MUL64(   in1[2*4] - in1[2*8] , -2*C8);
983
        t2 = MUL64(2*(in1[2*2] + in1[2*8]),   -C4);
984

985
        tmp1[10] = (t3 - t0 - t2) >> 32;
986
        tmp1[ 2] = (t3 + t0 + t1) >> 32;
987
        tmp1[14] = (t3 + t2 - t1) >> 32;
988

989
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
990
        t2 = MUL64(2*(in1[2*1] + in1[2*5]),    C1);
991
        t3 = MUL64(   in1[2*5] - in1[2*7] , -2*C7);
992
        t0 = MUL64(2*in1[2*3], C3);
993

994
        t1 = MUL64(2*(in1[2*1] + in1[2*7]),   -C5);
995

996
        tmp1[ 0] = (t2 + t3 + t0) >> 32;
997
        tmp1[12] = (t2 + t1 - t0) >> 32;
998
        tmp1[ 8] = (t3 - t1 - t0) >> 32;
999
#else
1000
        t2 = in1[2*4] + in1[2*8] - in1[2*2];
1001

    
1002
        t3 = in1[2*0] + (in1[2*6]>>1);
1003
        t1 = in1[2*0] - in1[2*6];
1004
        tmp1[ 6] = t1 - (t2>>1);
1005
        tmp1[16] = t1 + t2;
1006

    
1007
        t0 = MULH(2*(in1[2*2] + in1[2*4]),    C2);
1008
        t1 = MULH(   in1[2*4] - in1[2*8] , -2*C8);
1009
        t2 = MULH(2*(in1[2*2] + in1[2*8]),   -C4);
1010

    
1011
        tmp1[10] = t3 - t0 - t2;
1012
        tmp1[ 2] = t3 + t0 + t1;
1013
        tmp1[14] = t3 + t2 - t1;
1014

    
1015
        tmp1[ 4] = MULH(2*(in1[2*5] + in1[2*7] - in1[2*1]), -C3);
1016
        t2 = MULH(2*(in1[2*1] + in1[2*5]),    C1);
1017
        t3 = MULH(   in1[2*5] - in1[2*7] , -2*C7);
1018
        t0 = MULH(2*in1[2*3], C3);
1019

    
1020
        t1 = MULH(2*(in1[2*1] + in1[2*7]),   -C5);
1021

    
1022
        tmp1[ 0] = t2 + t3 + t0;
1023
        tmp1[12] = t2 + t1 - t0;
1024
        tmp1[ 8] = t3 - t1 - t0;
1025
#endif
1026
    }
1027

    
1028
    i = 0;
1029
    for(j=0;j<4;j++) {
1030
        t0 = tmp[i];
1031
        t1 = tmp[i + 2];
1032
        s0 = t1 + t0;
1033
        s2 = t1 - t0;
1034

    
1035
        t2 = tmp[i + 1];
1036
        t3 = tmp[i + 3];
1037
        s1 = MULH(2*(t3 + t2), icos36h[j]);
1038
        s3 = MULL(t3 - t2, icos36[8 - j]);
1039

    
1040
        t0 = s0 + s1;
1041
        t1 = s0 - s1;
1042
        out[(9 + j)*SBLIMIT] =  MULH(t1, win[9 + j]) + buf[9 + j];
1043
        out[(8 - j)*SBLIMIT] =  MULH(t1, win[8 - j]) + buf[8 - j];
1044
        buf[9 + j] = MULH(t0, win[18 + 9 + j]);
1045
        buf[8 - j] = MULH(t0, win[18 + 8 - j]);
1046

    
1047
        t0 = s2 + s3;
1048
        t1 = s2 - s3;
1049
        out[(9 + 8 - j)*SBLIMIT] =  MULH(t1, win[9 + 8 - j]) + buf[9 + 8 - j];
1050
        out[(        j)*SBLIMIT] =  MULH(t1, win[        j]) + buf[        j];
1051
        buf[9 + 8 - j] = MULH(t0, win[18 + 9 + 8 - j]);
1052
        buf[      + j] = MULH(t0, win[18         + j]);
1053
        i += 4;
1054
    }
1055

    
1056
    s0 = tmp[16];
1057
    s1 = MULH(2*tmp[17], icos36h[4]);
1058
    t0 = s0 + s1;
1059
    t1 = s0 - s1;
1060
    out[(9 + 4)*SBLIMIT] =  MULH(t1, win[9 + 4]) + buf[9 + 4];
1061
    out[(8 - 4)*SBLIMIT] =  MULH(t1, win[8 - 4]) + buf[8 - 4];
1062
    buf[9 + 4] = MULH(t0, win[18 + 9 + 4]);
1063
    buf[8 - 4] = MULH(t0, win[18 + 8 - 4]);
1064
}
1065

    
1066
/* return the number of decoded frames */
1067
static int mp_decode_layer1(MPADecodeContext *s)
1068
{
1069
    int bound, i, v, n, ch, j, mant;
1070
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
1071
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
1072

    
1073
    if (s->mode == MPA_JSTEREO)
1074
        bound = (s->mode_ext + 1) * 4;
1075
    else
1076
        bound = SBLIMIT;
1077

    
1078
    /* allocation bits */
1079
    for(i=0;i<bound;i++) {
1080
        for(ch=0;ch<s->nb_channels;ch++) {
1081
            allocation[ch][i] = get_bits(&s->gb, 4);
1082
        }
1083
    }
1084
    for(i=bound;i<SBLIMIT;i++) {
1085
        allocation[0][i] = get_bits(&s->gb, 4);
1086
    }
1087

    
1088
    /* scale factors */
1089
    for(i=0;i<bound;i++) {
1090
        for(ch=0;ch<s->nb_channels;ch++) {
1091
            if (allocation[ch][i])
1092
                scale_factors[ch][i] = get_bits(&s->gb, 6);
1093
        }
1094
    }
1095
    for(i=bound;i<SBLIMIT;i++) {
1096
        if (allocation[0][i]) {
1097
            scale_factors[0][i] = get_bits(&s->gb, 6);
1098
            scale_factors[1][i] = get_bits(&s->gb, 6);
1099
        }
1100
    }
1101

    
1102
    /* compute samples */
1103
    for(j=0;j<12;j++) {
1104
        for(i=0;i<bound;i++) {
1105
            for(ch=0;ch<s->nb_channels;ch++) {
1106
                n = allocation[ch][i];
1107
                if (n) {
1108
                    mant = get_bits(&s->gb, n + 1);
1109
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
1110
                } else {
1111
                    v = 0;
1112
                }
1113
                s->sb_samples[ch][j][i] = v;
1114
            }
1115
        }
1116
        for(i=bound;i<SBLIMIT;i++) {
1117
            n = allocation[0][i];
1118
            if (n) {
1119
                mant = get_bits(&s->gb, n + 1);
1120
                v = l1_unscale(n, mant, scale_factors[0][i]);
1121
                s->sb_samples[0][j][i] = v;
1122
                v = l1_unscale(n, mant, scale_factors[1][i]);
1123
                s->sb_samples[1][j][i] = v;
1124
            } else {
1125
                s->sb_samples[0][j][i] = 0;
1126
                s->sb_samples[1][j][i] = 0;
1127
            }
1128
        }
1129
    }
1130
    return 12;
1131
}
1132

    
1133
static int mp_decode_layer2(MPADecodeContext *s)
1134
{
1135
    int sblimit; /* number of used subbands */
1136
    const unsigned char *alloc_table;
1137
    int table, bit_alloc_bits, i, j, ch, bound, v;
1138
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
1139
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
1140
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
1141
    int scale, qindex, bits, steps, k, l, m, b;
1142

    
1143
    /* select decoding table */
1144
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
1145
                            s->sample_rate, s->lsf);
1146
    sblimit = ff_mpa_sblimit_table[table];
1147
    alloc_table = ff_mpa_alloc_tables[table];
1148

    
1149
    if (s->mode == MPA_JSTEREO)
1150
        bound = (s->mode_ext + 1) * 4;
1151
    else
1152
        bound = sblimit;
1153

    
1154
    dprintf(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
1155

    
1156
    /* sanity check */
1157
    if( bound > sblimit ) bound = sblimit;
1158

    
1159
    /* parse bit allocation */
1160
    j = 0;
1161
    for(i=0;i<bound;i++) {
1162
        bit_alloc_bits = alloc_table[j];
1163
        for(ch=0;ch<s->nb_channels;ch++) {
1164
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
1165
        }
1166
        j += 1 << bit_alloc_bits;
1167
    }
1168
    for(i=bound;i<sblimit;i++) {
1169
        bit_alloc_bits = alloc_table[j];
1170
        v = get_bits(&s->gb, bit_alloc_bits);
1171
        bit_alloc[0][i] = v;
1172
        bit_alloc[1][i] = v;
1173
        j += 1 << bit_alloc_bits;
1174
    }
1175

    
1176
#ifdef DEBUG
1177
    {
1178
        for(ch=0;ch<s->nb_channels;ch++) {
1179
            for(i=0;i<sblimit;i++)
1180
                dprintf(s->avctx, " %d", bit_alloc[ch][i]);
1181
            dprintf(s->avctx, "\n");
1182
        }
1183
    }
1184
#endif
1185

    
1186
    /* scale codes */
1187
    for(i=0;i<sblimit;i++) {
1188
        for(ch=0;ch<s->nb_channels;ch++) {
1189
            if (bit_alloc[ch][i])
1190
                scale_code[ch][i] = get_bits(&s->gb, 2);
1191
        }
1192
    }
1193

    
1194
    /* scale factors */
1195
    for(i=0;i<sblimit;i++) {
1196
        for(ch=0;ch<s->nb_channels;ch++) {
1197
            if (bit_alloc[ch][i]) {
1198
                sf = scale_factors[ch][i];
1199
                switch(scale_code[ch][i]) {
1200
                default:
1201
                case 0:
1202
                    sf[0] = get_bits(&s->gb, 6);
1203
                    sf[1] = get_bits(&s->gb, 6);
1204
                    sf[2] = get_bits(&s->gb, 6);
1205
                    break;
1206
                case 2:
1207
                    sf[0] = get_bits(&s->gb, 6);
1208
                    sf[1] = sf[0];
1209
                    sf[2] = sf[0];
1210
                    break;
1211
                case 1:
1212
                    sf[0] = get_bits(&s->gb, 6);
1213
                    sf[2] = get_bits(&s->gb, 6);
1214
                    sf[1] = sf[0];
1215
                    break;
1216
                case 3:
1217
                    sf[0] = get_bits(&s->gb, 6);
1218
                    sf[2] = get_bits(&s->gb, 6);
1219
                    sf[1] = sf[2];
1220
                    break;
1221
                }
1222
            }
1223
        }
1224
    }
1225

    
1226
#ifdef DEBUG
1227
    for(ch=0;ch<s->nb_channels;ch++) {
1228
        for(i=0;i<sblimit;i++) {
1229
            if (bit_alloc[ch][i]) {
1230
                sf = scale_factors[ch][i];
1231
                dprintf(s->avctx, " %d %d %d", sf[0], sf[1], sf[2]);
1232
            } else {
1233
                dprintf(s->avctx, " -");
1234
            }
1235
        }
1236
        dprintf(s->avctx, "\n");
1237
    }
1238
#endif
1239

    
1240
    /* samples */
1241
    for(k=0;k<3;k++) {
1242
        for(l=0;l<12;l+=3) {
1243
            j = 0;
1244
            for(i=0;i<bound;i++) {
1245
                bit_alloc_bits = alloc_table[j];
1246
                for(ch=0;ch<s->nb_channels;ch++) {
1247
                    b = bit_alloc[ch][i];
1248
                    if (b) {
1249
                        scale = scale_factors[ch][i][k];
1250
                        qindex = alloc_table[j+b];
1251
                        bits = ff_mpa_quant_bits[qindex];
1252
                        if (bits < 0) {
1253
                            /* 3 values at the same time */
1254
                            v = get_bits(&s->gb, -bits);
1255
                            steps = ff_mpa_quant_steps[qindex];
1256
                            s->sb_samples[ch][k * 12 + l + 0][i] =
1257
                                l2_unscale_group(steps, v % steps, scale);
1258
                            v = v / steps;
1259
                            s->sb_samples[ch][k * 12 + l + 1][i] =
1260
                                l2_unscale_group(steps, v % steps, scale);
1261
                            v = v / steps;
1262
                            s->sb_samples[ch][k * 12 + l + 2][i] =
1263
                                l2_unscale_group(steps, v, scale);
1264
                        } else {
1265
                            for(m=0;m<3;m++) {
1266
                                v = get_bits(&s->gb, bits);
1267
                                v = l1_unscale(bits - 1, v, scale);
1268
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
1269
                            }
1270
                        }
1271
                    } else {
1272
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1273
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1274
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1275
                    }
1276
                }
1277
                /* next subband in alloc table */
1278
                j += 1 << bit_alloc_bits;
1279
            }
1280
            /* XXX: find a way to avoid this duplication of code */
1281
            for(i=bound;i<sblimit;i++) {
1282
                bit_alloc_bits = alloc_table[j];
1283
                b = bit_alloc[0][i];
1284
                if (b) {
1285
                    int mant, scale0, scale1;
1286
                    scale0 = scale_factors[0][i][k];
1287
                    scale1 = scale_factors[1][i][k];
1288
                    qindex = alloc_table[j+b];
1289
                    bits = ff_mpa_quant_bits[qindex];
1290
                    if (bits < 0) {
1291
                        /* 3 values at the same time */
1292
                        v = get_bits(&s->gb, -bits);
1293
                        steps = ff_mpa_quant_steps[qindex];
1294
                        mant = v % steps;
1295
                        v = v / steps;
1296
                        s->sb_samples[0][k * 12 + l + 0][i] =
1297
                            l2_unscale_group(steps, mant, scale0);
1298
                        s->sb_samples[1][k * 12 + l + 0][i] =
1299
                            l2_unscale_group(steps, mant, scale1);
1300
                        mant = v % steps;
1301
                        v = v / steps;
1302
                        s->sb_samples[0][k * 12 + l + 1][i] =
1303
                            l2_unscale_group(steps, mant, scale0);
1304
                        s->sb_samples[1][k * 12 + l + 1][i] =
1305
                            l2_unscale_group(steps, mant, scale1);
1306
                        s->sb_samples[0][k * 12 + l + 2][i] =
1307
                            l2_unscale_group(steps, v, scale0);
1308
                        s->sb_samples[1][k * 12 + l + 2][i] =
1309
                            l2_unscale_group(steps, v, scale1);
1310
                    } else {
1311
                        for(m=0;m<3;m++) {
1312
                            mant = get_bits(&s->gb, bits);
1313
                            s->sb_samples[0][k * 12 + l + m][i] =
1314
                                l1_unscale(bits - 1, mant, scale0);
1315
                            s->sb_samples[1][k * 12 + l + m][i] =
1316
                                l1_unscale(bits - 1, mant, scale1);
1317
                        }
1318
                    }
1319
                } else {
1320
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
1321
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
1322
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
1323
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
1324
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
1325
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
1326
                }
1327
                /* next subband in alloc table */
1328
                j += 1 << bit_alloc_bits;
1329
            }
1330
            /* fill remaining samples to zero */
1331
            for(i=sblimit;i<SBLIMIT;i++) {
1332
                for(ch=0;ch<s->nb_channels;ch++) {
1333
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
1334
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
1335
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
1336
                }
1337
            }
1338
        }
1339
    }
1340
    return 3 * 12;
1341
}
1342

    
1343
static inline void lsf_sf_expand(int *slen,
1344
                                 int sf, int n1, int n2, int n3)
1345
{
1346
    if (n3) {
1347
        slen[3] = sf % n3;
1348
        sf /= n3;
1349
    } else {
1350
        slen[3] = 0;
1351
    }
1352
    if (n2) {
1353
        slen[2] = sf % n2;
1354
        sf /= n2;
1355
    } else {
1356
        slen[2] = 0;
1357
    }
1358
    slen[1] = sf % n1;
1359
    sf /= n1;
1360
    slen[0] = sf;
1361
}
1362

    
1363
static void exponents_from_scale_factors(MPADecodeContext *s,
1364
                                         GranuleDef *g,
1365
                                         int16_t *exponents)
1366
{
1367
    const uint8_t *bstab, *pretab;
1368
    int len, i, j, k, l, v0, shift, gain, gains[3];
1369
    int16_t *exp_ptr;
1370

    
1371
    exp_ptr = exponents;
1372
    gain = g->global_gain - 210;
1373
    shift = g->scalefac_scale + 1;
1374

    
1375
    bstab = band_size_long[s->sample_rate_index];
1376
    pretab = mpa_pretab[g->preflag];
1377
    for(i=0;i<g->long_end;i++) {
1378
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
1379
        len = bstab[i];
1380
        for(j=len;j>0;j--)
1381
            *exp_ptr++ = v0;
1382
    }
1383

    
1384
    if (g->short_start < 13) {
1385
        bstab = band_size_short[s->sample_rate_index];
1386
        gains[0] = gain - (g->subblock_gain[0] << 3);
1387
        gains[1] = gain - (g->subblock_gain[1] << 3);
1388
        gains[2] = gain - (g->subblock_gain[2] << 3);
1389
        k = g->long_end;
1390
        for(i=g->short_start;i<13;i++) {
1391
            len = bstab[i];
1392
            for(l=0;l<3;l++) {
1393
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
1394
                for(j=len;j>0;j--)
1395
                *exp_ptr++ = v0;
1396
            }
1397
        }
1398
    }
1399
}
1400

    
1401
/* handle n = 0 too */
1402
static inline int get_bitsz(GetBitContext *s, int n)
1403
{
1404
    if (n == 0)
1405
        return 0;
1406
    else
1407
        return get_bits(s, n);
1408
}
1409

    
1410

    
1411
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos, int *end_pos2){
1412
    if(s->in_gb.buffer && *pos >= s->gb.size_in_bits){
1413
        s->gb= s->in_gb;
1414
        s->in_gb.buffer=NULL;
1415
        assert((get_bits_count(&s->gb) & 7) == 0);
1416
        skip_bits_long(&s->gb, *pos - *end_pos);
1417
        *end_pos2=
1418
        *end_pos= *end_pos2 + get_bits_count(&s->gb) - *pos;
1419
        *pos= get_bits_count(&s->gb);
1420
    }
1421
}
1422

    
1423
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
1424
                          int16_t *exponents, int end_pos2)
1425
{
1426
    int s_index;
1427
    int i;
1428
    int last_pos, bits_left;
1429
    VLC *vlc;
1430
    int end_pos= FFMIN(end_pos2, s->gb.size_in_bits);
1431

    
1432
    /* low frequencies (called big values) */
1433
    s_index = 0;
1434
    for(i=0;i<3;i++) {
1435
        int j, k, l, linbits;
1436
        j = g->region_size[i];
1437
        if (j == 0)
1438
            continue;
1439
        /* select vlc table */
1440
        k = g->table_select[i];
1441
        l = mpa_huff_data[k][0];
1442
        linbits = mpa_huff_data[k][1];
1443
        vlc = &huff_vlc[l];
1444

    
1445
        if(!l){
1446
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*2*j);
1447
            s_index += 2*j;
1448
            continue;
1449
        }
1450

    
1451
        /* read huffcode and compute each couple */
1452
        for(;j>0;j--) {
1453
            int exponent, x, y, v;
1454
            int pos= get_bits_count(&s->gb);
1455

    
1456
            if (pos >= end_pos){
1457
//                av_log(NULL, AV_LOG_ERROR, "pos: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1458
                switch_buffer(s, &pos, &end_pos, &end_pos2);
1459
//                av_log(NULL, AV_LOG_ERROR, "new pos: %d %d\n", pos, end_pos);
1460
                if(pos >= end_pos)
1461
                    break;
1462
            }
1463
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
1464

    
1465
            if(!y){
1466
                g->sb_hybrid[s_index  ] =
1467
                g->sb_hybrid[s_index+1] = 0;
1468
                s_index += 2;
1469
                continue;
1470
            }
1471

    
1472
            exponent= exponents[s_index];
1473

    
1474
            dprintf(s->avctx, "region=%d n=%d x=%d y=%d exp=%d\n",
1475
                    i, g->region_size[i] - j, x, y, exponent);
1476
            if(y&16){
1477
                x = y >> 5;
1478
                y = y & 0x0f;
1479
                if (x < 15){
1480
                    v = expval_table[ exponent ][ x ];
1481
//                      v = expval_table[ (exponent&3) ][ x ] >> FFMIN(0 - (exponent>>2), 31);
1482
                }else{
1483
                    x += get_bitsz(&s->gb, linbits);
1484
                    v = l3_unscale(x, exponent);
1485
                }
1486
                if (get_bits1(&s->gb))
1487
                    v = -v;
1488
                g->sb_hybrid[s_index] = v;
1489
                if (y < 15){
1490
                    v = expval_table[ exponent ][ y ];
1491
                }else{
1492
                    y += get_bitsz(&s->gb, linbits);
1493
                    v = l3_unscale(y, exponent);
1494
                }
1495
                if (get_bits1(&s->gb))
1496
                    v = -v;
1497
                g->sb_hybrid[s_index+1] = v;
1498
            }else{
1499
                x = y >> 5;
1500
                y = y & 0x0f;
1501
                x += y;
1502
                if (x < 15){
1503
                    v = expval_table[ exponent ][ x ];
1504
                }else{
1505
                    x += get_bitsz(&s->gb, linbits);
1506
                    v = l3_unscale(x, exponent);
1507
                }
1508
                if (get_bits1(&s->gb))
1509
                    v = -v;
1510
                g->sb_hybrid[s_index+!!y] = v;
1511
                g->sb_hybrid[s_index+ !y] = 0;
1512
            }
1513
            s_index+=2;
1514
        }
1515
    }
1516

    
1517
    /* high frequencies */
1518
    vlc = &huff_quad_vlc[g->count1table_select];
1519
    last_pos=0;
1520
    while (s_index <= 572) {
1521
        int pos, code;
1522
        pos = get_bits_count(&s->gb);
1523
        if (pos >= end_pos) {
1524
            if (pos > end_pos2 && last_pos){
1525
                /* some encoders generate an incorrect size for this
1526
                   part. We must go back into the data */
1527
                s_index -= 4;
1528
                skip_bits_long(&s->gb, last_pos - pos);
1529
                av_log(NULL, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
1530
                if(s->error_resilience >= FF_ER_COMPLIANT)
1531
                    s_index=0;
1532
                break;
1533
            }
1534
//                av_log(NULL, AV_LOG_ERROR, "pos2: %d %d %d %d\n", pos, end_pos, end_pos2, s_index);
1535
            switch_buffer(s, &pos, &end_pos, &end_pos2);
1536
//                av_log(NULL, AV_LOG_ERROR, "new pos2: %d %d %d\n", pos, end_pos, s_index);
1537
            if(pos >= end_pos)
1538
                break;
1539
        }
1540
        last_pos= pos;
1541

    
1542
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1543
        dprintf(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1544
        g->sb_hybrid[s_index+0]=
1545
        g->sb_hybrid[s_index+1]=
1546
        g->sb_hybrid[s_index+2]=
1547
        g->sb_hybrid[s_index+3]= 0;
1548
        while(code){
1549
            static const int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};
1550
            int v;
1551
            int pos= s_index+idxtab[code];
1552
            code ^= 8>>idxtab[code];
1553
            v = exp_table[ exponents[pos] ];
1554
//            v = exp_table[ (exponents[pos]&3) ] >> FFMIN(0 - (exponents[pos]>>2), 31);
1555
            if(get_bits1(&s->gb))
1556
                v = -v;
1557
            g->sb_hybrid[pos] = v;
1558
        }
1559
        s_index+=4;
1560
    }
1561
    /* skip extension bits */
1562
    bits_left = end_pos2 - get_bits_count(&s->gb);
1563
//av_log(NULL, AV_LOG_ERROR, "left:%d buf:%p\n", bits_left, s->in_gb.buffer);
1564
    if (bits_left < 0/* || bits_left > 500*/) {
1565
        av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1566
        s_index=0;
1567
    }else if(bits_left > 0 && s->error_resilience >= FF_ER_AGGRESSIVE){
1568
        av_log(NULL, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1569
        s_index=0;
1570
    }
1571
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));
1572
    skip_bits_long(&s->gb, bits_left);
1573

    
1574
    i= get_bits_count(&s->gb);
1575
    switch_buffer(s, &i, &end_pos, &end_pos2);
1576

    
1577
    return 0;
1578
}
1579

    
1580
/* Reorder short blocks from bitstream order to interleaved order. It
1581
   would be faster to do it in parsing, but the code would be far more
1582
   complicated */
1583
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1584
{
1585
    int i, j, len;
1586
    int32_t *ptr, *dst, *ptr1;
1587
    int32_t tmp[576];
1588

    
1589
    if (g->block_type != 2)
1590
        return;
1591

    
1592
    if (g->switch_point) {
1593
        if (s->sample_rate_index != 8) {
1594
            ptr = g->sb_hybrid + 36;
1595
        } else {
1596
            ptr = g->sb_hybrid + 48;
1597
        }
1598
    } else {
1599
        ptr = g->sb_hybrid;
1600
    }
1601

    
1602
    for(i=g->short_start;i<13;i++) {
1603
        len = band_size_short[s->sample_rate_index][i];
1604
        ptr1 = ptr;
1605
        dst = tmp;
1606
        for(j=len;j>0;j--) {
1607
            *dst++ = ptr[0*len];
1608
            *dst++ = ptr[1*len];
1609
            *dst++ = ptr[2*len];
1610
            ptr++;
1611
        }
1612
        ptr+=2*len;
1613
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1614
    }
1615
}
1616

    
1617
#define ISQRT2 FIXR(0.70710678118654752440)
1618

    
1619
static void compute_stereo(MPADecodeContext *s,
1620
                           GranuleDef *g0, GranuleDef *g1)
1621
{
1622
    int i, j, k, l;
1623
    int32_t v1, v2;
1624
    int sf_max, tmp0, tmp1, sf, len, non_zero_found;
1625
    int32_t (*is_tab)[16];
1626
    int32_t *tab0, *tab1;
1627
    int non_zero_found_short[3];
1628

    
1629
    /* intensity stereo */
1630
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1631
        if (!s->lsf) {
1632
            is_tab = is_table;
1633
            sf_max = 7;
1634
        } else {
1635
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1636
            sf_max = 16;
1637
        }
1638

    
1639
        tab0 = g0->sb_hybrid + 576;
1640
        tab1 = g1->sb_hybrid + 576;
1641

    
1642
        non_zero_found_short[0] = 0;
1643
        non_zero_found_short[1] = 0;
1644
        non_zero_found_short[2] = 0;
1645
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1646
        for(i = 12;i >= g1->short_start;i--) {
1647
            /* for last band, use previous scale factor */
1648
            if (i != 11)
1649
                k -= 3;
1650
            len = band_size_short[s->sample_rate_index][i];
1651
            for(l=2;l>=0;l--) {
1652
                tab0 -= len;
1653
                tab1 -= len;
1654
                if (!non_zero_found_short[l]) {
1655
                    /* test if non zero band. if so, stop doing i-stereo */
1656
                    for(j=0;j<len;j++) {
1657
                        if (tab1[j] != 0) {
1658
                            non_zero_found_short[l] = 1;
1659
                            goto found1;
1660
                        }
1661
                    }
1662
                    sf = g1->scale_factors[k + l];
1663
                    if (sf >= sf_max)
1664
                        goto found1;
1665

    
1666
                    v1 = is_tab[0][sf];
1667
                    v2 = is_tab[1][sf];
1668
                    for(j=0;j<len;j++) {
1669
                        tmp0 = tab0[j];
1670
                        tab0[j] = MULL(tmp0, v1);
1671
                        tab1[j] = MULL(tmp0, v2);
1672
                    }
1673
                } else {
1674
                found1:
1675
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1676
                        /* lower part of the spectrum : do ms stereo
1677
                           if enabled */
1678
                        for(j=0;j<len;j++) {
1679
                            tmp0 = tab0[j];
1680
                            tmp1 = tab1[j];
1681
                            tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1682
                            tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1683
                        }
1684
                    }
1685
                }
1686
            }
1687
        }
1688

    
1689
        non_zero_found = non_zero_found_short[0] |
1690
            non_zero_found_short[1] |
1691
            non_zero_found_short[2];
1692

    
1693
        for(i = g1->long_end - 1;i >= 0;i--) {
1694
            len = band_size_long[s->sample_rate_index][i];
1695
            tab0 -= len;
1696
            tab1 -= len;
1697
            /* test if non zero band. if so, stop doing i-stereo */
1698
            if (!non_zero_found) {
1699
                for(j=0;j<len;j++) {
1700
                    if (tab1[j] != 0) {
1701
                        non_zero_found = 1;
1702
                        goto found2;
1703
                    }
1704
                }
1705
                /* for last band, use previous scale factor */
1706
                k = (i == 21) ? 20 : i;
1707
                sf = g1->scale_factors[k];
1708
                if (sf >= sf_max)
1709
                    goto found2;
1710
                v1 = is_tab[0][sf];
1711
                v2 = is_tab[1][sf];
1712
                for(j=0;j<len;j++) {
1713
                    tmp0 = tab0[j];
1714
                    tab0[j] = MULL(tmp0, v1);
1715
                    tab1[j] = MULL(tmp0, v2);
1716
                }
1717
            } else {
1718
            found2:
1719
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1720
                    /* lower part of the spectrum : do ms stereo
1721
                       if enabled */
1722
                    for(j=0;j<len;j++) {
1723
                        tmp0 = tab0[j];
1724
                        tmp1 = tab1[j];
1725
                        tab0[j] = MULL(tmp0 + tmp1, ISQRT2);
1726
                        tab1[j] = MULL(tmp0 - tmp1, ISQRT2);
1727
                    }
1728
                }
1729
            }
1730
        }
1731
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1732
        /* ms stereo ONLY */
1733
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1734
           global gain */
1735
        tab0 = g0->sb_hybrid;
1736
        tab1 = g1->sb_hybrid;
1737
        for(i=0;i<576;i++) {
1738
            tmp0 = tab0[i];
1739
            tmp1 = tab1[i];
1740
            tab0[i] = tmp0 + tmp1;
1741
            tab1[i] = tmp0 - tmp1;
1742
        }
1743
    }
1744
}
1745

    
1746
static void compute_antialias_integer(MPADecodeContext *s,
1747
                              GranuleDef *g)
1748
{
1749
    int32_t *ptr, *csa;
1750
    int n, i;
1751

    
1752
    /* we antialias only "long" bands */
1753
    if (g->block_type == 2) {
1754
        if (!g->switch_point)
1755
            return;
1756
        /* XXX: check this for 8000Hz case */
1757
        n = 1;
1758
    } else {
1759
        n = SBLIMIT - 1;
1760
    }
1761

    
1762
    ptr = g->sb_hybrid + 18;
1763
    for(i = n;i > 0;i--) {
1764
        int tmp0, tmp1, tmp2;
1765
        csa = &csa_table[0][0];
1766
#define INT_AA(j) \
1767
            tmp0 = ptr[-1-j];\
1768
            tmp1 = ptr[   j];\
1769
            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\
1770
            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\
1771
            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));
1772

    
1773
        INT_AA(0)
1774
        INT_AA(1)
1775
        INT_AA(2)
1776
        INT_AA(3)
1777
        INT_AA(4)
1778
        INT_AA(5)
1779
        INT_AA(6)
1780
        INT_AA(7)
1781

    
1782
        ptr += 18;
1783
    }
1784
}
1785

    
1786
static void compute_antialias_float(MPADecodeContext *s,
1787
                              GranuleDef *g)
1788
{
1789
    int32_t *ptr;
1790
    int n, i;
1791

    
1792
    /* we antialias only "long" bands */
1793
    if (g->block_type == 2) {
1794
        if (!g->switch_point)
1795
            return;
1796
        /* XXX: check this for 8000Hz case */
1797
        n = 1;
1798
    } else {
1799
        n = SBLIMIT - 1;
1800
    }
1801

    
1802
    ptr = g->sb_hybrid + 18;
1803
    for(i = n;i > 0;i--) {
1804
        float tmp0, tmp1;
1805
        float *csa = &csa_table_float[0][0];
1806
#define FLOAT_AA(j)\
1807
        tmp0= ptr[-1-j];\
1808
        tmp1= ptr[   j];\
1809
        ptr[-1-j] = lrintf(tmp0 * csa[0+4*j] - tmp1 * csa[1+4*j]);\
1810
        ptr[   j] = lrintf(tmp0 * csa[1+4*j] + tmp1 * csa[0+4*j]);
1811

    
1812
        FLOAT_AA(0)
1813
        FLOAT_AA(1)
1814
        FLOAT_AA(2)
1815
        FLOAT_AA(3)
1816
        FLOAT_AA(4)
1817
        FLOAT_AA(5)
1818
        FLOAT_AA(6)
1819
        FLOAT_AA(7)
1820

    
1821
        ptr += 18;
1822
    }
1823
}
1824

    
1825
static void compute_imdct(MPADecodeContext *s,
1826
                          GranuleDef *g,
1827
                          int32_t *sb_samples,
1828
                          int32_t *mdct_buf)
1829
{
1830
    int32_t *ptr, *win, *win1, *buf, *out_ptr, *ptr1;
1831
    int32_t out2[12];
1832
    int i, j, mdct_long_end, v, sblimit;
1833

    
1834
    /* find last non zero block */
1835
    ptr = g->sb_hybrid + 576;
1836
    ptr1 = g->sb_hybrid + 2 * 18;
1837
    while (ptr >= ptr1) {
1838
        ptr -= 6;
1839
        v = ptr[0] | ptr[1] | ptr[2] | ptr[3] | ptr[4] | ptr[5];
1840
        if (v != 0)
1841
            break;
1842
    }
1843
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1844

    
1845
    if (g->block_type == 2) {
1846
        /* XXX: check for 8000 Hz */
1847
        if (g->switch_point)
1848
            mdct_long_end = 2;
1849
        else
1850
            mdct_long_end = 0;
1851
    } else {
1852
        mdct_long_end = sblimit;
1853
    }
1854

    
1855
    buf = mdct_buf;
1856
    ptr = g->sb_hybrid;
1857
    for(j=0;j<mdct_long_end;j++) {
1858
        /* apply window & overlap with previous buffer */
1859
        out_ptr = sb_samples + j;
1860
        /* select window */
1861
        if (g->switch_point && j < 2)
1862
            win1 = mdct_win[0];
1863
        else
1864
            win1 = mdct_win[g->block_type];
1865
        /* select frequency inversion */
1866
        win = win1 + ((4 * 36) & -(j & 1));
1867
        imdct36(out_ptr, buf, ptr, win);
1868
        out_ptr += 18*SBLIMIT;
1869
        ptr += 18;
1870
        buf += 18;
1871
    }
1872
    for(j=mdct_long_end;j<sblimit;j++) {
1873
        /* select frequency inversion */
1874
        win = mdct_win[2] + ((4 * 36) & -(j & 1));
1875
        out_ptr = sb_samples + j;
1876

    
1877
        for(i=0; i<6; i++){
1878
            *out_ptr = buf[i];
1879
            out_ptr += SBLIMIT;
1880
        }
1881
        imdct12(out2, ptr + 0);
1882
        for(i=0;i<6;i++) {
1883
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*1];
1884
            buf[i + 6*2] = MULH(out2[i + 6], win[i + 6]);
1885
            out_ptr += SBLIMIT;
1886
        }
1887
        imdct12(out2, ptr + 1);
1888
        for(i=0;i<6;i++) {
1889
            *out_ptr = MULH(out2[i], win[i]) + buf[i + 6*2];
1890
            buf[i + 6*0] = MULH(out2[i + 6], win[i + 6]);
1891
            out_ptr += SBLIMIT;
1892
        }
1893
        imdct12(out2, ptr + 2);
1894
        for(i=0;i<6;i++) {
1895
            buf[i + 6*0] = MULH(out2[i], win[i]) + buf[i + 6*0];
1896
            buf[i + 6*1] = MULH(out2[i + 6], win[i + 6]);
1897
            buf[i + 6*2] = 0;
1898
        }
1899
        ptr += 18;
1900
        buf += 18;
1901
    }
1902
    /* zero bands */
1903
    for(j=sblimit;j<SBLIMIT;j++) {
1904
        /* overlap */
1905
        out_ptr = sb_samples + j;
1906
        for(i=0;i<18;i++) {
1907
            *out_ptr = buf[i];
1908
            buf[i] = 0;
1909
            out_ptr += SBLIMIT;
1910
        }
1911
        buf += 18;
1912
    }
1913
}
1914

    
1915
#if defined(DEBUG)
1916
void sample_dump(int fnum, int32_t *tab, int n)
1917
{
1918
    static FILE *files[16], *f;
1919
    char buf[512];
1920
    int i;
1921
    int32_t v;
1922

    
1923
    f = files[fnum];
1924
    if (!f) {
1925
        snprintf(buf, sizeof(buf), "/tmp/out%d.%s.pcm",
1926
                fnum,
1927
#ifdef USE_HIGHPRECISION
1928
                "hp"
1929
#else
1930
                "lp"
1931
#endif
1932
                );
1933
        f = fopen(buf, "w");
1934
        if (!f)
1935
            return;
1936
        files[fnum] = f;
1937
    }
1938

    
1939
    if (fnum == 0) {
1940
        static int pos = 0;
1941
        av_log(NULL, AV_LOG_DEBUG, "pos=%d\n", pos);
1942
        for(i=0;i<n;i++) {
1943
            av_log(NULL, AV_LOG_DEBUG, " %0.4f", (double)tab[i] / FRAC_ONE);
1944
            if ((i % 18) == 17)
1945
                av_log(NULL, AV_LOG_DEBUG, "\n");
1946
        }
1947
        pos += n;
1948
    }
1949
    for(i=0;i<n;i++) {
1950
        /* normalize to 23 frac bits */
1951
        v = tab[i] << (23 - FRAC_BITS);
1952
        fwrite(&v, 1, sizeof(int32_t), f);
1953
    }
1954
}
1955
#endif
1956

    
1957

    
1958
/* main layer3 decoding function */
1959
static int mp_decode_layer3(MPADecodeContext *s)
1960
{
1961
    int nb_granules, main_data_begin, private_bits;
1962
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1963
    GranuleDef granules[2][2], *g;
1964
    int16_t exponents[576];
1965

    
1966
    /* read side info */
1967
    if (s->lsf) {
1968
        main_data_begin = get_bits(&s->gb, 8);
1969
        private_bits = get_bits(&s->gb, s->nb_channels);
1970
        nb_granules = 1;
1971
    } else {
1972
        main_data_begin = get_bits(&s->gb, 9);
1973
        if (s->nb_channels == 2)
1974
            private_bits = get_bits(&s->gb, 3);
1975
        else
1976
            private_bits = get_bits(&s->gb, 5);
1977
        nb_granules = 2;
1978
        for(ch=0;ch<s->nb_channels;ch++) {
1979
            granules[ch][0].scfsi = 0; /* all scale factors are transmitted */
1980
            granules[ch][1].scfsi = get_bits(&s->gb, 4);
1981
        }
1982
    }
1983

    
1984
    for(gr=0;gr<nb_granules;gr++) {
1985
        for(ch=0;ch<s->nb_channels;ch++) {
1986
            dprintf(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1987
            g = &granules[ch][gr];
1988
            g->part2_3_length = get_bits(&s->gb, 12);
1989
            g->big_values = get_bits(&s->gb, 9);
1990
            if(g->big_values > 288){
1991
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1992
                return -1;
1993
            }
1994

    
1995
            g->global_gain = get_bits(&s->gb, 8);
1996
            /* if MS stereo only is selected, we precompute the
1997
               1/sqrt(2) renormalization factor */
1998
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1999
                MODE_EXT_MS_STEREO)
2000
                g->global_gain -= 2;
2001
            if (s->lsf)
2002
                g->scalefac_compress = get_bits(&s->gb, 9);
2003
            else
2004
                g->scalefac_compress = get_bits(&s->gb, 4);
2005
            blocksplit_flag = get_bits1(&s->gb);
2006
            if (blocksplit_flag) {
2007
                g->block_type = get_bits(&s->gb, 2);
2008
                if (g->block_type == 0){
2009
                    av_log(NULL, AV_LOG_ERROR, "invalid block type\n");
2010
                    return -1;
2011
                }
2012
                g->switch_point = get_bits1(&s->gb);
2013
                for(i=0;i<2;i++)
2014
                    g->table_select[i] = get_bits(&s->gb, 5);
2015
                for(i=0;i<3;i++)
2016
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
2017
                /* compute huffman coded region sizes */
2018
                if (g->block_type == 2)
2019
                    g->region_size[0] = (36 / 2);
2020
                else {
2021
                    if (s->sample_rate_index <= 2)
2022
                        g->region_size[0] = (36 / 2);
2023
                    else if (s->sample_rate_index != 8)
2024
                        g->region_size[0] = (54 / 2);
2025
                    else
2026
                        g->region_size[0] = (108 / 2);
2027
                }
2028
                g->region_size[1] = (576 / 2);
2029
            } else {
2030
                int region_address1, region_address2, l;
2031
                g->block_type = 0;
2032
                g->switch_point = 0;
2033
                for(i=0;i<3;i++)
2034
                    g->table_select[i] = get_bits(&s->gb, 5);
2035
                /* compute huffman coded region sizes */
2036
                region_address1 = get_bits(&s->gb, 4);
2037
                region_address2 = get_bits(&s->gb, 3);
2038
                dprintf(s->avctx, "region1=%d region2=%d\n",
2039
                        region_address1, region_address2);
2040
                g->region_size[0] =
2041
                    band_index_long[s->sample_rate_index][region_address1 + 1] >> 1;
2042
                l = region_address1 + region_address2 + 2;
2043
                /* should not overflow */
2044
                if (l > 22)
2045
                    l = 22;
2046
                g->region_size[1] =
2047
                    band_index_long[s->sample_rate_index][l] >> 1;
2048
            }
2049
            /* convert region offsets to region sizes and truncate
2050
               size to big_values */
2051
            g->region_size[2] = (576 / 2);
2052
            j = 0;
2053
            for(i=0;i<3;i++) {
2054
                k = FFMIN(g->region_size[i], g->big_values);
2055
                g->region_size[i] = k - j;
2056
                j = k;
2057
            }
2058

    
2059
            /* compute band indexes */
2060
            if (g->block_type == 2) {
2061
                if (g->switch_point) {
2062
                    /* if switched mode, we handle the 36 first samples as
2063
                       long blocks.  For 8000Hz, we handle the 48 first
2064
                       exponents as long blocks (XXX: check this!) */
2065
                    if (s->sample_rate_index <= 2)
2066
                        g->long_end = 8;
2067
                    else if (s->sample_rate_index != 8)
2068
                        g->long_end = 6;
2069
                    else
2070
                        g->long_end = 4; /* 8000 Hz */
2071

    
2072
                    g->short_start = 2 + (s->sample_rate_index != 8);
2073
                } else {
2074
                    g->long_end = 0;
2075
                    g->short_start = 0;
2076
                }
2077
            } else {
2078
                g->short_start = 13;
2079
                g->long_end = 22;
2080
            }
2081

    
2082
            g->preflag = 0;
2083
            if (!s->lsf)
2084
                g->preflag = get_bits1(&s->gb);
2085
            g->scalefac_scale = get_bits1(&s->gb);
2086
            g->count1table_select = get_bits1(&s->gb);
2087
            dprintf(s->avctx, "block_type=%d switch_point=%d\n",
2088
                    g->block_type, g->switch_point);
2089
        }
2090
    }
2091

    
2092
  if (!s->adu_mode) {
2093
    const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
2094
    assert((get_bits_count(&s->gb) & 7) == 0);
2095
    /* now we get bits from the main_data_begin offset */
2096
    dprintf(s->avctx, "seekback: %d\n", main_data_begin);
2097
//av_log(NULL, AV_LOG_ERROR, "backstep:%d, lastbuf:%d\n", main_data_begin, s->last_buf_size);
2098

    
2099
    memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
2100
    s->in_gb= s->gb;
2101
        init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
2102
        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
2103
  }
2104

    
2105
    for(gr=0;gr<nb_granules;gr++) {
2106
        for(ch=0;ch<s->nb_channels;ch++) {
2107
            g = &granules[ch][gr];
2108
            if(get_bits_count(&s->gb)<0){
2109
                av_log(NULL, AV_LOG_ERROR, "mdb:%d, lastbuf:%d skipping granule %d\n",
2110
                                            main_data_begin, s->last_buf_size, gr);
2111
                skip_bits_long(&s->gb, g->part2_3_length);
2112
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
2113
                if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer){
2114
                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
2115
                    s->gb= s->in_gb;
2116
                    s->in_gb.buffer=NULL;
2117
                }
2118
                continue;
2119
            }
2120

    
2121
            bits_pos = get_bits_count(&s->gb);
2122

    
2123
            if (!s->lsf) {
2124
                uint8_t *sc;
2125
                int slen, slen1, slen2;
2126

    
2127
                /* MPEG1 scale factors */
2128
                slen1 = slen_table[0][g->scalefac_compress];
2129
                slen2 = slen_table[1][g->scalefac_compress];
2130
                dprintf(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
2131
                if (g->block_type == 2) {
2132
                    n = g->switch_point ? 17 : 18;
2133
                    j = 0;
2134
                    if(slen1){
2135
                        for(i=0;i<n;i++)
2136
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
2137
                    }else{
2138
                        for(i=0;i<n;i++)
2139
                            g->scale_factors[j++] = 0;
2140
                    }
2141
                    if(slen2){
2142
                        for(i=0;i<18;i++)
2143
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
2144
                        for(i=0;i<3;i++)
2145
                            g->scale_factors[j++] = 0;
2146
                    }else{
2147
                        for(i=0;i<21;i++)
2148
                            g->scale_factors[j++] = 0;
2149
                    }
2150
                } else {
2151
                    sc = granules[ch][0].scale_factors;
2152
                    j = 0;
2153
                    for(k=0;k<4;k++) {
2154
                        n = (k == 0 ? 6 : 5);
2155
                        if ((g->scfsi & (0x8 >> k)) == 0) {
2156
                            slen = (k < 2) ? slen1 : slen2;
2157
                            if(slen){
2158
                                for(i=0;i<n;i++)
2159
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
2160
                            }else{
2161
                                for(i=0;i<n;i++)
2162
                                    g->scale_factors[j++] = 0;
2163
                            }
2164
                        } else {
2165
                            /* simply copy from last granule */
2166
                            for(i=0;i<n;i++) {
2167
                                g->scale_factors[j] = sc[j];
2168
                                j++;
2169
                            }
2170
                        }
2171
                    }
2172
                    g->scale_factors[j++] = 0;
2173
                }
2174
#if defined(DEBUG)
2175
                {
2176
                    dprintf(s->avctx, "scfsi=%x gr=%d ch=%d scale_factors:\n",
2177
                           g->scfsi, gr, ch);
2178
                    for(i=0;i<j;i++)
2179
                        dprintf(s->avctx, " %d", g->scale_factors[i]);
2180
                    dprintf(s->avctx, "\n");
2181
                }
2182
#endif
2183
            } else {
2184
                int tindex, tindex2, slen[4], sl, sf;
2185

    
2186
                /* LSF scale factors */
2187
                if (g->block_type == 2) {
2188
                    tindex = g->switch_point ? 2 : 1;
2189
                } else {
2190
                    tindex = 0;
2191
                }
2192
                sf = g->scalefac_compress;
2193
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
2194
                    /* intensity stereo case */
2195
                    sf >>= 1;
2196
                    if (sf < 180) {
2197
                        lsf_sf_expand(slen, sf, 6, 6, 0);
2198
                        tindex2 = 3;
2199
                    } else if (sf < 244) {
2200
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
2201
                        tindex2 = 4;
2202
                    } else {
2203
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
2204
                        tindex2 = 5;
2205
                    }
2206
                } else {
2207
                    /* normal case */
2208
                    if (sf < 400) {
2209
                        lsf_sf_expand(slen, sf, 5, 4, 4);
2210
                        tindex2 = 0;
2211
                    } else if (sf < 500) {
2212
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
2213
                        tindex2 = 1;
2214
                    } else {
2215
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
2216
                        tindex2 = 2;
2217
                        g->preflag = 1;
2218
                    }
2219
                }
2220

    
2221
                j = 0;
2222
                for(k=0;k<4;k++) {
2223
                    n = lsf_nsf_table[tindex2][tindex][k];
2224
                    sl = slen[k];
2225
                    if(sl){
2226
                        for(i=0;i<n;i++)
2227
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
2228
                    }else{
2229
                        for(i=0;i<n;i++)
2230
                            g->scale_factors[j++] = 0;
2231
                    }
2232
                }
2233
                /* XXX: should compute exact size */
2234
                for(;j<40;j++)
2235
                    g->scale_factors[j] = 0;
2236
#if defined(DEBUG)
2237
                {
2238
                    dprintf(s->avctx, "gr=%d ch=%d scale_factors:\n",
2239
                           gr, ch);
2240
                    for(i=0;i<40;i++)
2241
                        dprintf(s->avctx, " %d", g->scale_factors[i]);
2242
                    dprintf(s->avctx, "\n");
2243
                }
2244
#endif
2245
            }
2246

    
2247
            exponents_from_scale_factors(s, g, exponents);
2248

    
2249
            /* read Huffman coded residue */
2250
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
2251
#if defined(DEBUG)
2252
            sample_dump(0, g->sb_hybrid, 576);
2253
#endif
2254
        } /* ch */
2255

    
2256
        if (s->nb_channels == 2)
2257
            compute_stereo(s, &granules[0][gr], &granules[1][gr]);
2258

    
2259
        for(ch=0;ch<s->nb_channels;ch++) {
2260
            g = &granules[ch][gr];
2261

    
2262
            reorder_block(s, g);
2263
#if defined(DEBUG)
2264
            sample_dump(0, g->sb_hybrid, 576);
2265
#endif
2266
            s->compute_antialias(s, g);
2267
#if defined(DEBUG)
2268
            sample_dump(1, g->sb_hybrid, 576);
2269
#endif
2270
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
2271
#if defined(DEBUG)
2272
            sample_dump(2, &s->sb_samples[ch][18 * gr][0], 576);
2273
#endif
2274
        }
2275
    } /* gr */
2276
    if(get_bits_count(&s->gb)<0)
2277
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
2278
    return nb_granules * 18;
2279
}
2280

    
2281
static int mp_decode_frame(MPADecodeContext *s,
2282
                           OUT_INT *samples, const uint8_t *buf, int buf_size)
2283
{
2284
    int i, nb_frames, ch;
2285
    OUT_INT *samples_ptr;
2286

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

    
2289
    /* skip error protection field */
2290
    if (s->error_protection)
2291
        skip_bits(&s->gb, 16);
2292

    
2293
    dprintf(s->avctx, "frame %d:\n", s->frame_count);
2294
    switch(s->layer) {
2295
    case 1:
2296
        nb_frames = mp_decode_layer1(s);
2297
        break;
2298
    case 2:
2299
        nb_frames = mp_decode_layer2(s);
2300
        break;
2301
    case 3:
2302
    default:
2303
        nb_frames = mp_decode_layer3(s);
2304

    
2305
        s->last_buf_size=0;
2306
        if(s->in_gb.buffer){
2307
            align_get_bits(&s->gb);
2308
            i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2309
            if(i >= 0 && i <= BACKSTEP_SIZE){
2310
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);
2311
                s->last_buf_size=i;
2312
            }else
2313
                av_log(NULL, AV_LOG_ERROR, "invalid old backstep %d\n", i);
2314
            s->gb= s->in_gb;
2315
            s->in_gb.buffer= NULL;
2316
        }
2317

    
2318
        align_get_bits(&s->gb);
2319
        assert((get_bits_count(&s->gb) & 7) == 0);
2320
        i= (s->gb.size_in_bits - get_bits_count(&s->gb))>>3;
2321

    
2322
        if(i<0 || i > BACKSTEP_SIZE || nb_frames<0){
2323
            av_log(NULL, AV_LOG_ERROR, "invalid new backstep %d\n", i);
2324
            i= FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
2325
        }
2326
        assert(i <= buf_size - HEADER_SIZE && i>= 0);
2327
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
2328
        s->last_buf_size += i;
2329

    
2330
        break;
2331
    }
2332
#if defined(DEBUG)
2333
    for(i=0;i<nb_frames;i++) {
2334
        for(ch=0;ch<s->nb_channels;ch++) {
2335
            int j;
2336
            dprintf(s->avctx, "%d-%d:", i, ch);
2337
            for(j=0;j<SBLIMIT;j++)
2338
                dprintf(s->avctx, " %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);
2339
            dprintf(s->avctx, "\n");
2340
        }
2341
    }
2342
#endif
2343
    /* apply the synthesis filter */
2344
    for(ch=0;ch<s->nb_channels;ch++) {
2345
        samples_ptr = samples + ch;
2346
        for(i=0;i<nb_frames;i++) {
2347
            ff_mpa_synth_filter(s->synth_buf[ch], &(s->synth_buf_offset[ch]),
2348
                         window, &s->dither_state,
2349
                         samples_ptr, s->nb_channels,
2350
                         s->sb_samples[ch][i]);
2351
            samples_ptr += 32 * s->nb_channels;
2352
        }
2353
    }
2354
#ifdef DEBUG
2355
    s->frame_count++;
2356
#endif
2357
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
2358
}
2359

    
2360
static int decode_frame(AVCodecContext * avctx,
2361
                        void *data, int *data_size,
2362
                        uint8_t * buf, int buf_size)
2363
{
2364
    MPADecodeContext *s = avctx->priv_data;
2365
    uint32_t header;
2366
    int out_size;
2367
    OUT_INT *out_samples = data;
2368

    
2369
retry:
2370
    if(buf_size < HEADER_SIZE)
2371
        return -1;
2372

    
2373
    header = AV_RB32(buf);
2374
    if(ff_mpa_check_header(header) < 0){
2375
        buf++;
2376
//        buf_size--;
2377
        av_log(avctx, AV_LOG_ERROR, "Header missing skipping one byte.\n");
2378
        goto retry;
2379
    }
2380

    
2381
    if (ff_mpegaudio_decode_header(s, header) == 1) {
2382
        /* free format: prepare to compute frame size */
2383
        s->frame_size = -1;
2384
        return -1;
2385
    }
2386
    /* update codec info */
2387
    avctx->channels = s->nb_channels;
2388
    avctx->bit_rate = s->bit_rate;
2389
    avctx->sub_id = s->layer;
2390
    switch(s->layer) {
2391
    case 1:
2392
        avctx->frame_size = 384;
2393
        break;
2394
    case 2:
2395
        avctx->frame_size = 1152;
2396
        break;
2397
    case 3:
2398
        if (s->lsf)
2399
            avctx->frame_size = 576;
2400
        else
2401
            avctx->frame_size = 1152;
2402
        break;
2403
    }
2404

    
2405
    if(s->frame_size<=0 || s->frame_size > buf_size){
2406
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
2407
        return -1;
2408
    }else if(s->frame_size < buf_size){
2409
        av_log(avctx, AV_LOG_ERROR, "incorrect frame size\n");
2410
        buf_size= s->frame_size;
2411
    }
2412

    
2413
    out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2414
    if(out_size>=0){
2415
        *data_size = out_size;
2416
        avctx->sample_rate = s->sample_rate;
2417
        //FIXME maybe move the other codec info stuff from above here too
2418
    }else
2419
        av_log(avctx, AV_LOG_DEBUG, "Error while decoding MPEG audio frame.\n"); //FIXME return -1 / but also return the number of bytes consumed
2420
    s->frame_size = 0;
2421
    return buf_size;
2422
}
2423

    
2424
static void flush(AVCodecContext *avctx){
2425
    MPADecodeContext *s = avctx->priv_data;
2426
    s->last_buf_size= 0;
2427
}
2428

    
2429
#ifdef CONFIG_MP3ADU_DECODER
2430
static int decode_frame_adu(AVCodecContext * avctx,
2431
                        void *data, int *data_size,
2432
                        uint8_t * buf, int buf_size)
2433
{
2434
    MPADecodeContext *s = avctx->priv_data;
2435
    uint32_t header;
2436
    int len, out_size;
2437
    OUT_INT *out_samples = data;
2438

    
2439
    len = buf_size;
2440

    
2441
    // Discard too short frames
2442
    if (buf_size < HEADER_SIZE) {
2443
        *data_size = 0;
2444
        return buf_size;
2445
    }
2446

    
2447

    
2448
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2449
        len = MPA_MAX_CODED_FRAME_SIZE;
2450

    
2451
    // Get header and restore sync word
2452
    header = AV_RB32(buf) | 0xffe00000;
2453

    
2454
    if (ff_mpa_check_header(header) < 0) { // Bad header, discard frame
2455
        *data_size = 0;
2456
        return buf_size;
2457
    }
2458

    
2459
    ff_mpegaudio_decode_header(s, header);
2460
    /* update codec info */
2461
    avctx->sample_rate = s->sample_rate;
2462
    avctx->channels = s->nb_channels;
2463
    avctx->bit_rate = s->bit_rate;
2464
    avctx->sub_id = s->layer;
2465

    
2466
    avctx->frame_size=s->frame_size = len;
2467

    
2468
    if (avctx->parse_only) {
2469
        out_size = buf_size;
2470
    } else {
2471
        out_size = mp_decode_frame(s, out_samples, buf, buf_size);
2472
    }
2473

    
2474
    *data_size = out_size;
2475
    return buf_size;
2476
}
2477
#endif /* CONFIG_MP3ADU_DECODER */
2478

    
2479
#ifdef CONFIG_MP3ON4_DECODER
2480
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
2481
static int mp3Frames[16] = {0,1,1,2,3,3,4,5,2};   /* number of mp3 decoder instances */
2482
static int mp3Channels[16] = {0,1,2,3,4,5,6,8,4}; /* total output channels */
2483
/* offsets into output buffer, assume output order is FL FR BL BR C LFE */
2484
static int chan_offset[9][5] = {
2485
    {0},
2486
    {0},            // C
2487
    {0},            // FLR
2488
    {2,0},          // C FLR
2489
    {2,0,3},        // C FLR BS
2490
    {4,0,2},        // C FLR BLRS
2491
    {4,0,2,5},      // C FLR BLRS LFE
2492
    {4,0,2,6,5},    // C FLR BLRS BLR LFE
2493
    {0,2}           // FLR BLRS
2494
};
2495

    
2496

    
2497
static int decode_init_mp3on4(AVCodecContext * avctx)
2498
{
2499
    MP3On4DecodeContext *s = avctx->priv_data;
2500
    int i;
2501

    
2502
    if ((avctx->extradata_size < 2) || (avctx->extradata == NULL)) {
2503
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
2504
        return -1;
2505
    }
2506

    
2507
    s->chan_cfg = (((unsigned char *)avctx->extradata)[1] >> 3) & 0x0f;
2508
    s->frames = mp3Frames[s->chan_cfg];
2509
    if(!s->frames) {
2510
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
2511
        return -1;
2512
    }
2513
    avctx->channels = mp3Channels[s->chan_cfg];
2514

    
2515
    /* Init the first mp3 decoder in standard way, so that all tables get builded
2516
     * We replace avctx->priv_data with the context of the first decoder so that
2517
     * decode_init() does not have to be changed.
2518
     * Other decoders will be inited here copying data from the first context
2519
     */
2520
    // Allocate zeroed memory for the first decoder context
2521
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
2522
    // Put decoder context in place to make init_decode() happy
2523
    avctx->priv_data = s->mp3decctx[0];
2524
    decode_init(avctx);
2525
    // Restore mp3on4 context pointer
2526
    avctx->priv_data = s;
2527
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
2528

    
2529
    /* Create a separate codec/context for each frame (first is already ok).
2530
     * Each frame is 1 or 2 channels - up to 5 frames allowed
2531
     */
2532
    for (i = 1; i < s->frames; i++) {
2533
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
2534
        s->mp3decctx[i]->compute_antialias = s->mp3decctx[0]->compute_antialias;
2535
        s->mp3decctx[i]->adu_mode = 1;
2536
        s->mp3decctx[i]->avctx = avctx;
2537
    }
2538

    
2539
    return 0;
2540
}
2541

    
2542

    
2543
static int decode_close_mp3on4(AVCodecContext * avctx)
2544
{
2545
    MP3On4DecodeContext *s = avctx->priv_data;
2546
    int i;
2547

    
2548
    for (i = 0; i < s->frames; i++)
2549
        if (s->mp3decctx[i])
2550
            av_free(s->mp3decctx[i]);
2551

    
2552
    return 0;
2553
}
2554

    
2555

    
2556
static int decode_frame_mp3on4(AVCodecContext * avctx,
2557
                        void *data, int *data_size,
2558
                        uint8_t * buf, int buf_size)
2559
{
2560
    MP3On4DecodeContext *s = avctx->priv_data;
2561
    MPADecodeContext *m;
2562
    int len, out_size = 0;
2563
    uint32_t header;
2564
    OUT_INT *out_samples = data;
2565
    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];
2566
    OUT_INT *outptr, *bp;
2567
    int fsize;
2568
    unsigned char *start2 = buf, *start;
2569
    int fr, i, j, n;
2570
    int off = avctx->channels;
2571
    int *coff = chan_offset[s->chan_cfg];
2572

    
2573
    len = buf_size;
2574

    
2575
    // Discard too short frames
2576
    if (buf_size < HEADER_SIZE) {
2577
        *data_size = 0;
2578
        return buf_size;
2579
    }
2580

    
2581
    // If only one decoder interleave is not needed
2582
    outptr = s->frames == 1 ? out_samples : decoded_buf;
2583

    
2584
    for (fr = 0; fr < s->frames; fr++) {
2585
        start = start2;
2586
        fsize = (start[0] << 4) | (start[1] >> 4);
2587
        start2 += fsize;
2588
        if (fsize > len)
2589
            fsize = len;
2590
        len -= fsize;
2591
        if (fsize > MPA_MAX_CODED_FRAME_SIZE)
2592
            fsize = MPA_MAX_CODED_FRAME_SIZE;
2593
        m = s->mp3decctx[fr];
2594
        assert (m != NULL);
2595

    
2596
        // Get header
2597
        header = AV_RB32(start) | 0xfff00000;
2598

    
2599
        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block
2600
            *data_size = 0;
2601
            return buf_size;
2602
        }
2603

    
2604
        ff_mpegaudio_decode_header(m, header);
2605
        mp_decode_frame(m, decoded_buf, start, fsize);
2606

    
2607
        n = MPA_FRAME_SIZE * m->nb_channels;
2608
        out_size += n * sizeof(OUT_INT);
2609
        if(s->frames > 1) {
2610
            /* interleave output data */
2611
            bp = out_samples + coff[fr];
2612
            if(m->nb_channels == 1) {
2613
                for(j = 0; j < n; j++) {
2614
                    *bp = decoded_buf[j];
2615
                    bp += off;
2616
                }
2617
            } else {
2618
                for(j = 0; j < n; j++) {
2619
                    bp[0] = decoded_buf[j++];
2620
                    bp[1] = decoded_buf[j];
2621
                    bp += off;
2622
                }
2623
            }
2624
        }
2625
    }
2626

    
2627
    /* update codec info */
2628
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2629
    avctx->frame_size= buf_size;
2630
    avctx->bit_rate = 0;
2631
    for (i = 0; i < s->frames; i++)
2632
        avctx->bit_rate += s->mp3decctx[i]->bit_rate;
2633

    
2634
    *data_size = out_size;
2635
    return buf_size;
2636
}
2637
#endif /* CONFIG_MP3ON4_DECODER */
2638

    
2639
#ifdef CONFIG_MP2_DECODER
2640
AVCodec mp2_decoder =
2641
{
2642
    "mp2",
2643
    CODEC_TYPE_AUDIO,
2644
    CODEC_ID_MP2,
2645
    sizeof(MPADecodeContext),
2646
    decode_init,
2647
    NULL,
2648
    NULL,
2649
    decode_frame,
2650
    CODEC_CAP_PARSE_ONLY,
2651
};
2652
#endif
2653
#ifdef CONFIG_MP3_DECODER
2654
AVCodec mp3_decoder =
2655
{
2656
    "mp3",
2657
    CODEC_TYPE_AUDIO,
2658
    CODEC_ID_MP3,
2659
    sizeof(MPADecodeContext),
2660
    decode_init,
2661
    NULL,
2662
    NULL,
2663
    decode_frame,
2664
    CODEC_CAP_PARSE_ONLY,
2665
    .flush= flush,
2666
};
2667
#endif
2668
#ifdef CONFIG_MP3ADU_DECODER
2669
AVCodec mp3adu_decoder =
2670
{
2671
    "mp3adu",
2672
    CODEC_TYPE_AUDIO,
2673
    CODEC_ID_MP3ADU,
2674
    sizeof(MPADecodeContext),
2675
    decode_init,
2676
    NULL,
2677
    NULL,
2678
    decode_frame_adu,
2679
    CODEC_CAP_PARSE_ONLY,
2680
    .flush= flush,
2681
};
2682
#endif
2683
#ifdef CONFIG_MP3ON4_DECODER
2684
AVCodec mp3on4_decoder =
2685
{
2686
    "mp3on4",
2687
    CODEC_TYPE_AUDIO,
2688
    CODEC_ID_MP3ON4,
2689
    sizeof(MP3On4DecodeContext),
2690
    decode_init_mp3on4,
2691
    NULL,
2692
    decode_close_mp3on4,
2693
    decode_frame_mp3on4,
2694
    .flush= flush,
2695
};
2696
#endif