libavcodec/atrac3.c
10e26bc7
 /*
7df9e693
  * ATRAC3 compatible decoder
d311f8f3
  * Copyright (c) 2006-2008 Maxim Poliakovski
  * Copyright (c) 2006-2008 Benjamin Larsson
10e26bc7
  *
  * 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
  */
 
 /**
ba87f080
  * @file
7df9e693
  * ATRAC3 compatible decoder.
d311f8f3
  * This decoder handles Sony's ATRAC3 data.
  *
7df9e693
  * Container formats used to store ATRAC3 data:
d311f8f3
  * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
10e26bc7
  *
  * To use this decoder, a calling application must supply the extradata
d311f8f3
  * bytes provided in the containers above.
10e26bc7
  */
 
 #include <math.h>
 #include <stddef.h>
 #include <stdio.h>
 
6fee1b90
 #include "libavutil/attributes.h"
d5a7229b
 #include "libavutil/float_dsp.h"
c5f0b6bf
 #include "libavutil/libm.h"
10e26bc7
 #include "avcodec.h"
 #include "bytestream.h"
1429224b
 #include "fft.h"
e55d5390
 #include "get_bits.h"
594d4d5d
 #include "internal.h"
10e26bc7
 
0e1baede
 #include "atrac.h"
10e26bc7
 #include "atrac3data.h"
 
c61b28e0
 #define MIN_CHANNELS    1
 #define MAX_CHANNELS    8
 #define MAX_JS_PAIRS    8 / 2
 
10e26bc7
 #define JOINT_STEREO    0x12
cab0f3ab
 #define SINGLE          0x2
10e26bc7
 
c9161385
 #define SAMPLES_PER_FRAME 1024
 #define MDCT_SIZE          512
10e26bc7
 
e55d5390
 typedef struct GainBlock {
dc80e250
     AtracGainInfo g_block[4];
e55d5390
 } 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];
10e26bc7
 
c9161385
     DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
e55d5390
     DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
10e26bc7
 
e55d5390
     float          delay_buf1[46]; ///<qmf delay buffers
     float          delay_buf2[46];
     float          delay_buf3[46];
 } ChannelUnit;
10e26bc7
 
e55d5390
 typedef struct ATRAC3Context {
     GetBitContext gb;
10e26bc7
     //@{
     /** stream data */
e55d5390
     int coding_mode;
 
     ChannelUnit *units;
10e26bc7
     //@}
     //@{
     /** joint-stereo related variables */
c61b28e0
     int matrix_coeff_index_prev[MAX_JS_PAIRS][4];
     int matrix_coeff_index_now[MAX_JS_PAIRS][4];
     int matrix_coeff_index_next[MAX_JS_PAIRS][4];
     int weighting_delay[MAX_JS_PAIRS][6];
10e26bc7
     //@}
     //@{
     /** data buffers */
e55d5390
     uint8_t *decoded_bytes_buffer;
     float temp_buf[1070];
10e26bc7
     //@}
     //@{
     /** extradata */
e55d5390
     int scrambled_stream;
10e26bc7
     //@}
a28cccf6
 
d49f3fa5
     AtracGCContext    gainc_ctx;
     FFTContext        mdct_ctx;
93f959b6
     AVFloatDSPContext *fdsp;
10e26bc7
 } ATRAC3Context;
 
c9161385
 static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
5d1007f7
 static VLC_TYPE atrac3_vlc_table[4096][2];
e55d5390
 static VLC   spectral_coeff_tab[7];
10e26bc7
 
9ccc349f
 /**
e55d5390
  * Regular 512 points IMDCT without overlapping, with the exception of the
  * swapping of odd bands caused by the reverse spectra of the QMF.
10e26bc7
  *
  * @param odd_band  1 if the band is an odd band
  */
e55d5390
 static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
10e26bc7
 {
e55d5390
     int i;
10e26bc7
 
     if (odd_band) {
         /**
e55d5390
          * 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]);
10e26bc7
     }
 
e55d5390
     q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
10e26bc7
 
     /* Perform windowing on the output. */
93f959b6
     q->fdsp->vector_fmul(output, output, mdct_window, MDCT_SIZE);
10e26bc7
 }
 
e55d5390
 /*
  * indata descrambling, only used for data coming from the rm container
10e26bc7
  */
e55d5390
 static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
 {
10e26bc7
     int i, off;
     uint32_t c;
e55d5390
     const uint32_t *buf;
     uint32_t *output = (uint32_t *)out;
10e26bc7
 
e55d5390
     off = (intptr_t)input & 3;
     buf = (const uint32_t *)(input - off);
eba1ff31
     if (off)
         c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
     else
         c = av_be2ne32(0x537F6103U);
10e26bc7
     bytes += 3 + off;
e55d5390
     for (i = 0; i < bytes / 4; i++)
         output[i] = c ^ buf[i];
10e26bc7
 
     if (off)
6d97484d
         avpriv_request_sample(NULL, "Offset of %d", off);
10e26bc7
 
     return off;
 }
 
2d528349
 static av_cold void init_imdct_window(void)
e55d5390
 {
327747de
     int i, j;
10e26bc7
 
e55d5390
     /* generate the mdct window, for details see
10e26bc7
      * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
327747de
     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;
e55d5390
     }
10e26bc7
 }
 
5ef251e5
 static av_cold int atrac3_decode_close(AVCodecContext *avctx)
10e26bc7
 {
     ATRAC3Context *q = avctx->priv_data;
 
ea77d3b8
     av_freep(&q->units);
     av_freep(&q->decoded_bytes_buffer);
93f959b6
     av_freep(&q->fdsp);
5e76b8bb
 
a28cccf6
     ff_mdct_end(&q->mdct_ctx);
10e26bc7
 
     return 0;
 }
 
9ccc349f
 /**
e55d5390
  * Mantissa decoding
10e26bc7
  *
e55d5390
  * @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
10e26bc7
  */
e55d5390
 static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
                                        int coding_flag, int *mantissas,
                                        int num_codes)
10e26bc7
 {
e55d5390
     int i, code, huff_symb;
10e26bc7
 
     if (selector == 1)
e55d5390
         num_codes /= 2;
10e26bc7
 
e55d5390
     if (coding_flag != 0) {
10e26bc7
         /* constant length coding (CLC) */
e55d5390
         int num_bits = clc_length_tab[selector];
10e26bc7
 
         if (selector > 1) {
e55d5390
             for (i = 0; i < num_codes; i++) {
                 if (num_bits)
                     code = get_sbits(gb, num_bits);
10e26bc7
                 else
                     code = 0;
e55d5390
                 mantissas[i] = code;
10e26bc7
             }
         } else {
e55d5390
             for (i = 0; i < num_codes; i++) {
                 if (num_bits)
                     code = get_bits(gb, num_bits); // num_bits is always 4 in this case
10e26bc7
                 else
                     code = 0;
e55d5390
                 mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
                 mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
10e26bc7
             }
         }
     } else {
         /* variable length coding (VLC) */
         if (selector != 1) {
e55d5390
             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)
10e26bc7
                     code = -code;
e55d5390
                 mantissas[i] = code;
10e26bc7
             }
         } else {
e55d5390
             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];
10e26bc7
             }
         }
     }
 }
 
9ccc349f
 /**
10e26bc7
  * Restore the quantized band spectrum coefficients
  *
e55d5390
  * @return subband count, fix for broken specification/files
10e26bc7
  */
e55d5390
 static int decode_spectrum(GetBitContext *gb, float *output)
10e26bc7
 {
e55d5390
     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);
10e26bc7
     }
 
e55d5390
     for (i = 0; i <= num_subbands; i++) {
         first = subband_tab[i    ];
         last  = subband_tab[i + 1];
10e26bc7
 
e55d5390
         subband_size = last - first;
10e26bc7
 
e55d5390
         if (subband_vlc_index[i] != 0) {
             /* decode spectral coefficients for this subband */
10e26bc7
             /* TODO: This can be done faster is several blocks share the
              * same VLC selector (subband_vlc_index) */
e55d5390
             read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
                                        mantissas, subband_size);
10e26bc7
 
e55d5390
             /* decode the scale factor for this subband */
             scale_factor = ff_atrac_sf_table[sf_index[i]] *
                            inv_max_quant[subband_vlc_index[i]];
10e26bc7
 
e55d5390
             /* inverse quantize the coefficients */
             for (j = 0; first < last; first++, j++)
                 output[first] = mantissas[j] * scale_factor;
10e26bc7
         } else {
e55d5390
             /* this subband was not coded, so zero the entire subband */
89a6c32b
             memset(output + first, 0, subband_size * sizeof(*output));
10e26bc7
         }
     }
 
e55d5390
     /* clear the subbands that were not coded */
     first = subband_tab[i];
89a6c32b
     memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
e55d5390
     return num_subbands;
10e26bc7
 }
 
9ccc349f
 /**
10e26bc7
  * Restore the quantized tonal components
  *
e55d5390
  * @param components tonal components
  * @param num_bands  number of coded bands
10e26bc7
  */
e55d5390
 static int decode_tonal_components(GetBitContext *gb,
                                    TonalComponent *components, int num_bands)
10e26bc7
 {
e55d5390
     int i, b, c, m;
     int nb_components, coding_mode_selector, coding_mode;
     int band_flags[4], mantissa[8];
     int component_count = 0;
10e26bc7
 
e55d5390
     nb_components = get_bits(gb, 5);
10e26bc7
 
     /* no tonal components */
e55d5390
     if (nb_components == 0)
10e26bc7
         return 0;
 
e55d5390
     coding_mode_selector = get_bits(gb, 2);
10e26bc7
     if (coding_mode_selector == 2)
8f98577d
         return AVERROR_INVALIDDATA;
10e26bc7
 
     coding_mode = coding_mode_selector & 1;
 
e55d5390
     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);
10e26bc7
 
e55d5390
         coded_values_per_component = get_bits(gb, 3);
10e26bc7
 
e55d5390
         quant_step_index = get_bits(gb, 3);
10e26bc7
         if (quant_step_index <= 1)
8f98577d
             return AVERROR_INVALIDDATA;
10e26bc7
 
         if (coding_mode_selector == 3)
             coding_mode = get_bits1(gb);
 
e55d5390
         for (b = 0; b < (num_bands + 1) * 4; b++) {
             int coded_components;
 
             if (band_flags[b >> 2] == 0)
10e26bc7
                 continue;
 
e55d5390
             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;
10e26bc7
 
e55d5390
                 sf_index = get_bits(gb, 6);
c509f4f7
                 if (component_count >= 64)
9af6abdc
                     return AVERROR_INVALIDDATA;
10e26bc7
 
e55d5390
                 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);
10e26bc7
 
e55d5390
                 scale_factor = ff_atrac_sf_table[sf_index] *
                                inv_max_quant[quant_step_index];
10e26bc7
 
e55d5390
                 read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
                                            mantissa, coded_values);
 
                 cmp->num_coefs = coded_values;
10e26bc7
 
                 /* inverse quant */
e55d5390
                 for (m = 0; m < coded_values; m++)
                     cmp->coef[m] = mantissa[m] * scale_factor;
10e26bc7
 
                 component_count++;
             }
         }
     }
 
b8c4a515
     return component_count;
10e26bc7
 }
 
9ccc349f
 /**
10e26bc7
  * Decode gain parameters for the coded bands
  *
e55d5390
  * @param block      the gainblock for the current band
  * @param num_bands  amount of coded bands
10e26bc7
  */
e55d5390
 static int decode_gain_control(GetBitContext *gb, GainBlock *block,
                                int num_bands)
10e26bc7
 {
4a63c69f
     int b, j;
e55d5390
     int *level, *loc;
 
dc80e250
     AtracGainInfo *gain = block->g_block;
e55d5390
 
4fa24840
     for (b = 0; b <= num_bands; b++) {
         gain[b].num_points = get_bits(gb, 3);
4a63c69f
         level              = gain[b].lev_code;
         loc                = gain[b].loc_code;
e55d5390
 
c2df9597
         for (j = 0; j < gain[b].num_points; j++) {
be0b4c70
             level[j] = get_bits(gb, 4);
             loc[j]   = get_bits(gb, 5);
             if (j && loc[j] <= loc[j - 1])
8f98577d
                 return AVERROR_INVALIDDATA;
10e26bc7
         }
     }
 
     /* Clear the unused blocks. */
4fa24840
     for (; b < 4 ; b++)
         gain[b].num_points = 0;
10e26bc7
 
     return 0;
 }
 
9ccc349f
 /**
10e26bc7
  * Combine the tonal band spectrum and regular band spectrum
  *
e55d5390
  * @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
10e26bc7
  */
e55d5390
 static int add_tonal_components(float *spectrum, int num_components,
                                 TonalComponent *components)
10e26bc7
 {
e55d5390
     int i, j, last_pos = -1;
     float *input, *output;
10e26bc7
 
e55d5390
     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];
10e26bc7
 
e55d5390
         for (j = 0; j < components[i].num_coefs; j++)
dcbb920f
             output[j] += input[j];
10e26bc7
     }
9d278d88
 
e55d5390
     return last_pos;
10e26bc7
 }
 
e55d5390
 #define INTERPOLATE(old, new, nsample) \
     ((old) + (nsample) * 0.125 * ((new) - (old)))
10e26bc7
 
e55d5390
 static void reverse_matrixing(float *su1, float *su2, int *prev_code,
                               int *curr_code)
10e26bc7
 {
e55d5390
     int i, nsample, band;
     float mc1_l, mc1_r, mc2_l, mc2_r;
10e26bc7
 
e55d5390
     for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
         int s1 = prev_code[i];
         int s2 = curr_code[i];
aefdb735
         nsample = band;
10e26bc7
 
         if (s1 != s2) {
             /* Selector value changed, interpolation needed. */
e55d5390
             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];
10e26bc7
 
             /* Interpolation is done over the first eight samples. */
aefdb735
             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;
10e26bc7
             }
         }
 
         /* Apply the matrix without interpolation. */
         switch (s2) {
e55d5390
         case 0:     /* M/S decoding */
aefdb735
             for (; nsample < band + 256; nsample++) {
                 float c1 = su1[nsample];
                 float c2 = su2[nsample];
                 su1[nsample] =  c2       * 2.0;
                 su2[nsample] = (c1 - c2) * 2.0;
e55d5390
             }
             break;
         case 1:
aefdb735
             for (; nsample < band + 256; nsample++) {
                 float c1 = su1[nsample];
                 float c2 = su2[nsample];
                 su1[nsample] = (c1 + c2) *  2.0;
                 su2[nsample] =  c2       * -2.0;
e55d5390
             }
             break;
         case 2:
         case 3:
aefdb735
             for (; nsample < band + 256; nsample++) {
                 float c1 = su1[nsample];
                 float c2 = su2[nsample];
                 su1[nsample] = c1 + c2;
                 su2[nsample] = c1 - c2;
e55d5390
             }
             break;
         default:
dcb0d119
             av_assert1(0);
10e26bc7
         }
     }
 }
 
e55d5390
 static void get_channel_weights(int index, int flag, float ch[2])
 {
     if (index == 7) {
10e26bc7
         ch[0] = 1.0;
         ch[1] = 1.0;
     } else {
e55d5390
         ch[0] = (index & 7) / 7.0;
         ch[1] = sqrt(2 - ch[0] * ch[0]);
         if (flag)
10e26bc7
             FFSWAP(float, ch[0], ch[1]);
     }
 }
 
e55d5390
 static void channel_weighting(float *su1, float *su2, int *p3)
10e26bc7
 {
e55d5390
     int band, nsample;
10e26bc7
     /* w[x][y] y=0 is left y=1 is right */
     float w[2][2];
 
e55d5390
     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]);
10e26bc7
 
aefdb735
         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);
10e26bc7
             }
aefdb735
             for(; nsample < band + 256; nsample++) {
                 su1[nsample] *= w[1][0];
                 su2[nsample] *= w[1][1];
10e26bc7
             }
         }
     }
 }
 
9ccc349f
 /**
10e26bc7
  * Decode a Sound Unit
  *
e55d5390
  * @param snd           the channel unit to be used
  * @param output        the decoded samples before IQMF in float representation
  * @param channel_num   channel number
cab0f3ab
  * @param coding_mode   the coding mode (JOINT_STEREO or single channels)
10e26bc7
  */
e55d5390
 static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
                                      ChannelUnit *snd, float *output,
                                      int channel_num, int coding_mode)
10e26bc7
 {
e55d5390
     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];
10e26bc7
 
c61b28e0
     if (coding_mode == JOINT_STEREO && (channel_num % 2) == 1) {
e55d5390
         if (get_bits(gb, 2) != 3) {
10e26bc7
             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
8f98577d
             return AVERROR_INVALIDDATA;
10e26bc7
         }
     } else {
e55d5390
         if (get_bits(gb, 6) != 0x28) {
10e26bc7
             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
8f98577d
             return AVERROR_INVALIDDATA;
10e26bc7
         }
     }
 
     /* number of coded QMF bands */
e55d5390
     snd->bands_coded = get_bits(gb, 2);
10e26bc7
 
e55d5390
     ret = decode_gain_control(gb, gain2, snd->bands_coded);
     if (ret)
         return ret;
10e26bc7
 
e55d5390
     snd->num_components = decode_tonal_components(gb, snd->components,
                                                   snd->bands_coded);
5eaed6d3
     if (snd->num_components < 0)
         return snd->num_components;
10e26bc7
 
e55d5390
     num_subbands = decode_spectrum(gb, snd->spectrum);
10e26bc7
 
     /* Merge the decoded spectrum and tonal components. */
e55d5390
     last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
                                       snd->components);
10e26bc7
 
 
e55d5390
     /* 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);
10e26bc7
 
 
     /* Reconstruct time domain samples. */
e55d5390
     for (band = 0; band < 4; band++) {
10e26bc7
         /* Perform the IMDCT step without overlapping. */
e55d5390
         if (band <= num_bands)
             imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
         else
89a6c32b
             memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
10e26bc7
 
         /* gain compensation and overlapping */
d49f3fa5
         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]);
10e26bc7
     }
 
     /* Swap the gain control buffers for the next frame. */
e55d5390
     snd->gc_blk_switch ^= 1;
10e26bc7
 
     return 0;
 }
 
5ac673b5
 static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
e55d5390
                         float **out_samples)
10e26bc7
 {
5ac673b5
     ATRAC3Context *q = avctx->priv_data;
c61b28e0
     int ret, i, ch;
15ae1959
     uint8_t *ptr1;
10e26bc7
 
e55d5390
     if (q->coding_mode == JOINT_STEREO) {
10e26bc7
         /* channel coupling mode */
 
c61b28e0
         /* Decode sound unit pairs (channels are expected to be even).
          * Multichannel joint stereo interleaves pairs (6ch: 2ch + 2ch + 2ch) */
b47582f4
         const uint8_t *js_databuf;
c61b28e0
         int js_pair, js_block_align;
10e26bc7
 
c61b28e0
         js_block_align = (avctx->block_align / avctx->channels) * 2; /* block pair */
10e26bc7
 
c61b28e0
         for (ch = 0; ch < avctx->channels; ch = ch + 2) {
             js_pair = ch/2;
             js_databuf = databuf + js_pair * js_block_align; /* align to current pair */
10e26bc7
 
c61b28e0
             /* Set the bitstream reader at the start of first channel sound unit. */
             init_get_bits(&q->gb,
                           js_databuf, js_block_align * 8);
10e26bc7
 
c61b28e0
             /* decode Sound Unit 1 */
             ret = decode_channel_sound_unit(q, &q->gb, &q->units[ch],
                                             out_samples[ch], ch, JOINT_STEREO);
             if (ret != 0)
                 return ret;
 
             /* Framedata of the su2 in the joint-stereo mode is encoded in
              * reverse byte order so we need to swap it first. */
             if (js_databuf == q->decoded_bytes_buffer) {
                 uint8_t *ptr2 = q->decoded_bytes_buffer + js_block_align - 1;
                 ptr1          = q->decoded_bytes_buffer;
                 for (i = 0; i < js_block_align / 2; i++, ptr1++, ptr2--)
                     FFSWAP(uint8_t, *ptr1, *ptr2);
             } else {
                 const uint8_t *ptr2 = js_databuf + js_block_align - 1;
                 for (i = 0; i < js_block_align; i++)
                     q->decoded_bytes_buffer[i] = *ptr2--;
             }
 
             /* Skip the sync codes (0xF8). */
             ptr1 = q->decoded_bytes_buffer;
             for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
                 if (i >= js_block_align)
                     return AVERROR_INVALIDDATA;
             }
10e26bc7
 
 
c61b28e0
             /* set the bitstream reader at the start of the second Sound Unit */
e976e68f
             ret = init_get_bits8(&q->gb,
c61b28e0
                            ptr1, q->decoded_bytes_buffer + js_block_align - ptr1);
e976e68f
             if (ret < 0)
                 return ret;
10e26bc7
 
c61b28e0
             /* Fill the Weighting coeffs delay buffer */
             memmove(q->weighting_delay[js_pair], &q->weighting_delay[js_pair][2],
                     4 * sizeof(*q->weighting_delay[js_pair]));
             q->weighting_delay[js_pair][4] = get_bits1(&q->gb);
             q->weighting_delay[js_pair][5] = get_bits(&q->gb, 3);
 
             for (i = 0; i < 4; i++) {
                 q->matrix_coeff_index_prev[js_pair][i] = q->matrix_coeff_index_now[js_pair][i];
                 q->matrix_coeff_index_now[js_pair][i]  = q->matrix_coeff_index_next[js_pair][i];
                 q->matrix_coeff_index_next[js_pair][i] = get_bits(&q->gb, 2);
             }
 
             /* Decode Sound Unit 2. */
             ret = decode_channel_sound_unit(q, &q->gb, &q->units[ch+1],
                                             out_samples[ch+1], ch+1, JOINT_STEREO);
             if (ret != 0)
                 return ret;
 
             /* Reconstruct the channel coefficients. */
             reverse_matrixing(out_samples[ch], out_samples[ch+1],
                               q->matrix_coeff_index_prev[js_pair],
                               q->matrix_coeff_index_now[js_pair]);
 
             channel_weighting(out_samples[ch], out_samples[ch+1], q->weighting_delay[js_pair]);
         }
10e26bc7
     } else {
cab0f3ab
         /* single channels */
10e26bc7
         /* Decode the channel sound units. */
5ac673b5
         for (i = 0; i < avctx->channels; i++) {
10e26bc7
             /* Set the bitstream reader at the start of a channel sound unit. */
ee41963f
             init_get_bits(&q->gb,
cdd0e0de
                           databuf + i * avctx->block_align / avctx->channels,
                           avctx->block_align * 8 / avctx->channels);
10e26bc7
 
e55d5390
             ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
                                             out_samples[i], i, q->coding_mode);
             if (ret != 0)
                 return ret;
10e26bc7
         }
     }
 
     /* Apply the iQMF synthesis filter. */
5ac673b5
     for (i = 0; i < avctx->channels; i++) {
e55d5390
         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);
10e26bc7
     }
 
     return 0;
 }
 
280a40dd
 static int al_decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
                            int size, float **out_samples)
 {
     ATRAC3Context *q = avctx->priv_data;
     int ret, i;
 
     /* Set the bitstream reader at the start of a channel sound unit. */
     init_get_bits(&q->gb, databuf, size * 8);
     /* single channels */
     /* Decode the channel sound units. */
     for (i = 0; i < avctx->channels; i++) {
         ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
                                         out_samples[i], i, q->coding_mode);
         if (ret != 0)
             return ret;
         while (i < avctx->channels && get_bits_left(&q->gb) > 6 && show_bits(&q->gb, 6) != 0x28) {
             skip_bits(&q->gb, 1);
         }
     }
 
     /* Apply the iQMF synthesis filter. */
     for (i = 0; i < avctx->channels; i++) {
         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);
     }
 
     return 0;
 }
 
0eea2129
 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
                                int *got_frame_ptr, AVPacket *avpkt)
 {
9a75ace2
     AVFrame *frame     = data;
7a00bbad
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
10e26bc7
     ATRAC3Context *q = avctx->priv_data;
e55d5390
     int ret;
     const uint8_t *databuf;
10e26bc7
 
46a76dec
     if (buf_size < avctx->block_align) {
         av_log(avctx, AV_LOG_ERROR,
                "Frame too small (%d bytes). Truncated file?\n", buf_size);
1fead73d
         return AVERROR_INVALIDDATA;
46a76dec
     }
10e26bc7
 
0eea2129
     /* get output buffer */
9a75ace2
     frame->nb_samples = SAMPLES_PER_FRAME;
1ec94b0f
     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
e55d5390
         return ret;
10e26bc7
 
     /* 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;
     }
 
9a75ace2
     ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
e55d5390
     if (ret) {
c9fb81ff
         av_log(avctx, AV_LOG_ERROR, "Frame decoding error!\n");
e55d5390
         return ret;
10e26bc7
     }
 
9a75ace2
     *got_frame_ptr = 1;
10e26bc7
 
     return avctx->block_align;
 }
 
280a40dd
 static int atrac3al_decode_frame(AVCodecContext *avctx, void *data,
                                  int *got_frame_ptr, AVPacket *avpkt)
 {
     AVFrame *frame = data;
     int ret;
 
     frame->nb_samples = SAMPLES_PER_FRAME;
     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
         return ret;
 
     ret = al_decode_frame(avctx, avpkt->data, avpkt->size,
                           (float **)frame->extended_data);
     if (ret) {
         av_log(avctx, AV_LOG_ERROR, "Frame decoding error!\n");
         return ret;
     }
 
     *got_frame_ptr = 1;
 
     return avpkt->size;
 }
 
0aa09548
 static av_cold void atrac3_init_static_data(void)
5d1007f7
 {
     int i;
 
2d528349
     init_imdct_window();
5d1007f7
     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);
     }
 }
 
5ef251e5
 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
10e26bc7
 {
8aa29f06
     static int static_init_done;
c61b28e0
     int i, js_pair, ret;
c51311b9
     int version, delay, samples_per_frame, frame_factor;
8687f767
     const uint8_t *edata_ptr = avctx->extradata;
10e26bc7
     ATRAC3Context *q = avctx->priv_data;
 
c61b28e0
     if (avctx->channels < MIN_CHANNELS || avctx->channels > MAX_CHANNELS) {
5ac673b5
         av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
         return AVERROR(EINVAL);
     }
 
8aa29f06
     if (!static_init_done)
         atrac3_init_static_data();
     static_init_done = 1;
 
10e26bc7
     /* Take care of the codec-specific extradata. */
280a40dd
     if (avctx->codec_id == AV_CODEC_ID_ATRAC3AL) {
         version           = 4;
         samples_per_frame = SAMPLES_PER_FRAME * avctx->channels;
         delay             = 0x88E;
         q->coding_mode    = SINGLE;
     } else if (avctx->extradata_size == 14) {
10e26bc7
         /* Parse the extradata, WAV format */
e55d5390
         av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
                bytestream_get_le16(&edata_ptr));  // Unknown value always 1
7c1f93af
         edata_ptr += 4;                             // samples per channel
e55d5390
         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
c51311b9
         frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1
e55d5390
         av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
                bytestream_get_le16(&edata_ptr));  // Unknown always 0
10e26bc7
 
         /* setup */
a2664c91
         samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;
56a9d2b4
         version              = 4;
64ebbb8f
         delay                = 0x88E;
cab0f3ab
         q->coding_mode       = q->coding_mode ? JOINT_STEREO : SINGLE;
e55d5390
         q->scrambled_stream  = 0;
 
c51311b9
         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) {
e55d5390
             av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
cdd0e0de
                    "configuration %d/%d/%d\n", avctx->block_align,
c51311b9
                    avctx->channels, frame_factor);
8f98577d
             return AVERROR_INVALIDDATA;
10e26bc7
         }
034a125c
     } else if (avctx->extradata_size == 12 || avctx->extradata_size == 10) {
10e26bc7
         /* Parse the extradata, RM format. */
56a9d2b4
         version                = bytestream_get_be32(&edata_ptr);
a2664c91
         samples_per_frame      = bytestream_get_be16(&edata_ptr);
64ebbb8f
         delay                  = bytestream_get_be16(&edata_ptr);
e55d5390
         q->coding_mode         = bytestream_get_be16(&edata_ptr);
         q->scrambled_stream    = 1;
10e26bc7
 
     } else {
c9fb81ff
         av_log(avctx, AV_LOG_ERROR, "Unknown extradata size %d.\n",
e55d5390
                avctx->extradata_size);
44d854a5
         return AVERROR(EINVAL);
10e26bc7
     }
 
e55d5390
     /* Check the extradata */
 
56a9d2b4
     if (version != 4) {
         av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
8f98577d
         return AVERROR_INVALIDDATA;
10e26bc7
     }
 
cab0f3ab
     if (samples_per_frame != SAMPLES_PER_FRAME * avctx->channels) {
e55d5390
         av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
a2664c91
                samples_per_frame);
8f98577d
         return AVERROR_INVALIDDATA;
10e26bc7
     }
 
64ebbb8f
     if (delay != 0x88E) {
e55d5390
         av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
64ebbb8f
                delay);
8f98577d
         return AVERROR_INVALIDDATA;
10e26bc7
     }
 
cab0f3ab
     if (q->coding_mode == SINGLE)
         av_log(avctx, AV_LOG_DEBUG, "Single channels detected.\n");
50cf5a7f
     else if (q->coding_mode == JOINT_STEREO) {
c61b28e0
         if (avctx->channels % 2 == 1) { /* Joint stereo channels must be even */
             av_log(avctx, AV_LOG_ERROR, "Invalid joint stereo channel configuration.\n");
50cf5a7f
             return AVERROR_INVALIDDATA;
a3d9a216
         }
e55d5390
         av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
50cf5a7f
     } else {
e55d5390
         av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
                q->coding_mode);
8f98577d
         return AVERROR_INVALIDDATA;
10e26bc7
     }
 
ed04ecd2
     if (avctx->block_align > 1024 || avctx->block_align <= 0)
8f98577d
         return AVERROR(EINVAL);
10e26bc7
 
a1f4cd37
     q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
059a9348
                                          AV_INPUT_BUFFER_PADDING_SIZE);
f929ab05
     if (!q->decoded_bytes_buffer)
6611c0b4
         return AVERROR(ENOMEM);
10e26bc7
 
9af4eaa8
     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
20732246
 
78edce3f
     /* initialize the MDCT transform */
     if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
47b61702
         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
         av_freep(&q->decoded_bytes_buffer);
         return ret;
     }
10e26bc7
 
     /* init the joint-stereo decoding data */
c61b28e0
     for (js_pair = 0; js_pair < MAX_JS_PAIRS; js_pair++) {
         q->weighting_delay[js_pair][0] = 0;
         q->weighting_delay[js_pair][1] = 7;
         q->weighting_delay[js_pair][2] = 0;
         q->weighting_delay[js_pair][3] = 7;
         q->weighting_delay[js_pair][4] = 0;
         q->weighting_delay[js_pair][5] = 7;
 
         for (i = 0; i < 4; i++) {
             q->matrix_coeff_index_prev[js_pair][i] = 3;
             q->matrix_coeff_index_now[js_pair][i]  = 3;
             q->matrix_coeff_index_next[js_pair][i] = 3;
         }
10e26bc7
     }
 
d49f3fa5
     ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
94d68a41
     q->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
10e26bc7
 
606a49d2
     q->units = av_mallocz_array(avctx->channels, sizeof(*q->units));
93f959b6
     if (!q->units || !q->fdsp) {
47b61702
         atrac3_decode_close(avctx);
6654296c
         return AVERROR(ENOMEM);
     }
10e26bc7
 
     return 0;
 }
 
e55d5390
 AVCodec ff_atrac3_decoder = {
     .name             = "atrac3",
7df9e693
     .long_name        = NULL_IF_CONFIG_SMALL("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
e55d5390
     .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,
def97856
     .capabilities     = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
e55d5390
     .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                         AV_SAMPLE_FMT_NONE },
10e26bc7
 };
280a40dd
 
 AVCodec ff_atrac3al_decoder = {
     .name             = "atrac3al",
     .long_name        = NULL_IF_CONFIG_SMALL("ATRAC3 AL (Adaptive TRansform Acoustic Coding 3 Advanced Lossless)"),
     .type             = AVMEDIA_TYPE_AUDIO,
     .id               = AV_CODEC_ID_ATRAC3AL,
     .priv_data_size   = sizeof(ATRAC3Context),
     .init             = atrac3_decode_init,
     .close            = atrac3_decode_close,
     .decode           = atrac3al_decode_frame,
     .capabilities     = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
     .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                         AV_SAMPLE_FMT_NONE },
 };