GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/mpegaudiodec_template.c Lines: 742 1071 69.3 %
Date: 2020-11-28 20:53:16 Branches: 390 592 65.9 %

Line Branch Exec Source
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/attributes.h"
28
#include "libavutil/avassert.h"
29
#include "libavutil/channel_layout.h"
30
#include "libavutil/crc.h"
31
#include "libavutil/float_dsp.h"
32
#include "libavutil/libm.h"
33
#include "avcodec.h"
34
#include "get_bits.h"
35
#include "internal.h"
36
#include "mathops.h"
37
#include "mpegaudiodsp.h"
38
39
/*
40
 * TODO:
41
 *  - test lsf / mpeg25 extensively.
42
 */
43
44
#include "mpegaudio.h"
45
#include "mpegaudiodecheader.h"
46
47
#define BACKSTEP_SIZE 512
48
#define EXTRABYTES 24
49
#define LAST_BUF_SIZE 2 * BACKSTEP_SIZE + EXTRABYTES
50
51
/* layer 3 "granule" */
52
typedef struct GranuleDef {
53
    uint8_t scfsi;
54
    int part2_3_length;
55
    int big_values;
56
    int global_gain;
57
    int scalefac_compress;
58
    uint8_t block_type;
59
    uint8_t switch_point;
60
    int table_select[3];
61
    int subblock_gain[3];
62
    uint8_t scalefac_scale;
63
    uint8_t count1table_select;
64
    int region_size[3]; /* number of huffman codes in each region */
65
    int preflag;
66
    int short_start, long_end; /* long/short band indexes */
67
    uint8_t scale_factors[40];
68
    DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
69
} GranuleDef;
70
71
typedef struct MPADecodeContext {
72
    MPA_DECODE_HEADER
73
    uint8_t last_buf[LAST_BUF_SIZE];
74
    int last_buf_size;
75
    int extrasize;
76
    /* next header (used in free format parsing) */
77
    uint32_t free_format_next_header;
78
    GetBitContext gb;
79
    GetBitContext in_gb;
80
    DECLARE_ALIGNED(32, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
81
    int synth_buf_offset[MPA_MAX_CHANNELS];
82
    DECLARE_ALIGNED(32, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
83
    INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
84
    GranuleDef granules[2][2]; /* Used in Layer 3 */
85
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
86
    int dither_state;
87
    int err_recognition;
88
    AVCodecContext* avctx;
89
    MPADSPContext mpadsp;
90
    void (*butterflies_float)(float *av_restrict v1, float *av_restrict v2, int len);
91
    AVFrame *frame;
92
    uint32_t crc;
93
} MPADecodeContext;
94
95
#define HEADER_SIZE 4
96
97
#include "mpegaudiodata.h"
98
#include "mpegaudiodectab.h"
99
100
/* vlc structure for decoding layer 3 huffman tables */
101
static VLC huff_vlc[16];
102
static VLC_TYPE huff_vlc_tables[
103
    0 + 128 + 128 + 128 + 130 + 128 + 154 + 166 +
104
  142 + 204 + 190 + 170 + 542 + 460 + 662 + 414
105
  ][2];
106
static const int huff_vlc_tables_sizes[16] = {
107
    0,  128,  128,  128,  130,  128,  154,  166,
108
  142,  204,  190,  170,  542,  460,  662,  414
109
};
110
static VLC huff_quad_vlc[2];
111
static VLC_TYPE  huff_quad_vlc_tables[64+16][2];
112
static const int huff_quad_vlc_tables_sizes[2] = { 64, 16 };
113
/* computed from band_size_long */
114
static uint16_t band_index_long[9][23];
115
#include "mpegaudio_tablegen.h"
116
/* intensity stereo coef table */
117
static INTFLOAT is_table[2][16];
118
static INTFLOAT is_table_lsf[2][2][16];
119
static INTFLOAT csa_table[8][4];
120
121
static int16_t division_tab3[1 << 6 ];
122
static int16_t division_tab5[1 << 8 ];
123
static int16_t division_tab9[1 << 11];
124
125
static int16_t * const division_tabs[4] = {
126
    division_tab3, division_tab5, NULL, division_tab9
127
};
128
129
/* lower 2 bits: modulo 3, higher bits: shift */
130
static uint16_t scale_factor_modshift[64];
131
/* [i][j]:  2^(-j/3) * FRAC_ONE * 2^(i+2) / (2^(i+2) - 1) */
132
static int32_t scale_factor_mult[15][3];
133
/* mult table for layer 2 group quantization */
134
135
#define SCALE_GEN(v) \
136
{ FIXR_OLD(1.0 * (v)), FIXR_OLD(0.7937005259 * (v)), FIXR_OLD(0.6299605249 * (v)) }
137
138
static const int32_t scale_factor_mult2[3][3] = {
139
    SCALE_GEN(4.0 / 3.0), /* 3 steps */
140
    SCALE_GEN(4.0 / 5.0), /* 5 steps */
141
    SCALE_GEN(4.0 / 9.0), /* 9 steps */
142
};
143
144
/**
145
 * Convert region offsets to region sizes and truncate
146
 * size to big_values.
147
 */
148
8116
static void region_offset2size(GranuleDef *g)
149
{
150
8116
    int i, k, j = 0;
151
8116
    g->region_size[2] = 576 / 2;
152
32464
    for (i = 0; i < 3; i++) {
153
24348
        k = FFMIN(g->region_size[i], g->big_values);
154
24348
        g->region_size[i] = k - j;
155
24348
        j = k;
156
    }
157
8116
}
158
159
845
static void init_short_region(MPADecodeContext *s, GranuleDef *g)
160
{
161
845
    if (g->block_type == 2) {
162
305
        if (s->sample_rate_index != 8)
163
305
            g->region_size[0] = (36 / 2);
164
        else
165
            g->region_size[0] = (72 / 2);
166
    } else {
167
540
        if (s->sample_rate_index <= 2)
168
539
            g->region_size[0] = (36 / 2);
169
1
        else if (s->sample_rate_index != 8)
170
1
            g->region_size[0] = (54 / 2);
171
        else
172
            g->region_size[0] = (108 / 2);
173
    }
174
845
    g->region_size[1] = (576 / 2);
175
845
}
176
177
7271
static void init_long_region(MPADecodeContext *s, GranuleDef *g,
178
                             int ra1, int ra2)
179
{
180
    int l;
181
7271
    g->region_size[0] = band_index_long[s->sample_rate_index][ra1 + 1] >> 1;
182
    /* should not overflow */
183
7271
    l = FFMIN(ra1 + ra2 + 2, 22);
184
7271
    g->region_size[1] = band_index_long[s->sample_rate_index][      l] >> 1;
185
7271
}
186
187
8116
static void compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
188
{
189
8116
    if (g->block_type == 2) {
190
305
        if (g->switch_point) {
191
13
            if(s->sample_rate_index == 8)
192
                avpriv_request_sample(s->avctx, "switch point in 8khz");
193
            /* if switched mode, we handle the 36 first samples as
194
                long blocks.  For 8000Hz, we handle the 72 first
195
                exponents as long blocks */
196
13
            if (s->sample_rate_index <= 2)
197
13
                g->long_end = 8;
198
            else
199
                g->long_end = 6;
200
201
13
            g->short_start = 3;
202
        } else {
203
292
            g->long_end    = 0;
204
292
            g->short_start = 0;
205
        }
206
    } else {
207
7811
        g->short_start = 13;
208
7811
        g->long_end    = 22;
209
    }
210
8116
}
211
212
/* layer 1 unscaling */
213
/* n = number of bits of the mantissa minus 1 */
214
5010120
static inline int l1_unscale(int n, int mant, int scale_factor)
215
{
216
    int shift, mod;
217
    int64_t val;
218
219
5010120
    shift   = scale_factor_modshift[scale_factor];
220
5010120
    mod     = shift & 3;
221
5010120
    shift >>= 2;
222
5010120
    val     = MUL64((int)(mant + (-1U << n) + 1), scale_factor_mult[n-1][mod]);
223
5010120
    shift  += n;
224
    /* NOTE: at this point, 1 <= shift >= 21 + 15 */
225
5010120
    return (int)((val + (1LL << (shift - 1))) >> shift);
226
}
227
228
883224
static inline int l2_unscale_group(int steps, int mant, int scale_factor)
229
{
230
    int shift, mod, val;
231
232
883224
    shift   = scale_factor_modshift[scale_factor];
233
883224
    mod     = shift & 3;
234
883224
    shift >>= 2;
235
236
883224
    val = (mant - (steps >> 1)) * scale_factor_mult2[steps >> 2][mod];
237
    /* NOTE: at this point, 0 <= shift <= 21 */
238
883224
    if (shift > 0)
239
883224
        val = (val + (1 << (shift - 1))) >> shift;
240
883224
    return val;
241
}
242
243
/* compute value^(4/3) * 2^(exponent/4). It normalized to FRAC_BITS */
244
56735
static inline int l3_unscale(int value, int exponent)
245
{
246
    unsigned int m;
247
    int e;
248
249
56735
    e  = table_4_3_exp  [4 * value + (exponent & 3)];
250
56735
    m  = table_4_3_value[4 * value + (exponent & 3)];
251
56735
    e -= exponent >> 2;
252
#ifdef DEBUG
253
    if(e < 1)
254
        av_log(NULL, AV_LOG_WARNING, "l3_unscale: e is %d\n", e);
255
#endif
256
56735
    if (e > (SUINT)31)
257
10
        return 0;
258
56725
    m = (m + ((1U << e) >> 1)) >> e;
259
260
56725
    return m;
261
}
262
263
90
static av_cold void decode_init_static(void)
264
{
265
    int i, j, k;
266
    int offset;
267
268
    /* scale factors table for layer 1/2 */
269
5850
    for (i = 0; i < 64; i++) {
270
        int shift, mod;
271
        /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */
272
5760
        shift = i / 3;
273
5760
        mod   = i % 3;
274
5760
        scale_factor_modshift[i] = mod | (shift << 2);
275
    }
276
277
    /* scale factor multiply for layer 1 */
278
1440
    for (i = 0; i < 15; i++) {
279
        int n, norm;
280
1350
        n = i + 2;
281
1350
        norm = ((INT64_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);
282
1350
        scale_factor_mult[i][0] = MULLx(norm, FIXR(1.0          * 2.0), FRAC_BITS);
283
1350
        scale_factor_mult[i][1] = MULLx(norm, FIXR(0.7937005259 * 2.0), FRAC_BITS);
284
1350
        scale_factor_mult[i][2] = MULLx(norm, FIXR(0.6299605249 * 2.0), FRAC_BITS);
285
        ff_dlog(NULL, "%d: norm=%x s=%"PRIx32" %"PRIx32" %"PRIx32"\n", i,
286
                (unsigned)norm,
287
                scale_factor_mult[i][0],
288
                scale_factor_mult[i][1],
289
                scale_factor_mult[i][2]);
290
    }
291
292
    /* huffman decode tables */
293
90
    offset = 0;
294
1440
    for (i = 1; i < 16; i++) {
295
1350
        const HuffTable *h = &mpa_huff_tables[i];
296
        int xsize, x, y;
297
1350
        uint8_t  tmp_bits [512] = { 0 };
298
1350
        uint16_t tmp_codes[512] = { 0 };
299
300
1350
        xsize = h->xsize;
301
302
1350
        j = 0;
303
12330
        for (x = 0; x < xsize; x++) {
304
135000
            for (y = 0; y < xsize; y++) {
305

124020
                tmp_bits [(x << 5) | y | ((x && y) << 4)]= h->bits [j  ];
306

124020
                tmp_codes[(x << 5) | y | ((x && y) << 4)]= h->codes[j++];
307
            }
308
        }
309
310
        /* XXX: fail test */
311
1350
        huff_vlc[i].table = huff_vlc_tables+offset;
312
1350
        huff_vlc[i].table_allocated = huff_vlc_tables_sizes[i];
313
1350
        init_vlc(&huff_vlc[i], 7, 512,
314
                 tmp_bits, 1, 1, tmp_codes, 2, 2,
315
                 INIT_VLC_USE_NEW_STATIC);
316
1350
        offset += huff_vlc_tables_sizes[i];
317
    }
318
90
    av_assert0(offset == FF_ARRAY_ELEMS(huff_vlc_tables));
319
320
90
    offset = 0;
321
270
    for (i = 0; i < 2; i++) {
322
180
        huff_quad_vlc[i].table = huff_quad_vlc_tables+offset;
323
180
        huff_quad_vlc[i].table_allocated = huff_quad_vlc_tables_sizes[i];
324
180
        init_vlc(&huff_quad_vlc[i], i == 0 ? 6 : 4, 16,
325
                 mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1,
326
                 INIT_VLC_USE_NEW_STATIC);
327
180
        offset += huff_quad_vlc_tables_sizes[i];
328
    }
329
90
    av_assert0(offset == FF_ARRAY_ELEMS(huff_quad_vlc_tables));
330
331
900
    for (i = 0; i < 9; i++) {
332
810
        k = 0;
333
18630
        for (j = 0; j < 22; j++) {
334
17820
            band_index_long[i][j] = k;
335
17820
            k += band_size_long[i][j];
336
        }
337
810
        band_index_long[i][22] = k;
338
    }
339
340
    /* compute n ^ (4/3) and store it in mantissa/exp format */
341
342
90
    mpegaudio_tableinit();
343
344
450
    for (i = 0; i < 4; i++) {
345
360
        if (ff_mpa_quant_bits[i] < 0) {
346
213390
            for (j = 0; j < (1 << (-ff_mpa_quant_bits[i] + 1)); j++) {
347
                int val1, val2, val3, steps;
348
213120
                int val = j;
349
213120
                steps   = ff_mpa_quant_steps[i];
350
213120
                val1    = val % steps;
351
213120
                val    /= steps;
352
213120
                val2    = val % steps;
353
213120
                val3    = val / steps;
354
213120
                division_tabs[i][j] = val1 + (val2 << 4) + (val3 << 8);
355
            }
356
        }
357
    }
358
359
360
720
    for (i = 0; i < 7; i++) {
361
        float f;
362
        INTFLOAT v;
363
630
        if (i != 6) {
364
540
            f = tan((double)i * M_PI / 12.0);
365
540
            v = FIXR(f / (1.0 + f));
366
        } else {
367
90
            v = FIXR(1.0);
368
        }
369
630
        is_table[0][    i] = v;
370
630
        is_table[1][6 - i] = v;
371
    }
372
    /* invalid values */
373
900
    for (i = 7; i < 16; i++)
374
810
        is_table[0][i] = is_table[1][i] = 0.0;
375
376
1530
    for (i = 0; i < 16; i++) {
377
        double f;
378
        int e, k;
379
380
4320
        for (j = 0; j < 2; j++) {
381
2880
            e = -(j + 1) * ((i + 1) >> 1);
382
2880
            f = exp2(e / 4.0);
383
2880
            k = i & 1;
384
2880
            is_table_lsf[j][k ^ 1][i] = FIXR(f);
385
2880
            is_table_lsf[j][k    ][i] = FIXR(1.0);
386
            ff_dlog(NULL, "is_table_lsf %d %d: %f %f\n",
387
                    i, j, (float) is_table_lsf[j][0][i],
388
                    (float) is_table_lsf[j][1][i]);
389
        }
390
    }
391
392
810
    for (i = 0; i < 8; i++) {
393
        double ci, cs, ca;
394
720
        ci = ci_table[i];
395
720
        cs = 1.0 / sqrt(1.0 + ci * ci);
396
720
        ca = cs * ci;
397
#if !USE_FLOATS
398
352
        csa_table[i][0] = FIXHR(cs/4);
399
352
        csa_table[i][1] = FIXHR(ca/4);
400
352
        csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);
401
352
        csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);
402
#else
403
368
        csa_table[i][0] = cs;
404
368
        csa_table[i][1] = ca;
405
368
        csa_table[i][2] = ca + cs;
406
368
        csa_table[i][3] = ca - cs;
407
#endif
408
    }
409
90
    RENAME(ff_mpa_synth_init)();
410
90
}
411
412
132
static av_cold int decode_init(AVCodecContext * avctx)
413
{
414
    static int initialized_tables = 0;
415
132
    MPADecodeContext *s = avctx->priv_data;
416
417
132
    if (!initialized_tables) {
418
90
        decode_init_static();
419
90
        initialized_tables = 1;
420
    }
421
422
132
    s->avctx = avctx;
423
424
#if USE_FLOATS
425
    {
426
        AVFloatDSPContext *fdsp;
427
63
        fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
428
63
        if (!fdsp)
429
            return AVERROR(ENOMEM);
430
63
        s->butterflies_float = fdsp->butterflies_float;
431
63
        av_free(fdsp);
432
    }
433
#endif
434
435
132
    ff_mpadsp_init(&s->mpadsp);
436
437
132
    if (avctx->request_sample_fmt == OUT_FMT &&
438
        avctx->codec_id != AV_CODEC_ID_MP3ON4)
439
        avctx->sample_fmt = OUT_FMT;
440
    else
441
132
        avctx->sample_fmt = OUT_FMT_P;
442
132
    s->err_recognition = avctx->err_recognition;
443
444
132
    if (avctx->codec_id == AV_CODEC_ID_MP3ADU)
445
        s->adu_mode = 1;
446
447
132
    return 0;
448
}
449
450
#define C3 FIXHR(0.86602540378443864676/2)
451
#define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
452
#define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
453
#define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
454
455
/* 12 points IMDCT. We compute it "by hand" by factorizing obvious
456
   cases. */
457
19371
static void imdct12(INTFLOAT *out, SUINTFLOAT *in)
458
{
459
    SUINTFLOAT in0, in1, in2, in3, in4, in5, t1, t2;
460
461
19371
    in0  = in[0*3];
462
19371
    in1  = in[1*3] + in[0*3];
463
19371
    in2  = in[2*3] + in[1*3];
464
19371
    in3  = in[3*3] + in[2*3];
465
19371
    in4  = in[4*3] + in[3*3];
466
19371
    in5  = in[5*3] + in[4*3];
467
19371
    in5 += in3;
468
19371
    in3 += in1;
469
470
19371
    in2  = MULH3(in2, C3, 2);
471
19371
    in3  = MULH3(in3, C3, 4);
472
473
19371
    t1   = in0 - in4;
474
19371
    t2   = MULH3(in1 - in5, C4, 2);
475
476
19371
    out[ 7] =
477
19371
    out[10] = t1 + t2;
478
19371
    out[ 1] =
479
19371
    out[ 4] = t1 - t2;
480
481
19371
    in0    += SHR(in4, 1);
482
19371
    in4     = in0 + in2;
483
19371
    in5    += 2*in1;
484
19371
    in1     = MULH3(in5 + in3, C5, 1);
485
19371
    out[ 8] =
486
19371
    out[ 9] = in4 + in1;
487
19371
    out[ 2] =
488
19371
    out[ 3] = in4 - in1;
489
490
19371
    in0    -= in2;
491
19371
    in5     = MULH3(in5 - in3, C6, 2);
492
19371
    out[ 0] =
493
19371
    out[ 5] = in0 - in5;
494
19371
    out[ 6] =
495
19371
    out[11] = in0 + in5;
496
19371
}
497
498
10041
static int handle_crc(MPADecodeContext *s, int sec_len)
499
{
500

10041
    if (s->error_protection && (s->err_recognition & AV_EF_CRCCHECK)) {
501
        const uint8_t *buf = s->gb.buffer - HEADER_SIZE;
502
        int sec_byte_len  = sec_len >> 3;
503
        int sec_rem_bits  = sec_len & 7;
504
        const AVCRC *crc_tab = av_crc_get_table(AV_CRC_16_ANSI);
505
        uint8_t tmp_buf[4];
506
        uint32_t crc_val = av_crc(crc_tab, UINT16_MAX, &buf[2], 2);
507
        crc_val = av_crc(crc_tab, crc_val, &buf[6], sec_byte_len);
508
509
        AV_WB32(tmp_buf,
510
                ((buf[6 + sec_byte_len] & (0xFF00 >> sec_rem_bits)) << 24) +
511
                ((s->crc << 16) >> sec_rem_bits));
512
513
        crc_val = av_crc(crc_tab, crc_val, tmp_buf, 3);
514
515
        if (crc_val) {
516
            av_log(s->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", crc_val);
517
            if (s->err_recognition & AV_EF_EXPLODE)
518
                return AVERROR_INVALIDDATA;
519
        }
520
    }
521
10041
    return 0;
522
}
523
524
/* return the number of decoded frames */
525
static int mp_decode_layer1(MPADecodeContext *s)
526
{
527
    int bound, i, v, n, ch, j, mant;
528
    uint8_t allocation[MPA_MAX_CHANNELS][SBLIMIT];
529
    uint8_t scale_factors[MPA_MAX_CHANNELS][SBLIMIT];
530
    int ret;
531
532
    ret = handle_crc(s, (s->nb_channels == 1) ? 8*16  : 8*32);
533
    if (ret < 0)
534
        return ret;
535
536
    if (s->mode == MPA_JSTEREO)
537
        bound = (s->mode_ext + 1) * 4;
538
    else
539
        bound = SBLIMIT;
540
541
    /* allocation bits */
542
    for (i = 0; i < bound; i++) {
543
        for (ch = 0; ch < s->nb_channels; ch++) {
544
            allocation[ch][i] = get_bits(&s->gb, 4);
545
        }
546
    }
547
    for (i = bound; i < SBLIMIT; i++)
548
        allocation[0][i] = get_bits(&s->gb, 4);
549
550
    /* scale factors */
551
    for (i = 0; i < bound; i++) {
552
        for (ch = 0; ch < s->nb_channels; ch++) {
553
            if (allocation[ch][i])
554
                scale_factors[ch][i] = get_bits(&s->gb, 6);
555
        }
556
    }
557
    for (i = bound; i < SBLIMIT; i++) {
558
        if (allocation[0][i]) {
559
            scale_factors[0][i] = get_bits(&s->gb, 6);
560
            scale_factors[1][i] = get_bits(&s->gb, 6);
561
        }
562
    }
563
564
    /* compute samples */
565
    for (j = 0; j < 12; j++) {
566
        for (i = 0; i < bound; i++) {
567
            for (ch = 0; ch < s->nb_channels; ch++) {
568
                n = allocation[ch][i];
569
                if (n) {
570
                    mant = get_bits(&s->gb, n + 1);
571
                    v = l1_unscale(n, mant, scale_factors[ch][i]);
572
                } else {
573
                    v = 0;
574
                }
575
                s->sb_samples[ch][j][i] = v;
576
            }
577
        }
578
        for (i = bound; i < SBLIMIT; i++) {
579
            n = allocation[0][i];
580
            if (n) {
581
                mant = get_bits(&s->gb, n + 1);
582
                v = l1_unscale(n, mant, scale_factors[0][i]);
583
                s->sb_samples[0][j][i] = v;
584
                v = l1_unscale(n, mant, scale_factors[1][i]);
585
                s->sb_samples[1][j][i] = v;
586
            } else {
587
                s->sb_samples[0][j][i] = 0;
588
                s->sb_samples[1][j][i] = 0;
589
            }
590
        }
591
    }
592
    return 12;
593
}
594
595
7238
static int mp_decode_layer2(MPADecodeContext *s)
596
{
597
    int sblimit; /* number of used subbands */
598
    const unsigned char *alloc_table;
599
    int table, bit_alloc_bits, i, j, ch, bound, v;
600
    unsigned char bit_alloc[MPA_MAX_CHANNELS][SBLIMIT];
601
    unsigned char scale_code[MPA_MAX_CHANNELS][SBLIMIT];
602
    unsigned char scale_factors[MPA_MAX_CHANNELS][SBLIMIT][3], *sf;
603
    int scale, qindex, bits, steps, k, l, m, b;
604
    int ret;
605
606
    /* select decoding table */
607
7238
    table = ff_mpa_l2_select_table(s->bit_rate / 1000, s->nb_channels,
608
                                   s->sample_rate, s->lsf);
609
7238
    sblimit     = ff_mpa_sblimit_table[table];
610
7238
    alloc_table = ff_mpa_alloc_tables[table];
611
612
7238
    if (s->mode == MPA_JSTEREO)
613
        bound = (s->mode_ext + 1) * 4;
614
    else
615
7238
        bound = sblimit;
616
617
    ff_dlog(s->avctx, "bound=%d sblimit=%d\n", bound, sblimit);
618
619
    /* sanity check */
620
7238
    if (bound > sblimit)
621
        bound = sblimit;
622
623
    /* parse bit allocation */
624
7238
    j = 0;
625
221897
    for (i = 0; i < bound; i++) {
626
214659
        bit_alloc_bits = alloc_table[j];
627
447456
        for (ch = 0; ch < s->nb_channels; ch++)
628
232797
            bit_alloc[ch][i] = get_bits(&s->gb, bit_alloc_bits);
629
214659
        j += 1 << bit_alloc_bits;
630
    }
631
7238
    for (i = bound; i < sblimit; i++) {
632
        bit_alloc_bits = alloc_table[j];
633
        v = get_bits(&s->gb, bit_alloc_bits);
634
        bit_alloc[0][i] = v;
635
        bit_alloc[1][i] = v;
636
        j += 1 << bit_alloc_bits;
637
    }
638
639
    /* scale codes */
640
221897
    for (i = 0; i < sblimit; i++) {
641
447456
        for (ch = 0; ch < s->nb_channels; ch++) {
642
232797
            if (bit_alloc[ch][i])
643
163704
                scale_code[ch][i] = get_bits(&s->gb, 2);
644
        }
645
    }
646
647
7238
    ret = handle_crc(s, get_bits_count(&s->gb) - 16);
648
7238
    if (ret < 0)
649
        return ret;
650
651
    /* scale factors */
652
221897
    for (i = 0; i < sblimit; i++) {
653
447456
        for (ch = 0; ch < s->nb_channels; ch++) {
654
232797
            if (bit_alloc[ch][i]) {
655
163704
                sf = scale_factors[ch][i];
656

163704
                switch (scale_code[ch][i]) {
657
2940
                default:
658
                case 0:
659
2940
                    sf[0] = get_bits(&s->gb, 6);
660
2940
                    sf[1] = get_bits(&s->gb, 6);
661
2940
                    sf[2] = get_bits(&s->gb, 6);
662
2940
                    break;
663
153193
                case 2:
664
153193
                    sf[0] = get_bits(&s->gb, 6);
665
153193
                    sf[1] = sf[0];
666
153193
                    sf[2] = sf[0];
667
153193
                    break;
668
2542
                case 1:
669
2542
                    sf[0] = get_bits(&s->gb, 6);
670
2542
                    sf[2] = get_bits(&s->gb, 6);
671
2542
                    sf[1] = sf[0];
672
2542
                    break;
673
5029
                case 3:
674
5029
                    sf[0] = get_bits(&s->gb, 6);
675
5029
                    sf[2] = get_bits(&s->gb, 6);
676
5029
                    sf[1] = sf[2];
677
5029
                    break;
678
                }
679
69093
            }
680
        }
681
    }
682
683
    /* samples */
684
28952
    for (k = 0; k < 3; k++) {
685
108570
        for (l = 0; l < 12; l += 3) {
686
86856
            j = 0;
687
2662764
            for (i = 0; i < bound; i++) {
688
2575908
                bit_alloc_bits = alloc_table[j];
689
5369472
                for (ch = 0; ch < s->nb_channels; ch++) {
690
2793564
                    b = bit_alloc[ch][i];
691
2793564
                    if (b) {
692
1964448
                        scale = scale_factors[ch][i][k];
693
1964448
                        qindex = alloc_table[j+b];
694
1964448
                        bits = ff_mpa_quant_bits[qindex];
695
1964448
                        if (bits < 0) {
696
                            int v2;
697
                            /* 3 values at the same time */
698
294408
                            v = get_bits(&s->gb, -bits);
699
294408
                            v2 = division_tabs[qindex][v];
700
294408
                            steps  = ff_mpa_quant_steps[qindex];
701
702
586728
                            s->sb_samples[ch][k * 12 + l + 0][i] =
703
294408
                                l2_unscale_group(steps,  v2       & 15, scale);
704
586728
                            s->sb_samples[ch][k * 12 + l + 1][i] =
705
294408
                                l2_unscale_group(steps, (v2 >> 4) & 15, scale);
706
294408
                            s->sb_samples[ch][k * 12 + l + 2][i] =
707
294408
                                l2_unscale_group(steps,  v2 >> 8      , scale);
708
                        } else {
709
6680160
                            for (m = 0; m < 3; m++) {
710
5010120
                                v = get_bits(&s->gb, bits);
711
5010120
                                v = l1_unscale(bits - 1, v, scale);
712
5010120
                                s->sb_samples[ch][k * 12 + l + m][i] = v;
713
                            }
714
                        }
715
                    } else {
716
829116
                        s->sb_samples[ch][k * 12 + l + 0][i] = 0;
717
829116
                        s->sb_samples[ch][k * 12 + l + 1][i] = 0;
718
829116
                        s->sb_samples[ch][k * 12 + l + 2][i] = 0;
719
                    }
720
                }
721
                /* next subband in alloc table */
722
2575908
                j += 1 << bit_alloc_bits;
723
            }
724
            /* XXX: find a way to avoid this duplication of code */
725
86856
            for (i = bound; i < sblimit; i++) {
726
                bit_alloc_bits = alloc_table[j];
727
                b = bit_alloc[0][i];
728
                if (b) {
729
                    int mant, scale0, scale1;
730
                    scale0 = scale_factors[0][i][k];
731
                    scale1 = scale_factors[1][i][k];
732
                    qindex = alloc_table[j + b];
733
                    bits = ff_mpa_quant_bits[qindex];
734
                    if (bits < 0) {
735
                        /* 3 values at the same time */
736
                        v = get_bits(&s->gb, -bits);
737
                        steps = ff_mpa_quant_steps[qindex];
738
                        mant = v % steps;
739
                        v = v / steps;
740
                        s->sb_samples[0][k * 12 + l + 0][i] =
741
                            l2_unscale_group(steps, mant, scale0);
742
                        s->sb_samples[1][k * 12 + l + 0][i] =
743
                            l2_unscale_group(steps, mant, scale1);
744
                        mant = v % steps;
745
                        v = v / steps;
746
                        s->sb_samples[0][k * 12 + l + 1][i] =
747
                            l2_unscale_group(steps, mant, scale0);
748
                        s->sb_samples[1][k * 12 + l + 1][i] =
749
                            l2_unscale_group(steps, mant, scale1);
750
                        s->sb_samples[0][k * 12 + l + 2][i] =
751
                            l2_unscale_group(steps, v, scale0);
752
                        s->sb_samples[1][k * 12 + l + 2][i] =
753
                            l2_unscale_group(steps, v, scale1);
754
                    } else {
755
                        for (m = 0; m < 3; m++) {
756
                            mant = get_bits(&s->gb, bits);
757
                            s->sb_samples[0][k * 12 + l + m][i] =
758
                                l1_unscale(bits - 1, mant, scale0);
759
                            s->sb_samples[1][k * 12 + l + m][i] =
760
                                l1_unscale(bits - 1, mant, scale1);
761
                        }
762
                    }
763
                } else {
764
                    s->sb_samples[0][k * 12 + l + 0][i] = 0;
765
                    s->sb_samples[0][k * 12 + l + 1][i] = 0;
766
                    s->sb_samples[0][k * 12 + l + 2][i] = 0;
767
                    s->sb_samples[1][k * 12 + l + 0][i] = 0;
768
                    s->sb_samples[1][k * 12 + l + 1][i] = 0;
769
                    s->sb_samples[1][k * 12 + l + 2][i] = 0;
770
                }
771
                /* next subband in alloc table */
772
                j += 1 << bit_alloc_bits;
773
            }
774
            /* fill remaining samples to zero */
775
290340
            for (i = sblimit; i < SBLIMIT; i++) {
776
437376
                for (ch = 0; ch < s->nb_channels; ch++) {
777
233892
                    s->sb_samples[ch][k * 12 + l + 0][i] = 0;
778
233892
                    s->sb_samples[ch][k * 12 + l + 1][i] = 0;
779
233892
                    s->sb_samples[ch][k * 12 + l + 2][i] = 0;
780
                }
781
            }
782
        }
783
    }
784
7238
    return 3 * 12;
785
}
786
787
#define SPLIT(dst,sf,n)             \
788
    if (n == 3) {                   \
789
        int m = (sf * 171) >> 9;    \
790
        dst   = sf - 3 * m;         \
791
        sf    = m;                  \
792
    } else if (n == 4) {            \
793
        dst  = sf & 3;              \
794
        sf >>= 2;                   \
795
    } else if (n == 5) {            \
796
        int m = (sf * 205) >> 10;   \
797
        dst   = sf - 5 * m;         \
798
        sf    = m;                  \
799
    } else if (n == 6) {            \
800
        int m = (sf * 171) >> 10;   \
801
        dst   = sf - 6 * m;         \
802
        sf    = m;                  \
803
    } else {                        \
804
        dst = 0;                    \
805
    }
806
807
4
static av_always_inline void lsf_sf_expand(int *slen, int sf, int n1, int n2,
808
                                           int n3)
809
{
810


4
    SPLIT(slen[3], sf, n3)
811


4
    SPLIT(slen[2], sf, n2)
812


4
    SPLIT(slen[1], sf, n1)
813
4
    slen[0] = sf;
814
4
}
815
816
8112
static void exponents_from_scale_factors(MPADecodeContext *s, GranuleDef *g,
817
                                         int16_t *exponents)
818
{
819
    const uint8_t *bstab, *pretab;
820
    int len, i, j, k, l, v0, shift, gain, gains[3];
821
    int16_t *exp_ptr;
822
823
8112
    exp_ptr = exponents;
824
8112
    gain    = g->global_gain - 210;
825
8112
    shift   = g->scalefac_scale + 1;
826
827
8112
    bstab  = band_size_long[s->sample_rate_index];
828
8112
    pretab = mpa_pretab[g->preflag];
829
179992
    for (i = 0; i < g->long_end; i++) {
830
171880
        v0 = gain - ((g->scale_factors[i] + pretab[i]) << shift) + 400;
831
171880
        len = bstab[i];
832
4669756
        for (j = len; j > 0; j--)
833
4497876
            *exp_ptr++ = v0;
834
    }
835
836
8112
    if (g->short_start < 13) {
837
304
        bstab    = band_size_short[s->sample_rate_index];
838
304
        gains[0] = gain - (g->subblock_gain[0] << 3);
839
304
        gains[1] = gain - (g->subblock_gain[1] << 3);
840
304
        gains[2] = gain - (g->subblock_gain[2] << 3);
841
304
        k        = g->long_end;
842
4217
        for (i = g->short_start; i < 13; i++) {
843
3913
            len = bstab[i];
844
15652
            for (l = 0; l < 3; l++) {
845
11739
                v0 = gains[l] - (g->scale_factors[k++] << shift) + 400;
846
186375
                for (j = len; j > 0; j--)
847
174636
                    *exp_ptr++ = v0;
848
            }
849
        }
850
    }
851
8112
}
852
853
16799
static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,
854
                          int *end_pos2)
855
{
856

16799
    if (s->in_gb.buffer && *pos >= s->gb.size_in_bits - s->extrasize * 8) {
857
939
        s->gb           = s->in_gb;
858
939
        s->in_gb.buffer = NULL;
859
939
        s->extrasize    = 0;
860
        av_assert2((get_bits_count(&s->gb) & 7) == 0);
861
939
        skip_bits_long(&s->gb, *pos - *end_pos);
862
939
        *end_pos2 =
863
939
        *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;
864
939
        *pos      = get_bits_count(&s->gb);
865
    }
866
16799
}
867
868
/* Following is an optimized code for
869
            INTFLOAT v = *src
870
            if(get_bits1(&s->gb))
871
                v = -v;
872
            *dst = v;
873
*/
874
#if USE_FLOATS
875
#define READ_FLIP_SIGN(dst,src)                     \
876
    v = AV_RN32A(src) ^ (get_bits1(&s->gb) << 31);  \
877
    AV_WN32A(dst, v);
878
#else
879
#define READ_FLIP_SIGN(dst,src)     \
880
    v      = -get_bits1(&s->gb);    \
881
    *(dst) = (*(src) ^ v) - v;
882
#endif
883
884
8112
static int huffman_decode(MPADecodeContext *s, GranuleDef *g,
885
                          int16_t *exponents, int end_pos2)
886
{
887
    int s_index;
888
    int i;
889
    int last_pos, bits_left;
890
    VLC *vlc;
891
8112
    int end_pos = FFMIN(end_pos2, s->gb.size_in_bits - s->extrasize * 8);
892
893
    /* low frequencies (called big values) */
894
8112
    s_index = 0;
895
32448
    for (i = 0; i < 3; i++) {
896
        int j, k, l, linbits;
897
24336
        j = g->region_size[i];
898
24336
        if (j == 0)
899
1292
            continue;
900
        /* select vlc table */
901
23044
        k       = g->table_select[i];
902
23044
        l       = mpa_huff_data[k][0];
903
23044
        linbits = mpa_huff_data[k][1];
904
23044
        vlc     = &huff_vlc[l];
905
906
23044
        if (!l) {
907
92
            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * 2 * j);
908
92
            s_index += 2 * j;
909
92
            continue;
910
        }
911
912
        /* read huffcode and compute each couple */
913
909472
        for (; j > 0; j--) {
914
            int exponent, x, y;
915
            int v;
916
886520
            int pos = get_bits_count(&s->gb);
917
918
886520
            if (pos >= end_pos){
919
789
                switch_buffer(s, &pos, &end_pos, &end_pos2);
920
789
                if (pos >= end_pos)
921
                    break;
922
            }
923
886520
            y = get_vlc2(&s->gb, vlc->table, 7, 3);
924
925
886520
            if (!y) {
926
215662
                g->sb_hybrid[s_index    ] =
927
215662
                g->sb_hybrid[s_index + 1] = 0;
928
215662
                s_index += 2;
929
215662
                continue;
930
            }
931
932
670858
            exponent= exponents[s_index];
933
934
            ff_dlog(s->avctx, "region=%d n=%d y=%d exp=%d\n",
935
                    i, g->region_size[i] - j, y, exponent);
936
670858
            if (y & 16) {
937
426226
                x = y >> 5;
938
426226
                y = y & 0x0f;
939
426226
                if (x < 15) {
940
400278
                    READ_FLIP_SIGN(g->sb_hybrid + s_index, RENAME(expval_table)[exponent] + x)
941
                } else {
942
25948
                    x += get_bitsz(&s->gb, linbits);
943
25948
                    v  = l3_unscale(x, exponent);
944
25948
                    if (get_bits1(&s->gb))
945
12440
                        v = -v;
946
25948
                    g->sb_hybrid[s_index] = v;
947
                }
948
426226
                if (y < 15) {
949
401244
                    READ_FLIP_SIGN(g->sb_hybrid + s_index + 1, RENAME(expval_table)[exponent] + y)
950
                } else {
951
24982
                    y += get_bitsz(&s->gb, linbits);
952
24982
                    v  = l3_unscale(y, exponent);
953
24982
                    if (get_bits1(&s->gb))
954
11889
                        v = -v;
955
24982
                    g->sb_hybrid[s_index + 1] = v;
956
                }
957
            } else {
958
244632
                x = y >> 5;
959
244632
                y = y & 0x0f;
960
244632
                x += y;
961
244632
                if (x < 15) {
962
238827
                    READ_FLIP_SIGN(g->sb_hybrid + s_index + !!y, RENAME(expval_table)[exponent] + x)
963
                } else {
964
5805
                    x += get_bitsz(&s->gb, linbits);
965
5805
                    v  = l3_unscale(x, exponent);
966
5805
                    if (get_bits1(&s->gb))
967
2114
                        v = -v;
968
5805
                    g->sb_hybrid[s_index+!!y] = v;
969
                }
970
244632
                g->sb_hybrid[s_index + !y] = 0;
971
            }
972
670858
            s_index += 2;
973
        }
974
    }
975
976
    /* high frequencies */
977
8112
    vlc = &huff_quad_vlc[g->count1table_select];
978
8112
    last_pos = 0;
979
226739
    while (s_index <= 572) {
980
        int pos, code;
981
226438
        pos = get_bits_count(&s->gb);
982
226438
        if (pos >= end_pos) {
983

7898
            if (pos > end_pos2 && last_pos) {
984
                /* some encoders generate an incorrect size for this
985
                   part. We must go back into the data */
986
                s_index -= 4;
987
                skip_bits_long(&s->gb, last_pos - pos);
988
                av_log(s->avctx, AV_LOG_INFO, "overread, skip %d enddists: %d %d\n", last_pos - pos, end_pos-pos, end_pos2-pos);
989
                if(s->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))
990
                    s_index=0;
991
7811
                break;
992
            }
993
7898
            switch_buffer(s, &pos, &end_pos, &end_pos2);
994
7898
            if (pos >= end_pos)
995
7811
                break;
996
        }
997
218627
        last_pos = pos;
998
999
218627
        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);
1000
        ff_dlog(s->avctx, "t=%d code=%d\n", g->count1table_select, code);
1001
218627
        g->sb_hybrid[s_index + 0] =
1002
218627
        g->sb_hybrid[s_index + 1] =
1003
218627
        g->sb_hybrid[s_index + 2] =
1004
218627
        g->sb_hybrid[s_index + 3] = 0;
1005
366945
        while (code) {
1006
            static const int idxtab[16] = { 3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0 };
1007
            int v;
1008
148318
            int pos = s_index + idxtab[code];
1009
148318
            code   ^= 8 >> idxtab[code];
1010
148318
            READ_FLIP_SIGN(g->sb_hybrid + pos, RENAME(exp_table)+exponents[pos])
1011
        }
1012
218627
        s_index += 4;
1013
    }
1014
    /* skip extension bits */
1015
8112
    bits_left = end_pos2 - get_bits_count(&s->gb);
1016

8112
    if (bits_left < 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_COMPLIANT))) {
1017
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1018
        s_index=0;
1019

8112
    } else if (bits_left > 0 && (s->err_recognition & (AV_EF_BUFFER|AV_EF_AGGRESSIVE))) {
1020
        av_log(s->avctx, AV_LOG_ERROR, "bits_left=%d\n", bits_left);
1021
        s_index = 0;
1022
    }
1023
8112
    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid) * (576 - s_index));
1024
8112
    skip_bits_long(&s->gb, bits_left);
1025
1026
8112
    i = get_bits_count(&s->gb);
1027
8112
    switch_buffer(s, &i, &end_pos, &end_pos2);
1028
1029
8112
    return 0;
1030
}
1031
1032
/* Reorder short blocks from bitstream order to interleaved order. It
1033
   would be faster to do it in parsing, but the code would be far more
1034
   complicated */
1035
8112
static void reorder_block(MPADecodeContext *s, GranuleDef *g)
1036
{
1037
    int i, j, len;
1038
    INTFLOAT *ptr, *dst, *ptr1;
1039
    INTFLOAT tmp[576];
1040
1041
8112
    if (g->block_type != 2)
1042
7808
        return;
1043
1044
304
    if (g->switch_point) {
1045
13
        if (s->sample_rate_index != 8)
1046
13
            ptr = g->sb_hybrid + 36;
1047
        else
1048
            ptr = g->sb_hybrid + 72;
1049
    } else {
1050
291
        ptr = g->sb_hybrid;
1051
    }
1052
1053
4217
    for (i = g->short_start; i < 13; i++) {
1054
3913
        len  = band_size_short[s->sample_rate_index][i];
1055
3913
        ptr1 = ptr;
1056
3913
        dst  = tmp;
1057
62125
        for (j = len; j > 0; j--) {
1058
58212
            *dst++ = ptr[0*len];
1059
58212
            *dst++ = ptr[1*len];
1060
58212
            *dst++ = ptr[2*len];
1061
58212
            ptr++;
1062
        }
1063
3913
        ptr += 2 * len;
1064
3913
        memcpy(ptr1, tmp, len * 3 * sizeof(*ptr1));
1065
    }
1066
}
1067
1068
#define ISQRT2 FIXR(0.70710678118654752440)
1069
1070
2447
static void compute_stereo(MPADecodeContext *s, GranuleDef *g0, GranuleDef *g1)
1071
{
1072
    int i, j, k, l;
1073
    int sf_max, sf, len, non_zero_found;
1074
    INTFLOAT (*is_tab)[16], *tab0, *tab1, v1, v2;
1075
    SUINTFLOAT tmp0, tmp1;
1076
    int non_zero_found_short[3];
1077
1078
    /* intensity stereo */
1079
2447
    if (s->mode_ext & MODE_EXT_I_STEREO) {
1080
1
        if (!s->lsf) {
1081
            is_tab = is_table;
1082
            sf_max = 7;
1083
        } else {
1084
1
            is_tab = is_table_lsf[g1->scalefac_compress & 1];
1085
1
            sf_max = 16;
1086
        }
1087
1088
1
        tab0 = g0->sb_hybrid + 576;
1089
1
        tab1 = g1->sb_hybrid + 576;
1090
1091
1
        non_zero_found_short[0] = 0;
1092
1
        non_zero_found_short[1] = 0;
1093
1
        non_zero_found_short[2] = 0;
1094
1
        k = (13 - g1->short_start) * 3 + g1->long_end - 3;
1095
1
        for (i = 12; i >= g1->short_start; i--) {
1096
            /* for last band, use previous scale factor */
1097
            if (i != 11)
1098
                k -= 3;
1099
            len = band_size_short[s->sample_rate_index][i];
1100
            for (l = 2; l >= 0; l--) {
1101
                tab0 -= len;
1102
                tab1 -= len;
1103
                if (!non_zero_found_short[l]) {
1104
                    /* test if non zero band. if so, stop doing i-stereo */
1105
                    for (j = 0; j < len; j++) {
1106
                        if (tab1[j] != 0) {
1107
                            non_zero_found_short[l] = 1;
1108
                            goto found1;
1109
                        }
1110
                    }
1111
                    sf = g1->scale_factors[k + l];
1112
                    if (sf >= sf_max)
1113
                        goto found1;
1114
1115
                    v1 = is_tab[0][sf];
1116
                    v2 = is_tab[1][sf];
1117
                    for (j = 0; j < len; j++) {
1118
                        tmp0    = tab0[j];
1119
                        tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1120
                        tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1121
                    }
1122
                } else {
1123
found1:
1124
                    if (s->mode_ext & MODE_EXT_MS_STEREO) {
1125
                        /* lower part of the spectrum : do ms stereo
1126
                           if enabled */
1127
                        for (j = 0; j < len; j++) {
1128
                            tmp0    = tab0[j];
1129
                            tmp1    = tab1[j];
1130
                            tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1131
                            tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1132
                        }
1133
                    }
1134
                }
1135
            }
1136
        }
1137
1138
1
        non_zero_found = non_zero_found_short[0] |
1139
1
                         non_zero_found_short[1] |
1140
1
                         non_zero_found_short[2];
1141
1142
23
        for (i = g1->long_end - 1;i >= 0;i--) {
1143
22
            len   = band_size_long[s->sample_rate_index][i];
1144
22
            tab0 -= len;
1145
22
            tab1 -= len;
1146
            /* test if non zero band. if so, stop doing i-stereo */
1147
22
            if (!non_zero_found) {
1148
598
                for (j = 0; j < len; j++) {
1149
576
                    if (tab1[j] != 0) {
1150
                        non_zero_found = 1;
1151
                        goto found2;
1152
                    }
1153
                }
1154
                /* for last band, use previous scale factor */
1155
22
                k  = (i == 21) ? 20 : i;
1156
22
                sf = g1->scale_factors[k];
1157
22
                if (sf >= sf_max)
1158
                    goto found2;
1159
22
                v1 = is_tab[0][sf];
1160
22
                v2 = is_tab[1][sf];
1161
598
                for (j = 0; j < len; j++) {
1162
576
                    tmp0    = tab0[j];
1163
576
                    tab0[j] = MULLx(tmp0, v1, FRAC_BITS);
1164
576
                    tab1[j] = MULLx(tmp0, v2, FRAC_BITS);
1165
                }
1166
            } else {
1167
found2:
1168
                if (s->mode_ext & MODE_EXT_MS_STEREO) {
1169
                    /* lower part of the spectrum : do ms stereo
1170
                       if enabled */
1171
                    for (j = 0; j < len; j++) {
1172
                        tmp0    = tab0[j];
1173
                        tmp1    = tab1[j];
1174
                        tab0[j] = MULLx(tmp0 + tmp1, ISQRT2, FRAC_BITS);
1175
                        tab1[j] = MULLx(tmp0 - tmp1, ISQRT2, FRAC_BITS);
1176
                    }
1177
                }
1178
            }
1179
        }
1180
2446
    } else if (s->mode_ext & MODE_EXT_MS_STEREO) {
1181
        /* ms stereo ONLY */
1182
        /* NOTE: the 1/sqrt(2) normalization factor is included in the
1183
           global gain */
1184
#if USE_FLOATS
1185
52
       s->butterflies_float(g0->sb_hybrid, g1->sb_hybrid, 576);
1186
#else
1187
2176
        tab0 = g0->sb_hybrid;
1188
2176
        tab1 = g1->sb_hybrid;
1189
1255552
        for (i = 0; i < 576; i++) {
1190
1253376
            tmp0    = tab0[i];
1191
1253376
            tmp1    = tab1[i];
1192
1253376
            tab0[i] = tmp0 + tmp1;
1193
1253376
            tab1[i] = tmp0 - tmp1;
1194
        }
1195
#endif
1196
    }
1197
2447
}
1198
1199
#if USE_FLOATS
1200
#if HAVE_MIPSFPU
1201
#   include "mips/compute_antialias_float.h"
1202
#endif /* HAVE_MIPSFPU */
1203
#else
1204
#if HAVE_MIPSDSP
1205
#   include "mips/compute_antialias_fixed.h"
1206
#endif /* HAVE_MIPSDSP */
1207
#endif /* USE_FLOATS */
1208
1209
#ifndef compute_antialias
1210
#if USE_FLOATS
1211
#define AA(j) do {                                                      \
1212
        float tmp0 = ptr[-1-j];                                         \
1213
        float tmp1 = ptr[   j];                                         \
1214
        ptr[-1-j] = tmp0 * csa_table[j][0] - tmp1 * csa_table[j][1];    \
1215
        ptr[   j] = tmp0 * csa_table[j][1] + tmp1 * csa_table[j][0];    \
1216
    } while (0)
1217
#else
1218
#define AA(j) do {                                              \
1219
        SUINT tmp0 = ptr[-1-j];                                   \
1220
        SUINT tmp1 = ptr[   j];                                   \
1221
        SUINT tmp2 = MULH(tmp0 + tmp1, csa_table[j][0]);          \
1222
        ptr[-1-j] = 4 * (tmp2 - MULH(tmp1, csa_table[j][2]));   \
1223
        ptr[   j] = 4 * (tmp2 + MULH(tmp0, csa_table[j][3]));   \
1224
    } while (0)
1225
#endif
1226
1227
8112
static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
1228
{
1229
    INTFLOAT *ptr;
1230
    int n, i;
1231
1232
    /* we antialias only "long" bands */
1233
8112
    if (g->block_type == 2) {
1234
304
        if (!g->switch_point)
1235
291
            return;
1236
        /* XXX: check this for 8000Hz case */
1237
13
        n = 1;
1238
    } else {
1239
7808
        n = SBLIMIT - 1;
1240
    }
1241
1242
7821
    ptr = g->sb_hybrid + 18;
1243
249882
    for (i = n; i > 0; i--) {
1244
242061
        AA(0);
1245
242061
        AA(1);
1246
242061
        AA(2);
1247
242061
        AA(3);
1248
242061
        AA(4);
1249
242061
        AA(5);
1250
242061
        AA(6);
1251
242061
        AA(7);
1252
1253
242061
        ptr += 18;
1254
    }
1255
}
1256
#endif /* compute_antialias */
1257
1258
8116
static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
1259
                          INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
1260
{
1261
    INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
1262
    INTFLOAT out2[12];
1263
    int i, j, mdct_long_end, sblimit;
1264
1265
    /* find last non zero block */
1266
8116
    ptr  = g->sb_hybrid + 576;
1267
8116
    ptr1 = g->sb_hybrid + 2 * 18;
1268
312005
    while (ptr >= ptr1) {
1269
        int32_t *p;
1270
311823
        ptr -= 6;
1271
311823
        p    = (int32_t*)ptr;
1272
311823
        if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5])
1273
7934
            break;
1274
    }
1275
8116
    sblimit = ((ptr - g->sb_hybrid) / 18) + 1;
1276
1277
8116
    if (g->block_type == 2) {
1278
        /* XXX: check for 8000 Hz */
1279
305
        if (g->switch_point)
1280
13
            mdct_long_end = 2;
1281
        else
1282
292
            mdct_long_end = 0;
1283
    } else {
1284
7811
        mdct_long_end = sblimit;
1285
    }
1286
1287
8116
    s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
1288
8116
                                     mdct_long_end, g->switch_point,
1289
8116
                                     g->block_type);
1290
1291
8116
    buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
1292
8116
    ptr = g->sb_hybrid + 18 * mdct_long_end;
1293
1294
14573
    for (j = mdct_long_end; j < sblimit; j++) {
1295
        /* select frequency inversion */
1296
6457
        win     = RENAME(ff_mdct_win)[2 + (4  & -(j & 1))];
1297
6457
        out_ptr = sb_samples + j;
1298
1299
45199
        for (i = 0; i < 6; i++) {
1300
38742
            *out_ptr = buf[4*i];
1301
38742
            out_ptr += SBLIMIT;
1302
        }
1303
6457
        imdct12(out2, ptr + 0);
1304
45199
        for (i = 0; i < 6; i++) {
1305
38742
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*1)];
1306
38742
            buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
1307
38742
            out_ptr += SBLIMIT;
1308
        }
1309
6457
        imdct12(out2, ptr + 1);
1310
45199
        for (i = 0; i < 6; i++) {
1311
38742
            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*2)];
1312
38742
            buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
1313
38742
            out_ptr += SBLIMIT;
1314
        }
1315
6457
        imdct12(out2, ptr + 2);
1316
45199
        for (i = 0; i < 6; i++) {
1317
38742
            buf[4*(i + 6*0)] = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*0)];
1318
38742
            buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
1319
38742
            buf[4*(i + 6*2)] = 0;
1320
        }
1321
6457
        ptr += 18;
1322
6457
        buf += (j&3) != 3 ? 1 : (4*18-3);
1323
    }
1324
    /* zero bands */
1325
105676
    for (j = sblimit; j < SBLIMIT; j++) {
1326
        /* overlap */
1327
97560
        out_ptr = sb_samples + j;
1328
1853640
        for (i = 0; i < 18; i++) {
1329
1756080
            *out_ptr = buf[4*i];
1330
1756080
            buf[4*i]   = 0;
1331
1756080
            out_ptr += SBLIMIT;
1332
        }
1333
97560
        buf += (j&3) != 3 ? 1 : (4*18-3);
1334
    }
1335
8116
}
1336
1337
/* main layer3 decoding function */
1338
2803
static int mp_decode_layer3(MPADecodeContext *s)
1339
{
1340
    int nb_granules, main_data_begin;
1341
    int gr, ch, blocksplit_flag, i, j, k, n, bits_pos;
1342
    GranuleDef *g;
1343
    int16_t exponents[576]; //FIXME try INTFLOAT
1344
    int ret;
1345
1346
    /* read side info */
1347
2803
    if (s->lsf) {
1348
3
        ret = handle_crc(s, ((s->nb_channels == 1) ? 8*9  : 8*17));
1349
3
        main_data_begin = get_bits(&s->gb, 8);
1350
3
        skip_bits(&s->gb, s->nb_channels);
1351
3
        nb_granules = 1;
1352
    } else {
1353
2800
        ret = handle_crc(s, ((s->nb_channels == 1) ? 8*17 : 8*32));
1354
2800
        main_data_begin = get_bits(&s->gb, 9);
1355
2800
        if (s->nb_channels == 2)
1356
1256
            skip_bits(&s->gb, 3);
1357
        else
1358
1544
            skip_bits(&s->gb, 5);
1359
2800
        nb_granules = 2;
1360
6856
        for (ch = 0; ch < s->nb_channels; ch++) {
1361
4056
            s->granules[ch][0].scfsi = 0;/* all scale factors are transmitted */
1362
4056
            s->granules[ch][1].scfsi = get_bits(&s->gb, 4);
1363
        }
1364
    }
1365
2803
    if (ret < 0)
1366
        return ret;
1367
1368
8406
    for (gr = 0; gr < nb_granules; gr++) {
1369
13719
        for (ch = 0; ch < s->nb_channels; ch++) {
1370
            ff_dlog(s->avctx, "gr=%d ch=%d: side_info\n", gr, ch);
1371
8116
            g = &s->granules[ch][gr];
1372
8116
            g->part2_3_length = get_bits(&s->gb, 12);
1373
8116
            g->big_values     = get_bits(&s->gb,  9);
1374
8116
            if (g->big_values > 288) {
1375
                av_log(s->avctx, AV_LOG_ERROR, "big_values too big\n");
1376
                return AVERROR_INVALIDDATA;
1377
            }
1378
1379
8116
            g->global_gain = get_bits(&s->gb, 8);
1380
            /* if MS stereo only is selected, we precompute the
1381
               1/sqrt(2) renormalization factor */
1382
8116
            if ((s->mode_ext & (MODE_EXT_MS_STEREO | MODE_EXT_I_STEREO)) ==
1383
                MODE_EXT_MS_STEREO)
1384
4456
                g->global_gain -= 2;
1385
8116
            if (s->lsf)
1386
4
                g->scalefac_compress = get_bits(&s->gb, 9);
1387
            else
1388
8112
                g->scalefac_compress = get_bits(&s->gb, 4);
1389
8116
            blocksplit_flag = get_bits1(&s->gb);
1390
8116
            if (blocksplit_flag) {
1391
845
                g->block_type = get_bits(&s->gb, 2);
1392
845
                if (g->block_type == 0) {
1393
                    av_log(s->avctx, AV_LOG_ERROR, "invalid block type\n");
1394
                    return AVERROR_INVALIDDATA;
1395
                }
1396
845
                g->switch_point = get_bits1(&s->gb);
1397
2535
                for (i = 0; i < 2; i++)
1398
1690
                    g->table_select[i] = get_bits(&s->gb, 5);
1399
3380
                for (i = 0; i < 3; i++)
1400
2535
                    g->subblock_gain[i] = get_bits(&s->gb, 3);
1401
845
                init_short_region(s, g);
1402
            } else {
1403
                int region_address1, region_address2;
1404
7271
                g->block_type = 0;
1405
7271
                g->switch_point = 0;
1406
29084
                for (i = 0; i < 3; i++)
1407
21813
                    g->table_select[i] = get_bits(&s->gb, 5);
1408
                /* compute huffman coded region sizes */
1409
7271
                region_address1 = get_bits(&s->gb, 4);
1410
7271
                region_address2 = get_bits(&s->gb, 3);
1411
                ff_dlog(s->avctx, "region1=%d region2=%d\n",
1412
                        region_address1, region_address2);
1413
7271
                init_long_region(s, g, region_address1, region_address2);
1414
            }
1415
8116
            region_offset2size(g);
1416
8116
            compute_band_indexes(s, g);
1417
1418
8116
            g->preflag = 0;
1419
8116
            if (!s->lsf)
1420
8112
                g->preflag = get_bits1(&s->gb);
1421
8116
            g->scalefac_scale     = get_bits1(&s->gb);
1422
8116
            g->count1table_select = get_bits1(&s->gb);
1423
            ff_dlog(s->avctx, "block_type=%d switch_point=%d\n",
1424
                    g->block_type, g->switch_point);
1425
        }
1426
    }
1427
1428
2803
    if (!s->adu_mode) {
1429
        int skip;
1430
2803
        const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb) >> 3);
1431
2803
        s->extrasize = av_clip((get_bits_left(&s->gb) >> 3) - s->extrasize, 0,
1432
2803
                               FFMAX(0, LAST_BUF_SIZE - s->last_buf_size));
1433
        av_assert1((get_bits_count(&s->gb) & 7) == 0);
1434
        /* now we get bits from the main_data_begin offset */
1435
        ff_dlog(s->avctx, "seekback:%d, lastbuf:%d\n",
1436
                main_data_begin, s->last_buf_size);
1437
1438
2803
        memcpy(s->last_buf + s->last_buf_size, ptr, s->extrasize);
1439
2803
        s->in_gb = s->gb;
1440
2803
        init_get_bits(&s->gb, s->last_buf, (s->last_buf_size + s->extrasize) * 8);
1441
2803
        s->last_buf_size <<= 3;
1442

2807
        for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
1443
8
            for (ch = 0; ch < s->nb_channels; ch++) {
1444
4
                g = &s->granules[ch][gr];
1445
4
                s->last_buf_size += g->part2_3_length;
1446
4
                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
1447
4
                compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1448
            }
1449
        }
1450
2803
        skip = s->last_buf_size - 8 * main_data_begin;
1451

2803
        if (skip >= s->gb.size_in_bits - s->extrasize * 8 && s->in_gb.buffer) {
1452
145
            skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits + s->extrasize * 8);
1453
145
            s->gb           = s->in_gb;
1454
145
            s->in_gb.buffer = NULL;
1455
145
            s->extrasize    = 0;
1456
        } else {
1457
2658
            skip_bits_long(&s->gb, skip);
1458
        }
1459
    } else {
1460
        gr = 0;
1461
        s->extrasize = 0;
1462
    }
1463
1464
8402
    for (; gr < nb_granules; gr++) {
1465
13711
        for (ch = 0; ch < s->nb_channels; ch++) {
1466
8112
            g = &s->granules[ch][gr];
1467
8112
            bits_pos = get_bits_count(&s->gb);
1468
1469
8112
            if (!s->lsf) {
1470
                uint8_t *sc;
1471
                int slen, slen1, slen2;
1472
1473
                /* MPEG-1 scale factors */
1474
8108
                slen1 = slen_table[0][g->scalefac_compress];
1475
8108
                slen2 = slen_table[1][g->scalefac_compress];
1476
                ff_dlog(s->avctx, "slen1=%d slen2=%d\n", slen1, slen2);
1477
8108
                if (g->block_type == 2) {
1478
304
                    n = g->switch_point ? 17 : 18;
1479
304
                    j = 0;
1480
304
                    if (slen1) {
1481
756
                        for (i = 0; i < n; i++)
1482
716
                            g->scale_factors[j++] = get_bits(&s->gb, slen1);
1483
                    } else {
1484
5007
                        for (i = 0; i < n; i++)
1485
4743
                            g->scale_factors[j++] = 0;
1486
                    }
1487
304
                    if (slen2) {
1488
4826
                        for (i = 0; i < 18; i++)
1489
4572
                            g->scale_factors[j++] = get_bits(&s->gb, slen2);
1490
1016
                        for (i = 0; i < 3; i++)
1491
762
                            g->scale_factors[j++] = 0;
1492
                    } else {
1493
1100
                        for (i = 0; i < 21; i++)
1494
1050
                            g->scale_factors[j++] = 0;
1495
                    }
1496
                } else {
1497
7804
                    sc = s->granules[ch][0].scale_factors;
1498
7804
                    j = 0;
1499
39020
                    for (k = 0; k < 4; k++) {
1500
31216
                        n = k == 0 ? 6 : 5;
1501
31216
                        if ((g->scfsi & (0x8 >> k)) == 0) {
1502
26870
                            slen = (k < 2) ? slen1 : slen2;
1503
26870
                            if (slen) {
1504
88829
                                for (i = 0; i < n; i++)
1505
74467
                                    g->scale_factors[j++] = get_bits(&s->gb, slen);
1506
                            } else {
1507
78786
                                for (i = 0; i < n; i++)
1508
66278
                                    g->scale_factors[j++] = 0;
1509
                            }
1510
                        } else {
1511
                            /* simply copy from last granule */
1512
27485
                            for (i = 0; i < n; i++) {
1513
23139
                                g->scale_factors[j] = sc[j];
1514
23139
                                j++;
1515
                            }
1516
                        }
1517
                    }
1518
7804
                    g->scale_factors[j++] = 0;
1519
                }
1520
            } else {
1521
                int tindex, tindex2, slen[4], sl, sf;
1522
1523
                /* LSF scale factors */
1524
4
                if (g->block_type == 2)
1525
                    tindex = g->switch_point ? 2 : 1;
1526
                else
1527
4
                    tindex = 0;
1528
1529
4
                sf = g->scalefac_compress;
1530

4
                if ((s->mode_ext & MODE_EXT_I_STEREO) && ch == 1) {
1531
                    /* intensity stereo case */
1532
1
                    sf >>= 1;
1533
1
                    if (sf < 180) {
1534
1
                        lsf_sf_expand(slen, sf, 6, 6, 0);
1535
1
                        tindex2 = 3;
1536
                    } else if (sf < 244) {
1537
                        lsf_sf_expand(slen, sf - 180, 4, 4, 0);
1538
                        tindex2 = 4;
1539
                    } else {
1540
                        lsf_sf_expand(slen, sf - 244, 3, 0, 0);
1541
                        tindex2 = 5;
1542
                    }
1543
                } else {
1544
                    /* normal case */
1545
3
                    if (sf < 400) {
1546
1
                        lsf_sf_expand(slen, sf, 5, 4, 4);
1547
1
                        tindex2 = 0;
1548
2
                    } else if (sf < 500) {
1549
2
                        lsf_sf_expand(slen, sf - 400, 5, 4, 0);
1550
2
                        tindex2 = 1;
1551
                    } else {
1552
                        lsf_sf_expand(slen, sf - 500, 3, 0, 0);
1553
                        tindex2 = 2;
1554
                        g->preflag = 1;
1555
                    }
1556
                }
1557
1558
4
                j = 0;
1559
20
                for (k = 0; k < 4; k++) {
1560
16
                    n  = lsf_nsf_table[tindex2][tindex][k];
1561
16
                    sl = slen[k];
1562
16
                    if (sl) {
1563
45
                        for (i = 0; i < n; i++)
1564
39
                            g->scale_factors[j++] = get_bits(&s->gb, sl);
1565
                    } else {
1566
55
                        for (i = 0; i < n; i++)
1567
45
                            g->scale_factors[j++] = 0;
1568
                    }
1569
                }
1570
                /* XXX: should compute exact size */
1571
80
                for (; j < 40; j++)
1572
76
                    g->scale_factors[j] = 0;
1573
            }
1574
1575
8112
            exponents_from_scale_factors(s, g, exponents);
1576
1577
            /* read Huffman coded residue */
1578
8112
            huffman_decode(s, g, exponents, bits_pos + g->part2_3_length);
1579
        } /* ch */
1580
1581
5599
        if (s->mode == MPA_JSTEREO)
1582
2447
            compute_stereo(s, &s->granules[0][gr], &s->granules[1][gr]);
1583
1584
13711
        for (ch = 0; ch < s->nb_channels; ch++) {
1585
8112
            g = &s->granules[ch][gr];
1586
1587
8112
            reorder_block(s, g);
1588
8112
            compute_antialias(s, g);
1589
8112
            compute_imdct(s, g, &s->sb_samples[ch][18 * gr][0], s->mdct_buf[ch]);
1590
        }
1591
    } /* gr */
1592
2803
    if (get_bits_count(&s->gb) < 0)
1593
        skip_bits_long(&s->gb, -get_bits_count(&s->gb));
1594
2803
    return nb_granules * 18;
1595
}
1596
1597
10041
static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,
1598
                           const uint8_t *buf, int buf_size)
1599
{
1600
    int i, nb_frames, ch, ret;
1601
    OUT_INT *samples_ptr;
1602
1603
10041
    init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);
1604
10041
    if (s->error_protection)
1605
117
        s->crc = get_bits(&s->gb, 16);
1606
1607

10041
    switch(s->layer) {
1608
    case 1:
1609
        s->avctx->frame_size = 384;
1610
        nb_frames = mp_decode_layer1(s);
1611
        break;
1612
7238
    case 2:
1613
7238
        s->avctx->frame_size = 1152;
1614
7238
        nb_frames = mp_decode_layer2(s);
1615
7238
        break;
1616
2803
    case 3:
1617
2803
        s->avctx->frame_size = s->lsf ? 576 : 1152;
1618
2803
    default:
1619
2803
        nb_frames = mp_decode_layer3(s);
1620
1621
2803
        s->last_buf_size=0;
1622
2803
        if (s->in_gb.buffer) {
1623
1719
            align_get_bits(&s->gb);
1624
1719
            i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1625

1719
            if (i >= 0 && i <= BACKSTEP_SIZE) {
1626
1719
                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb) >> 3), i);
1627
1719
                s->last_buf_size=i;
1628
            } else
1629
                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);
1630
1719
            s->gb           = s->in_gb;
1631
1719
            s->in_gb.buffer = NULL;
1632
1719
            s->extrasize    = 0;
1633
        }
1634
1635
2803
        align_get_bits(&s->gb);
1636
        av_assert1((get_bits_count(&s->gb) & 7) == 0);
1637
2803
        i = (get_bits_left(&s->gb) >> 3) - s->extrasize;
1638

2803
        if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {
1639
230
            if (i < 0)
1640
                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);
1641
230
            i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);
1642
        }
1643
        av_assert1(i <= buf_size - HEADER_SIZE && i >= 0);
1644
2803
        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);
1645
2803
        s->last_buf_size += i;
1646
    }
1647
1648
10041
    if(nb_frames < 0)
1649
        return nb_frames;
1650
1651
    /* get output buffer */
1652
10041
    if (!samples) {
1653
10041
        av_assert0(s->frame);
1654
10041
        s->frame->nb_samples = s->avctx->frame_size;
1655
10041
        if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0)
1656
            return ret;
1657
10041
        samples = (OUT_INT **)s->frame->extended_data;
1658
    }
1659
1660
    /* apply the synthesis filter */
1661
21985
    for (ch = 0; ch < s->nb_channels; ch++) {
1662
        int sample_stride;
1663
11944
        if (s->avctx->sample_fmt == OUT_FMT_P) {
1664
11944
            samples_ptr   = samples[ch];
1665
11944
            sample_stride = 1;
1666
        } else {
1667
            samples_ptr   = samples[0] + ch;
1668
            sample_stride = s->nb_channels;
1669
        }
1670
441856
        for (i = 0; i < nb_frames; i++) {
1671
429912
            RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],
1672
                                        &(s->synth_buf_offset[ch]),
1673
                                        RENAME(ff_mpa_synth_window),
1674
                                        &s->dither_state, samples_ptr,
1675
429912
                                        sample_stride, s->sb_samples[ch][i]);
1676
429912
            samples_ptr += 32 * sample_stride;
1677
        }
1678
    }
1679
1680
10041
    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;
1681
}
1682
1683
10043
static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
1684
                        AVPacket *avpkt)
1685
{
1686
10043
    const uint8_t *buf  = avpkt->data;
1687
10043
    int buf_size        = avpkt->size;
1688
10043
    MPADecodeContext *s = avctx->priv_data;
1689
    uint32_t header;
1690
    int ret;
1691
1692
10043
    int skipped = 0;
1693

10043
    while(buf_size && !*buf){
1694
        buf++;
1695
        buf_size--;
1696
        skipped++;
1697
    }
1698
1699
10043
    if (buf_size < HEADER_SIZE)
1700
        return AVERROR_INVALIDDATA;
1701
1702
10043
    header = AV_RB32(buf);
1703
10043
    if (header >> 8 == AV_RB32("TAG") >> 8) {
1704
        av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n");
1705
        return buf_size + skipped;
1706
    }
1707
10043
    ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1708
10043
    if (ret < 0) {
1709
2
        av_log(avctx, AV_LOG_ERROR, "Header missing\n");
1710
2
        return AVERROR_INVALIDDATA;
1711
10041
    } else if (ret == 1) {
1712
        /* free format: prepare to compute frame size */
1713
        s->frame_size = -1;
1714
        return AVERROR_INVALIDDATA;
1715
    }
1716
    /* update codec info */
1717
10041
    avctx->channels       = s->nb_channels;
1718
10041
    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1719
10041
    if (!avctx->bit_rate)
1720
4
        avctx->bit_rate = s->bit_rate;
1721
1722
10041
    if (s->frame_size <= 0) {
1723
        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
1724
        return AVERROR_INVALIDDATA;
1725
10041
    } else if (s->frame_size < buf_size) {
1726
        av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
1727
        buf_size= s->frame_size;
1728
    }
1729
1730
10041
    s->frame = data;
1731
1732
10041
    ret = mp_decode_frame(s, NULL, buf, buf_size);
1733
10041
    if (ret >= 0) {
1734
10041
        s->frame->nb_samples = avctx->frame_size;
1735
10041
        *got_frame_ptr       = 1;
1736
10041
        avctx->sample_rate   = s->sample_rate;
1737
        //FIXME maybe move the other codec info stuff from above here too
1738
    } else {
1739
        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1740
        /* Only return an error if the bad frame makes up the whole packet or
1741
         * the error is related to buffer management.
1742
         * If there is more data in the packet, just consume the bad frame
1743
         * instead of returning an error, which would discard the whole
1744
         * packet. */
1745
        *got_frame_ptr = 0;
1746
        if (buf_size == avpkt->size || ret != AVERROR_INVALIDDATA)
1747
            return ret;
1748
    }
1749
10041
    s->frame_size = 0;
1750
10041
    return buf_size + skipped;
1751
}
1752
1753
static void mp_flush(MPADecodeContext *ctx)
1754
{
1755
    memset(ctx->synth_buf, 0, sizeof(ctx->synth_buf));
1756
    memset(ctx->mdct_buf, 0, sizeof(ctx->mdct_buf));
1757
    ctx->last_buf_size = 0;
1758
    ctx->dither_state = 0;
1759
}
1760
1761
static void flush(AVCodecContext *avctx)
1762
{
1763
    mp_flush(avctx->priv_data);
1764
}
1765
1766
#if CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER
1767
static int decode_frame_adu(AVCodecContext *avctx, void *data,
1768
                            int *got_frame_ptr, AVPacket *avpkt)
1769
{
1770
    const uint8_t *buf  = avpkt->data;
1771
    int buf_size        = avpkt->size;
1772
    MPADecodeContext *s = avctx->priv_data;
1773
    uint32_t header;
1774
    int len, ret;
1775
    int av_unused out_size;
1776
1777
    len = buf_size;
1778
1779
    // Discard too short frames
1780
    if (buf_size < HEADER_SIZE) {
1781
        av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1782
        return AVERROR_INVALIDDATA;
1783
    }
1784
1785
1786
    if (len > MPA_MAX_CODED_FRAME_SIZE)
1787
        len = MPA_MAX_CODED_FRAME_SIZE;
1788
1789
    // Get header and restore sync word
1790
    header = AV_RB32(buf) | 0xffe00000;
1791
1792
    ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header);
1793
    if (ret < 0) {
1794
        av_log(avctx, AV_LOG_ERROR, "Invalid frame header\n");
1795
        return ret;
1796
    }
1797
    /* update codec info */
1798
    avctx->sample_rate = s->sample_rate;
1799
    avctx->channels    = s->nb_channels;
1800
    avctx->channel_layout = s->nb_channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
1801
    if (!avctx->bit_rate)
1802
        avctx->bit_rate = s->bit_rate;
1803
1804
    s->frame_size = len;
1805
1806
    s->frame = data;
1807
1808
    ret = mp_decode_frame(s, NULL, buf, buf_size);
1809
    if (ret < 0) {
1810
        av_log(avctx, AV_LOG_ERROR, "Error while decoding MPEG audio frame.\n");
1811
        return ret;
1812
    }
1813
1814
    *got_frame_ptr = 1;
1815
1816
    return buf_size;
1817
}
1818
#endif /* CONFIG_MP3ADU_DECODER || CONFIG_MP3ADUFLOAT_DECODER */
1819
1820
#if CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER
1821
1822
/**
1823
 * Context for MP3On4 decoder
1824
 */
1825
typedef struct MP3On4DecodeContext {
1826
    int frames;                     ///< number of mp3 frames per block (number of mp3 decoder instances)
1827
    int syncword;                   ///< syncword patch
1828
    const uint8_t *coff;            ///< channel offsets in output buffer
1829
    MPADecodeContext *mp3decctx[5]; ///< MPADecodeContext for every decoder instance
1830
} MP3On4DecodeContext;
1831
1832
#include "mpeg4audio.h"
1833
1834
/* Next 3 arrays are indexed by channel config number (passed via codecdata) */
1835
1836
/* number of mp3 decoder instances */
1837
static const uint8_t mp3Frames[8] = { 0, 1, 1, 2, 3, 3, 4, 5 };
1838
1839
/* offsets into output buffer, assume output order is FL FR C LFE BL BR SL SR */
1840
static const uint8_t chan_offset[8][5] = {
1841
    { 0             },
1842
    { 0             },  // C
1843
    { 0             },  // FLR
1844
    { 2, 0          },  // C FLR
1845
    { 2, 0, 3       },  // C FLR BS
1846
    { 2, 0, 3       },  // C FLR BLRS
1847
    { 2, 0, 4, 3    },  // C FLR BLRS LFE
1848
    { 2, 0, 6, 4, 3 },  // C FLR BLRS BLR LFE
1849
};
1850
1851
/* mp3on4 channel layouts */
1852
static const int16_t chan_layout[8] = {
1853
    0,
1854
    AV_CH_LAYOUT_MONO,
1855
    AV_CH_LAYOUT_STEREO,
1856
    AV_CH_LAYOUT_SURROUND,
1857
    AV_CH_LAYOUT_4POINT0,
1858
    AV_CH_LAYOUT_5POINT0,
1859
    AV_CH_LAYOUT_5POINT1,
1860
    AV_CH_LAYOUT_7POINT1
1861
};
1862
1863
static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
1864
{
1865
    MP3On4DecodeContext *s = avctx->priv_data;
1866
    int i;
1867
1868
    for (i = 0; i < s->frames; i++)
1869
        av_freep(&s->mp3decctx[i]);
1870
1871
    return 0;
1872
}
1873
1874
1875
static av_cold int decode_init_mp3on4(AVCodecContext * avctx)
1876
{
1877
    MP3On4DecodeContext *s = avctx->priv_data;
1878
    MPEG4AudioConfig cfg;
1879
    int i, ret;
1880
1881
    if ((avctx->extradata_size < 2) || !avctx->extradata) {
1882
        av_log(avctx, AV_LOG_ERROR, "Codec extradata missing or too short.\n");
1883
        return AVERROR_INVALIDDATA;
1884
    }
1885
1886
    avpriv_mpeg4audio_get_config2(&cfg, avctx->extradata,
1887
                                  avctx->extradata_size, 1, avctx);
1888
    if (!cfg.chan_config || cfg.chan_config > 7) {
1889
        av_log(avctx, AV_LOG_ERROR, "Invalid channel config number.\n");
1890
        return AVERROR_INVALIDDATA;
1891
    }
1892
    s->frames             = mp3Frames[cfg.chan_config];
1893
    s->coff               = chan_offset[cfg.chan_config];
1894
    avctx->channels       = ff_mpeg4audio_channels[cfg.chan_config];
1895
    avctx->channel_layout = chan_layout[cfg.chan_config];
1896
1897
    if (cfg.sample_rate < 16000)
1898
        s->syncword = 0xffe00000;
1899
    else
1900
        s->syncword = 0xfff00000;
1901
1902
    /* Init the first mp3 decoder in standard way, so that all tables get builded
1903
     * We replace avctx->priv_data with the context of the first decoder so that
1904
     * decode_init() does not have to be changed.
1905
     * Other decoders will be initialized here copying data from the first context
1906
     */
1907
    // Allocate zeroed memory for the first decoder context
1908
    s->mp3decctx[0] = av_mallocz(sizeof(MPADecodeContext));
1909
    if (!s->mp3decctx[0])
1910
        return AVERROR(ENOMEM);
1911
    // Put decoder context in place to make init_decode() happy
1912
    avctx->priv_data = s->mp3decctx[0];
1913
    ret = decode_init(avctx);
1914
    // Restore mp3on4 context pointer
1915
    avctx->priv_data = s;
1916
    if (ret < 0)
1917
        return ret;
1918
    s->mp3decctx[0]->adu_mode = 1; // Set adu mode
1919
1920
    /* Create a separate codec/context for each frame (first is already ok).
1921
     * Each frame is 1 or 2 channels - up to 5 frames allowed
1922
     */
1923
    for (i = 1; i < s->frames; i++) {
1924
        s->mp3decctx[i] = av_mallocz(sizeof(MPADecodeContext));
1925
        if (!s->mp3decctx[i])
1926
            return AVERROR(ENOMEM);
1927
        s->mp3decctx[i]->adu_mode = 1;
1928
        s->mp3decctx[i]->avctx = avctx;
1929
        s->mp3decctx[i]->mpadsp = s->mp3decctx[0]->mpadsp;
1930
        s->mp3decctx[i]->butterflies_float = s->mp3decctx[0]->butterflies_float;
1931
    }
1932
1933
    return 0;
1934
}
1935
1936
1937
static void flush_mp3on4(AVCodecContext *avctx)
1938
{
1939
    int i;
1940
    MP3On4DecodeContext *s = avctx->priv_data;
1941
1942
    for (i = 0; i < s->frames; i++)
1943
        mp_flush(s->mp3decctx[i]);
1944
}
1945
1946
1947
static int decode_frame_mp3on4(AVCodecContext *avctx, void *data,
1948
                               int *got_frame_ptr, AVPacket *avpkt)
1949
{
1950
    AVFrame *frame         = data;
1951
    const uint8_t *buf     = avpkt->data;
1952
    int buf_size           = avpkt->size;
1953
    MP3On4DecodeContext *s = avctx->priv_data;
1954
    MPADecodeContext *m;
1955
    int fsize, len = buf_size, out_size = 0;
1956
    uint32_t header;
1957
    OUT_INT **out_samples;
1958
    OUT_INT *outptr[2];
1959
    int fr, ch, ret;
1960
1961
    /* get output buffer */
1962
    frame->nb_samples = MPA_FRAME_SIZE;
1963
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1964
        return ret;
1965
    out_samples = (OUT_INT **)frame->extended_data;
1966
1967
    // Discard too short frames
1968
    if (buf_size < HEADER_SIZE)
1969
        return AVERROR_INVALIDDATA;
1970
1971
    avctx->bit_rate = 0;
1972
1973
    ch = 0;
1974
    for (fr = 0; fr < s->frames; fr++) {
1975
        fsize = AV_RB16(buf) >> 4;
1976
        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);
1977
        m     = s->mp3decctx[fr];
1978
        av_assert1(m);
1979
1980
        if (fsize < HEADER_SIZE) {
1981
            av_log(avctx, AV_LOG_ERROR, "Frame size smaller than header size\n");
1982
            return AVERROR_INVALIDDATA;
1983
        }
1984
        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header
1985
1986
        ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);
1987
        if (ret < 0) {
1988
            av_log(avctx, AV_LOG_ERROR, "Bad header, discard block\n");
1989
            return AVERROR_INVALIDDATA;
1990
        }
1991
1992
        if (ch + m->nb_channels > avctx->channels ||
1993
            s->coff[fr] + m->nb_channels > avctx->channels) {
1994
            av_log(avctx, AV_LOG_ERROR, "frame channel count exceeds codec "
1995
                                        "channel count\n");
1996
            return AVERROR_INVALIDDATA;
1997
        }
1998
        ch += m->nb_channels;
1999
2000
        outptr[0] = out_samples[s->coff[fr]];
2001
        if (m->nb_channels > 1)
2002
            outptr[1] = out_samples[s->coff[fr] + 1];
2003
2004
        if ((ret = mp_decode_frame(m, outptr, buf, fsize)) < 0) {
2005
            av_log(avctx, AV_LOG_ERROR, "failed to decode channel %d\n", ch);
2006
            memset(outptr[0], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2007
            if (m->nb_channels > 1)
2008
                memset(outptr[1], 0, MPA_FRAME_SIZE*sizeof(OUT_INT));
2009
            ret = m->nb_channels * MPA_FRAME_SIZE*sizeof(OUT_INT);
2010
        }
2011
2012
        out_size += ret;
2013
        buf      += fsize;
2014
        len      -= fsize;
2015
2016
        avctx->bit_rate += m->bit_rate;
2017
    }
2018
    if (ch != avctx->channels) {
2019
        av_log(avctx, AV_LOG_ERROR, "failed to decode all channels\n");
2020
        return AVERROR_INVALIDDATA;
2021
    }
2022
2023
    /* update codec info */
2024
    avctx->sample_rate = s->mp3decctx[0]->sample_rate;
2025
2026
    frame->nb_samples = out_size / (avctx->channels * sizeof(OUT_INT));
2027
    *got_frame_ptr    = 1;
2028
2029
    return buf_size;
2030
}
2031
#endif /* CONFIG_MP3ON4_DECODER || CONFIG_MP3ON4FLOAT_DECODER */