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