LCOV - code coverage report
Current view: top level - src/libavcodec - atrac3.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 278 401 69.3 %
Date: 2017-01-24 04:42:20 Functions: 16 17 94.1 %

          Line data    Source code
       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             : #include <stdio.h>
      38             : 
      39             : #include "libavutil/attributes.h"
      40             : #include "libavutil/float_dsp.h"
      41             : #include "libavutil/libm.h"
      42             : #include "avcodec.h"
      43             : #include "bytestream.h"
      44             : #include "fft.h"
      45             : #include "get_bits.h"
      46             : #include "internal.h"
      47             : 
      48             : #include "atrac.h"
      49             : #include "atrac3data.h"
      50             : 
      51             : #define JOINT_STEREO    0x12
      52             : #define SINGLE          0x2
      53             : 
      54             : #define SAMPLES_PER_FRAME 1024
      55             : #define MDCT_SIZE          512
      56             : 
      57             : typedef struct GainBlock {
      58             :     AtracGainInfo g_block[4];
      59             : } GainBlock;
      60             : 
      61             : typedef struct TonalComponent {
      62             :     int pos;
      63             :     int num_coefs;
      64             :     float coef[8];
      65             : } TonalComponent;
      66             : 
      67             : typedef struct ChannelUnit {
      68             :     int            bands_coded;
      69             :     int            num_components;
      70             :     float          prev_frame[SAMPLES_PER_FRAME];
      71             :     int            gc_blk_switch;
      72             :     TonalComponent components[64];
      73             :     GainBlock      gain_block[2];
      74             : 
      75             :     DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
      76             :     DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
      77             : 
      78             :     float          delay_buf1[46]; ///<qmf delay buffers
      79             :     float          delay_buf2[46];
      80             :     float          delay_buf3[46];
      81             : } ChannelUnit;
      82             : 
      83             : typedef struct ATRAC3Context {
      84             :     GetBitContext gb;
      85             :     //@{
      86             :     /** stream data */
      87             :     int coding_mode;
      88             : 
      89             :     ChannelUnit *units;
      90             :     //@}
      91             :     //@{
      92             :     /** joint-stereo related variables */
      93             :     int matrix_coeff_index_prev[4];
      94             :     int matrix_coeff_index_now[4];
      95             :     int matrix_coeff_index_next[4];
      96             :     int weighting_delay[6];
      97             :     //@}
      98             :     //@{
      99             :     /** data buffers */
     100             :     uint8_t *decoded_bytes_buffer;
     101             :     float temp_buf[1070];
     102             :     //@}
     103             :     //@{
     104             :     /** extradata */
     105             :     int scrambled_stream;
     106             :     //@}
     107             : 
     108             :     AtracGCContext    gainc_ctx;
     109             :     FFTContext        mdct_ctx;
     110             :     AVFloatDSPContext *fdsp;
     111             : } ATRAC3Context;
     112             : 
     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];
     116             : 
     117             : /**
     118             :  * Regular 512 points IMDCT without overlapping, with the exception of the
     119             :  * swapping of odd bands caused by the reverse spectra of the QMF.
     120             :  *
     121             :  * @param odd_band  1 if the band is an odd band
     122             :  */
     123        2800 : static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
     124             : {
     125             :     int i;
     126             : 
     127        2800 :     if (odd_band) {
     128             :         /**
     129             :          * Reverse the odd bands before IMDCT, this is an effect of the QMF
     130             :          * transform or it gives better compression to do it this way.
     131             :          * FIXME: It should be possible to handle this in imdct_calc
     132             :          * for that to happen a modification of the prerotation step of
     133             :          * all SIMD code and C code is needed.
     134             :          * Or fix the functions before so they generate a pre reversed spectrum.
     135             :          */
     136      109392 :         for (i = 0; i < 128; i++)
     137      108544 :             FFSWAP(float, input[i], input[255 - i]);
     138             :     }
     139             : 
     140        2800 :     q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
     141             : 
     142             :     /* Perform windowing on the output. */
     143        2800 :     q->fdsp->vector_fmul(output, output, mdct_window, MDCT_SIZE);
     144        2800 : }
     145             : 
     146             : /*
     147             :  * indata descrambling, only used for data coming from the rm container
     148             :  */
     149           0 : static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
     150             : {
     151             :     int i, off;
     152             :     uint32_t c;
     153             :     const uint32_t *buf;
     154           0 :     uint32_t *output = (uint32_t *)out;
     155             : 
     156           0 :     off = (intptr_t)input & 3;
     157           0 :     buf = (const uint32_t *)(input - off);
     158           0 :     if (off)
     159           0 :         c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
     160             :     else
     161           0 :         c = av_be2ne32(0x537F6103U);
     162           0 :     bytes += 3 + off;
     163           0 :     for (i = 0; i < bytes / 4; i++)
     164           0 :         output[i] = c ^ buf[i];
     165             : 
     166           0 :     if (off)
     167           0 :         avpriv_request_sample(NULL, "Offset of %d", off);
     168             : 
     169           0 :     return off;
     170             : }
     171             : 
     172           4 : static av_cold void init_imdct_window(void)
     173             : {
     174             :     int i, j;
     175             : 
     176             :     /* generate the mdct window, for details see
     177             :      * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
     178         516 :     for (i = 0, j = 255; i < 128; i++, j--) {
     179         512 :         float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
     180         512 :         float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
     181         512 :         float w  = 0.5 * (wi * wi + wj * wj);
     182         512 :         mdct_window[i] = mdct_window[511 - i] = wi / w;
     183         512 :         mdct_window[j] = mdct_window[511 - j] = wj / w;
     184             :     }
     185           4 : }
     186             : 
     187           7 : static av_cold int atrac3_decode_close(AVCodecContext *avctx)
     188             : {
     189           7 :     ATRAC3Context *q = avctx->priv_data;
     190             : 
     191           7 :     av_freep(&q->units);
     192           7 :     av_freep(&q->decoded_bytes_buffer);
     193           7 :     av_freep(&q->fdsp);
     194             : 
     195           7 :     ff_mdct_end(&q->mdct_ctx);
     196             : 
     197           7 :     return 0;
     198             : }
     199             : 
     200             : /**
     201             :  * Mantissa decoding
     202             :  *
     203             :  * @param selector     which table the output values are coded with
     204             :  * @param coding_flag  constant length coding or variable length coding
     205             :  * @param mantissas    mantissa output table
     206             :  * @param num_codes    number of values to get
     207             :  */
     208       28209 : static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,
     209             :                                        int coding_flag, int *mantissas,
     210             :                                        int num_codes)
     211             : {
     212             :     int i, code, huff_symb;
     213             : 
     214       28209 :     if (selector == 1)
     215       15517 :         num_codes /= 2;
     216             : 
     217       28209 :     if (coding_flag != 0) {
     218             :         /* constant length coding (CLC) */
     219           0 :         int num_bits = clc_length_tab[selector];
     220             : 
     221           0 :         if (selector > 1) {
     222           0 :             for (i = 0; i < num_codes; i++) {
     223           0 :                 if (num_bits)
     224           0 :                     code = get_sbits(gb, num_bits);
     225             :                 else
     226           0 :                     code = 0;
     227           0 :                 mantissas[i] = code;
     228             :             }
     229             :         } else {
     230           0 :             for (i = 0; i < num_codes; i++) {
     231           0 :                 if (num_bits)
     232           0 :                     code = get_bits(gb, num_bits); // num_bits is always 4 in this case
     233             :                 else
     234           0 :                     code = 0;
     235           0 :                 mantissas[i * 2    ] = mantissa_clc_tab[code >> 2];
     236           0 :                 mantissas[i * 2 + 1] = mantissa_clc_tab[code &  3];
     237             :             }
     238             :         }
     239             :     } else {
     240             :         /* variable length coding (VLC) */
     241       28209 :         if (selector != 1) {
     242      192516 :             for (i = 0; i < num_codes; i++) {
     243      179824 :                 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,
     244      179824 :                                      spectral_coeff_tab[selector-1].bits, 3);
     245      179824 :                 huff_symb += 1;
     246      179824 :                 code = huff_symb >> 1;
     247      179824 :                 if (huff_symb & 1)
     248      139733 :                     code = -code;
     249      179824 :                 mantissas[i] = code;
     250             :             }
     251             :         } else {
     252      250405 :             for (i = 0; i < num_codes; i++) {
     253      234888 :                 huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,
     254      234888 :                                      spectral_coeff_tab[selector - 1].bits, 3);
     255      234888 :                 mantissas[i * 2    ] = mantissa_vlc_tab[huff_symb * 2    ];
     256      234888 :                 mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
     257             :             }
     258             :         }
     259             :     }
     260       28209 : }
     261             : 
     262             : /**
     263             :  * Restore the quantized band spectrum coefficients
     264             :  *
     265             :  * @return subband count, fix for broken specification/files
     266             :  */
     267        1108 : static int decode_spectrum(GetBitContext *gb, float *output)
     268             : {
     269             :     int num_subbands, coding_mode, i, j, first, last, subband_size;
     270             :     int subband_vlc_index[32], sf_index[32];
     271             :     int mantissas[128];
     272             :     float scale_factor;
     273             : 
     274        1108 :     num_subbands = get_bits(gb, 5);  // number of coded subbands
     275        1108 :     coding_mode  = get_bits1(gb);    // coding Mode: 0 - VLC/ 1-CLC
     276             : 
     277             :     /* get the VLC selector table for the subbands, 0 means not coded */
     278       29317 :     for (i = 0; i <= num_subbands; i++)
     279       28209 :         subband_vlc_index[i] = get_bits(gb, 3);
     280             : 
     281             :     /* read the scale factor indexes from the stream */
     282       29317 :     for (i = 0; i <= num_subbands; i++) {
     283       28209 :         if (subband_vlc_index[i] != 0)
     284       28209 :             sf_index[i] = get_bits(gb, 6);
     285             :     }
     286             : 
     287       29317 :     for (i = 0; i <= num_subbands; i++) {
     288       28209 :         first = subband_tab[i    ];
     289       28209 :         last  = subband_tab[i + 1];
     290             : 
     291       28209 :         subband_size = last - first;
     292             : 
     293       28209 :         if (subband_vlc_index[i] != 0) {
     294             :             /* decode spectral coefficients for this subband */
     295             :             /* TODO: This can be done faster is several blocks share the
     296             :              * same VLC selector (subband_vlc_index) */
     297       28209 :             read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,
     298             :                                        mantissas, subband_size);
     299             : 
     300             :             /* decode the scale factor for this subband */
     301       56418 :             scale_factor = ff_atrac_sf_table[sf_index[i]] *
     302       28209 :                            inv_max_quant[subband_vlc_index[i]];
     303             : 
     304             :             /* inverse quantize the coefficients */
     305      677809 :             for (j = 0; first < last; first++, j++)
     306      649600 :                 output[first] = mantissas[j] * scale_factor;
     307             :         } else {
     308             :             /* this subband was not coded, so zero the entire subband */
     309           0 :             memset(output + first, 0, subband_size * sizeof(*output));
     310             :         }
     311             :     }
     312             : 
     313             :     /* clear the subbands that were not coded */
     314        1108 :     first = subband_tab[i];
     315        1108 :     memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
     316        1108 :     return num_subbands;
     317             : }
     318             : 
     319             : /**
     320             :  * Restore the quantized tonal components
     321             :  *
     322             :  * @param components tonal components
     323             :  * @param num_bands  number of coded bands
     324             :  */
     325        1108 : static int decode_tonal_components(GetBitContext *gb,
     326             :                                    TonalComponent *components, int num_bands)
     327             : {
     328             :     int i, b, c, m;
     329             :     int nb_components, coding_mode_selector, coding_mode;
     330             :     int band_flags[4], mantissa[8];
     331        1108 :     int component_count = 0;
     332             : 
     333        1108 :     nb_components = get_bits(gb, 5);
     334             : 
     335             :     /* no tonal components */
     336        1108 :     if (nb_components == 0)
     337        1108 :         return 0;
     338             : 
     339           0 :     coding_mode_selector = get_bits(gb, 2);
     340           0 :     if (coding_mode_selector == 2)
     341           0 :         return AVERROR_INVALIDDATA;
     342             : 
     343           0 :     coding_mode = coding_mode_selector & 1;
     344             : 
     345           0 :     for (i = 0; i < nb_components; i++) {
     346             :         int coded_values_per_component, quant_step_index;
     347             : 
     348           0 :         for (b = 0; b <= num_bands; b++)
     349           0 :             band_flags[b] = get_bits1(gb);
     350             : 
     351           0 :         coded_values_per_component = get_bits(gb, 3);
     352             : 
     353           0 :         quant_step_index = get_bits(gb, 3);
     354           0 :         if (quant_step_index <= 1)
     355           0 :             return AVERROR_INVALIDDATA;
     356             : 
     357           0 :         if (coding_mode_selector == 3)
     358           0 :             coding_mode = get_bits1(gb);
     359             : 
     360           0 :         for (b = 0; b < (num_bands + 1) * 4; b++) {
     361             :             int coded_components;
     362             : 
     363           0 :             if (band_flags[b >> 2] == 0)
     364           0 :                 continue;
     365             : 
     366           0 :             coded_components = get_bits(gb, 3);
     367             : 
     368           0 :             for (c = 0; c < coded_components; c++) {
     369           0 :                 TonalComponent *cmp = &components[component_count];
     370             :                 int sf_index, coded_values, max_coded_values;
     371             :                 float scale_factor;
     372             : 
     373           0 :                 sf_index = get_bits(gb, 6);
     374           0 :                 if (component_count >= 64)
     375           0 :                     return AVERROR_INVALIDDATA;
     376             : 
     377           0 :                 cmp->pos = b * 64 + get_bits(gb, 6);
     378             : 
     379           0 :                 max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
     380           0 :                 coded_values     = coded_values_per_component + 1;
     381           0 :                 coded_values     = FFMIN(max_coded_values, coded_values);
     382             : 
     383           0 :                 scale_factor = ff_atrac_sf_table[sf_index] *
     384           0 :                                inv_max_quant[quant_step_index];
     385             : 
     386           0 :                 read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,
     387             :                                            mantissa, coded_values);
     388             : 
     389           0 :                 cmp->num_coefs = coded_values;
     390             : 
     391             :                 /* inverse quant */
     392           0 :                 for (m = 0; m < coded_values; m++)
     393           0 :                     cmp->coef[m] = mantissa[m] * scale_factor;
     394             : 
     395           0 :                 component_count++;
     396             :             }
     397             :         }
     398             :     }
     399             : 
     400           0 :     return component_count;
     401             : }
     402             : 
     403             : /**
     404             :  * Decode gain parameters for the coded bands
     405             :  *
     406             :  * @param block      the gainblock for the current band
     407             :  * @param num_bands  amount of coded bands
     408             :  */
     409        1108 : static int decode_gain_control(GetBitContext *gb, GainBlock *block,
     410             :                                int num_bands)
     411             : {
     412             :     int b, j;
     413             :     int *level, *loc;
     414             : 
     415        1108 :     AtracGainInfo *gain = block->g_block;
     416             : 
     417        3912 :     for (b = 0; b <= num_bands; b++) {
     418        2804 :         gain[b].num_points = get_bits(gb, 3);
     419        2804 :         level              = gain[b].lev_code;
     420        2804 :         loc                = gain[b].loc_code;
     421             : 
     422        3678 :         for (j = 0; j < gain[b].num_points; j++) {
     423         874 :             level[j] = get_bits(gb, 4);
     424         874 :             loc[j]   = get_bits(gb, 5);
     425         874 :             if (j && loc[j] <= loc[j - 1])
     426           0 :                 return AVERROR_INVALIDDATA;
     427             :         }
     428             :     }
     429             : 
     430             :     /* Clear the unused blocks. */
     431        2736 :     for (; b < 4 ; b++)
     432        1628 :         gain[b].num_points = 0;
     433             : 
     434        1108 :     return 0;
     435             : }
     436             : 
     437             : /**
     438             :  * Combine the tonal band spectrum and regular band spectrum
     439             :  *
     440             :  * @param spectrum        output spectrum buffer
     441             :  * @param num_components  number of tonal components
     442             :  * @param components      tonal components for this band
     443             :  * @return                position of the last tonal coefficient
     444             :  */
     445        1108 : static int add_tonal_components(float *spectrum, int num_components,
     446             :                                 TonalComponent *components)
     447             : {
     448        1108 :     int i, j, last_pos = -1;
     449             :     float *input, *output;
     450             : 
     451        1108 :     for (i = 0; i < num_components; i++) {
     452           0 :         last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
     453           0 :         input    = components[i].coef;
     454           0 :         output   = &spectrum[components[i].pos];
     455             : 
     456           0 :         for (j = 0; j < components[i].num_coefs; j++)
     457           0 :             output[j] += input[j];
     458             :     }
     459             : 
     460        1108 :     return last_pos;
     461             : }
     462             : 
     463             : #define INTERPOLATE(old, new, nsample) \
     464             :     ((old) + (nsample) * 0.125 * ((new) - (old)))
     465             : 
     466         260 : static void reverse_matrixing(float *su1, float *su2, int *prev_code,
     467             :                               int *curr_code)
     468             : {
     469             :     int i, nsample, band;
     470             :     float mc1_l, mc1_r, mc2_l, mc2_r;
     471             : 
     472        1300 :     for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
     473        1040 :         int s1 = prev_code[i];
     474        1040 :         int s2 = curr_code[i];
     475        1040 :         nsample = band;
     476             : 
     477        1040 :         if (s1 != s2) {
     478             :             /* Selector value changed, interpolation needed. */
     479          38 :             mc1_l = matrix_coeffs[s1 * 2    ];
     480          38 :             mc1_r = matrix_coeffs[s1 * 2 + 1];
     481          38 :             mc2_l = matrix_coeffs[s2 * 2    ];
     482          38 :             mc2_r = matrix_coeffs[s2 * 2 + 1];
     483             : 
     484             :             /* Interpolation is done over the first eight samples. */
     485         342 :             for (; nsample < band + 8; nsample++) {
     486         304 :                 float c1 = su1[nsample];
     487         304 :                 float c2 = su2[nsample];
     488         608 :                 c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
     489         304 :                      c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
     490         304 :                 su1[nsample] = c2;
     491         304 :                 su2[nsample] = c1 * 2.0 - c2;
     492             :             }
     493             :         }
     494             : 
     495             :         /* Apply the matrix without interpolation. */
     496        1040 :         switch (s2) {
     497             :         case 0:     /* M/S decoding */
     498       11413 :             for (; nsample < band + 256; nsample++) {
     499       11368 :                 float c1 = su1[nsample];
     500       11368 :                 float c2 = su2[nsample];
     501       11368 :                 su1[nsample] =  c2       * 2.0;
     502       11368 :                 su2[nsample] = (c1 - c2) * 2.0;
     503             :             }
     504          45 :             break;
     505             :         case 1:
     506           0 :             for (; nsample < band + 256; nsample++) {
     507           0 :                 float c1 = su1[nsample];
     508           0 :                 float c2 = su2[nsample];
     509           0 :                 su1[nsample] = (c1 + c2) *  2.0;
     510           0 :                 su2[nsample] =  c2       * -2.0;
     511             :             }
     512           0 :             break;
     513             :         case 2:
     514             :         case 3:
     515      255563 :             for (; nsample < band + 256; nsample++) {
     516      254568 :                 float c1 = su1[nsample];
     517      254568 :                 float c2 = su2[nsample];
     518      254568 :                 su1[nsample] = c1 + c2;
     519      254568 :                 su2[nsample] = c1 - c2;
     520             :             }
     521         995 :             break;
     522             :         default:
     523             :             av_assert1(0);
     524             :         }
     525             :     }
     526         260 : }
     527             : 
     528         492 : static void get_channel_weights(int index, int flag, float ch[2])
     529             : {
     530         492 :     if (index == 7) {
     531          53 :         ch[0] = 1.0;
     532          53 :         ch[1] = 1.0;
     533             :     } else {
     534         439 :         ch[0] = (index & 7) / 7.0;
     535         439 :         ch[1] = sqrt(2 - ch[0] * ch[0]);
     536         439 :         if (flag)
     537         115 :             FFSWAP(float, ch[0], ch[1]);
     538             :     }
     539         492 : }
     540             : 
     541         260 : static void channel_weighting(float *su1, float *su2, int *p3)
     542             : {
     543             :     int band, nsample;
     544             :     /* w[x][y] y=0 is left y=1 is right */
     545             :     float w[2][2];
     546             : 
     547         260 :     if (p3[1] != 7 || p3[3] != 7) {
     548         246 :         get_channel_weights(p3[1], p3[0], w[0]);
     549         246 :         get_channel_weights(p3[3], p3[2], w[1]);
     550             : 
     551         984 :         for (band = 256; band < 4 * 256; band += 256) {
     552        6642 :             for (nsample = band; nsample < band + 8; nsample++) {
     553        5904 :                 su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
     554        5904 :                 su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
     555             :             }
     556      183762 :             for(; nsample < band + 256; nsample++) {
     557      183024 :                 su1[nsample] *= w[1][0];
     558      183024 :                 su2[nsample] *= w[1][1];
     559             :             }
     560             :         }
     561             :     }
     562         260 : }
     563             : 
     564             : /**
     565             :  * Decode a Sound Unit
     566             :  *
     567             :  * @param snd           the channel unit to be used
     568             :  * @param output        the decoded samples before IQMF in float representation
     569             :  * @param channel_num   channel number
     570             :  * @param coding_mode   the coding mode (JOINT_STEREO or single channels)
     571             :  */
     572        1108 : static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
     573             :                                      ChannelUnit *snd, float *output,
     574             :                                      int channel_num, int coding_mode)
     575             : {
     576             :     int band, ret, num_subbands, last_tonal, num_bands;
     577        1108 :     GainBlock *gain1 = &snd->gain_block[    snd->gc_blk_switch];
     578        1108 :     GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
     579             : 
     580        1108 :     if (coding_mode == JOINT_STEREO && channel_num == 1) {
     581         520 :         if (get_bits(gb, 2) != 3) {
     582           0 :             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
     583           0 :             return AVERROR_INVALIDDATA;
     584             :         }
     585             :     } else {
     586         848 :         if (get_bits(gb, 6) != 0x28) {
     587           0 :             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
     588           0 :             return AVERROR_INVALIDDATA;
     589             :         }
     590             :     }
     591             : 
     592             :     /* number of coded QMF bands */
     593        1108 :     snd->bands_coded = get_bits(gb, 2);
     594             : 
     595        1108 :     ret = decode_gain_control(gb, gain2, snd->bands_coded);
     596        1108 :     if (ret)
     597           0 :         return ret;
     598             : 
     599        1108 :     snd->num_components = decode_tonal_components(gb, snd->components,
     600             :                                                   snd->bands_coded);
     601        1108 :     if (snd->num_components < 0)
     602           0 :         return snd->num_components;
     603             : 
     604        1108 :     num_subbands = decode_spectrum(gb, snd->spectrum);
     605             : 
     606             :     /* Merge the decoded spectrum and tonal components. */
     607        1108 :     last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
     608        1108 :                                       snd->components);
     609             : 
     610             : 
     611             :     /* calculate number of used MLT/QMF bands according to the amount of coded
     612             :        spectral lines */
     613        1108 :     num_bands = (subband_tab[num_subbands] - 1) >> 8;
     614        1108 :     if (last_tonal >= 0)
     615           0 :         num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
     616             : 
     617             : 
     618             :     /* Reconstruct time domain samples. */
     619        5540 :     for (band = 0; band < 4; band++) {
     620             :         /* Perform the IMDCT step without overlapping. */
     621        4432 :         if (band <= num_bands)
     622        2800 :             imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
     623             :         else
     624        1632 :             memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
     625             : 
     626             :         /* gain compensation and overlapping */
     627        8864 :         ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,
     628        4432 :                                    &snd->prev_frame[band * 256],
     629             :                                    &gain1->g_block[band], &gain2->g_block[band],
     630             :                                    256, &output[band * 256]);
     631             :     }
     632             : 
     633             :     /* Swap the gain control buffers for the next frame. */
     634        1108 :     snd->gc_blk_switch ^= 1;
     635             : 
     636        1108 :     return 0;
     637             : }
     638             : 
     639         554 : static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
     640             :                         float **out_samples)
     641             : {
     642         554 :     ATRAC3Context *q = avctx->priv_data;
     643             :     int ret, i;
     644             :     uint8_t *ptr1;
     645             : 
     646         554 :     if (q->coding_mode == JOINT_STEREO) {
     647             :         /* channel coupling mode */
     648             :         /* decode Sound Unit 1 */
     649         260 :         init_get_bits(&q->gb, databuf, avctx->block_align * 8);
     650             : 
     651         260 :         ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
     652             :                                         JOINT_STEREO);
     653         260 :         if (ret != 0)
     654           0 :             return ret;
     655             : 
     656             :         /* Framedata of the su2 in the joint-stereo mode is encoded in
     657             :          * reverse byte order so we need to swap it first. */
     658         260 :         if (databuf == q->decoded_bytes_buffer) {
     659           0 :             uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
     660           0 :             ptr1          = q->decoded_bytes_buffer;
     661           0 :             for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
     662           0 :                 FFSWAP(uint8_t, *ptr1, *ptr2);
     663             :         } else {
     664         260 :             const uint8_t *ptr2 = databuf + avctx->block_align - 1;
     665       50180 :             for (i = 0; i < avctx->block_align; i++)
     666       49920 :                 q->decoded_bytes_buffer[i] = *ptr2--;
     667             :         }
     668             : 
     669             :         /* Skip the sync codes (0xF8). */
     670         260 :         ptr1 = q->decoded_bytes_buffer;
     671         260 :         for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
     672           0 :             if (i >= avctx->block_align)
     673           0 :                 return AVERROR_INVALIDDATA;
     674             :         }
     675             : 
     676             : 
     677             :         /* set the bitstream reader at the start of the second Sound Unit*/
     678         260 :         init_get_bits8(&q->gb, ptr1, q->decoded_bytes_buffer + avctx->block_align - ptr1);
     679             : 
     680             :         /* Fill the Weighting coeffs delay buffer */
     681         260 :         memmove(q->weighting_delay, &q->weighting_delay[2],
     682             :                 4 * sizeof(*q->weighting_delay));
     683         260 :         q->weighting_delay[4] = get_bits1(&q->gb);
     684         260 :         q->weighting_delay[5] = get_bits(&q->gb, 3);
     685             : 
     686        1300 :         for (i = 0; i < 4; i++) {
     687        1040 :             q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
     688        1040 :             q->matrix_coeff_index_now[i]  = q->matrix_coeff_index_next[i];
     689        1040 :             q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
     690             :         }
     691             : 
     692             :         /* Decode Sound Unit 2. */
     693         260 :         ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
     694         260 :                                         out_samples[1], 1, JOINT_STEREO);
     695         260 :         if (ret != 0)
     696           0 :             return ret;
     697             : 
     698             :         /* Reconstruct the channel coefficients. */
     699         260 :         reverse_matrixing(out_samples[0], out_samples[1],
     700         260 :                           q->matrix_coeff_index_prev,
     701         260 :                           q->matrix_coeff_index_now);
     702             : 
     703         260 :         channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
     704             :     } else {
     705             :         /* single channels */
     706             :         /* Decode the channel sound units. */
     707         882 :         for (i = 0; i < avctx->channels; i++) {
     708             :             /* Set the bitstream reader at the start of a channel sound unit. */
     709        1176 :             init_get_bits(&q->gb,
     710         588 :                           databuf + i * avctx->block_align / avctx->channels,
     711         588 :                           avctx->block_align * 8 / avctx->channels);
     712             : 
     713        1176 :             ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
     714         588 :                                             out_samples[i], i, q->coding_mode);
     715         588 :             if (ret != 0)
     716           0 :                 return ret;
     717             :         }
     718             :     }
     719             : 
     720             :     /* Apply the iQMF synthesis filter. */
     721        1662 :     for (i = 0; i < avctx->channels; i++) {
     722        1108 :         float *p1 = out_samples[i];
     723        1108 :         float *p2 = p1 + 256;
     724        1108 :         float *p3 = p2 + 256;
     725        1108 :         float *p4 = p3 + 256;
     726        1108 :         ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
     727        1108 :         ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
     728        1108 :         ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
     729             :     }
     730             : 
     731         554 :     return 0;
     732             : }
     733             : 
     734         557 : static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
     735             :                                int *got_frame_ptr, AVPacket *avpkt)
     736             : {
     737         557 :     AVFrame *frame     = data;
     738         557 :     const uint8_t *buf = avpkt->data;
     739         557 :     int buf_size = avpkt->size;
     740         557 :     ATRAC3Context *q = avctx->priv_data;
     741             :     int ret;
     742             :     const uint8_t *databuf;
     743             : 
     744         557 :     if (buf_size < avctx->block_align) {
     745           3 :         av_log(avctx, AV_LOG_ERROR,
     746             :                "Frame too small (%d bytes). Truncated file?\n", buf_size);
     747           3 :         return AVERROR_INVALIDDATA;
     748             :     }
     749             : 
     750             :     /* get output buffer */
     751         554 :     frame->nb_samples = SAMPLES_PER_FRAME;
     752         554 :     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
     753           0 :         return ret;
     754             : 
     755             :     /* Check if we need to descramble and what buffer to pass on. */
     756         554 :     if (q->scrambled_stream) {
     757           0 :         decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
     758           0 :         databuf = q->decoded_bytes_buffer;
     759             :     } else {
     760         554 :         databuf = buf;
     761             :     }
     762             : 
     763         554 :     ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
     764         554 :     if (ret) {
     765           0 :         av_log(avctx, AV_LOG_ERROR, "Frame decoding error!\n");
     766           0 :         return ret;
     767             :     }
     768             : 
     769         554 :     *got_frame_ptr = 1;
     770             : 
     771         554 :     return avctx->block_align;
     772             : }
     773             : 
     774           4 : static av_cold void atrac3_init_static_data(void)
     775             : {
     776             :     int i;
     777             : 
     778           4 :     init_imdct_window();
     779           4 :     ff_atrac_generate_tables();
     780             : 
     781             :     /* Initialize the VLC tables. */
     782          32 :     for (i = 0; i < 7; i++) {
     783          28 :         spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
     784          56 :         spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
     785          28 :                                                 atrac3_vlc_offs[i    ];
     786          28 :         init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
     787             :                  huff_bits[i],  1, 1,
     788             :                  huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
     789             :     }
     790           4 : }
     791             : 
     792           7 : static av_cold int atrac3_decode_init(AVCodecContext *avctx)
     793             : {
     794             :     static int static_init_done;
     795             :     int i, ret;
     796             :     int version, delay, samples_per_frame, frame_factor;
     797           7 :     const uint8_t *edata_ptr = avctx->extradata;
     798           7 :     ATRAC3Context *q = avctx->priv_data;
     799             : 
     800           7 :     if (avctx->channels <= 0 || avctx->channels > 6) {
     801           0 :         av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
     802           0 :         return AVERROR(EINVAL);
     803             :     }
     804             : 
     805           7 :     if (!static_init_done)
     806           4 :         atrac3_init_static_data();
     807           7 :     static_init_done = 1;
     808             : 
     809             :     /* Take care of the codec-specific extradata. */
     810           7 :     if (avctx->extradata_size == 14) {
     811             :         /* Parse the extradata, WAV format */
     812           7 :         av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
     813             :                bytestream_get_le16(&edata_ptr));  // Unknown value always 1
     814           7 :         edata_ptr += 4;                             // samples per channel
     815           7 :         q->coding_mode = bytestream_get_le16(&edata_ptr);
     816           7 :         av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
     817             :                bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
     818           7 :         frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1
     819           7 :         av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
     820             :                bytestream_get_le16(&edata_ptr));  // Unknown always 0
     821             : 
     822             :         /* setup */
     823           7 :         samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;
     824           7 :         version              = 4;
     825           7 :         delay                = 0x88E;
     826           7 :         q->coding_mode       = q->coding_mode ? JOINT_STEREO : SINGLE;
     827           7 :         q->scrambled_stream  = 0;
     828             : 
     829          12 :         if (avctx->block_align !=  96 * avctx->channels * frame_factor &&
     830           8 :             avctx->block_align != 152 * avctx->channels * frame_factor &&
     831           3 :             avctx->block_align != 192 * avctx->channels * frame_factor) {
     832           0 :             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           0 :             return AVERROR_INVALIDDATA;
     836             :         }
     837           0 :     } else if (avctx->extradata_size == 12 || avctx->extradata_size == 10) {
     838             :         /* Parse the extradata, RM format. */
     839           0 :         version                = bytestream_get_be32(&edata_ptr);
     840           0 :         samples_per_frame      = bytestream_get_be16(&edata_ptr);
     841           0 :         delay                  = bytestream_get_be16(&edata_ptr);
     842           0 :         q->coding_mode         = bytestream_get_be16(&edata_ptr);
     843           0 :         q->scrambled_stream    = 1;
     844             : 
     845             :     } else {
     846           0 :         av_log(avctx, AV_LOG_ERROR, "Unknown extradata size %d.\n",
     847             :                avctx->extradata_size);
     848           0 :         return AVERROR(EINVAL);
     849             :     }
     850             : 
     851             :     /* Check the extradata */
     852             : 
     853           7 :     if (version != 4) {
     854           0 :         av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
     855           0 :         return AVERROR_INVALIDDATA;
     856             :     }
     857             : 
     858           7 :     if (samples_per_frame != SAMPLES_PER_FRAME * avctx->channels) {
     859           0 :         av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
     860             :                samples_per_frame);
     861           0 :         return AVERROR_INVALIDDATA;
     862             :     }
     863             : 
     864           7 :     if (delay != 0x88E) {
     865           0 :         av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
     866             :                delay);
     867           0 :         return AVERROR_INVALIDDATA;
     868             :     }
     869             : 
     870           7 :     if (q->coding_mode == SINGLE)
     871           5 :         av_log(avctx, AV_LOG_DEBUG, "Single channels detected.\n");
     872           2 :     else if (q->coding_mode == JOINT_STEREO) {
     873           2 :         if (avctx->channels != 2) {
     874           0 :             av_log(avctx, AV_LOG_ERROR, "Invalid coding mode\n");
     875           0 :             return AVERROR_INVALIDDATA;
     876             :         }
     877           2 :         av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
     878             :     } else {
     879           0 :         av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
     880             :                q->coding_mode);
     881           0 :         return AVERROR_INVALIDDATA;
     882             :     }
     883             : 
     884           7 :     if (avctx->block_align >= UINT_MAX / 2)
     885           0 :         return AVERROR(EINVAL);
     886             : 
     887           7 :     q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
     888             :                                          AV_INPUT_BUFFER_PADDING_SIZE);
     889           7 :     if (!q->decoded_bytes_buffer)
     890           0 :         return AVERROR(ENOMEM);
     891             : 
     892           7 :     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
     893             : 
     894             :     /* initialize the MDCT transform */
     895           7 :     if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
     896           0 :         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
     897           0 :         av_freep(&q->decoded_bytes_buffer);
     898           0 :         return ret;
     899             :     }
     900             : 
     901             :     /* init the joint-stereo decoding data */
     902           7 :     q->weighting_delay[0] = 0;
     903           7 :     q->weighting_delay[1] = 7;
     904           7 :     q->weighting_delay[2] = 0;
     905           7 :     q->weighting_delay[3] = 7;
     906           7 :     q->weighting_delay[4] = 0;
     907           7 :     q->weighting_delay[5] = 7;
     908             : 
     909          35 :     for (i = 0; i < 4; i++) {
     910          28 :         q->matrix_coeff_index_prev[i] = 3;
     911          28 :         q->matrix_coeff_index_now[i]  = 3;
     912          28 :         q->matrix_coeff_index_next[i] = 3;
     913             :     }
     914             : 
     915           7 :     ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
     916           7 :     q->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
     917             : 
     918           7 :     q->units = av_mallocz_array(avctx->channels, sizeof(*q->units));
     919           7 :     if (!q->units || !q->fdsp) {
     920           0 :         atrac3_decode_close(avctx);
     921           0 :         return AVERROR(ENOMEM);
     922             :     }
     923             : 
     924           7 :     return 0;
     925             : }
     926             : 
     927             : AVCodec ff_atrac3_decoder = {
     928             :     .name             = "atrac3",
     929             :     .long_name        = NULL_IF_CONFIG_SMALL("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
     930             :     .type             = AVMEDIA_TYPE_AUDIO,
     931             :     .id               = AV_CODEC_ID_ATRAC3,
     932             :     .priv_data_size   = sizeof(ATRAC3Context),
     933             :     .init             = atrac3_decode_init,
     934             :     .close            = atrac3_decode_close,
     935             :     .decode           = atrac3_decode_frame,
     936             :     .capabilities     = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
     937             :     .sample_fmts      = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
     938             :                                                         AV_SAMPLE_FMT_NONE },
     939             : };

Generated by: LCOV version 1.12