Coverage Report

Created: 2026-05-16 07:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/atrac3.c
Line
Count
Source
1
/*
2
 * ATRAC3 compatible decoder
3
 * Copyright (c) 2006-2008 Maxim Poliakovski
4
 * Copyright (c) 2006-2008 Benjamin Larsson
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * ATRAC3 compatible decoder.
26
 * This decoder handles Sony's ATRAC3 data.
27
 *
28
 * Container formats used to store ATRAC3 data:
29
 * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
30
 *
31
 * To use this decoder, a calling application must supply the extradata
32
 * bytes provided in the containers above.
33
 */
34
35
#include <math.h>
36
#include <stddef.h>
37
38
#include "libavutil/attributes.h"
39
#include "libavutil/float_dsp.h"
40
#include "libavutil/libm.h"
41
#include "libavutil/mem.h"
42
#include "libavutil/mem_internal.h"
43
#include "libavutil/thread.h"
44
#include "libavutil/tx.h"
45
46
#include "avcodec.h"
47
#include "bytestream.h"
48
#include "codec_internal.h"
49
#include "decode.h"
50
#include "get_bits.h"
51
52
#include "atrac.h"
53
#include "atrac3data.h"
54
55
3.91k
#define MIN_CHANNELS    1
56
1.95k
#define MAX_CHANNELS    8
57
7.91k
#define MAX_JS_PAIRS    8 / 2
58
59
2.43M
#define JOINT_STEREO    0x12
60
2.68k
#define SINGLE          0x2
61
62
2.46M
#define SAMPLES_PER_FRAME 1024
63
1.07M
#define MDCT_SIZE          512
64
65
4.03M
#define ATRAC3_VLC_BITS 8
66
67
typedef struct GainBlock {
68
    AtracGainInfo g_block[4];
69
} GainBlock;
70
71
typedef struct TonalComponent {
72
    int pos;
73
    int num_coefs;
74
    float coef[8];
75
} TonalComponent;
76
77
typedef struct ChannelUnit {
78
    int            bands_coded;
79
    int            num_components;
80
    float          prev_frame[SAMPLES_PER_FRAME];
81
    int            gc_blk_switch;
82
    TonalComponent components[64];
83
    GainBlock      gain_block[2];
84
85
    DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
86
    DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
87
88
    float          delay_buf1[46]; ///<qmf delay buffers
89
    float          delay_buf2[46];
90
    float          delay_buf3[46];
91
} ChannelUnit;
92
93
typedef struct ATRAC3Context {
94
    GetBitContext gb;
95
    //@{
96
    /** stream data */
97
    int coding_mode;
98
99
    ChannelUnit *units;
100
    //@}
101
    //@{
102
    /** joint-stereo related variables */
103
    int matrix_coeff_index_prev[MAX_JS_PAIRS][4];
104
    int matrix_coeff_index_now[MAX_JS_PAIRS][4];
105
    int matrix_coeff_index_next[MAX_JS_PAIRS][4];
106
    int weighting_delay[MAX_JS_PAIRS][6];
107
    //@}
108
    //@{
109
    /** data buffers */
110
    uint8_t *decoded_bytes_buffer;
111
    float temp_buf[1070];
112
    //@}
113
    //@{
114
    /** extradata */
115
    int scrambled_stream;
116
    //@}
117
118
    AtracGCContext    gainc_ctx;
119
    AVTXContext      *mdct_ctx;
120
    av_tx_fn          mdct_fn;
121
    void (*vector_fmul)(float *dst, const float *src0, const float *src1,
122
                        int len);
123
} ATRAC3Context;
124
125
static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
126
static VLCElem atrac3_vlc_table[7 * 1 << ATRAC3_VLC_BITS];
127
static VLC   spectral_coeff_tab[7];
128
129
/**
130
 * Regular 512 points IMDCT without overlapping, with the exception of the
131
 * swapping of odd bands caused by the reverse spectra of the QMF.
132
 *
133
 * @param odd_band  1 if the band is an odd band
134
 */
135
static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
136
1.07M
{
137
1.07M
    int i;
138
139
1.07M
    if (odd_band) {
140
        /**
141
         * Reverse the odd bands before IMDCT, this is an effect of the QMF
142
         * transform or it gives better compression to do it this way.
143
         * FIXME: It should be possible to handle this in imdct_calc
144
         * for that to happen a modification of the prerotation step of
145
         * all SIMD code and C code is needed.
146
         * Or fix the functions before so they generate a pre reversed spectrum.
147
         */
148
19.5M
        for (i = 0; i < 128; i++)
149
19.3M
            FFSWAP(float, input[i], input[255 - i]);
150
151k
    }
151
152
1.07M
    q->mdct_fn(q->mdct_ctx, output, input, sizeof(float));
153
154
    /* Perform windowing on the output. */
155
1.07M
    q->vector_fmul(output, output, mdct_window, MDCT_SIZE);
156
1.07M
}
157
158
/*
159
 * indata descrambling, only used for data coming from the rm container
160
 */
161
static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
162
255k
{
163
255k
    int i, off;
164
255k
    uint32_t c;
165
255k
    const uint32_t *buf;
166
255k
    uint32_t *output = (uint32_t *)out;
167
168
255k
    off = (intptr_t)input & 3;
169
255k
    buf = (const uint32_t *)(input - off);
170
255k
    if (off)
171
9.42k
        c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
172
245k
    else
173
245k
        c = av_be2ne32(0x537F6103U);
174
255k
    bytes += 3 + off;
175
1.19M
    for (i = 0; i < bytes / 4; i++)
176
943k
        output[i] = c ^ buf[i];
177
178
255k
    if (off)
179
9.42k
        avpriv_request_sample(NULL, "Offset of %d", off);
180
181
255k
    return off;
182
255k
}
183
184
static av_cold void init_imdct_window(void)
185
2
{
186
2
    int i, j;
187
188
    /* generate the mdct window, for details see
189
     * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
190
258
    for (i = 0, j = 255; i < 128; i++, j--) {
191
256
        float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
192
256
        float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
193
256
        float w  = 0.5 * (wi * wi + wj * wj);
194
256
        mdct_window[i] = mdct_window[511 - i] = wi / w;
195
256
        mdct_window[j] = mdct_window[511 - j] = wj / w;
196
256
    }
197
2
}
198
199
static av_cold int atrac3_decode_close(AVCodecContext *avctx)
200
1.95k
{
201
1.95k
    ATRAC3Context *q = avctx->priv_data;
202
203
1.95k
    av_freep(&q->units);
204
1.95k
    av_freep(&q->decoded_bytes_buffer);
205
206
1.95k
    av_tx_uninit(&q->mdct_ctx);
207
208
1.95k
    return 0;
209
1.95k
}
210
211
/**
212
 * Mantissa decoding
213
 *
214
 * @param selector     which table the output values are coded with
215
 * @param coding_flag  constant length coding or variable length coding
216
 * @param mantissas    mantissa output table
217
 * @param num_codes    number of values to get
218
 */
219
static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
220
                                       int coding_flag, int *mantissas,
221
                                       int num_codes)
222
1.34M
{
223
1.34M
    int i, code, huff_symb;
224
225
1.34M
    if (selector == 1)
226
11.4k
        num_codes /= 2;
227
228
1.34M
    if (coding_flag != 0) {
229
        /* constant length coding (CLC) */
230
961k
        int num_bits = clc_length_tab[selector];
231
232
961k
        if (selector > 1) {
233
4.27M
            for (i = 0; i < num_codes; i++) {
234
3.31M
                if (num_bits)
235
3.31M
                    code = get_sbits(gb, num_bits);
236
0
                else
237
0
                    code = 0;
238
3.31M
                mantissas[i] = code;
239
3.31M
            }
240
958k
        } else {
241
43.7k
            for (i = 0; i < num_codes; i++) {
242
40.4k
                if (num_bits)
243
40.4k
                    code = get_bits(gb, num_bits); // num_bits is always 4 in this case
244
0
                else
245
0
                    code = 0;
246
40.4k
                mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
247
40.4k
                mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
248
40.4k
            }
249
3.36k
        }
250
961k
    } else {
251
        /* variable length coding (VLC) */
252
383k
        if (selector != 1) {
253
4.35M
            for (i = 0; i < num_codes; i++) {
254
3.98M
                mantissas[i] = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
255
3.98M
                                        ATRAC3_VLC_BITS, 1);
256
3.98M
            }
257
375k
        } else {
258
58.3k
            for (i = 0; i < num_codes; i++) {
259
50.2k
                huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
260
50.2k
                                     ATRAC3_VLC_BITS, 1);
261
50.2k
                mantissas[i * 2    ] = mantissa_vlc_tab[huff_symb * 2    ];
262
50.2k
                mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
263
50.2k
            }
264
8.08k
        }
265
383k
    }
266
1.34M
}
267
268
/**
269
 * Restore the quantized band spectrum coefficients
270
 *
271
 * @return subband count, fix for broken specification/files
272
 */
273
static int decode_spectrum(GetBitContext *gb, float *output)
274
921k
{
275
921k
    int num_subbands, coding_mode, i, j, first, last, subband_size;
276
921k
    int subband_vlc_index[32], sf_index[32];
277
921k
    int mantissas[128];
278
921k
    float scale_factor;
279
280
921k
    num_subbands = get_bits(gb, 5);  // number of coded subbands
281
921k
    coding_mode  = get_bits1(gb);    // coding Mode: 0 - VLC/ 1-CLC
282
283
    /* get the VLC selector table for the subbands, 0 means not coded */
284
2.27M
    for (i = 0; i <= num_subbands; i++)
285
1.34M
        subband_vlc_index[i] = get_bits(gb, 3);
286
287
    /* read the scale factor indexes from the stream */
288
2.27M
    for (i = 0; i <= num_subbands; i++) {
289
1.34M
        if (subband_vlc_index[i] != 0)
290
365k
            sf_index[i] = get_bits(gb, 6);
291
1.34M
    }
292
293
2.27M
    for (i = 0; i <= num_subbands; i++) {
294
1.34M
        first = subband_tab[i    ];
295
1.34M
        last  = subband_tab[i + 1];
296
297
1.34M
        subband_size = last - first;
298
299
1.34M
        if (subband_vlc_index[i] != 0) {
300
            /* decode spectral coefficients for this subband */
301
            /* TODO: This can be done faster is several blocks share the
302
             * same VLC selector (subband_vlc_index) */
303
365k
            read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
304
365k
                                       mantissas, subband_size);
305
306
            /* decode the scale factor for this subband */
307
365k
            scale_factor = ff_atrac_sf_table[sf_index[i]] *
308
365k
                           inv_max_quant[subband_vlc_index[i]];
309
310
            /* inverse quantize the coefficients */
311
5.03M
            for (j = 0; first < last; first++, j++)
312
4.66M
                output[first] = mantissas[j] * scale_factor;
313
984k
        } else {
314
            /* this subband was not coded, so zero the entire subband */
315
984k
            memset(output + first, 0, subband_size * sizeof(*output));
316
984k
        }
317
1.34M
    }
318
319
    /* clear the subbands that were not coded */
320
921k
    first = subband_tab[i];
321
921k
    memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
322
921k
    return num_subbands;
323
921k
}
324
325
/**
326
 * Restore the quantized tonal components
327
 *
328
 * @param components tonal components
329
 * @param num_bands  number of coded bands
330
 */
331
static int decode_tonal_components(GetBitContext *gb,
332
                                   TonalComponent *components, int num_bands)
333
931k
{
334
931k
    int i, b, c, m;
335
931k
    int nb_components, coding_mode_selector, coding_mode;
336
931k
    int band_flags[4], mantissa[8];
337
931k
    int component_count = 0;
338
339
931k
    nb_components = get_bits(gb, 5);
340
341
    /* no tonal components */
342
931k
    if (nb_components == 0)
343
761k
        return 0;
344
345
170k
    coding_mode_selector = get_bits(gb, 2);
346
170k
    if (coding_mode_selector == 2)
347
1.83k
        return AVERROR_INVALIDDATA;
348
349
168k
    coding_mode = coding_mode_selector & 1;
350
351
668k
    for (i = 0; i < nb_components; i++) {
352
509k
        int coded_values_per_component, quant_step_index;
353
354
1.20M
        for (b = 0; b <= num_bands; b++)
355
693k
            band_flags[b] = get_bits1(gb);
356
357
509k
        coded_values_per_component = get_bits(gb, 3);
358
359
509k
        quant_step_index = get_bits(gb, 3);
360
509k
        if (quant_step_index <= 1)
361
7.99k
            return AVERROR_INVALIDDATA;
362
363
501k
        if (coding_mode_selector == 3)
364
100k
            coding_mode = get_bits1(gb);
365
366
3.23M
        for (b = 0; b < (num_bands + 1) * 4; b++) {
367
2.73M
            int coded_components;
368
369
2.73M
            if (band_flags[b >> 2] == 0)
370
2.11M
                continue;
371
372
613k
            coded_components = get_bits(gb, 3);
373
374
1.59M
            for (c = 0; c < coded_components; c++) {
375
979k
                TonalComponent *cmp = &components[component_count];
376
979k
                int sf_index, coded_values, max_coded_values;
377
979k
                float scale_factor;
378
379
979k
                sf_index = get_bits(gb, 6);
380
979k
                if (component_count >= 64)
381
610
                    return AVERROR_INVALIDDATA;
382
383
979k
                cmp->pos = b * 64 + get_bits(gb, 6);
384
385
979k
                max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
386
979k
                coded_values     = coded_values_per_component + 1;
387
979k
                coded_values     = FFMIN(max_coded_values, coded_values);
388
389
979k
                scale_factor = ff_atrac_sf_table[sf_index] *
390
979k
                               inv_max_quant[quant_step_index];
391
392
979k
                read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
393
979k
                                           mantissa, coded_values);
394
395
979k
                cmp->num_coefs = coded_values;
396
397
                /* inverse quant */
398
3.78M
                for (m = 0; m < coded_values; m++)
399
2.80M
                    cmp->coef[m] = mantissa[m] * scale_factor;
400
401
979k
                component_count++;
402
979k
            }
403
613k
        }
404
501k
    }
405
406
159k
    return component_count;
407
168k
}
408
409
/**
410
 * Decode gain parameters for the coded bands
411
 *
412
 * @param block      the gainblock for the current band
413
 * @param num_bands  amount of coded bands
414
 */
415
static int decode_gain_control(GetBitContext *gb, GainBlock *block,
416
                               int num_bands)
417
937k
{
418
937k
    int b, j;
419
937k
    int *level, *loc;
420
421
937k
    AtracGainInfo *gain = block->g_block;
422
423
3.00M
    for (b = 0; b <= num_bands; b++) {
424
2.07M
        gain[b].num_points = get_bits(gb, 3);
425
2.07M
        level              = gain[b].lev_code;
426
2.07M
        loc                = gain[b].loc_code;
427
428
2.30M
        for (j = 0; j < gain[b].num_points; j++) {
429
241k
            level[j] = get_bits(gb, 4);
430
241k
            loc[j]   = get_bits(gb, 5);
431
241k
            if (j && loc[j] <= loc[j - 1])
432
5.23k
                return AVERROR_INVALIDDATA;
433
241k
        }
434
2.07M
    }
435
436
    /* Clear the unused blocks. */
437
2.59M
    for (; b < 4 ; b++)
438
1.66M
        gain[b].num_points = 0;
439
440
931k
    return 0;
441
937k
}
442
443
/**
444
 * Combine the tonal band spectrum and regular band spectrum
445
 *
446
 * @param spectrum        output spectrum buffer
447
 * @param num_components  number of tonal components
448
 * @param components      tonal components for this band
449
 * @return                position of the last tonal coefficient
450
 */
451
static int add_tonal_components(float *spectrum, int num_components,
452
                                TonalComponent *components)
453
921k
{
454
921k
    int i, j, last_pos = -1;
455
921k
    float *input, *output;
456
457
1.83M
    for (i = 0; i < num_components; i++) {
458
916k
        last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
459
916k
        input    = components[i].coef;
460
916k
        output   = &spectrum[components[i].pos];
461
462
3.41M
        for (j = 0; j < components[i].num_coefs; j++)
463
2.50M
            output[j] += input[j];
464
916k
    }
465
466
921k
    return last_pos;
467
921k
}
468
469
#define INTERPOLATE(old, new, nsample) \
470
320k
    ((old) + (nsample) * 0.125 * ((new) - (old)))
471
472
static void reverse_matrixing(float *su1, float *su2, int *prev_code,
473
                              int *curr_code)
474
6.11k
{
475
6.11k
    int i, nsample, band;
476
6.11k
    float mc1_l, mc1_r, mc2_l, mc2_r;
477
478
30.5k
    for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
479
24.4k
        int s1 = prev_code[i];
480
24.4k
        int s2 = curr_code[i];
481
24.4k
        nsample = band;
482
483
24.4k
        if (s1 != s2) {
484
            /* Selector value changed, interpolation needed. */
485
6.64k
            mc1_l = matrix_coeffs[s1 * 2    ];
486
6.64k
            mc1_r = matrix_coeffs[s1 * 2 + 1];
487
6.64k
            mc2_l = matrix_coeffs[s2 * 2    ];
488
6.64k
            mc2_r = matrix_coeffs[s2 * 2 + 1];
489
490
            /* Interpolation is done over the first eight samples. */
491
59.8k
            for (; nsample < band + 8; nsample++) {
492
53.1k
                float c1 = su1[nsample];
493
53.1k
                float c2 = su2[nsample];
494
53.1k
                c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
495
53.1k
                     c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
496
53.1k
                su1[nsample] = c2;
497
53.1k
                su2[nsample] = c1 * 2.0 - c2;
498
53.1k
            }
499
6.64k
        }
500
501
        /* Apply the matrix without interpolation. */
502
24.4k
        switch (s2) {
503
6.24k
        case 0:     /* M/S decoding */
504
1.59M
            for (; nsample < band + 256; nsample++) {
505
1.58M
                float c1 = su1[nsample];
506
1.58M
                float c2 = su2[nsample];
507
1.58M
                su1[nsample] =  c2       * 2.0;
508
1.58M
                su2[nsample] = (c1 - c2) * 2.0;
509
1.58M
            }
510
6.24k
            break;
511
6.76k
        case 1:
512
1.72M
            for (; nsample < band + 256; nsample++) {
513
1.71M
                float c1 = su1[nsample];
514
1.71M
                float c2 = su2[nsample];
515
1.71M
                su1[nsample] = (c1 + c2) *  2.0;
516
1.71M
                su2[nsample] =  c2       * -2.0;
517
1.71M
            }
518
6.76k
            break;
519
4.63k
        case 2:
520
11.4k
        case 3:
521
2.92M
            for (; nsample < band + 256; nsample++) {
522
2.91M
                float c1 = su1[nsample];
523
2.91M
                float c2 = su2[nsample];
524
2.91M
                su1[nsample] = c1 + c2;
525
2.91M
                su2[nsample] = c1 - c2;
526
2.91M
            }
527
11.4k
            break;
528
0
        default:
529
0
            av_unreachable("curr_code/matrix_coeff_index_* values are stored in two bits");
530
24.4k
        }
531
24.4k
    }
532
6.11k
}
533
534
static void get_channel_weights(int index, int flag, float ch[2])
535
8.93k
{
536
8.93k
    if (index == 7) {
537
1.55k
        ch[0] = 1.0;
538
1.55k
        ch[1] = 1.0;
539
7.38k
    } else {
540
7.38k
        ch[0] = (index & 7) / 7.0;
541
7.38k
        ch[1] = sqrt(2 - ch[0] * ch[0]);
542
7.38k
        if (flag)
543
913
            FFSWAP(float, ch[0], ch[1]);
544
7.38k
    }
545
8.93k
}
546
547
static void channel_weighting(float *su1, float *su2, int *p3)
548
6.11k
{
549
6.11k
    int band, nsample;
550
    /* w[x][y] y=0 is left y=1 is right */
551
6.11k
    float w[2][2];
552
553
6.11k
    if (p3[1] != 7 || p3[3] != 7) {
554
4.46k
        get_channel_weights(p3[1], p3[0], w[0]);
555
4.46k
        get_channel_weights(p3[3], p3[2], w[1]);
556
557
17.8k
        for (band = 256; band < 4 * 256; band += 256) {
558
120k
            for (nsample = band; nsample < band + 8; nsample++) {
559
107k
                su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
560
107k
                su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
561
107k
            }
562
3.33M
            for(; nsample < band + 256; nsample++) {
563
3.32M
                su1[nsample] *= w[1][0];
564
3.32M
                su2[nsample] *= w[1][1];
565
3.32M
            }
566
13.4k
        }
567
4.46k
    }
568
6.11k
}
569
570
/**
571
 * Decode a Sound Unit
572
 *
573
 * @param snd           the channel unit to be used
574
 * @param output        the decoded samples before IQMF in float representation
575
 * @param channel_num   channel number
576
 * @param coding_mode   the coding mode (JOINT_STEREO or single channels)
577
 */
578
static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
579
                                     ChannelUnit *snd, float *output,
580
                                     int channel_num, int coding_mode)
581
1.07M
{
582
1.07M
    int band, ret, num_subbands, last_tonal, num_bands;
583
1.07M
    GainBlock *gain1 = &snd->gain_block[    snd->gc_blk_switch];
584
1.07M
    GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
585
586
1.07M
    if (coding_mode == JOINT_STEREO && (channel_num % 2) == 1) {
587
9.09k
        if (get_bits(gb, 2) != 3) {
588
2.65k
            av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
589
2.65k
            return AVERROR_INVALIDDATA;
590
2.65k
        }
591
1.06M
    } else {
592
1.06M
        if (get_bits(gb, 6) != 0x28) {
593
135k
            av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
594
135k
            return AVERROR_INVALIDDATA;
595
135k
        }
596
1.06M
    }
597
598
    /* number of coded QMF bands */
599
937k
    snd->bands_coded = get_bits(gb, 2);
600
601
937k
    ret = decode_gain_control(gb, gain2, snd->bands_coded);
602
937k
    if (ret)
603
5.23k
        return ret;
604
605
931k
    snd->num_components = decode_tonal_components(gb, snd->components,
606
931k
                                                  snd->bands_coded);
607
931k
    if (snd->num_components < 0)
608
10.4k
        return snd->num_components;
609
610
921k
    num_subbands = decode_spectrum(gb, snd->spectrum);
611
612
    /* Merge the decoded spectrum and tonal components. */
613
921k
    last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
614
921k
                                      snd->components);
615
616
617
    /* calculate number of used MLT/QMF bands according to the amount of coded
618
       spectral lines */
619
921k
    num_bands = (subband_tab[num_subbands + 1] - 1) >> 8;
620
921k
    if (last_tonal >= 0)
621
142k
        num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
622
623
624
    /* Reconstruct time domain samples. */
625
4.60M
    for (band = 0; band < 4; band++) {
626
        /* Perform the IMDCT step without overlapping. */
627
3.68M
        if (band <= num_bands)
628
1.07M
            imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
629
2.60M
        else
630
2.60M
            memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
631
632
        /* gain compensation and overlapping */
633
3.68M
        ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,
634
3.68M
                                   &snd->prev_frame[band * 256],
635
3.68M
                                   &gain1->g_block[band], &gain2->g_block[band],
636
3.68M
                                   256, &output[band * 256]);
637
3.68M
    }
638
639
    /* Swap the gain control buffers for the next frame. */
640
921k
    snd->gc_blk_switch ^= 1;
641
642
921k
    return 0;
643
931k
}
644
645
static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
646
                        float **out_samples)
647
256k
{
648
256k
    ATRAC3Context *q = avctx->priv_data;
649
256k
    int ret, i, ch;
650
256k
    uint8_t *ptr1;
651
256k
    int channels = avctx->ch_layout.nb_channels;
652
653
256k
    if (q->coding_mode == JOINT_STEREO) {
654
        /* channel coupling mode */
655
656
        /* Decode sound unit pairs (channels are expected to be even).
657
         * Multichannel joint stereo interleaves pairs (6ch: 2ch + 2ch + 2ch) */
658
9.13k
        const uint8_t *js_databuf;
659
9.13k
        int js_pair, js_block_align;
660
661
9.13k
        js_block_align = (avctx->block_align / channels) * 2; /* block pair */
662
663
15.2k
        for (ch = 0; ch < channels; ch = ch + 2) {
664
14.7k
            js_pair = ch/2;
665
14.7k
            js_databuf = databuf + js_pair * js_block_align; /* align to current pair */
666
667
            /* Set the bitstream reader at the start of first channel sound unit. */
668
14.7k
            init_get_bits(&q->gb,
669
14.7k
                          js_databuf, js_block_align * 8);
670
671
            /* decode Sound Unit 1 */
672
14.7k
            ret = decode_channel_sound_unit(q, &q->gb, &q->units[ch],
673
14.7k
                                            out_samples[ch], ch, JOINT_STEREO);
674
14.7k
            if (ret != 0)
675
5.48k
                return ret;
676
677
            /* Framedata of the su2 in the joint-stereo mode is encoded in
678
             * reverse byte order so we need to swap it first. */
679
9.30k
            if (js_databuf == q->decoded_bytes_buffer) {
680
7.44k
                uint8_t *ptr2 = q->decoded_bytes_buffer + js_block_align - 1;
681
7.44k
                ptr1          = q->decoded_bytes_buffer;
682
25.0k
                for (i = 0; i < js_block_align / 2; i++, ptr1++, ptr2--)
683
17.5k
                    FFSWAP(uint8_t, *ptr1, *ptr2);
684
7.44k
            } else {
685
1.85k
                const uint8_t *ptr2 = js_databuf + js_block_align - 1;
686
185k
                for (i = 0; i < js_block_align; i++)
687
183k
                    q->decoded_bytes_buffer[i] = *ptr2--;
688
1.85k
            }
689
690
            /* Skip the sync codes (0xF8). */
691
9.30k
            ptr1 = q->decoded_bytes_buffer;
692
12.0k
            for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
693
2.93k
                if (i >= js_block_align)
694
202
                    return AVERROR_INVALIDDATA;
695
2.93k
            }
696
697
698
            /* set the bitstream reader at the start of the second Sound Unit */
699
9.09k
            ret = init_get_bits8(&q->gb,
700
9.09k
                           ptr1, q->decoded_bytes_buffer + js_block_align - ptr1);
701
9.09k
            if (ret < 0)
702
0
                return ret;
703
704
            /* Fill the Weighting coeffs delay buffer */
705
9.09k
            memmove(q->weighting_delay[js_pair], &q->weighting_delay[js_pair][2],
706
9.09k
                    4 * sizeof(*q->weighting_delay[js_pair]));
707
9.09k
            q->weighting_delay[js_pair][4] = get_bits1(&q->gb);
708
9.09k
            q->weighting_delay[js_pair][5] = get_bits(&q->gb, 3);
709
710
45.4k
            for (i = 0; i < 4; i++) {
711
36.3k
                q->matrix_coeff_index_prev[js_pair][i] = q->matrix_coeff_index_now[js_pair][i];
712
36.3k
                q->matrix_coeff_index_now[js_pair][i]  = q->matrix_coeff_index_next[js_pair][i];
713
36.3k
                q->matrix_coeff_index_next[js_pair][i] = get_bits(&q->gb, 2);
714
36.3k
            }
715
716
            /* Decode Sound Unit 2. */
717
9.09k
            ret = decode_channel_sound_unit(q, &q->gb, &q->units[ch+1],
718
9.09k
                                            out_samples[ch+1], ch+1, JOINT_STEREO);
719
9.09k
            if (ret != 0)
720
2.98k
                return ret;
721
722
            /* Reconstruct the channel coefficients. */
723
6.11k
            reverse_matrixing(out_samples[ch], out_samples[ch+1],
724
6.11k
                              q->matrix_coeff_index_prev[js_pair],
725
6.11k
                              q->matrix_coeff_index_now[js_pair]);
726
727
6.11k
            channel_weighting(out_samples[ch], out_samples[ch+1], q->weighting_delay[js_pair]);
728
6.11k
        }
729
247k
    } else {
730
        /* single channels */
731
        /* Decode the channel sound units. */
732
953k
        for (i = 0; i < channels; i++) {
733
            /* Set the bitstream reader at the start of a channel sound unit. */
734
729k
            init_get_bits(&q->gb,
735
729k
                          databuf + i * avctx->block_align / channels,
736
729k
                          avctx->block_align * 8 / channels);
737
738
729k
            ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
739
729k
                                            out_samples[i], i, q->coding_mode);
740
729k
            if (ret != 0)
741
23.2k
                return ret;
742
729k
        }
743
247k
    }
744
745
    /* Apply the iQMF synthesis filter. */
746
930k
    for (i = 0; i < channels; i++) {
747
706k
        float *p1 = out_samples[i];
748
706k
        float *p2 = p1 + 256;
749
706k
        float *p3 = p2 + 256;
750
706k
        float *p4 = p3 + 256;
751
706k
        ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
752
706k
        ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
753
706k
        ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
754
706k
    }
755
756
224k
    return 0;
757
256k
}
758
759
static int al_decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
760
                           int size, float **out_samples)
761
300k
{
762
300k
    ATRAC3Context *q = avctx->priv_data;
763
300k
    int channels = avctx->ch_layout.nb_channels;
764
300k
    int ret, i;
765
766
    /* Set the bitstream reader at the start of a channel sound unit. */
767
300k
    init_get_bits(&q->gb, databuf, size * 8);
768
    /* single channels */
769
    /* Decode the channel sound units. */
770
500k
    for (i = 0; i < channels; i++) {
771
322k
        ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
772
322k
                                        out_samples[i], i, q->coding_mode);
773
322k
        if (ret != 0)
774
122k
            return ret;
775
8.03M
        while (i < channels && get_bits_left(&q->gb) > 6 && show_bits(&q->gb, 6) != 0x28) {
776
7.83M
            skip_bits(&q->gb, 1);
777
7.83M
        }
778
200k
    }
779
780
    /* Apply the iQMF synthesis filter. */
781
358k
    for (i = 0; i < channels; i++) {
782
179k
        float *p1 = out_samples[i];
783
179k
        float *p2 = p1 + 256;
784
179k
        float *p3 = p2 + 256;
785
179k
        float *p4 = p3 + 256;
786
179k
        ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
787
179k
        ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
788
179k
        ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
789
179k
    }
790
791
178k
    return 0;
792
300k
}
793
794
static int atrac3_decode_frame(AVCodecContext *avctx, AVFrame *frame,
795
                               int *got_frame_ptr, AVPacket *avpkt)
796
349k
{
797
349k
    const uint8_t *buf = avpkt->data;
798
349k
    int buf_size = avpkt->size;
799
349k
    ATRAC3Context *q = avctx->priv_data;
800
349k
    int ret;
801
349k
    const uint8_t *databuf;
802
803
349k
    if (buf_size < avctx->block_align) {
804
93.5k
        av_log(avctx, AV_LOG_ERROR,
805
93.5k
               "Frame too small (%d bytes). Truncated file?\n", buf_size);
806
93.5k
        return AVERROR_INVALIDDATA;
807
93.5k
    }
808
809
    /* get output buffer */
810
256k
    frame->nb_samples = SAMPLES_PER_FRAME;
811
256k
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
812
0
        return ret;
813
814
    /* Check if we need to descramble and what buffer to pass on. */
815
256k
    if (q->scrambled_stream) {
816
255k
        decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
817
255k
        databuf = q->decoded_bytes_buffer;
818
255k
    } else {
819
1.01k
        databuf = buf;
820
1.01k
    }
821
822
256k
    ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
823
256k
    if (ret) {
824
31.8k
        av_log(avctx, AV_LOG_ERROR, "Frame decoding error!\n");
825
31.8k
        return ret;
826
31.8k
    }
827
828
224k
    *got_frame_ptr = 1;
829
830
224k
    return avctx->block_align;
831
256k
}
832
833
static int atrac3al_decode_frame(AVCodecContext *avctx, AVFrame *frame,
834
                                 int *got_frame_ptr, AVPacket *avpkt)
835
300k
{
836
300k
    int ret;
837
838
300k
    frame->nb_samples = SAMPLES_PER_FRAME;
839
300k
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
840
0
        return ret;
841
842
300k
    ret = al_decode_frame(avctx, avpkt->data, avpkt->size,
843
300k
                          (float **)frame->extended_data);
844
300k
    if (ret) {
845
122k
        av_log(avctx, AV_LOG_ERROR, "Frame decoding error!\n");
846
122k
        return ret;
847
122k
    }
848
849
178k
    *got_frame_ptr = 1;
850
851
178k
    return avpkt->size;
852
300k
}
853
854
static av_cold void atrac3_init_static_data(void)
855
2
{
856
2
    VLCElem *table = atrac3_vlc_table;
857
2
    const uint8_t (*hufftabs)[2] = atrac3_hufftabs;
858
2
    int i;
859
860
2
    init_imdct_window();
861
2
    ff_atrac_generate_tables();
862
863
    /* Initialize the VLC tables. */
864
16
    for (i = 0; i < 7; i++) {
865
14
        spectral_coeff_tab[i].table           = table;
866
14
        spectral_coeff_tab[i].table_allocated = 256;
867
14
        ff_vlc_init_from_lengths(&spectral_coeff_tab[i], ATRAC3_VLC_BITS, huff_tab_sizes[i],
868
14
                                 &hufftabs[0][1], 2,
869
14
                                 &hufftabs[0][0], 2, 1,
870
14
                                 -31, VLC_INIT_USE_STATIC, NULL);
871
14
        hufftabs += huff_tab_sizes[i];
872
14
        table += 256;
873
14
    }
874
2
}
875
876
static av_cold int atrac3_decode_init(AVCodecContext *avctx)
877
1.95k
{
878
1.95k
    static AVOnce init_static_once = AV_ONCE_INIT;
879
1.95k
    int i, js_pair, ret;
880
1.95k
    int version, delay, samples_per_frame, frame_factor;
881
1.95k
    const uint8_t *edata_ptr = avctx->extradata;
882
1.95k
    ATRAC3Context *q = avctx->priv_data;
883
1.95k
    AVFloatDSPContext *fdsp;
884
1.95k
    float scale = 1.0 / 32768;
885
1.95k
    int channels = avctx->ch_layout.nb_channels;
886
887
1.95k
    if (channels < MIN_CHANNELS || channels > MAX_CHANNELS) {
888
160
        av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
889
160
        return AVERROR(EINVAL);
890
160
    }
891
892
    /* Take care of the codec-specific extradata. */
893
1.79k
    if (avctx->codec_id == AV_CODEC_ID_ATRAC3AL) {
894
868
        version           = 4;
895
868
        samples_per_frame = SAMPLES_PER_FRAME * channels;
896
868
        delay             = 0x88E;
897
868
        q->coding_mode    = SINGLE;
898
931
    } else if (avctx->extradata_size == 14) {
899
        /* Parse the extradata, WAV format */
900
171
        av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
901
171
               bytestream_get_le16(&edata_ptr));  // Unknown value always 1
902
171
        edata_ptr += 4;                             // samples per channel
903
171
        q->coding_mode = bytestream_get_le16(&edata_ptr);
904
171
        av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
905
171
               bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
906
171
        frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1
907
171
        av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
908
171
               bytestream_get_le16(&edata_ptr));  // Unknown always 0
909
910
        /* setup */
911
171
        samples_per_frame    = SAMPLES_PER_FRAME * channels;
912
171
        version              = 4;
913
171
        delay                = 0x88E;
914
171
        q->coding_mode       = q->coding_mode ? JOINT_STEREO : SINGLE;
915
171
        q->scrambled_stream  = 0;
916
917
171
        if (avctx->block_align !=  96 * channels * frame_factor &&
918
50
            avctx->block_align != 152 * channels * frame_factor &&
919
48
            avctx->block_align != 192 * channels * frame_factor) {
920
44
            av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
921
44
                   "configuration %d/%d/%d\n", avctx->block_align,
922
44
                   channels, frame_factor);
923
44
            return AVERROR_INVALIDDATA;
924
44
        }
925
760
    } else if (avctx->extradata_size == 12 || avctx->extradata_size == 10) {
926
        /* Parse the extradata, RM format. */
927
726
        version                = bytestream_get_be32(&edata_ptr);
928
726
        samples_per_frame      = bytestream_get_be16(&edata_ptr);
929
726
        delay                  = bytestream_get_be16(&edata_ptr);
930
726
        q->coding_mode         = bytestream_get_be16(&edata_ptr);
931
726
        q->scrambled_stream    = 1;
932
933
726
    } else {
934
34
        av_log(avctx, AV_LOG_ERROR, "Unknown extradata size %d.\n",
935
34
               avctx->extradata_size);
936
34
        return AVERROR(EINVAL);
937
34
    }
938
939
    /* Check the extradata */
940
941
1.72k
    if (version != 4) {
942
38
        av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
943
38
        return AVERROR_INVALIDDATA;
944
38
    }
945
946
1.68k
    if (samples_per_frame != SAMPLES_PER_FRAME * channels) {
947
24
        av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
948
24
               samples_per_frame);
949
24
        return AVERROR_INVALIDDATA;
950
24
    }
951
952
1.65k
    if (delay != 0x88E) {
953
21
        av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
954
21
               delay);
955
21
        return AVERROR_INVALIDDATA;
956
21
    }
957
958
1.63k
    if (q->coding_mode == SINGLE)
959
1.27k
        av_log(avctx, AV_LOG_DEBUG, "Single channels detected.\n");
960
359
    else if (q->coding_mode == JOINT_STEREO) {
961
345
        if (channels % 2 == 1) { /* Joint stereo channels must be even */
962
1
            av_log(avctx, AV_LOG_ERROR, "Invalid joint stereo channel configuration.\n");
963
1
            return AVERROR_INVALIDDATA;
964
1
        }
965
344
        av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
966
344
    } else {
967
14
        av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
968
14
               q->coding_mode);
969
14
        return AVERROR_INVALIDDATA;
970
14
    }
971
972
1.62k
    if (avctx->block_align > 4096 || avctx->block_align <= 0)
973
41
        return AVERROR(EINVAL);
974
975
1.58k
    q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
976
1.58k
                                         AV_INPUT_BUFFER_PADDING_SIZE);
977
1.58k
    if (!q->decoded_bytes_buffer)
978
0
        return AVERROR(ENOMEM);
979
980
1.58k
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
981
982
    /* initialize the MDCT transform */
983
1.58k
    if ((ret = av_tx_init(&q->mdct_ctx, &q->mdct_fn, AV_TX_FLOAT_MDCT, 1, 256,
984
1.58k
                          &scale, AV_TX_FULL_IMDCT)) < 0) {
985
0
        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
986
0
        return ret;
987
0
    }
988
989
    /* init the joint-stereo decoding data */
990
7.91k
    for (js_pair = 0; js_pair < MAX_JS_PAIRS; js_pair++) {
991
6.32k
        q->weighting_delay[js_pair][0] = 0;
992
6.32k
        q->weighting_delay[js_pair][1] = 7;
993
6.32k
        q->weighting_delay[js_pair][2] = 0;
994
6.32k
        q->weighting_delay[js_pair][3] = 7;
995
6.32k
        q->weighting_delay[js_pair][4] = 0;
996
6.32k
        q->weighting_delay[js_pair][5] = 7;
997
998
31.6k
        for (i = 0; i < 4; i++) {
999
25.3k
            q->matrix_coeff_index_prev[js_pair][i] = 3;
1000
25.3k
            q->matrix_coeff_index_now[js_pair][i]  = 3;
1001
25.3k
            q->matrix_coeff_index_next[js_pair][i] = 3;
1002
25.3k
        }
1003
6.32k
    }
1004
1005
1.58k
    ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
1006
1.58k
    fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1007
1.58k
    if (!fdsp)
1008
0
        return AVERROR(ENOMEM);
1009
1.58k
    q->vector_fmul = fdsp->vector_fmul;
1010
1.58k
    av_free(fdsp);
1011
1012
1.58k
    q->units = av_calloc(channels, sizeof(*q->units));
1013
1.58k
    if (!q->units)
1014
0
        return AVERROR(ENOMEM);
1015
1016
1.58k
    ff_thread_once(&init_static_once, atrac3_init_static_data);
1017
1018
1.58k
    return 0;
1019
1.58k
}
1020
1021
const FFCodec ff_atrac3_decoder = {
1022
    .p.name           = "atrac3",
1023
    CODEC_LONG_NAME("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
1024
    .p.type           = AVMEDIA_TYPE_AUDIO,
1025
    .p.id             = AV_CODEC_ID_ATRAC3,
1026
    .priv_data_size   = sizeof(ATRAC3Context),
1027
    .init             = atrac3_decode_init,
1028
    .close            = atrac3_decode_close,
1029
    FF_CODEC_DECODE_CB(atrac3_decode_frame),
1030
    .p.capabilities   = AV_CODEC_CAP_DR1,
1031
    .caps_internal    = FF_CODEC_CAP_INIT_CLEANUP,
1032
};
1033
1034
const FFCodec ff_atrac3al_decoder = {
1035
    .p.name           = "atrac3al",
1036
    CODEC_LONG_NAME("ATRAC3 AL (Adaptive TRansform Acoustic Coding 3 Advanced Lossless)"),
1037
    .p.type           = AVMEDIA_TYPE_AUDIO,
1038
    .p.id             = AV_CODEC_ID_ATRAC3AL,
1039
    .priv_data_size   = sizeof(ATRAC3Context),
1040
    .init             = atrac3_decode_init,
1041
    .close            = atrac3_decode_close,
1042
    FF_CODEC_DECODE_CB(atrac3al_decode_frame),
1043
    .p.capabilities   = AV_CODEC_CAP_DR1,
1044
    .caps_internal    = FF_CODEC_CAP_INIT_CLEANUP,
1045
};