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