1/*
2 * Atrac 3 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 * Atrac 3 compatible decoder.
26 * This decoder handles Sony's ATRAC3 data.
27 *
28 * Container formats used to store atrac 3 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 "avcodec.h"
40#include "get_bits.h"
41#include "dsputil.h"
42#include "bytestream.h"
43#include "fft.h"
44
45#include "atrac.h"
46#include "atrac3data.h"
47
48#define JOINT_STEREO    0x12
49#define STEREO          0x2
50
51
52/* These structures are needed to store the parsed gain control data. */
53typedef struct {
54    int   num_gain_data;
55    int   levcode[8];
56    int   loccode[8];
57} gain_info;
58
59typedef struct {
60    gain_info   gBlock[4];
61} gain_block;
62
63typedef struct {
64    int     pos;
65    int     numCoefs;
66    float   coef[8];
67} tonal_component;
68
69typedef struct {
70    int               bandsCoded;
71    int               numComponents;
72    tonal_component   components[64];
73    float             prevFrame[1024];
74    int               gcBlkSwitch;
75    gain_block        gainBlock[2];
76
77    DECLARE_ALIGNED(16, float, spectrum)[1024];
78    DECLARE_ALIGNED(16, float, IMDCT_buf)[1024];
79
80    float             delayBuf1[46]; ///<qmf delay buffers
81    float             delayBuf2[46];
82    float             delayBuf3[46];
83} channel_unit;
84
85typedef struct {
86    GetBitContext       gb;
87    //@{
88    /** stream data */
89    int                 channels;
90    int                 codingMode;
91    int                 bit_rate;
92    int                 sample_rate;
93    int                 samples_per_channel;
94    int                 samples_per_frame;
95
96    int                 bits_per_frame;
97    int                 bytes_per_frame;
98    int                 pBs;
99    channel_unit*       pUnits;
100    //@}
101    //@{
102    /** joint-stereo related variables */
103    int                 matrix_coeff_index_prev[4];
104    int                 matrix_coeff_index_now[4];
105    int                 matrix_coeff_index_next[4];
106    int                 weighting_delay[6];
107    //@}
108    //@{
109    /** data buffers */
110    float               outSamples[2048];
111    uint8_t*            decoded_bytes_buffer;
112    float               tempBuf[1070];
113    //@}
114    //@{
115    /** extradata */
116    int                 atrac3version;
117    int                 delay;
118    int                 scrambled_stream;
119    int                 frame_factor;
120    //@}
121} ATRAC3Context;
122
123static DECLARE_ALIGNED(16, float,mdct_window)[512];
124static VLC              spectral_coeff_tab[7];
125static float            gain_tab1[16];
126static float            gain_tab2[31];
127static FFTContext       mdct_ctx;
128static DSPContext       dsp;
129
130
131/**
132 * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
133 * caused by the reverse spectra of the QMF.
134 *
135 * @param pInput    float input
136 * @param pOutput   float output
137 * @param odd_band  1 if the band is an odd band
138 */
139
140static void IMLT(float *pInput, float *pOutput, int odd_band)
141{
142    int     i;
143
144    if (odd_band) {
145        /**
146        * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
147        * or it gives better compression to do it this way.
148        * FIXME: It should be possible to handle this in ff_imdct_calc
149        * for that to happen a modification of the prerotation step of
150        * all SIMD code and C code is needed.
151        * Or fix the functions before so they generate a pre reversed spectrum.
152        */
153
154        for (i=0; i<128; i++)
155            FFSWAP(float, pInput[i], pInput[255-i]);
156    }
157
158    ff_imdct_calc(&mdct_ctx,pOutput,pInput);
159
160    /* Perform windowing on the output. */
161    dsp.vector_fmul(pOutput,mdct_window,512);
162
163}
164
165
166/**
167 * Atrac 3 indata descrambling, only used for data coming from the rm container
168 *
169 * @param in        pointer to 8 bit array of indata
170 * @param bits      amount of bits
171 * @param out       pointer to 8 bit array of outdata
172 */
173
174static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
175    int i, off;
176    uint32_t c;
177    const uint32_t* buf;
178    uint32_t* obuf = (uint32_t*) out;
179
180    off = (intptr_t)inbuffer & 3;
181    buf = (const uint32_t*) (inbuffer - off);
182    c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
183    bytes += 3 + off;
184    for (i = 0; i < bytes/4; i++)
185        obuf[i] = c ^ buf[i];
186
187    if (off)
188        av_log(NULL,AV_LOG_DEBUG,"Offset of %d not handled, post sample on ffmpeg-dev.\n",off);
189
190    return off;
191}
192
193
194static av_cold void init_atrac3_transforms(ATRAC3Context *q) {
195    float enc_window[256];
196    int i;
197
198    /* Generate the mdct window, for details see
199     * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
200    for (i=0 ; i<256; i++)
201        enc_window[i] = (sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0) * 0.5;
202
203    if (!mdct_window[0])
204        for (i=0 ; i<256; i++) {
205            mdct_window[i] = enc_window[i]/(enc_window[i]*enc_window[i] + enc_window[255-i]*enc_window[255-i]);
206            mdct_window[511-i] = mdct_window[i];
207        }
208
209    /* Initialize the MDCT transform. */
210    ff_mdct_init(&mdct_ctx, 9, 1, 1.0);
211}
212
213/**
214 * Atrac3 uninit, free all allocated memory
215 */
216
217static av_cold int atrac3_decode_close(AVCodecContext *avctx)
218{
219    ATRAC3Context *q = avctx->priv_data;
220
221    av_free(q->pUnits);
222    av_free(q->decoded_bytes_buffer);
223
224    return 0;
225}
226
227/**
228/ * Mantissa decoding
229 *
230 * @param gb            the GetBit context
231 * @param selector      what table is the output values coded with
232 * @param codingFlag    constant length coding or variable length coding
233 * @param mantissas     mantissa output table
234 * @param numCodes      amount of values to get
235 */
236
237static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
238{
239    int   numBits, cnt, code, huffSymb;
240
241    if (selector == 1)
242        numCodes /= 2;
243
244    if (codingFlag != 0) {
245        /* constant length coding (CLC) */
246        numBits = CLCLengthTab[selector];
247
248        if (selector > 1) {
249            for (cnt = 0; cnt < numCodes; cnt++) {
250                if (numBits)
251                    code = get_sbits(gb, numBits);
252                else
253                    code = 0;
254                mantissas[cnt] = code;
255            }
256        } else {
257            for (cnt = 0; cnt < numCodes; cnt++) {
258                if (numBits)
259                    code = get_bits(gb, numBits); //numBits is always 4 in this case
260                else
261                    code = 0;
262                mantissas[cnt*2] = seTab_0[code >> 2];
263                mantissas[cnt*2+1] = seTab_0[code & 3];
264            }
265        }
266    } else {
267        /* variable length coding (VLC) */
268        if (selector != 1) {
269            for (cnt = 0; cnt < numCodes; cnt++) {
270                huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
271                huffSymb += 1;
272                code = huffSymb >> 1;
273                if (huffSymb & 1)
274                    code = -code;
275                mantissas[cnt] = code;
276            }
277        } else {
278            for (cnt = 0; cnt < numCodes; cnt++) {
279                huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
280                mantissas[cnt*2] = decTable1[huffSymb*2];
281                mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
282            }
283        }
284    }
285}
286
287/**
288 * Restore the quantized band spectrum coefficients
289 *
290 * @param gb            the GetBit context
291 * @param pOut          decoded band spectrum
292 * @return outSubbands   subband counter, fix for broken specification/files
293 */
294
295static int decodeSpectrum (GetBitContext *gb, float *pOut)
296{
297    int   numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
298    int   subband_vlc_index[32], SF_idxs[32];
299    int   mantissas[128];
300    float SF;
301
302    numSubbands = get_bits(gb, 5); // number of coded subbands
303    codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
304
305    /* Get the VLC selector table for the subbands, 0 means not coded. */
306    for (cnt = 0; cnt <= numSubbands; cnt++)
307        subband_vlc_index[cnt] = get_bits(gb, 3);
308
309    /* Read the scale factor indexes from the stream. */
310    for (cnt = 0; cnt <= numSubbands; cnt++) {
311        if (subband_vlc_index[cnt] != 0)
312            SF_idxs[cnt] = get_bits(gb, 6);
313    }
314
315    for (cnt = 0; cnt <= numSubbands; cnt++) {
316        first = subbandTab[cnt];
317        last = subbandTab[cnt+1];
318
319        subbWidth = last - first;
320
321        if (subband_vlc_index[cnt] != 0) {
322            /* Decode spectral coefficients for this subband. */
323            /* TODO: This can be done faster is several blocks share the
324             * same VLC selector (subband_vlc_index) */
325            readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
326
327            /* Decode the scale factor for this subband. */
328            SF = sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
329
330            /* Inverse quantize the coefficients. */
331            for (pIn=mantissas ; first<last; first++, pIn++)
332                pOut[first] = *pIn * SF;
333        } else {
334            /* This subband was not coded, so zero the entire subband. */
335            memset(pOut+first, 0, subbWidth*sizeof(float));
336        }
337    }
338
339    /* Clear the subbands that were not coded. */
340    first = subbandTab[cnt];
341    memset(pOut+first, 0, (1024 - first) * sizeof(float));
342    return numSubbands;
343}
344
345/**
346 * Restore the quantized tonal components
347 *
348 * @param gb            the GetBit context
349 * @param pComponent    tone component
350 * @param numBands      amount of coded bands
351 */
352
353static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
354{
355    int i,j,k,cnt;
356    int   components, coding_mode_selector, coding_mode, coded_values_per_component;
357    int   sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
358    int   band_flags[4], mantissa[8];
359    float  *pCoef;
360    float  scalefactor;
361    int   component_count = 0;
362
363    components = get_bits(gb,5);
364
365    /* no tonal components */
366    if (components == 0)
367        return 0;
368
369    coding_mode_selector = get_bits(gb,2);
370    if (coding_mode_selector == 2)
371        return -1;
372
373    coding_mode = coding_mode_selector & 1;
374
375    for (i = 0; i < components; i++) {
376        for (cnt = 0; cnt <= numBands; cnt++)
377            band_flags[cnt] = get_bits1(gb);
378
379        coded_values_per_component = get_bits(gb,3);
380
381        quant_step_index = get_bits(gb,3);
382        if (quant_step_index <= 1)
383            return -1;
384
385        if (coding_mode_selector == 3)
386            coding_mode = get_bits1(gb);
387
388        for (j = 0; j < (numBands + 1) * 4; j++) {
389            if (band_flags[j >> 2] == 0)
390                continue;
391
392            coded_components = get_bits(gb,3);
393
394            for (k=0; k<coded_components; k++) {
395                sfIndx = get_bits(gb,6);
396                pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
397                max_coded_values = 1024 - pComponent[component_count].pos;
398                coded_values = coded_values_per_component + 1;
399                coded_values = FFMIN(max_coded_values,coded_values);
400
401                scalefactor = sf_table[sfIndx] * iMaxQuant[quant_step_index];
402
403                readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
404
405                pComponent[component_count].numCoefs = coded_values;
406
407                /* inverse quant */
408                pCoef = pComponent[component_count].coef;
409                for (cnt = 0; cnt < coded_values; cnt++)
410                    pCoef[cnt] = mantissa[cnt] * scalefactor;
411
412                component_count++;
413            }
414        }
415    }
416
417    return component_count;
418}
419
420/**
421 * Decode gain parameters for the coded bands
422 *
423 * @param gb            the GetBit context
424 * @param pGb           the gainblock for the current band
425 * @param numBands      amount of coded bands
426 */
427
428static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
429{
430    int   i, cf, numData;
431    int   *pLevel, *pLoc;
432
433    gain_info   *pGain = pGb->gBlock;
434
435    for (i=0 ; i<=numBands; i++)
436    {
437        numData = get_bits(gb,3);
438        pGain[i].num_gain_data = numData;
439        pLevel = pGain[i].levcode;
440        pLoc = pGain[i].loccode;
441
442        for (cf = 0; cf < numData; cf++){
443            pLevel[cf]= get_bits(gb,4);
444            pLoc  [cf]= get_bits(gb,5);
445            if(cf && pLoc[cf] <= pLoc[cf-1])
446                return -1;
447        }
448    }
449
450    /* Clear the unused blocks. */
451    for (; i<4 ; i++)
452        pGain[i].num_gain_data = 0;
453
454    return 0;
455}
456
457/**
458 * Apply gain parameters and perform the MDCT overlapping part
459 *
460 * @param pIn           input float buffer
461 * @param pPrev         previous float buffer to perform overlap against
462 * @param pOut          output float buffer
463 * @param pGain1        current band gain info
464 * @param pGain2        next band gain info
465 */
466
467static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
468{
469    /* gain compensation function */
470    float  gain1, gain2, gain_inc;
471    int   cnt, numdata, nsample, startLoc, endLoc;
472
473
474    if (pGain2->num_gain_data == 0)
475        gain1 = 1.0;
476    else
477        gain1 = gain_tab1[pGain2->levcode[0]];
478
479    if (pGain1->num_gain_data == 0) {
480        for (cnt = 0; cnt < 256; cnt++)
481            pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
482    } else {
483        numdata = pGain1->num_gain_data;
484        pGain1->loccode[numdata] = 32;
485        pGain1->levcode[numdata] = 4;
486
487        nsample = 0; // current sample = 0
488
489        for (cnt = 0; cnt < numdata; cnt++) {
490            startLoc = pGain1->loccode[cnt] * 8;
491            endLoc = startLoc + 8;
492
493            gain2 = gain_tab1[pGain1->levcode[cnt]];
494            gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
495
496            /* interpolate */
497            for (; nsample < startLoc; nsample++)
498                pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
499
500            /* interpolation is done over eight samples */
501            for (; nsample < endLoc; nsample++) {
502                pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
503                gain2 *= gain_inc;
504            }
505        }
506
507        for (; nsample < 256; nsample++)
508            pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
509    }
510
511    /* Delay for the overlapping part. */
512    memcpy(pPrev, &pIn[256], 256*sizeof(float));
513}
514
515/**
516 * Combine the tonal band spectrum and regular band spectrum
517 * Return position of the last tonal coefficient
518 *
519 * @param pSpectrum     output spectrum buffer
520 * @param numComponents amount of tonal components
521 * @param pComponent    tonal components for this band
522 */
523
524static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
525{
526    int   cnt, i, lastPos = -1;
527    float   *pIn, *pOut;
528
529    for (cnt = 0; cnt < numComponents; cnt++){
530        lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
531        pIn = pComponent[cnt].coef;
532        pOut = &(pSpectrum[pComponent[cnt].pos]);
533
534        for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
535            pOut[i] += pIn[i];
536    }
537
538    return lastPos;
539}
540
541
542#define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
543
544static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
545{
546    int    i, band, nsample, s1, s2;
547    float    c1, c2;
548    float    mc1_l, mc1_r, mc2_l, mc2_r;
549
550    for (i=0,band = 0; band < 4*256; band+=256,i++) {
551        s1 = pPrevCode[i];
552        s2 = pCurrCode[i];
553        nsample = 0;
554
555        if (s1 != s2) {
556            /* Selector value changed, interpolation needed. */
557            mc1_l = matrixCoeffs[s1*2];
558            mc1_r = matrixCoeffs[s1*2+1];
559            mc2_l = matrixCoeffs[s2*2];
560            mc2_r = matrixCoeffs[s2*2+1];
561
562            /* Interpolation is done over the first eight samples. */
563            for(; nsample < 8; nsample++) {
564                c1 = su1[band+nsample];
565                c2 = su2[band+nsample];
566                c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
567                su1[band+nsample] = c2;
568                su2[band+nsample] = c1 * 2.0 - c2;
569            }
570        }
571
572        /* Apply the matrix without interpolation. */
573        switch (s2) {
574            case 0:     /* M/S decoding */
575                for (; nsample < 256; nsample++) {
576                    c1 = su1[band+nsample];
577                    c2 = su2[band+nsample];
578                    su1[band+nsample] = c2 * 2.0;
579                    su2[band+nsample] = (c1 - c2) * 2.0;
580                }
581                break;
582
583            case 1:
584                for (; nsample < 256; nsample++) {
585                    c1 = su1[band+nsample];
586                    c2 = su2[band+nsample];
587                    su1[band+nsample] = (c1 + c2) * 2.0;
588                    su2[band+nsample] = c2 * -2.0;
589                }
590                break;
591            case 2:
592            case 3:
593                for (; nsample < 256; nsample++) {
594                    c1 = su1[band+nsample];
595                    c2 = su2[band+nsample];
596                    su1[band+nsample] = c1 + c2;
597                    su2[band+nsample] = c1 - c2;
598                }
599                break;
600            default:
601                assert(0);
602        }
603    }
604}
605
606static void getChannelWeights (int indx, int flag, float ch[2]){
607
608    if (indx == 7) {
609        ch[0] = 1.0;
610        ch[1] = 1.0;
611    } else {
612        ch[0] = (float)(indx & 7) / 7.0;
613        ch[1] = sqrt(2 - ch[0]*ch[0]);
614        if(flag)
615            FFSWAP(float, ch[0], ch[1]);
616    }
617}
618
619static void channelWeighting (float *su1, float *su2, int *p3)
620{
621    int   band, nsample;
622    /* w[x][y] y=0 is left y=1 is right */
623    float w[2][2];
624
625    if (p3[1] != 7 || p3[3] != 7){
626        getChannelWeights(p3[1], p3[0], w[0]);
627        getChannelWeights(p3[3], p3[2], w[1]);
628
629        for(band = 1; band < 4; band++) {
630            /* scale the channels by the weights */
631            for(nsample = 0; nsample < 8; nsample++) {
632                su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
633                su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
634            }
635
636            for(; nsample < 256; nsample++) {
637                su1[band*256+nsample] *= w[1][0];
638                su2[band*256+nsample] *= w[1][1];
639            }
640        }
641    }
642}
643
644
645/**
646 * Decode a Sound Unit
647 *
648 * @param gb            the GetBit context
649 * @param pSnd          the channel unit to be used
650 * @param pOut          the decoded samples before IQMF in float representation
651 * @param channelNum    channel number
652 * @param codingMode    the coding mode (JOINT_STEREO or regular stereo/mono)
653 */
654
655
656static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
657{
658    int   band, result=0, numSubbands, lastTonal, numBands;
659
660    if (codingMode == JOINT_STEREO && channelNum == 1) {
661        if (get_bits(gb,2) != 3) {
662            av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
663            return -1;
664        }
665    } else {
666        if (get_bits(gb,6) != 0x28) {
667            av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
668            return -1;
669        }
670    }
671
672    /* number of coded QMF bands */
673    pSnd->bandsCoded = get_bits(gb,2);
674
675    result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
676    if (result) return result;
677
678    pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
679    if (pSnd->numComponents == -1) return -1;
680
681    numSubbands = decodeSpectrum (gb, pSnd->spectrum);
682
683    /* Merge the decoded spectrum and tonal components. */
684    lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
685
686
687    /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
688    numBands = (subbandTab[numSubbands] - 1) >> 8;
689    if (lastTonal >= 0)
690        numBands = FFMAX((lastTonal + 256) >> 8, numBands);
691
692
693    /* Reconstruct time domain samples. */
694    for (band=0; band<4; band++) {
695        /* Perform the IMDCT step without overlapping. */
696        if (band <= numBands) {
697            IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
698        } else
699            memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
700
701        /* gain compensation and overlapping */
702        gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),
703                                    &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),
704                                    &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));
705    }
706
707    /* Swap the gain control buffers for the next frame. */
708    pSnd->gcBlkSwitch ^= 1;
709
710    return 0;
711}
712
713/**
714 * Frame handling
715 *
716 * @param q             Atrac3 private context
717 * @param databuf       the input data
718 */
719
720static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf)
721{
722    int   result, i;
723    float   *p1, *p2, *p3, *p4;
724    uint8_t *ptr1;
725
726    if (q->codingMode == JOINT_STEREO) {
727
728        /* channel coupling mode */
729        /* decode Sound Unit 1 */
730        init_get_bits(&q->gb,databuf,q->bits_per_frame);
731
732        result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, q->outSamples, 0, JOINT_STEREO);
733        if (result != 0)
734            return (result);
735
736        /* Framedata of the su2 in the joint-stereo mode is encoded in
737         * reverse byte order so we need to swap it first. */
738        if (databuf == q->decoded_bytes_buffer) {
739            uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
740            ptr1 = q->decoded_bytes_buffer;
741            for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
742                FFSWAP(uint8_t,*ptr1,*ptr2);
743            }
744        } else {
745            const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
746            for (i = 0; i < q->bytes_per_frame; i++)
747                q->decoded_bytes_buffer[i] = *ptr2--;
748        }
749
750        /* Skip the sync codes (0xF8). */
751        ptr1 = q->decoded_bytes_buffer;
752        for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
753            if (i >= q->bytes_per_frame)
754                return -1;
755        }
756
757
758        /* set the bitstream reader at the start of the second Sound Unit*/
759        init_get_bits(&q->gb,ptr1,q->bits_per_frame);
760
761        /* Fill the Weighting coeffs delay buffer */
762        memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
763        q->weighting_delay[4] = get_bits1(&q->gb);
764        q->weighting_delay[5] = get_bits(&q->gb,3);
765
766        for (i = 0; i < 4; i++) {
767            q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
768            q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
769            q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
770        }
771
772        /* Decode Sound Unit 2. */
773        result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], &q->outSamples[1024], 1, JOINT_STEREO);
774        if (result != 0)
775            return (result);
776
777        /* Reconstruct the channel coefficients. */
778        reverseMatrixing(q->outSamples, &q->outSamples[1024], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
779
780        channelWeighting(q->outSamples, &q->outSamples[1024], q->weighting_delay);
781
782    } else {
783        /* normal stereo mode or mono */
784        /* Decode the channel sound units. */
785        for (i=0 ; i<q->channels ; i++) {
786
787            /* Set the bitstream reader at the start of a channel sound unit. */
788            init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels), (q->bits_per_frame)/q->channels);
789
790            result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], &q->outSamples[i*1024], i, q->codingMode);
791            if (result != 0)
792                return (result);
793        }
794    }
795
796    /* Apply the iQMF synthesis filter. */
797    p1= q->outSamples;
798    for (i=0 ; i<q->channels ; i++) {
799        p2= p1+256;
800        p3= p2+256;
801        p4= p3+256;
802        atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
803        atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
804        atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
805        p1 +=1024;
806    }
807
808    return 0;
809}
810
811
812/**
813 * Atrac frame decoding
814 *
815 * @param avctx     pointer to the AVCodecContext
816 */
817
818static int atrac3_decode_frame(AVCodecContext *avctx,
819            void *data, int *data_size,
820            AVPacket *avpkt) {
821    const uint8_t *buf = avpkt->data;
822    int buf_size = avpkt->size;
823    ATRAC3Context *q = avctx->priv_data;
824    int result = 0, i;
825    const uint8_t* databuf;
826    int16_t* samples = data;
827
828    if (buf_size < avctx->block_align)
829        return buf_size;
830
831    /* Check if we need to descramble and what buffer to pass on. */
832    if (q->scrambled_stream) {
833        decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
834        databuf = q->decoded_bytes_buffer;
835    } else {
836        databuf = buf;
837    }
838
839    result = decodeFrame(q, databuf);
840
841    if (result != 0) {
842        av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
843        return -1;
844    }
845
846    if (q->channels == 1) {
847        /* mono */
848        for (i = 0; i<1024; i++)
849            samples[i] = av_clip_int16(round(q->outSamples[i]));
850        *data_size = 1024 * sizeof(int16_t);
851    } else {
852        /* stereo */
853        for (i = 0; i < 1024; i++) {
854            samples[i*2] = av_clip_int16(round(q->outSamples[i]));
855            samples[i*2+1] = av_clip_int16(round(q->outSamples[1024+i]));
856        }
857        *data_size = 2048 * sizeof(int16_t);
858    }
859
860    return avctx->block_align;
861}
862
863
864/**
865 * Atrac3 initialization
866 *
867 * @param avctx     pointer to the AVCodecContext
868 */
869
870static av_cold int atrac3_decode_init(AVCodecContext *avctx)
871{
872    int i;
873    const uint8_t *edata_ptr = avctx->extradata;
874    ATRAC3Context *q = avctx->priv_data;
875    static VLC_TYPE atrac3_vlc_table[4096][2];
876    static int vlcs_initialized = 0;
877
878    /* Take data from the AVCodecContext (RM container). */
879    q->sample_rate = avctx->sample_rate;
880    q->channels = avctx->channels;
881    q->bit_rate = avctx->bit_rate;
882    q->bits_per_frame = avctx->block_align * 8;
883    q->bytes_per_frame = avctx->block_align;
884
885    /* Take care of the codec-specific extradata. */
886    if (avctx->extradata_size == 14) {
887        /* Parse the extradata, WAV format */
888        av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown value always 1
889        q->samples_per_channel = bytestream_get_le32(&edata_ptr);
890        q->codingMode = bytestream_get_le16(&edata_ptr);
891        av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
892        q->frame_factor = bytestream_get_le16(&edata_ptr);  //Unknown always 1
893        av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown always 0
894
895        /* setup */
896        q->samples_per_frame = 1024 * q->channels;
897        q->atrac3version = 4;
898        q->delay = 0x88E;
899        if (q->codingMode)
900            q->codingMode = JOINT_STEREO;
901        else
902            q->codingMode = STEREO;
903
904        q->scrambled_stream = 0;
905
906        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)) {
907        } else {
908            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);
909            return -1;
910        }
911
912    } else if (avctx->extradata_size == 10) {
913        /* Parse the extradata, RM format. */
914        q->atrac3version = bytestream_get_be32(&edata_ptr);
915        q->samples_per_frame = bytestream_get_be16(&edata_ptr);
916        q->delay = bytestream_get_be16(&edata_ptr);
917        q->codingMode = bytestream_get_be16(&edata_ptr);
918
919        q->samples_per_channel = q->samples_per_frame / q->channels;
920        q->scrambled_stream = 1;
921
922    } else {
923        av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
924    }
925    /* Check the extradata. */
926
927    if (q->atrac3version != 4) {
928        av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
929        return -1;
930    }
931
932    if (q->samples_per_frame != 1024 && q->samples_per_frame != 2048) {
933        av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
934        return -1;
935    }
936
937    if (q->delay != 0x88E) {
938        av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
939        return -1;
940    }
941
942    if (q->codingMode == STEREO) {
943        av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
944    } else if (q->codingMode == JOINT_STEREO) {
945        av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
946    } else {
947        av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
948        return -1;
949    }
950
951    if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
952        av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
953        return -1;
954    }
955
956
957    if(avctx->block_align >= UINT_MAX/2)
958        return -1;
959
960    /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
961     * this is for the bitstream reader. */
962    if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)))  == NULL)
963        return AVERROR(ENOMEM);
964
965
966    /* Initialize the VLC tables. */
967    if (!vlcs_initialized) {
968        for (i=0 ; i<7 ; i++) {
969            spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
970            spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
971            init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
972                huff_bits[i], 1, 1,
973                huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
974        }
975        vlcs_initialized = 1;
976    }
977
978    init_atrac3_transforms(q);
979
980    atrac_generate_tables();
981
982    /* Generate gain tables. */
983    for (i=0 ; i<16 ; i++)
984        gain_tab1[i] = powf (2.0, (4 - i));
985
986    for (i=-15 ; i<16 ; i++)
987        gain_tab2[i+15] = powf (2.0, i * -0.125);
988
989    /* init the joint-stereo decoding data */
990    q->weighting_delay[0] = 0;
991    q->weighting_delay[1] = 7;
992    q->weighting_delay[2] = 0;
993    q->weighting_delay[3] = 7;
994    q->weighting_delay[4] = 0;
995    q->weighting_delay[5] = 7;
996
997    for (i=0; i<4; i++) {
998        q->matrix_coeff_index_prev[i] = 3;
999        q->matrix_coeff_index_now[i] = 3;
1000        q->matrix_coeff_index_next[i] = 3;
1001    }
1002
1003    dsputil_init(&dsp, avctx);
1004
1005    q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
1006    if (!q->pUnits) {
1007        av_free(q->decoded_bytes_buffer);
1008        return AVERROR(ENOMEM);
1009    }
1010
1011    avctx->sample_fmt = SAMPLE_FMT_S16;
1012    return 0;
1013}
1014
1015
1016AVCodec atrac3_decoder =
1017{
1018    .name = "atrac3",
1019    .type = AVMEDIA_TYPE_AUDIO,
1020    .id = CODEC_ID_ATRAC3,
1021    .priv_data_size = sizeof(ATRAC3Context),
1022    .init = atrac3_decode_init,
1023    .close = atrac3_decode_close,
1024    .decode = atrac3_decode_frame,
1025    .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1026};
1027