libavcodec/atrac3.c
Go to the documentation of this file.
00001 /*
00002  * Atrac 3 compatible decoder
00003  * Copyright (c) 2006-2008 Maxim Poliakovski
00004  * Copyright (c) 2006-2008 Benjamin Larsson
00005  *
00006  * This file is part of Libav.
00007  *
00008  * Libav is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * Libav is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00035 #include <math.h>
00036 #include <stddef.h>
00037 #include <stdio.h>
00038 
00039 #include "avcodec.h"
00040 #include "get_bits.h"
00041 #include "dsputil.h"
00042 #include "bytestream.h"
00043 #include "fft.h"
00044 #include "fmtconvert.h"
00045 
00046 #include "atrac.h"
00047 #include "atrac3data.h"
00048 
00049 #define JOINT_STEREO    0x12
00050 #define STEREO          0x2
00051 
00052 #define SAMPLES_PER_FRAME 1024
00053 #define MDCT_SIZE          512
00054 
00055 /* These structures are needed to store the parsed gain control data. */
00056 typedef struct {
00057     int   num_gain_data;
00058     int   levcode[8];
00059     int   loccode[8];
00060 } gain_info;
00061 
00062 typedef struct {
00063     gain_info   gBlock[4];
00064 } gain_block;
00065 
00066 typedef struct {
00067     int     pos;
00068     int     numCoefs;
00069     float   coef[8];
00070 } tonal_component;
00071 
00072 typedef struct {
00073     int               bandsCoded;
00074     int               numComponents;
00075     tonal_component   components[64];
00076     float             prevFrame[SAMPLES_PER_FRAME];
00077     int               gcBlkSwitch;
00078     gain_block        gainBlock[2];
00079 
00080     DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
00081     DECLARE_ALIGNED(32, float, IMDCT_buf)[SAMPLES_PER_FRAME];
00082 
00083     float             delayBuf1[46]; 
00084     float             delayBuf2[46];
00085     float             delayBuf3[46];
00086 } channel_unit;
00087 
00088 typedef struct {
00089     AVFrame             frame;
00090     GetBitContext       gb;
00092 
00093     int                 channels;
00094     int                 codingMode;
00095     int                 bit_rate;
00096     int                 sample_rate;
00097     int                 samples_per_channel;
00098     int                 samples_per_frame;
00099 
00100     int                 bits_per_frame;
00101     int                 bytes_per_frame;
00102     int                 pBs;
00103     channel_unit*       pUnits;
00105 
00106 
00107     int                 matrix_coeff_index_prev[4];
00108     int                 matrix_coeff_index_now[4];
00109     int                 matrix_coeff_index_next[4];
00110     int                 weighting_delay[6];
00112 
00113 
00114     float              *outSamples[2];
00115     uint8_t*            decoded_bytes_buffer;
00116     float               tempBuf[1070];
00118 
00119 
00120     int                 atrac3version;
00121     int                 delay;
00122     int                 scrambled_stream;
00123     int                 frame_factor;
00125 
00126     FFTContext          mdct_ctx;
00127     FmtConvertContext   fmt_conv;
00128 } ATRAC3Context;
00129 
00130 static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
00131 static VLC              spectral_coeff_tab[7];
00132 static float            gain_tab1[16];
00133 static float            gain_tab2[31];
00134 static DSPContext       dsp;
00135 
00136 
00146 static void IMLT(ATRAC3Context *q, float *pInput, float *pOutput, int odd_band)
00147 {
00148     int     i;
00149 
00150     if (odd_band) {
00160         for (i=0; i<128; i++)
00161             FFSWAP(float, pInput[i], pInput[255-i]);
00162     }
00163 
00164     q->mdct_ctx.imdct_calc(&q->mdct_ctx,pOutput,pInput);
00165 
00166     /* Perform windowing on the output. */
00167     dsp.vector_fmul(pOutput, pOutput, mdct_window, MDCT_SIZE);
00168 
00169 }
00170 
00171 
00180 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
00181     int i, off;
00182     uint32_t c;
00183     const uint32_t* buf;
00184     uint32_t* obuf = (uint32_t*) out;
00185 
00186     off = (intptr_t)inbuffer & 3;
00187     buf = (const uint32_t *)(inbuffer - off);
00188     if (off)
00189         c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
00190     else
00191         c = av_be2ne32(0x537F6103U);
00192     bytes += 3 + off;
00193     for (i = 0; i < bytes/4; i++)
00194         obuf[i] = c ^ buf[i];
00195 
00196     if (off)
00197         av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
00198 
00199     return off;
00200 }
00201 
00202 
00203 static av_cold int init_atrac3_transforms(ATRAC3Context *q, int is_float) {
00204     float enc_window[256];
00205     int i;
00206 
00207     /* Generate the mdct window, for details see
00208      * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
00209     for (i=0 ; i<256; i++)
00210         enc_window[i] = (sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0) * 0.5;
00211 
00212     if (!mdct_window[0])
00213         for (i=0 ; i<256; i++) {
00214             mdct_window[i] = enc_window[i]/(enc_window[i]*enc_window[i] + enc_window[255-i]*enc_window[255-i]);
00215             mdct_window[511-i] = mdct_window[i];
00216         }
00217 
00218     /* Initialize the MDCT transform. */
00219     return ff_mdct_init(&q->mdct_ctx, 9, 1, is_float ? 1.0 / 32768 : 1.0);
00220 }
00221 
00226 static av_cold int atrac3_decode_close(AVCodecContext *avctx)
00227 {
00228     ATRAC3Context *q = avctx->priv_data;
00229 
00230     av_free(q->pUnits);
00231     av_free(q->decoded_bytes_buffer);
00232     av_freep(&q->outSamples[0]);
00233 
00234     ff_mdct_end(&q->mdct_ctx);
00235 
00236     return 0;
00237 }
00238 
00249 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
00250 {
00251     int   numBits, cnt, code, huffSymb;
00252 
00253     if (selector == 1)
00254         numCodes /= 2;
00255 
00256     if (codingFlag != 0) {
00257         /* constant length coding (CLC) */
00258         numBits = CLCLengthTab[selector];
00259 
00260         if (selector > 1) {
00261             for (cnt = 0; cnt < numCodes; cnt++) {
00262                 if (numBits)
00263                     code = get_sbits(gb, numBits);
00264                 else
00265                     code = 0;
00266                 mantissas[cnt] = code;
00267             }
00268         } else {
00269             for (cnt = 0; cnt < numCodes; cnt++) {
00270                 if (numBits)
00271                     code = get_bits(gb, numBits); //numBits is always 4 in this case
00272                 else
00273                     code = 0;
00274                 mantissas[cnt*2] = seTab_0[code >> 2];
00275                 mantissas[cnt*2+1] = seTab_0[code & 3];
00276             }
00277         }
00278     } else {
00279         /* variable length coding (VLC) */
00280         if (selector != 1) {
00281             for (cnt = 0; cnt < numCodes; cnt++) {
00282                 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
00283                 huffSymb += 1;
00284                 code = huffSymb >> 1;
00285                 if (huffSymb & 1)
00286                     code = -code;
00287                 mantissas[cnt] = code;
00288             }
00289         } else {
00290             for (cnt = 0; cnt < numCodes; cnt++) {
00291                 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
00292                 mantissas[cnt*2] = decTable1[huffSymb*2];
00293                 mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
00294             }
00295         }
00296     }
00297 }
00298 
00307 static int decodeSpectrum (GetBitContext *gb, float *pOut)
00308 {
00309     int   numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
00310     int   subband_vlc_index[32], SF_idxs[32];
00311     int   mantissas[128];
00312     float SF;
00313 
00314     numSubbands = get_bits(gb, 5); // number of coded subbands
00315     codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
00316 
00317     /* Get the VLC selector table for the subbands, 0 means not coded. */
00318     for (cnt = 0; cnt <= numSubbands; cnt++)
00319         subband_vlc_index[cnt] = get_bits(gb, 3);
00320 
00321     /* Read the scale factor indexes from the stream. */
00322     for (cnt = 0; cnt <= numSubbands; cnt++) {
00323         if (subband_vlc_index[cnt] != 0)
00324             SF_idxs[cnt] = get_bits(gb, 6);
00325     }
00326 
00327     for (cnt = 0; cnt <= numSubbands; cnt++) {
00328         first = subbandTab[cnt];
00329         last = subbandTab[cnt+1];
00330 
00331         subbWidth = last - first;
00332 
00333         if (subband_vlc_index[cnt] != 0) {
00334             /* Decode spectral coefficients for this subband. */
00335             /* TODO: This can be done faster is several blocks share the
00336              * same VLC selector (subband_vlc_index) */
00337             readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
00338 
00339             /* Decode the scale factor for this subband. */
00340             SF = ff_atrac_sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
00341 
00342             /* Inverse quantize the coefficients. */
00343             for (pIn=mantissas ; first<last; first++, pIn++)
00344                 pOut[first] = *pIn * SF;
00345         } else {
00346             /* This subband was not coded, so zero the entire subband. */
00347             memset(pOut+first, 0, subbWidth*sizeof(float));
00348         }
00349     }
00350 
00351     /* Clear the subbands that were not coded. */
00352     first = subbandTab[cnt];
00353     memset(pOut+first, 0, (SAMPLES_PER_FRAME - first) * sizeof(float));
00354     return numSubbands;
00355 }
00356 
00365 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
00366 {
00367     int i,j,k,cnt;
00368     int   components, coding_mode_selector, coding_mode, coded_values_per_component;
00369     int   sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
00370     int   band_flags[4], mantissa[8];
00371     float  *pCoef;
00372     float  scalefactor;
00373     int   component_count = 0;
00374 
00375     components = get_bits(gb,5);
00376 
00377     /* no tonal components */
00378     if (components == 0)
00379         return 0;
00380 
00381     coding_mode_selector = get_bits(gb,2);
00382     if (coding_mode_selector == 2)
00383         return AVERROR_INVALIDDATA;
00384 
00385     coding_mode = coding_mode_selector & 1;
00386 
00387     for (i = 0; i < components; i++) {
00388         for (cnt = 0; cnt <= numBands; cnt++)
00389             band_flags[cnt] = get_bits1(gb);
00390 
00391         coded_values_per_component = get_bits(gb,3);
00392 
00393         quant_step_index = get_bits(gb,3);
00394         if (quant_step_index <= 1)
00395             return AVERROR_INVALIDDATA;
00396 
00397         if (coding_mode_selector == 3)
00398             coding_mode = get_bits1(gb);
00399 
00400         for (j = 0; j < (numBands + 1) * 4; j++) {
00401             if (band_flags[j >> 2] == 0)
00402                 continue;
00403 
00404             coded_components = get_bits(gb,3);
00405 
00406             for (k=0; k<coded_components; k++) {
00407                 sfIndx = get_bits(gb,6);
00408                 if (component_count >= 64)
00409                     return AVERROR_INVALIDDATA;
00410                 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
00411                 max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;
00412                 coded_values = coded_values_per_component + 1;
00413                 coded_values = FFMIN(max_coded_values,coded_values);
00414 
00415                 scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
00416 
00417                 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
00418 
00419                 pComponent[component_count].numCoefs = coded_values;
00420 
00421                 /* inverse quant */
00422                 pCoef = pComponent[component_count].coef;
00423                 for (cnt = 0; cnt < coded_values; cnt++)
00424                     pCoef[cnt] = mantissa[cnt] * scalefactor;
00425 
00426                 component_count++;
00427             }
00428         }
00429     }
00430 
00431     return component_count;
00432 }
00433 
00442 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
00443 {
00444     int   i, cf, numData;
00445     int   *pLevel, *pLoc;
00446 
00447     gain_info   *pGain = pGb->gBlock;
00448 
00449     for (i=0 ; i<=numBands; i++)
00450     {
00451         numData = get_bits(gb,3);
00452         pGain[i].num_gain_data = numData;
00453         pLevel = pGain[i].levcode;
00454         pLoc = pGain[i].loccode;
00455 
00456         for (cf = 0; cf < numData; cf++){
00457             pLevel[cf]= get_bits(gb,4);
00458             pLoc  [cf]= get_bits(gb,5);
00459             if(cf && pLoc[cf] <= pLoc[cf-1])
00460                 return AVERROR_INVALIDDATA;
00461         }
00462     }
00463 
00464     /* Clear the unused blocks. */
00465     for (; i<4 ; i++)
00466         pGain[i].num_gain_data = 0;
00467 
00468     return 0;
00469 }
00470 
00481 static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
00482 {
00483     /* gain compensation function */
00484     float  gain1, gain2, gain_inc;
00485     int   cnt, numdata, nsample, startLoc, endLoc;
00486 
00487 
00488     if (pGain2->num_gain_data == 0)
00489         gain1 = 1.0;
00490     else
00491         gain1 = gain_tab1[pGain2->levcode[0]];
00492 
00493     if (pGain1->num_gain_data == 0) {
00494         for (cnt = 0; cnt < 256; cnt++)
00495             pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
00496     } else {
00497         numdata = pGain1->num_gain_data;
00498         pGain1->loccode[numdata] = 32;
00499         pGain1->levcode[numdata] = 4;
00500 
00501         nsample = 0; // current sample = 0
00502 
00503         for (cnt = 0; cnt < numdata; cnt++) {
00504             startLoc = pGain1->loccode[cnt] * 8;
00505             endLoc = startLoc + 8;
00506 
00507             gain2 = gain_tab1[pGain1->levcode[cnt]];
00508             gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
00509 
00510             /* interpolate */
00511             for (; nsample < startLoc; nsample++)
00512                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
00513 
00514             /* interpolation is done over eight samples */
00515             for (; nsample < endLoc; nsample++) {
00516                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
00517                 gain2 *= gain_inc;
00518             }
00519         }
00520 
00521         for (; nsample < 256; nsample++)
00522             pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
00523     }
00524 
00525     /* Delay for the overlapping part. */
00526     memcpy(pPrev, &pIn[256], 256*sizeof(float));
00527 }
00528 
00538 static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
00539 {
00540     int   cnt, i, lastPos = -1;
00541     float   *pIn, *pOut;
00542 
00543     for (cnt = 0; cnt < numComponents; cnt++){
00544         lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
00545         pIn = pComponent[cnt].coef;
00546         pOut = &(pSpectrum[pComponent[cnt].pos]);
00547 
00548         for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
00549             pOut[i] += pIn[i];
00550     }
00551 
00552     return lastPos;
00553 }
00554 
00555 
00556 #define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
00557 
00558 static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
00559 {
00560     int    i, band, nsample, s1, s2;
00561     float    c1, c2;
00562     float    mc1_l, mc1_r, mc2_l, mc2_r;
00563 
00564     for (i=0,band = 0; band < 4*256; band+=256,i++) {
00565         s1 = pPrevCode[i];
00566         s2 = pCurrCode[i];
00567         nsample = 0;
00568 
00569         if (s1 != s2) {
00570             /* Selector value changed, interpolation needed. */
00571             mc1_l = matrixCoeffs[s1*2];
00572             mc1_r = matrixCoeffs[s1*2+1];
00573             mc2_l = matrixCoeffs[s2*2];
00574             mc2_r = matrixCoeffs[s2*2+1];
00575 
00576             /* Interpolation is done over the first eight samples. */
00577             for(; nsample < 8; nsample++) {
00578                 c1 = su1[band+nsample];
00579                 c2 = su2[band+nsample];
00580                 c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
00581                 su1[band+nsample] = c2;
00582                 su2[band+nsample] = c1 * 2.0 - c2;
00583             }
00584         }
00585 
00586         /* Apply the matrix without interpolation. */
00587         switch (s2) {
00588             case 0:     /* M/S decoding */
00589                 for (; nsample < 256; nsample++) {
00590                     c1 = su1[band+nsample];
00591                     c2 = su2[band+nsample];
00592                     su1[band+nsample] = c2 * 2.0;
00593                     su2[band+nsample] = (c1 - c2) * 2.0;
00594                 }
00595                 break;
00596 
00597             case 1:
00598                 for (; nsample < 256; nsample++) {
00599                     c1 = su1[band+nsample];
00600                     c2 = su2[band+nsample];
00601                     su1[band+nsample] = (c1 + c2) * 2.0;
00602                     su2[band+nsample] = c2 * -2.0;
00603                 }
00604                 break;
00605             case 2:
00606             case 3:
00607                 for (; nsample < 256; nsample++) {
00608                     c1 = su1[band+nsample];
00609                     c2 = su2[band+nsample];
00610                     su1[band+nsample] = c1 + c2;
00611                     su2[band+nsample] = c1 - c2;
00612                 }
00613                 break;
00614             default:
00615                 assert(0);
00616         }
00617     }
00618 }
00619 
00620 static void getChannelWeights (int indx, int flag, float ch[2]){
00621 
00622     if (indx == 7) {
00623         ch[0] = 1.0;
00624         ch[1] = 1.0;
00625     } else {
00626         ch[0] = (float)(indx & 7) / 7.0;
00627         ch[1] = sqrt(2 - ch[0]*ch[0]);
00628         if(flag)
00629             FFSWAP(float, ch[0], ch[1]);
00630     }
00631 }
00632 
00633 static void channelWeighting (float *su1, float *su2, int *p3)
00634 {
00635     int   band, nsample;
00636     /* w[x][y] y=0 is left y=1 is right */
00637     float w[2][2];
00638 
00639     if (p3[1] != 7 || p3[3] != 7){
00640         getChannelWeights(p3[1], p3[0], w[0]);
00641         getChannelWeights(p3[3], p3[2], w[1]);
00642 
00643         for(band = 1; band < 4; band++) {
00644             /* scale the channels by the weights */
00645             for(nsample = 0; nsample < 8; nsample++) {
00646                 su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
00647                 su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
00648             }
00649 
00650             for(; nsample < 256; nsample++) {
00651                 su1[band*256+nsample] *= w[1][0];
00652                 su2[band*256+nsample] *= w[1][1];
00653             }
00654         }
00655     }
00656 }
00657 
00658 
00670 static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
00671 {
00672     int   band, result=0, numSubbands, lastTonal, numBands;
00673 
00674     if (codingMode == JOINT_STEREO && channelNum == 1) {
00675         if (get_bits(gb,2) != 3) {
00676             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
00677             return AVERROR_INVALIDDATA;
00678         }
00679     } else {
00680         if (get_bits(gb,6) != 0x28) {
00681             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
00682             return AVERROR_INVALIDDATA;
00683         }
00684     }
00685 
00686     /* number of coded QMF bands */
00687     pSnd->bandsCoded = get_bits(gb,2);
00688 
00689     result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
00690     if (result) return result;
00691 
00692     pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
00693     if (pSnd->numComponents < 0)
00694         return pSnd->numComponents;
00695 
00696     numSubbands = decodeSpectrum (gb, pSnd->spectrum);
00697 
00698     /* Merge the decoded spectrum and tonal components. */
00699     lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
00700 
00701 
00702     /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
00703     numBands = (subbandTab[numSubbands] - 1) >> 8;
00704     if (lastTonal >= 0)
00705         numBands = FFMAX((lastTonal + 256) >> 8, numBands);
00706 
00707 
00708     /* Reconstruct time domain samples. */
00709     for (band=0; band<4; band++) {
00710         /* Perform the IMDCT step without overlapping. */
00711         if (band <= numBands) {
00712             IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
00713         } else
00714             memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
00715 
00716         /* gain compensation and overlapping */
00717         gainCompensateAndOverlap(pSnd->IMDCT_buf, &pSnd->prevFrame[band * 256],
00718                                  &pOut[band * 256],
00719                                  &pSnd->gainBlock[1 - pSnd->gcBlkSwitch].gBlock[band],
00720                                  &pSnd->gainBlock[    pSnd->gcBlkSwitch].gBlock[band]);
00721     }
00722 
00723     /* Swap the gain control buffers for the next frame. */
00724     pSnd->gcBlkSwitch ^= 1;
00725 
00726     return 0;
00727 }
00728 
00736 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
00737                        float **out_samples)
00738 {
00739     int   result, i;
00740     float   *p1, *p2, *p3, *p4;
00741     uint8_t *ptr1;
00742 
00743     if (q->codingMode == JOINT_STEREO) {
00744 
00745         /* channel coupling mode */
00746         /* decode Sound Unit 1 */
00747         init_get_bits(&q->gb,databuf,q->bits_per_frame);
00748 
00749         result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
00750         if (result != 0)
00751             return result;
00752 
00753         /* Framedata of the su2 in the joint-stereo mode is encoded in
00754          * reverse byte order so we need to swap it first. */
00755         if (databuf == q->decoded_bytes_buffer) {
00756             uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
00757             ptr1 = q->decoded_bytes_buffer;
00758             for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
00759                 FFSWAP(uint8_t,*ptr1,*ptr2);
00760             }
00761         } else {
00762             const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
00763             for (i = 0; i < q->bytes_per_frame; i++)
00764                 q->decoded_bytes_buffer[i] = *ptr2--;
00765         }
00766 
00767         /* Skip the sync codes (0xF8). */
00768         ptr1 = q->decoded_bytes_buffer;
00769         for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
00770             if (i >= q->bytes_per_frame)
00771                 return AVERROR_INVALIDDATA;
00772         }
00773 
00774 
00775         /* set the bitstream reader at the start of the second Sound Unit*/
00776         init_get_bits(&q->gb, ptr1, (q->bytes_per_frame - i) * 8);
00777 
00778         /* Fill the Weighting coeffs delay buffer */
00779         memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
00780         q->weighting_delay[4] = get_bits1(&q->gb);
00781         q->weighting_delay[5] = get_bits(&q->gb,3);
00782 
00783         for (i = 0; i < 4; i++) {
00784             q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
00785             q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
00786             q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
00787         }
00788 
00789         /* Decode Sound Unit 2. */
00790         result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
00791         if (result != 0)
00792             return result;
00793 
00794         /* Reconstruct the channel coefficients. */
00795         reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
00796 
00797         channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
00798 
00799     } else {
00800         /* normal stereo mode or mono */
00801         /* Decode the channel sound units. */
00802         for (i=0 ; i<q->channels ; i++) {
00803 
00804             /* Set the bitstream reader at the start of a channel sound unit. */
00805             init_get_bits(&q->gb,
00806                           databuf + i * q->bytes_per_frame / q->channels,
00807                           q->bits_per_frame / q->channels);
00808 
00809             result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
00810             if (result != 0)
00811                 return result;
00812         }
00813     }
00814 
00815     /* Apply the iQMF synthesis filter. */
00816     for (i=0 ; i<q->channels ; i++) {
00817         p1 = out_samples[i];
00818         p2= p1+256;
00819         p3= p2+256;
00820         p4= p3+256;
00821         atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
00822         atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
00823         atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
00824     }
00825 
00826     return 0;
00827 }
00828 
00829 
00836 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
00837                                int *got_frame_ptr, AVPacket *avpkt)
00838 {
00839     const uint8_t *buf = avpkt->data;
00840     int buf_size = avpkt->size;
00841     ATRAC3Context *q = avctx->priv_data;
00842     int result;
00843     const uint8_t* databuf;
00844     float   *samples_flt;
00845     int16_t *samples_s16;
00846 
00847     if (buf_size < avctx->block_align) {
00848         av_log(avctx, AV_LOG_ERROR,
00849                "Frame too small (%d bytes). Truncated file?\n", buf_size);
00850         return AVERROR_INVALIDDATA;
00851     }
00852 
00853     /* get output buffer */
00854     q->frame.nb_samples = SAMPLES_PER_FRAME;
00855     if ((result = avctx->get_buffer(avctx, &q->frame)) < 0) {
00856         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00857         return result;
00858     }
00859     samples_flt = (float   *)q->frame.data[0];
00860     samples_s16 = (int16_t *)q->frame.data[0];
00861 
00862     /* Check if we need to descramble and what buffer to pass on. */
00863     if (q->scrambled_stream) {
00864         decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
00865         databuf = q->decoded_bytes_buffer;
00866     } else {
00867         databuf = buf;
00868     }
00869 
00870     if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
00871         result = decodeFrame(q, databuf, &samples_flt);
00872     else
00873         result = decodeFrame(q, databuf, q->outSamples);
00874 
00875     if (result != 0) {
00876         av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
00877         return result;
00878     }
00879 
00880     /* interleave */
00881     if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
00882         q->fmt_conv.float_interleave(samples_flt,
00883                                      (const float **)q->outSamples,
00884                                      SAMPLES_PER_FRAME, 2);
00885     } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
00886         q->fmt_conv.float_to_int16_interleave(samples_s16,
00887                                               (const float **)q->outSamples,
00888                                               SAMPLES_PER_FRAME, q->channels);
00889     }
00890 
00891     *got_frame_ptr   = 1;
00892     *(AVFrame *)data = q->frame;
00893 
00894     return avctx->block_align;
00895 }
00896 
00897 
00904 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
00905 {
00906     int i, ret;
00907     const uint8_t *edata_ptr = avctx->extradata;
00908     ATRAC3Context *q = avctx->priv_data;
00909     static VLC_TYPE atrac3_vlc_table[4096][2];
00910     static int vlcs_initialized = 0;
00911 
00912     /* Take data from the AVCodecContext (RM container). */
00913     q->sample_rate = avctx->sample_rate;
00914     q->channels = avctx->channels;
00915     q->bit_rate = avctx->bit_rate;
00916     q->bits_per_frame = avctx->block_align * 8;
00917     q->bytes_per_frame = avctx->block_align;
00918 
00919     /* Take care of the codec-specific extradata. */
00920     if (avctx->extradata_size == 14) {
00921         /* Parse the extradata, WAV format */
00922         av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown value always 1
00923         q->samples_per_channel = bytestream_get_le32(&edata_ptr);
00924         q->codingMode = bytestream_get_le16(&edata_ptr);
00925         av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
00926         q->frame_factor = bytestream_get_le16(&edata_ptr);  //Unknown always 1
00927         av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown always 0
00928 
00929         /* setup */
00930         q->samples_per_frame = SAMPLES_PER_FRAME * q->channels;
00931         q->atrac3version = 4;
00932         q->delay = 0x88E;
00933         if (q->codingMode)
00934             q->codingMode = JOINT_STEREO;
00935         else
00936             q->codingMode = STEREO;
00937 
00938         q->scrambled_stream = 0;
00939 
00940         if ((q->bytes_per_frame == 96*q->channels*q->frame_factor) || (q->bytes_per_frame == 152*q->channels*q->frame_factor) || (q->bytes_per_frame == 192*q->channels*q->frame_factor)) {
00941         } else {
00942             av_log(avctx,AV_LOG_ERROR,"Unknown frame/channel/frame_factor configuration %d/%d/%d\n", q->bytes_per_frame, q->channels, q->frame_factor);
00943             return AVERROR_INVALIDDATA;
00944         }
00945 
00946     } else if (avctx->extradata_size == 10) {
00947         /* Parse the extradata, RM format. */
00948         q->atrac3version = bytestream_get_be32(&edata_ptr);
00949         q->samples_per_frame = bytestream_get_be16(&edata_ptr);
00950         q->delay = bytestream_get_be16(&edata_ptr);
00951         q->codingMode = bytestream_get_be16(&edata_ptr);
00952 
00953         q->samples_per_channel = q->samples_per_frame / q->channels;
00954         q->scrambled_stream = 1;
00955 
00956     } else {
00957         av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
00958     }
00959     /* Check the extradata. */
00960 
00961     if (q->atrac3version != 4) {
00962         av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
00963         return AVERROR_INVALIDDATA;
00964     }
00965 
00966     if (q->samples_per_frame != SAMPLES_PER_FRAME && q->samples_per_frame != SAMPLES_PER_FRAME*2) {
00967         av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
00968         return AVERROR_INVALIDDATA;
00969     }
00970 
00971     if (q->delay != 0x88E) {
00972         av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
00973         return AVERROR_INVALIDDATA;
00974     }
00975 
00976     if (q->codingMode == STEREO) {
00977         av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
00978     } else if (q->codingMode == JOINT_STEREO) {
00979         if (avctx->channels != 2)
00980             return AVERROR_INVALIDDATA;
00981         av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
00982     } else {
00983         av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
00984         return AVERROR_INVALIDDATA;
00985     }
00986 
00987     if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
00988         av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
00989         return AVERROR(EINVAL);
00990     }
00991 
00992 
00993     if(avctx->block_align >= UINT_MAX/2)
00994         return AVERROR(EINVAL);
00995 
00996     /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
00997      * this is for the bitstream reader. */
00998     if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)))  == NULL)
00999         return AVERROR(ENOMEM);
01000 
01001 
01002     /* Initialize the VLC tables. */
01003     if (!vlcs_initialized) {
01004         for (i=0 ; i<7 ; i++) {
01005             spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
01006             spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
01007             init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
01008                 huff_bits[i], 1, 1,
01009                 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
01010         }
01011         vlcs_initialized = 1;
01012     }
01013 
01014     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
01015         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
01016     else
01017         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
01018 
01019     if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
01020         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
01021         av_freep(&q->decoded_bytes_buffer);
01022         return ret;
01023     }
01024 
01025     atrac_generate_tables();
01026 
01027     /* Generate gain tables. */
01028     for (i=0 ; i<16 ; i++)
01029         gain_tab1[i] = powf (2.0, (4 - i));
01030 
01031     for (i=-15 ; i<16 ; i++)
01032         gain_tab2[i+15] = powf (2.0, i * -0.125);
01033 
01034     /* init the joint-stereo decoding data */
01035     q->weighting_delay[0] = 0;
01036     q->weighting_delay[1] = 7;
01037     q->weighting_delay[2] = 0;
01038     q->weighting_delay[3] = 7;
01039     q->weighting_delay[4] = 0;
01040     q->weighting_delay[5] = 7;
01041 
01042     for (i=0; i<4; i++) {
01043         q->matrix_coeff_index_prev[i] = 3;
01044         q->matrix_coeff_index_now[i] = 3;
01045         q->matrix_coeff_index_next[i] = 3;
01046     }
01047 
01048     dsputil_init(&dsp, avctx);
01049     ff_fmt_convert_init(&q->fmt_conv, avctx);
01050 
01051     q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
01052     if (!q->pUnits) {
01053         atrac3_decode_close(avctx);
01054         return AVERROR(ENOMEM);
01055     }
01056 
01057     if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
01058         q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
01059         q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
01060         if (!q->outSamples[0]) {
01061             atrac3_decode_close(avctx);
01062             return AVERROR(ENOMEM);
01063         }
01064     }
01065 
01066     avcodec_get_frame_defaults(&q->frame);
01067     avctx->coded_frame = &q->frame;
01068 
01069     return 0;
01070 }
01071 
01072 
01073 AVCodec ff_atrac3_decoder =
01074 {
01075     .name = "atrac3",
01076     .type = AVMEDIA_TYPE_AUDIO,
01077     .id = CODEC_ID_ATRAC3,
01078     .priv_data_size = sizeof(ATRAC3Context),
01079     .init = atrac3_decode_init,
01080     .close = atrac3_decode_close,
01081     .decode = atrac3_decode_frame,
01082     .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
01083     .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
01084 };