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

/**
24
 * @file
25
 * ATRAC3 compatible decoder.
26 27
 * This decoder handles Sony's ATRAC3 data.
 *
28
 * Container formats used to store ATRAC3 data:
29
 * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
Benjamin Larsson's avatar
Benjamin Larsson committed
30 31
 *
 * To use this decoder, a calling application must supply the extradata
32
 * bytes provided in the containers above.
Benjamin Larsson's avatar
Benjamin Larsson committed
33 34 35 36 37 38
 */

#include <math.h>
#include <stddef.h>
#include <stdio.h>

39
#include "libavutil/attributes.h"
40
#include "libavutil/float_dsp.h"
41
#include "libavutil/libm.h"
Benjamin Larsson's avatar
Benjamin Larsson committed
42 43
#include "avcodec.h"
#include "bytestream.h"
44
#include "fft.h"
45
#include "get_bits.h"
46
#include "internal.h"
Benjamin Larsson's avatar
Benjamin Larsson committed
47

48
#include "atrac.h"
Benjamin Larsson's avatar
Benjamin Larsson committed
49 50 51 52 53
#include "atrac3data.h"

#define JOINT_STEREO    0x12
#define STEREO          0x2

54 55
#define SAMPLES_PER_FRAME 1024
#define MDCT_SIZE          512
Benjamin Larsson's avatar
Benjamin Larsson committed
56

57
typedef struct GainBlock {
58
    AtracGainInfo g_block[4];
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
} GainBlock;

typedef struct TonalComponent {
    int pos;
    int num_coefs;
    float coef[8];
} TonalComponent;

typedef struct ChannelUnit {
    int            bands_coded;
    int            num_components;
    float          prev_frame[SAMPLES_PER_FRAME];
    int            gc_blk_switch;
    TonalComponent components[64];
    GainBlock      gain_block[2];
Benjamin Larsson's avatar
Benjamin Larsson committed
74

75
    DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
76
    DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
Benjamin Larsson's avatar
Benjamin Larsson committed
77

78 79 80 81
    float          delay_buf1[46]; ///<qmf delay buffers
    float          delay_buf2[46];
    float          delay_buf3[46];
} ChannelUnit;
Benjamin Larsson's avatar
Benjamin Larsson committed
82

83 84
typedef struct ATRAC3Context {
    GetBitContext gb;
Benjamin Larsson's avatar
Benjamin Larsson committed
85 86
    //@{
    /** stream data */
87 88 89
    int coding_mode;

    ChannelUnit *units;
Benjamin Larsson's avatar
Benjamin Larsson committed
90 91 92
    //@}
    //@{
    /** joint-stereo related variables */
93 94 95 96
    int matrix_coeff_index_prev[4];
    int matrix_coeff_index_now[4];
    int matrix_coeff_index_next[4];
    int weighting_delay[6];
Benjamin Larsson's avatar
Benjamin Larsson committed
97 98 99
    //@}
    //@{
    /** data buffers */
100 101
    uint8_t *decoded_bytes_buffer;
    float temp_buf[1070];
Benjamin Larsson's avatar
Benjamin Larsson committed
102 103 104
    //@}
    //@{
    /** extradata */
105
    int scrambled_stream;
Benjamin Larsson's avatar
Benjamin Larsson committed
106
    //@}
107

108 109
    AtracGCContext    gainc_ctx;
    FFTContext        mdct_ctx;
110
    AVFloatDSPContext *fdsp;
Benjamin Larsson's avatar
Benjamin Larsson committed
111 112
} ATRAC3Context;

113
static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
114
static VLC_TYPE atrac3_vlc_table[4096][2];
115
static VLC   spectral_coeff_tab[7];
Benjamin Larsson's avatar
Benjamin Larsson committed
116

117
/**
118 119
 * Regular 512 points IMDCT without overlapping, with the exception of the
 * swapping of odd bands caused by the reverse spectra of the QMF.
Benjamin Larsson's avatar
Benjamin Larsson committed
120 121 122
 *
 * @param odd_band  1 if the band is an odd band
 */
123
static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
Benjamin Larsson's avatar
Benjamin Larsson committed
124
{
125
    int i;
Benjamin Larsson's avatar
Benjamin Larsson committed
126 127 128

    if (odd_band) {
        /**
129 130 131 132 133 134 135 136 137
         * Reverse the odd bands before IMDCT, this is an effect of the QMF
         * transform or it gives better compression to do it this way.
         * FIXME: It should be possible to handle this in imdct_calc
         * for that to happen a modification of the prerotation step of
         * all SIMD code and C code is needed.
         * Or fix the functions before so they generate a pre reversed spectrum.
         */
        for (i = 0; i < 128; i++)
            FFSWAP(float, input[i], input[255 - i]);
Benjamin Larsson's avatar
Benjamin Larsson committed
138 139
    }

140
    q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
Benjamin Larsson's avatar
Benjamin Larsson committed
141 142

    /* Perform windowing on the output. */
143
    q->fdsp->vector_fmul(output, output, mdct_window, MDCT_SIZE);
Benjamin Larsson's avatar
Benjamin Larsson committed
144 145
}

146 147
/*
 * indata descrambling, only used for data coming from the rm container
Benjamin Larsson's avatar
Benjamin Larsson committed
148
 */
149 150
static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
{
Benjamin Larsson's avatar
Benjamin Larsson committed
151 152
    int i, off;
    uint32_t c;
153 154
    const uint32_t *buf;
    uint32_t *output = (uint32_t *)out;
Benjamin Larsson's avatar
Benjamin Larsson committed
155

156 157
    off = (intptr_t)input & 3;
    buf = (const uint32_t *)(input - off);
158 159 160 161
    if (off)
        c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
    else
        c = av_be2ne32(0x537F6103U);
Benjamin Larsson's avatar
Benjamin Larsson committed
162
    bytes += 3 + off;
163 164
    for (i = 0; i < bytes / 4; i++)
        output[i] = c ^ buf[i];
Benjamin Larsson's avatar
Benjamin Larsson committed
165 166

    if (off)
167
        avpriv_request_sample(NULL, "Offset of %d", off);
Benjamin Larsson's avatar
Benjamin Larsson committed
168 169 170 171

    return off;
}

172
static av_cold void init_imdct_window(void)
173
{
174
    int i, j;
Benjamin Larsson's avatar
Benjamin Larsson committed
175

176
    /* generate the mdct window, for details see
Benjamin Larsson's avatar
Benjamin Larsson committed
177
     * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
178 179 180 181 182 183
    for (i = 0, j = 255; i < 128; i++, j--) {
        float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
        float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
        float w  = 0.5 * (wi * wi + wj * wj);
        mdct_window[i] = mdct_window[511 - i] = wi / w;
        mdct_window[j] = mdct_window[511 - j] = wj / w;
184
    }
Benjamin Larsson's avatar
Benjamin Larsson committed
185 186
}

187
static av_cold int atrac3_decode_close(AVCodecContext *avctx)
Benjamin Larsson's avatar
Benjamin Larsson committed
188 189 190
{
    ATRAC3Context *q = avctx->priv_data;

191 192
    av_freep(&q->units);
    av_freep(&q->decoded_bytes_buffer);
193
    av_freep(&q->fdsp);
194

195
    ff_mdct_end(&q->mdct_ctx);
Benjamin Larsson's avatar
Benjamin Larsson committed
196 197 198 199

    return 0;
}

200
/**
201
 * Mantissa decoding
Benjamin Larsson's avatar
Benjamin Larsson committed
202
 *
203 204 205 206
 * @param selector     which table the output values are coded with
 * @param coding_flag  constant length coding or variable length coding
 * @param mantissas    mantissa output table
 * @param num_codes    number of values to get
Benjamin Larsson's avatar
Benjamin Larsson committed
207
 */
208 209 210
static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
                                       int coding_flag, int *mantissas,
                                       int num_codes)
Benjamin Larsson's avatar
Benjamin Larsson committed
211
{
212
    int i, code, huff_symb;
Benjamin Larsson's avatar
Benjamin Larsson committed
213 214

    if (selector == 1)
215
        num_codes /= 2;
Benjamin Larsson's avatar
Benjamin Larsson committed
216

217
    if (coding_flag != 0) {
Benjamin Larsson's avatar
Benjamin Larsson committed
218
        /* constant length coding (CLC) */
219
        int num_bits = clc_length_tab[selector];
Benjamin Larsson's avatar
Benjamin Larsson committed
220 221

        if (selector > 1) {
222 223 224
            for (i = 0; i < num_codes; i++) {
                if (num_bits)
                    code = get_sbits(gb, num_bits);
Benjamin Larsson's avatar
Benjamin Larsson committed
225 226
                else
                    code = 0;
227
                mantissas[i] = code;
Benjamin Larsson's avatar
Benjamin Larsson committed
228 229
            }
        } else {
230 231 232
            for (i = 0; i < num_codes; i++) {
                if (num_bits)
                    code = get_bits(gb, num_bits); // num_bits is always 4 in this case
Benjamin Larsson's avatar
Benjamin Larsson committed
233 234
                else
                    code = 0;
235 236
                mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
                mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
Benjamin Larsson's avatar
Benjamin Larsson committed
237 238 239 240 241
            }
        }
    } else {
        /* variable length coding (VLC) */
        if (selector != 1) {
242 243 244 245 246 247
            for (i = 0; i < num_codes; i++) {
                huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
                                     spectral_coeff_tab[selector-1].bits, 3);
                huff_symb += 1;
                code = huff_symb >> 1;
                if (huff_symb & 1)
Benjamin Larsson's avatar
Benjamin Larsson committed
248
                    code = -code;
249
                mantissas[i] = code;
Benjamin Larsson's avatar
Benjamin Larsson committed
250 251
            }
        } else {
252 253 254 255 256
            for (i = 0; i < num_codes; i++) {
                huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
                                     spectral_coeff_tab[selector - 1].bits, 3);
                mantissas[i * 2    ] = mantissa_vlc_tab[huff_symb * 2    ];
                mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
Benjamin Larsson's avatar
Benjamin Larsson committed
257 258 259 260 261
            }
        }
    }
}

262
/**
Benjamin Larsson's avatar
Benjamin Larsson committed
263 264
 * Restore the quantized band spectrum coefficients
 *
265
 * @return subband count, fix for broken specification/files
Benjamin Larsson's avatar
Benjamin Larsson committed
266
 */
267
static int decode_spectrum(GetBitContext *gb, float *output)
Benjamin Larsson's avatar
Benjamin Larsson committed
268
{
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    int num_subbands, coding_mode, i, j, first, last, subband_size;
    int subband_vlc_index[32], sf_index[32];
    int mantissas[128];
    float scale_factor;

    num_subbands = get_bits(gb, 5);  // number of coded subbands
    coding_mode  = get_bits1(gb);    // coding Mode: 0 - VLC/ 1-CLC

    /* get the VLC selector table for the subbands, 0 means not coded */
    for (i = 0; i <= num_subbands; i++)
        subband_vlc_index[i] = get_bits(gb, 3);

    /* read the scale factor indexes from the stream */
    for (i = 0; i <= num_subbands; i++) {
        if (subband_vlc_index[i] != 0)
            sf_index[i] = get_bits(gb, 6);
Benjamin Larsson's avatar
Benjamin Larsson committed
285 286
    }

287 288 289
    for (i = 0; i <= num_subbands; i++) {
        first = subband_tab[i    ];
        last  = subband_tab[i + 1];
Benjamin Larsson's avatar
Benjamin Larsson committed
290

291
        subband_size = last - first;
Benjamin Larsson's avatar
Benjamin Larsson committed
292

293 294
        if (subband_vlc_index[i] != 0) {
            /* decode spectral coefficients for this subband */
Benjamin Larsson's avatar
Benjamin Larsson committed
295 296
            /* TODO: This can be done faster is several blocks share the
             * same VLC selector (subband_vlc_index) */
297 298
            read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
                                       mantissas, subband_size);
Benjamin Larsson's avatar
Benjamin Larsson committed
299

300 301 302
            /* decode the scale factor for this subband */
            scale_factor = ff_atrac_sf_table[sf_index[i]] *
                           inv_max_quant[subband_vlc_index[i]];
Benjamin Larsson's avatar
Benjamin Larsson committed
303

304 305 306
            /* inverse quantize the coefficients */
            for (j = 0; first < last; first++, j++)
                output[first] = mantissas[j] * scale_factor;
Benjamin Larsson's avatar
Benjamin Larsson committed
307
        } else {
308
            /* this subband was not coded, so zero the entire subband */
309
            memset(output + first, 0, subband_size * sizeof(*output));
Benjamin Larsson's avatar
Benjamin Larsson committed
310 311 312
        }
    }

313 314
    /* clear the subbands that were not coded */
    first = subband_tab[i];
315
    memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
316
    return num_subbands;
Benjamin Larsson's avatar
Benjamin Larsson committed
317 318
}

319
/**
Benjamin Larsson's avatar
Benjamin Larsson committed
320 321
 * Restore the quantized tonal components
 *
322 323
 * @param components tonal components
 * @param num_bands  number of coded bands
Benjamin Larsson's avatar
Benjamin Larsson committed
324
 */
325 326
static int decode_tonal_components(GetBitContext *gb,
                                   TonalComponent *components, int num_bands)
Benjamin Larsson's avatar
Benjamin Larsson committed
327
{
328 329 330 331
    int i, b, c, m;
    int nb_components, coding_mode_selector, coding_mode;
    int band_flags[4], mantissa[8];
    int component_count = 0;
Benjamin Larsson's avatar
Benjamin Larsson committed
332

333
    nb_components = get_bits(gb, 5);
Benjamin Larsson's avatar
Benjamin Larsson committed
334 335

    /* no tonal components */
336
    if (nb_components == 0)
Benjamin Larsson's avatar
Benjamin Larsson committed
337 338
        return 0;

339
    coding_mode_selector = get_bits(gb, 2);
Benjamin Larsson's avatar
Benjamin Larsson committed
340
    if (coding_mode_selector == 2)
341
        return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
342 343 344

    coding_mode = coding_mode_selector & 1;

345 346 347 348 349
    for (i = 0; i < nb_components; i++) {
        int coded_values_per_component, quant_step_index;

        for (b = 0; b <= num_bands; b++)
            band_flags[b] = get_bits1(gb);
Benjamin Larsson's avatar
Benjamin Larsson committed
350

351
        coded_values_per_component = get_bits(gb, 3);
Benjamin Larsson's avatar
Benjamin Larsson committed
352

353
        quant_step_index = get_bits(gb, 3);
Benjamin Larsson's avatar
Benjamin Larsson committed
354
        if (quant_step_index <= 1)
355
            return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
356 357 358 359

        if (coding_mode_selector == 3)
            coding_mode = get_bits1(gb);

360 361 362 363
        for (b = 0; b < (num_bands + 1) * 4; b++) {
            int coded_components;

            if (band_flags[b >> 2] == 0)
Benjamin Larsson's avatar
Benjamin Larsson committed
364 365
                continue;

366 367 368 369 370 371
            coded_components = get_bits(gb, 3);

            for (c = 0; c < coded_components; c++) {
                TonalComponent *cmp = &components[component_count];
                int sf_index, coded_values, max_coded_values;
                float scale_factor;
Benjamin Larsson's avatar
Benjamin Larsson committed
372

373
                sf_index = get_bits(gb, 6);
374
                if (component_count >= 64)
375
                    return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
376

377 378 379 380 381
                cmp->pos = b * 64 + get_bits(gb, 6);

                max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
                coded_values     = coded_values_per_component + 1;
                coded_values     = FFMIN(max_coded_values, coded_values);
Benjamin Larsson's avatar
Benjamin Larsson committed
382

383 384
                scale_factor = ff_atrac_sf_table[sf_index] *
                               inv_max_quant[quant_step_index];
Benjamin Larsson's avatar
Benjamin Larsson committed
385

386 387 388 389
                read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
                                           mantissa, coded_values);

                cmp->num_coefs = coded_values;
Benjamin Larsson's avatar
Benjamin Larsson committed
390 391

                /* inverse quant */
392 393
                for (m = 0; m < coded_values; m++)
                    cmp->coef[m] = mantissa[m] * scale_factor;
Benjamin Larsson's avatar
Benjamin Larsson committed
394 395 396 397 398 399

                component_count++;
            }
        }
    }

400
    return component_count;
Benjamin Larsson's avatar
Benjamin Larsson committed
401 402
}

403
/**
Benjamin Larsson's avatar
Benjamin Larsson committed
404 405
 * Decode gain parameters for the coded bands
 *
406 407
 * @param block      the gainblock for the current band
 * @param num_bands  amount of coded bands
Benjamin Larsson's avatar
Benjamin Larsson committed
408
 */
409 410
static int decode_gain_control(GetBitContext *gb, GainBlock *block,
                               int num_bands)
Benjamin Larsson's avatar
Benjamin Larsson committed
411
{
412
    int b, j;
413 414
    int *level, *loc;

415
    AtracGainInfo *gain = block->g_block;
416

417 418
    for (b = 0; b <= num_bands; b++) {
        gain[b].num_points = get_bits(gb, 3);
419 420
        level              = gain[b].lev_code;
        loc                = gain[b].loc_code;
421

422
        for (j = 0; j < gain[b].num_points; j++) {
423 424 425
            level[j] = get_bits(gb, 4);
            loc[j]   = get_bits(gb, 5);
            if (j && loc[j] <= loc[j - 1])
426
                return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
427 428 429 430
        }
    }

    /* Clear the unused blocks. */
431 432
    for (; b < 4 ; b++)
        gain[b].num_points = 0;
Benjamin Larsson's avatar
Benjamin Larsson committed
433 434 435 436

    return 0;
}

437
/**
Benjamin Larsson's avatar
Benjamin Larsson committed
438 439
 * Combine the tonal band spectrum and regular band spectrum
 *
440 441 442 443
 * @param spectrum        output spectrum buffer
 * @param num_components  number of tonal components
 * @param components      tonal components for this band
 * @return                position of the last tonal coefficient
Benjamin Larsson's avatar
Benjamin Larsson committed
444
 */
445 446
static int add_tonal_components(float *spectrum, int num_components,
                                TonalComponent *components)
Benjamin Larsson's avatar
Benjamin Larsson committed
447
{
448 449
    int i, j, last_pos = -1;
    float *input, *output;
Benjamin Larsson's avatar
Benjamin Larsson committed
450

451 452 453 454
    for (i = 0; i < num_components; i++) {
        last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
        input    = components[i].coef;
        output   = &spectrum[components[i].pos];
Benjamin Larsson's avatar
Benjamin Larsson committed
455

456
        for (j = 0; j < components[i].num_coefs; j++)
457
            output[j] += input[j];
Benjamin Larsson's avatar
Benjamin Larsson committed
458
    }
459

460
    return last_pos;
Benjamin Larsson's avatar
Benjamin Larsson committed
461 462
}

463 464
#define INTERPOLATE(old, new, nsample) \
    ((old) + (nsample) * 0.125 * ((new) - (old)))
Benjamin Larsson's avatar
Benjamin Larsson committed
465

466 467
static void reverse_matrixing(float *su1, float *su2, int *prev_code,
                              int *curr_code)
Benjamin Larsson's avatar
Benjamin Larsson committed
468
{
469 470
    int i, nsample, band;
    float mc1_l, mc1_r, mc2_l, mc2_r;
Benjamin Larsson's avatar
Benjamin Larsson committed
471

472 473 474
    for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
        int s1 = prev_code[i];
        int s2 = curr_code[i];
475
        nsample = band;
Benjamin Larsson's avatar
Benjamin Larsson committed
476 477 478

        if (s1 != s2) {
            /* Selector value changed, interpolation needed. */
479 480 481 482
            mc1_l = matrix_coeffs[s1 * 2    ];
            mc1_r = matrix_coeffs[s1 * 2 + 1];
            mc2_l = matrix_coeffs[s2 * 2    ];
            mc2_r = matrix_coeffs[s2 * 2 + 1];
Benjamin Larsson's avatar
Benjamin Larsson committed
483 484

            /* Interpolation is done over the first eight samples. */
485 486 487 488 489 490 491
            for (; nsample < band + 8; nsample++) {
                float c1 = su1[nsample];
                float c2 = su2[nsample];
                c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
                     c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
                su1[nsample] = c2;
                su2[nsample] = c1 * 2.0 - c2;
Benjamin Larsson's avatar
Benjamin Larsson committed
492 493 494 495 496
            }
        }

        /* Apply the matrix without interpolation. */
        switch (s2) {
497
        case 0:     /* M/S decoding */
498 499 500 501 502
            for (; nsample < band + 256; nsample++) {
                float c1 = su1[nsample];
                float c2 = su2[nsample];
                su1[nsample] =  c2       * 2.0;
                su2[nsample] = (c1 - c2) * 2.0;
503 504 505
            }
            break;
        case 1:
506 507 508 509 510
            for (; nsample < band + 256; nsample++) {
                float c1 = su1[nsample];
                float c2 = su2[nsample];
                su1[nsample] = (c1 + c2) *  2.0;
                su2[nsample] =  c2       * -2.0;
511 512 513 514
            }
            break;
        case 2:
        case 3:
515 516 517 518 519
            for (; nsample < band + 256; nsample++) {
                float c1 = su1[nsample];
                float c2 = su2[nsample];
                su1[nsample] = c1 + c2;
                su2[nsample] = c1 - c2;
520 521 522
            }
            break;
        default:
523
            av_assert1(0);
Benjamin Larsson's avatar
Benjamin Larsson committed
524 525 526 527
        }
    }
}

528 529 530
static void get_channel_weights(int index, int flag, float ch[2])
{
    if (index == 7) {
Benjamin Larsson's avatar
Benjamin Larsson committed
531 532 533
        ch[0] = 1.0;
        ch[1] = 1.0;
    } else {
534 535 536
        ch[0] = (index & 7) / 7.0;
        ch[1] = sqrt(2 - ch[0] * ch[0]);
        if (flag)
Benjamin Larsson's avatar
Benjamin Larsson committed
537 538 539 540
            FFSWAP(float, ch[0], ch[1]);
    }
}

541
static void channel_weighting(float *su1, float *su2, int *p3)
Benjamin Larsson's avatar
Benjamin Larsson committed
542
{
543
    int band, nsample;
Benjamin Larsson's avatar
Benjamin Larsson committed
544 545 546
    /* w[x][y] y=0 is left y=1 is right */
    float w[2][2];

547 548 549
    if (p3[1] != 7 || p3[3] != 7) {
        get_channel_weights(p3[1], p3[0], w[0]);
        get_channel_weights(p3[3], p3[2], w[1]);
Benjamin Larsson's avatar
Benjamin Larsson committed
550

551 552 553 554
        for (band = 256; band < 4 * 256; band += 256) {
            for (nsample = band; nsample < band + 8; nsample++) {
                su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
                su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
Benjamin Larsson's avatar
Benjamin Larsson committed
555
            }
556 557 558
            for(; nsample < band + 256; nsample++) {
                su1[nsample] *= w[1][0];
                su2[nsample] *= w[1][1];
Benjamin Larsson's avatar
Benjamin Larsson committed
559 560 561 562 563
            }
        }
    }
}

564
/**
Benjamin Larsson's avatar
Benjamin Larsson committed
565 566
 * Decode a Sound Unit
 *
567 568 569 570
 * @param snd           the channel unit to be used
 * @param output        the decoded samples before IQMF in float representation
 * @param channel_num   channel number
 * @param coding_mode   the coding mode (JOINT_STEREO or regular stereo/mono)
Benjamin Larsson's avatar
Benjamin Larsson committed
571
 */
572 573 574
static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
                                     ChannelUnit *snd, float *output,
                                     int channel_num, int coding_mode)
Benjamin Larsson's avatar
Benjamin Larsson committed
575
{
576 577 578
    int band, ret, num_subbands, last_tonal, num_bands;
    GainBlock *gain1 = &snd->gain_block[    snd->gc_blk_switch];
    GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
Benjamin Larsson's avatar
Benjamin Larsson committed
579

580 581
    if (coding_mode == JOINT_STEREO && channel_num == 1) {
        if (get_bits(gb, 2) != 3) {
Benjamin Larsson's avatar
Benjamin Larsson committed
582
            av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
583
            return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
584 585
        }
    } else {
586
        if (get_bits(gb, 6) != 0x28) {
Benjamin Larsson's avatar
Benjamin Larsson committed
587
            av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
588
            return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
589 590 591 592
        }
    }

    /* number of coded QMF bands */
593
    snd->bands_coded = get_bits(gb, 2);
Benjamin Larsson's avatar
Benjamin Larsson committed
594

595 596 597
    ret = decode_gain_control(gb, gain2, snd->bands_coded);
    if (ret)
        return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
598

599 600
    snd->num_components = decode_tonal_components(gb, snd->components,
                                                  snd->bands_coded);
601 602
    if (snd->num_components < 0)
        return snd->num_components;
Benjamin Larsson's avatar
Benjamin Larsson committed
603

604
    num_subbands = decode_spectrum(gb, snd->spectrum);
Benjamin Larsson's avatar
Benjamin Larsson committed
605 606

    /* Merge the decoded spectrum and tonal components. */
607 608
    last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
                                      snd->components);
Benjamin Larsson's avatar
Benjamin Larsson committed
609 610


611 612 613 614 615
    /* calculate number of used MLT/QMF bands according to the amount of coded
       spectral lines */
    num_bands = (subband_tab[num_subbands] - 1) >> 8;
    if (last_tonal >= 0)
        num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
Benjamin Larsson's avatar
Benjamin Larsson committed
616 617 618


    /* Reconstruct time domain samples. */
619
    for (band = 0; band < 4; band++) {
Benjamin Larsson's avatar
Benjamin Larsson committed
620
        /* Perform the IMDCT step without overlapping. */
621 622 623
        if (band <= num_bands)
            imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
        else
624
            memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
Benjamin Larsson's avatar
Benjamin Larsson committed
625 626

        /* gain compensation and overlapping */
627 628 629 630
        ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,
                                   &snd->prev_frame[band * 256],
                                   &gain1->g_block[band], &gain2->g_block[band],
                                   256, &output[band * 256]);
Benjamin Larsson's avatar
Benjamin Larsson committed
631 632 633
    }

    /* Swap the gain control buffers for the next frame. */
634
    snd->gc_blk_switch ^= 1;
Benjamin Larsson's avatar
Benjamin Larsson committed
635 636 637 638

    return 0;
}

639
static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
640
                        float **out_samples)
Benjamin Larsson's avatar
Benjamin Larsson committed
641
{
642
    ATRAC3Context *q = avctx->priv_data;
643
    int ret, i;
644
    uint8_t *ptr1;
Benjamin Larsson's avatar
Benjamin Larsson committed
645

646
    if (q->coding_mode == JOINT_STEREO) {
Benjamin Larsson's avatar
Benjamin Larsson committed
647 648
        /* channel coupling mode */
        /* decode Sound Unit 1 */
649
        init_get_bits(&q->gb, databuf, avctx->block_align * 8);
Benjamin Larsson's avatar
Benjamin Larsson committed
650

651 652 653 654
        ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
                                        JOINT_STEREO);
        if (ret != 0)
            return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
655 656 657

        /* Framedata of the su2 in the joint-stereo mode is encoded in
         * reverse byte order so we need to swap it first. */
658
        if (databuf == q->decoded_bytes_buffer) {
659
            uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
660
            ptr1          = q->decoded_bytes_buffer;
661
            for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
662
                FFSWAP(uint8_t, *ptr1, *ptr2);
663
        } else {
664 665
            const uint8_t *ptr2 = databuf + avctx->block_align - 1;
            for (i = 0; i < avctx->block_align; i++)
666 667
                q->decoded_bytes_buffer[i] = *ptr2--;
        }
Benjamin Larsson's avatar
Benjamin Larsson committed
668 669

        /* Skip the sync codes (0xF8). */
670
        ptr1 = q->decoded_bytes_buffer;
Benjamin Larsson's avatar
Benjamin Larsson committed
671
        for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
672
            if (i >= avctx->block_align)
673
                return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
674 675 676 677
        }


        /* set the bitstream reader at the start of the second Sound Unit*/
678
        init_get_bits8(&q->gb, ptr1, q->decoded_bytes_buffer + avctx->block_align - ptr1);
Benjamin Larsson's avatar
Benjamin Larsson committed
679 680

        /* Fill the Weighting coeffs delay buffer */
681 682
        memmove(q->weighting_delay, &q->weighting_delay[2],
                4 * sizeof(*q->weighting_delay));
683
        q->weighting_delay[4] = get_bits1(&q->gb);
684
        q->weighting_delay[5] = get_bits(&q->gb, 3);
Benjamin Larsson's avatar
Benjamin Larsson committed
685 686 687

        for (i = 0; i < 4; i++) {
            q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
688 689
            q->matrix_coeff_index_now[i]  = q->matrix_coeff_index_next[i];
            q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
Benjamin Larsson's avatar
Benjamin Larsson committed
690 691 692
        }

        /* Decode Sound Unit 2. */
693 694 695 696
        ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
                                        out_samples[1], 1, JOINT_STEREO);
        if (ret != 0)
            return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
697 698

        /* Reconstruct the channel coefficients. */
699 700 701
        reverse_matrixing(out_samples[0], out_samples[1],
                          q->matrix_coeff_index_prev,
                          q->matrix_coeff_index_now);
Benjamin Larsson's avatar
Benjamin Larsson committed
702

703
        channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
Benjamin Larsson's avatar
Benjamin Larsson committed
704 705 706
    } else {
        /* normal stereo mode or mono */
        /* Decode the channel sound units. */
707
        for (i = 0; i < avctx->channels; i++) {
Benjamin Larsson's avatar
Benjamin Larsson committed
708
            /* Set the bitstream reader at the start of a channel sound unit. */
709
            init_get_bits(&q->gb,
710 711
                          databuf + i * avctx->block_align / avctx->channels,
                          avctx->block_align * 8 / avctx->channels);
Benjamin Larsson's avatar
Benjamin Larsson committed
712

713 714 715 716
            ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
                                            out_samples[i], i, q->coding_mode);
            if (ret != 0)
                return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
717 718 719 720
        }
    }

    /* Apply the iQMF synthesis filter. */
721
    for (i = 0; i < avctx->channels; i++) {
722 723 724 725 726 727 728
        float *p1 = out_samples[i];
        float *p2 = p1 + 256;
        float *p3 = p2 + 256;
        float *p4 = p3 + 256;
        ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
        ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
        ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
Benjamin Larsson's avatar
Benjamin Larsson committed
729 730 731 732 733
    }

    return 0;
}

734 735 736
static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
                               int *got_frame_ptr, AVPacket *avpkt)
{
737
    AVFrame *frame     = data;
738 739
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
Benjamin Larsson's avatar
Benjamin Larsson committed
740
    ATRAC3Context *q = avctx->priv_data;
741 742
    int ret;
    const uint8_t *databuf;
Benjamin Larsson's avatar
Benjamin Larsson committed
743

744 745 746
    if (buf_size < avctx->block_align) {
        av_log(avctx, AV_LOG_ERROR,
               "Frame too small (%d bytes). Truncated file?\n", buf_size);
747
        return AVERROR_INVALIDDATA;
748
    }
Benjamin Larsson's avatar
Benjamin Larsson committed
749

750
    /* get output buffer */
751
    frame->nb_samples = SAMPLES_PER_FRAME;
752
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
753
        return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
754 755 756 757 758 759 760 761 762

    /* Check if we need to descramble and what buffer to pass on. */
    if (q->scrambled_stream) {
        decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
        databuf = q->decoded_bytes_buffer;
    } else {
        databuf = buf;
    }

763
    ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
764 765 766
    if (ret) {
        av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
        return ret;
Benjamin Larsson's avatar
Benjamin Larsson committed
767 768
    }

769
    *got_frame_ptr = 1;
Benjamin Larsson's avatar
Benjamin Larsson committed
770 771 772 773

    return avctx->block_align;
}

774
static av_cold void atrac3_init_static_data(void)
775 776 777
{
    int i;

778
    init_imdct_window();
779 780 781 782 783 784 785 786 787 788 789 790 791
    ff_atrac_generate_tables();

    /* Initialize the VLC tables. */
    for (i = 0; i < 7; i++) {
        spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
        spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
                                                atrac3_vlc_offs[i    ];
        init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
                 huff_bits[i],  1, 1,
                 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
    }
}

792
static av_cold int atrac3_decode_init(AVCodecContext *avctx)
Benjamin Larsson's avatar
Benjamin Larsson committed
793
{
794
    static int static_init_done;
795
    int i, ret;
796
    int version, delay, samples_per_frame, frame_factor;
Michael Niedermayer's avatar
Michael Niedermayer committed
797
    const uint8_t *edata_ptr = avctx->extradata;
Benjamin Larsson's avatar
Benjamin Larsson committed
798 799
    ATRAC3Context *q = avctx->priv_data;

800 801 802 803 804
    if (avctx->channels <= 0 || avctx->channels > 2) {
        av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
        return AVERROR(EINVAL);
    }

805 806 807 808
    if (!static_init_done)
        atrac3_init_static_data();
    static_init_done = 1;

Benjamin Larsson's avatar
Benjamin Larsson committed
809 810 811
    /* Take care of the codec-specific extradata. */
    if (avctx->extradata_size == 14) {
        /* Parse the extradata, WAV format */
812 813
        av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
               bytestream_get_le16(&edata_ptr));  // Unknown value always 1
814
        edata_ptr += 4;                             // samples per channel
815 816 817
        q->coding_mode = bytestream_get_le16(&edata_ptr);
        av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
               bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
818
        frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1
819 820
        av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
               bytestream_get_le16(&edata_ptr));  // Unknown always 0
Benjamin Larsson's avatar
Benjamin Larsson committed
821 822

        /* setup */
823
        samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;
824
        version              = 4;
825
        delay                = 0x88E;
826 827 828
        q->coding_mode       = q->coding_mode ? JOINT_STEREO : STEREO;
        q->scrambled_stream  = 0;

829 830 831
        if (avctx->block_align !=  96 * avctx->channels * frame_factor &&
            avctx->block_align != 152 * avctx->channels * frame_factor &&
            avctx->block_align != 192 * avctx->channels * frame_factor) {
832
            av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
833
                   "configuration %d/%d/%d\n", avctx->block_align,
834
                   avctx->channels, frame_factor);
835
            return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
836
        }
837
    } else if (avctx->extradata_size == 12 || avctx->extradata_size == 10) {
Benjamin Larsson's avatar
Benjamin Larsson committed
838
        /* Parse the extradata, RM format. */
839
        version                = bytestream_get_be32(&edata_ptr);
840
        samples_per_frame      = bytestream_get_be16(&edata_ptr);
841
        delay                  = bytestream_get_be16(&edata_ptr);
842 843
        q->coding_mode         = bytestream_get_be16(&edata_ptr);
        q->scrambled_stream    = 1;
Benjamin Larsson's avatar
Benjamin Larsson committed
844 845

    } else {
846 847
        av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
               avctx->extradata_size);
848
        return AVERROR(EINVAL);
Benjamin Larsson's avatar
Benjamin Larsson committed
849 850
    }

851 852
    /* Check the extradata */

853 854
    if (version != 4) {
        av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
855
        return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
856 857
    }

858 859
    if (samples_per_frame != SAMPLES_PER_FRAME &&
        samples_per_frame != SAMPLES_PER_FRAME * 2) {
860
        av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
861
               samples_per_frame);
862
        return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
863 864
    }

865
    if (delay != 0x88E) {
866
        av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
867
               delay);
868
        return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
869 870
    }

871 872
    if (q->coding_mode == STEREO)
        av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
873
    else if (q->coding_mode == JOINT_STEREO) {
874 875
        if (avctx->channels != 2) {
            av_log(avctx, AV_LOG_ERROR, "Invalid coding mode\n");
876
            return AVERROR_INVALIDDATA;
877
        }
878
        av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
879
    } else {
880 881
        av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
               q->coding_mode);
882
        return AVERROR_INVALIDDATA;
Benjamin Larsson's avatar
Benjamin Larsson committed
883 884
    }

885
    if (avctx->block_align >= UINT_MAX / 2)
886
        return AVERROR(EINVAL);
Benjamin Larsson's avatar
Benjamin Larsson committed
887

888
    q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
889
                                         FF_INPUT_BUFFER_PADDING_SIZE);
890
    if (!q->decoded_bytes_buffer)
891
        return AVERROR(ENOMEM);
Benjamin Larsson's avatar
Benjamin Larsson committed
892

893
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
894

895 896
    /* initialize the MDCT transform */
    if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
897 898 899 900
        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
        av_freep(&q->decoded_bytes_buffer);
        return ret;
    }
Benjamin Larsson's avatar
Benjamin Larsson committed
901 902 903 904 905 906 907 908 909

    /* init the joint-stereo decoding data */
    q->weighting_delay[0] = 0;
    q->weighting_delay[1] = 7;
    q->weighting_delay[2] = 0;
    q->weighting_delay[3] = 7;
    q->weighting_delay[4] = 0;
    q->weighting_delay[5] = 7;

910
    for (i = 0; i < 4; i++) {
Benjamin Larsson's avatar
Benjamin Larsson committed
911
        q->matrix_coeff_index_prev[i] = 3;
912
        q->matrix_coeff_index_now[i]  = 3;
Benjamin Larsson's avatar
Benjamin Larsson committed
913 914 915
        q->matrix_coeff_index_next[i] = 3;
    }

916
    ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
917
    q->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
Benjamin Larsson's avatar
Benjamin Larsson committed
918

919
    q->units = av_mallocz_array(avctx->channels, sizeof(*q->units));
920
    if (!q->units || !q->fdsp) {
921
        atrac3_decode_close(avctx);
922 923
        return AVERROR(ENOMEM);
    }
Benjamin Larsson's avatar
Benjamin Larsson committed
924 925 926 927

    return 0;
}

928 929
AVCodec ff_atrac3_decoder = {
    .name             = "atrac3",
930
    .long_name        = NULL_IF_CONFIG_SMALL("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
931 932 933 934 935 936 937 938 939
    .type             = AVMEDIA_TYPE_AUDIO,
    .id               = AV_CODEC_ID_ATRAC3,
    .priv_data_size   = sizeof(ATRAC3Context),
    .init             = atrac3_decode_init,
    .close            = atrac3_decode_close,
    .decode           = atrac3_decode_frame,
    .capabilities     = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
    .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                        AV_SAMPLE_FMT_NONE },
Benjamin Larsson's avatar
Benjamin Larsson committed
940
};