Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegaudiodec.c @ 3d929a60

History | View | Annotate | Download (70.9 KB)

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

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

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

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

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

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

    
62
/****************/
63

    
64
#define HEADER_SIZE 4
65

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
236
    return m;
237
}
238

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

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

    
247
static int dev_4_3_coefs[DEV_ORDER];
248

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

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

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

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

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

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

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

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

    
306
        RENAME(ff_mpa_synth_init)(RENAME(ff_mpa_synth_window));
307

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

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

    
319
            xsize = h->xsize;
320

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

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

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

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

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

    
361
        int_pow_init();
362
        mpegaudio_tableinit();
363

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

    
377

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

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

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

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

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

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

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

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

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

    
461
        init = 1;
462
    }
463

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

    
469

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

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

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

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

    
486
#else
487

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
622

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

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

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

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

    
646
#define C3 FIXHR(0.86602540378443864676/2)
647

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

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

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

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

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

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

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

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

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

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

    
727

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1139

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

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

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

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

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

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

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

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

    
1218
            exponent= exponents[s_index];
1219

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

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

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

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

    
1318
    return 0;
1319
}
1320

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

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

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

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

    
1358
#define ISQRT2 FIXR(0.70710678118654752440)
1359

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1841
            exponents_from_scale_factors(s, g, exponents);
1842

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

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

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

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

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

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

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

    
1875
    switch(s->layer) {
1876
    case 1:
1877
        s->avctx->frame_size = 384;
1878
        nb_frames = mp_decode_layer1(s);
1879
        break;
1880
    case 2:
1881
        s->avctx->frame_size = 1152;
1882
        nb_frames = mp_decode_layer2(s);
1883
        break;
1884
    case 3:
1885
        s->avctx->frame_size = s->lsf ? 576 : 1152;
1886
    default:
1887
        nb_frames = mp_decode_layer3(s);
1888

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

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

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

    
1915
        break;
1916
    }
1917

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

    
1934
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1935
}
1936

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

    
1948
    if(buf_size < HEADER_SIZE)
1949
        return -1;
1950

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

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

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

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

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

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

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

    
2010
    len = buf_size;
2011

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

    
2018

    
2019
    if (len > MPA_MAX_CODED_FRAME_SIZE)
2020
        len = MPA_MAX_CODED_FRAME_SIZE;
2021

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

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

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

    
2038
    s->frame_size = len;
2039

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

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

    
2051
#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
2052

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

    
2063
#include "mpeg4audio.h"
2064

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

    
2079

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

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

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

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

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

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

    
2128
    return 0;
2129
}
2130

    
2131

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

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

    
2140
    return 0;
2141
}
2142

    
2143

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

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

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

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

    
2170
    avctx->bit_rate = 0;
2171

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

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

    
2180
        if (ff_mpa_check_header(header) < 0) // Bad header, discard block
2181
            break;
2182

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

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

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

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

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