]> git.sesse.net Git - ffmpeg/blob - libavcodec/atrac3.c
3a48a5a64776f66395f0331db3747ba74809e137
[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 "avcodec.h"
40 #include "get_bits.h"
41 #include "dsputil.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     GetBitContext       gb;
90     //@{
91     /** stream data */
92     int                 channels;
93     int                 codingMode;
94     int                 bit_rate;
95     int                 sample_rate;
96     int                 samples_per_channel;
97     int                 samples_per_frame;
98
99     int                 bits_per_frame;
100     int                 bytes_per_frame;
101     int                 pBs;
102     channel_unit*       pUnits;
103     //@}
104     //@{
105     /** joint-stereo related variables */
106     int                 matrix_coeff_index_prev[4];
107     int                 matrix_coeff_index_now[4];
108     int                 matrix_coeff_index_next[4];
109     int                 weighting_delay[6];
110     //@}
111     //@{
112     /** data buffers */
113     float              *outSamples[2];
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 } ATRAC3Context;
128
129 static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
130 static VLC              spectral_coeff_tab[7];
131 static float            gain_tab1[16];
132 static float            gain_tab2[31];
133 static DSPContext       dsp;
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     dsp.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, int is_float) {
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, is_float ? 1.0 / 32768 : 1.0);
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     av_freep(&q->outSamples[0]);
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                 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
405                 max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;
406                 coded_values = coded_values_per_component + 1;
407                 coded_values = FFMIN(max_coded_values,coded_values);
408
409                 scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
410
411                 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
412
413                 pComponent[component_count].numCoefs = coded_values;
414
415                 /* inverse quant */
416                 pCoef = pComponent[component_count].coef;
417                 for (cnt = 0; cnt < coded_values; cnt++)
418                     pCoef[cnt] = mantissa[cnt] * scalefactor;
419
420                 component_count++;
421             }
422         }
423     }
424
425     return component_count;
426 }
427
428 /**
429  * Decode gain parameters for the coded bands
430  *
431  * @param gb            the GetBit context
432  * @param pGb           the gainblock for the current band
433  * @param numBands      amount of coded bands
434  */
435
436 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
437 {
438     int   i, cf, numData;
439     int   *pLevel, *pLoc;
440
441     gain_info   *pGain = pGb->gBlock;
442
443     for (i=0 ; i<=numBands; i++)
444     {
445         numData = get_bits(gb,3);
446         pGain[i].num_gain_data = numData;
447         pLevel = pGain[i].levcode;
448         pLoc = pGain[i].loccode;
449
450         for (cf = 0; cf < numData; cf++){
451             pLevel[cf]= get_bits(gb,4);
452             pLoc  [cf]= get_bits(gb,5);
453             if(cf && pLoc[cf] <= pLoc[cf-1])
454                 return AVERROR_INVALIDDATA;
455         }
456     }
457
458     /* Clear the unused blocks. */
459     for (; i<4 ; i++)
460         pGain[i].num_gain_data = 0;
461
462     return 0;
463 }
464
465 /**
466  * Apply gain parameters and perform the MDCT overlapping part
467  *
468  * @param pIn           input float buffer
469  * @param pPrev         previous float buffer to perform overlap against
470  * @param pOut          output float buffer
471  * @param pGain1        current band gain info
472  * @param pGain2        next band gain info
473  */
474
475 static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
476 {
477     /* gain compensation function */
478     float  gain1, gain2, gain_inc;
479     int   cnt, numdata, nsample, startLoc, endLoc;
480
481
482     if (pGain2->num_gain_data == 0)
483         gain1 = 1.0;
484     else
485         gain1 = gain_tab1[pGain2->levcode[0]];
486
487     if (pGain1->num_gain_data == 0) {
488         for (cnt = 0; cnt < 256; cnt++)
489             pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
490     } else {
491         numdata = pGain1->num_gain_data;
492         pGain1->loccode[numdata] = 32;
493         pGain1->levcode[numdata] = 4;
494
495         nsample = 0; // current sample = 0
496
497         for (cnt = 0; cnt < numdata; cnt++) {
498             startLoc = pGain1->loccode[cnt] * 8;
499             endLoc = startLoc + 8;
500
501             gain2 = gain_tab1[pGain1->levcode[cnt]];
502             gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
503
504             /* interpolate */
505             for (; nsample < startLoc; nsample++)
506                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
507
508             /* interpolation is done over eight samples */
509             for (; nsample < endLoc; nsample++) {
510                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
511                 gain2 *= gain_inc;
512             }
513         }
514
515         for (; nsample < 256; nsample++)
516             pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
517     }
518
519     /* Delay for the overlapping part. */
520     memcpy(pPrev, &pIn[256], 256*sizeof(float));
521 }
522
523 /**
524  * Combine the tonal band spectrum and regular band spectrum
525  * Return position of the last tonal coefficient
526  *
527  * @param pSpectrum     output spectrum buffer
528  * @param numComponents amount of tonal components
529  * @param pComponent    tonal components for this band
530  */
531
532 static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
533 {
534     int   cnt, i, lastPos = -1;
535     float   *pIn, *pOut;
536
537     for (cnt = 0; cnt < numComponents; cnt++){
538         lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
539         pIn = pComponent[cnt].coef;
540         pOut = &(pSpectrum[pComponent[cnt].pos]);
541
542         for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
543             pOut[i] += pIn[i];
544     }
545
546     return lastPos;
547 }
548
549
550 #define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
551
552 static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
553 {
554     int    i, band, nsample, s1, s2;
555     float    c1, c2;
556     float    mc1_l, mc1_r, mc2_l, mc2_r;
557
558     for (i=0,band = 0; band < 4*256; band+=256,i++) {
559         s1 = pPrevCode[i];
560         s2 = pCurrCode[i];
561         nsample = 0;
562
563         if (s1 != s2) {
564             /* Selector value changed, interpolation needed. */
565             mc1_l = matrixCoeffs[s1*2];
566             mc1_r = matrixCoeffs[s1*2+1];
567             mc2_l = matrixCoeffs[s2*2];
568             mc2_r = matrixCoeffs[s2*2+1];
569
570             /* Interpolation is done over the first eight samples. */
571             for(; nsample < 8; nsample++) {
572                 c1 = su1[band+nsample];
573                 c2 = su2[band+nsample];
574                 c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
575                 su1[band+nsample] = c2;
576                 su2[band+nsample] = c1 * 2.0 - c2;
577             }
578         }
579
580         /* Apply the matrix without interpolation. */
581         switch (s2) {
582             case 0:     /* M/S decoding */
583                 for (; nsample < 256; nsample++) {
584                     c1 = su1[band+nsample];
585                     c2 = su2[band+nsample];
586                     su1[band+nsample] = c2 * 2.0;
587                     su2[band+nsample] = (c1 - c2) * 2.0;
588                 }
589                 break;
590
591             case 1:
592                 for (; nsample < 256; nsample++) {
593                     c1 = su1[band+nsample];
594                     c2 = su2[band+nsample];
595                     su1[band+nsample] = (c1 + c2) * 2.0;
596                     su2[band+nsample] = c2 * -2.0;
597                 }
598                 break;
599             case 2:
600             case 3:
601                 for (; nsample < 256; nsample++) {
602                     c1 = su1[band+nsample];
603                     c2 = su2[band+nsample];
604                     su1[band+nsample] = c1 + c2;
605                     su2[band+nsample] = c1 - c2;
606                 }
607                 break;
608             default:
609                 assert(0);
610         }
611     }
612 }
613
614 static void getChannelWeights (int indx, int flag, float ch[2]){
615
616     if (indx == 7) {
617         ch[0] = 1.0;
618         ch[1] = 1.0;
619     } else {
620         ch[0] = (float)(indx & 7) / 7.0;
621         ch[1] = sqrt(2 - ch[0]*ch[0]);
622         if(flag)
623             FFSWAP(float, ch[0], ch[1]);
624     }
625 }
626
627 static void channelWeighting (float *su1, float *su2, int *p3)
628 {
629     int   band, nsample;
630     /* w[x][y] y=0 is left y=1 is right */
631     float w[2][2];
632
633     if (p3[1] != 7 || p3[3] != 7){
634         getChannelWeights(p3[1], p3[0], w[0]);
635         getChannelWeights(p3[3], p3[2], w[1]);
636
637         for(band = 1; band < 4; band++) {
638             /* scale the channels by the weights */
639             for(nsample = 0; nsample < 8; nsample++) {
640                 su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
641                 su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
642             }
643
644             for(; nsample < 256; nsample++) {
645                 su1[band*256+nsample] *= w[1][0];
646                 su2[band*256+nsample] *= w[1][1];
647             }
648         }
649     }
650 }
651
652
653 /**
654  * Decode a Sound Unit
655  *
656  * @param gb            the GetBit context
657  * @param pSnd          the channel unit to be used
658  * @param pOut          the decoded samples before IQMF in float representation
659  * @param channelNum    channel number
660  * @param codingMode    the coding mode (JOINT_STEREO or regular stereo/mono)
661  */
662
663
664 static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
665 {
666     int   band, result=0, numSubbands, lastTonal, numBands;
667
668     if (codingMode == JOINT_STEREO && channelNum == 1) {
669         if (get_bits(gb,2) != 3) {
670             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
671             return AVERROR_INVALIDDATA;
672         }
673     } else {
674         if (get_bits(gb,6) != 0x28) {
675             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
676             return AVERROR_INVALIDDATA;
677         }
678     }
679
680     /* number of coded QMF bands */
681     pSnd->bandsCoded = get_bits(gb,2);
682
683     result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
684     if (result) return result;
685
686     pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
687     if (pSnd->numComponents == -1) return -1;
688
689     numSubbands = decodeSpectrum (gb, pSnd->spectrum);
690
691     /* Merge the decoded spectrum and tonal components. */
692     lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
693
694
695     /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
696     numBands = (subbandTab[numSubbands] - 1) >> 8;
697     if (lastTonal >= 0)
698         numBands = FFMAX((lastTonal + 256) >> 8, numBands);
699
700
701     /* Reconstruct time domain samples. */
702     for (band=0; band<4; band++) {
703         /* Perform the IMDCT step without overlapping. */
704         if (band <= numBands) {
705             IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
706         } else
707             memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
708
709         /* gain compensation and overlapping */
710         gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),
711                                     &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),
712                                     &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));
713     }
714
715     /* Swap the gain control buffers for the next frame. */
716     pSnd->gcBlkSwitch ^= 1;
717
718     return 0;
719 }
720
721 /**
722  * Frame handling
723  *
724  * @param q             Atrac3 private context
725  * @param databuf       the input data
726  */
727
728 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
729                        float **out_samples)
730 {
731     int   result, i;
732     float   *p1, *p2, *p3, *p4;
733     uint8_t *ptr1;
734
735     if (q->codingMode == JOINT_STEREO) {
736
737         /* channel coupling mode */
738         /* decode Sound Unit 1 */
739         init_get_bits(&q->gb,databuf,q->bits_per_frame);
740
741         result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
742         if (result != 0)
743             return (result);
744
745         /* Framedata of the su2 in the joint-stereo mode is encoded in
746          * reverse byte order so we need to swap it first. */
747         if (databuf == q->decoded_bytes_buffer) {
748             uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
749             ptr1 = q->decoded_bytes_buffer;
750             for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
751                 FFSWAP(uint8_t,*ptr1,*ptr2);
752             }
753         } else {
754             const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
755             for (i = 0; i < q->bytes_per_frame; i++)
756                 q->decoded_bytes_buffer[i] = *ptr2--;
757         }
758
759         /* Skip the sync codes (0xF8). */
760         ptr1 = q->decoded_bytes_buffer;
761         for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
762             if (i >= q->bytes_per_frame)
763                 return AVERROR_INVALIDDATA;
764         }
765
766
767         /* set the bitstream reader at the start of the second Sound Unit*/
768         init_get_bits(&q->gb,ptr1,q->bits_per_frame);
769
770         /* Fill the Weighting coeffs delay buffer */
771         memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
772         q->weighting_delay[4] = get_bits1(&q->gb);
773         q->weighting_delay[5] = get_bits(&q->gb,3);
774
775         for (i = 0; i < 4; i++) {
776             q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
777             q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
778             q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
779         }
780
781         /* Decode Sound Unit 2. */
782         result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
783         if (result != 0)
784             return (result);
785
786         /* Reconstruct the channel coefficients. */
787         reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
788
789         channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
790
791     } else {
792         /* normal stereo mode or mono */
793         /* Decode the channel sound units. */
794         for (i=0 ; i<q->channels ; i++) {
795
796             /* Set the bitstream reader at the start of a channel sound unit. */
797             init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels), (q->bits_per_frame)/q->channels);
798
799             result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
800             if (result != 0)
801                 return (result);
802         }
803     }
804
805     /* Apply the iQMF synthesis filter. */
806     for (i=0 ; i<q->channels ; i++) {
807         p1 = out_samples[i];
808         p2= p1+256;
809         p3= p2+256;
810         p4= p3+256;
811         atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
812         atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
813         atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
814     }
815
816     return 0;
817 }
818
819
820 /**
821  * Atrac frame decoding
822  *
823  * @param avctx     pointer to the AVCodecContext
824  */
825
826 static int atrac3_decode_frame(AVCodecContext *avctx,
827             void *data, int *data_size,
828             AVPacket *avpkt) {
829     const uint8_t *buf = avpkt->data;
830     int buf_size = avpkt->size;
831     ATRAC3Context *q = avctx->priv_data;
832     int result = 0, out_size;
833     const uint8_t* databuf;
834     float   *samples_flt = data;
835     int16_t *samples_s16 = data;
836
837     if (buf_size < avctx->block_align) {
838         av_log(avctx, AV_LOG_ERROR,
839                "Frame too small (%d bytes). Truncated file?\n", buf_size);
840         return AVERROR_INVALIDDATA;
841     }
842
843     out_size = SAMPLES_PER_FRAME * q->channels *
844                av_get_bytes_per_sample(avctx->sample_fmt);
845     if (*data_size < out_size) {
846         av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
847         return AVERROR(EINVAL);
848     }
849
850     /* Check if we need to descramble and what buffer to pass on. */
851     if (q->scrambled_stream) {
852         decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
853         databuf = q->decoded_bytes_buffer;
854     } else {
855         databuf = buf;
856     }
857
858     if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
859         result = decodeFrame(q, databuf, &samples_flt);
860     else
861         result = decodeFrame(q, databuf, q->outSamples);
862
863     if (result != 0) {
864         av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
865         return result;
866     }
867
868     /* interleave */
869     if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
870         q->fmt_conv.float_interleave(samples_flt,
871                                      (const float **)q->outSamples,
872                                      SAMPLES_PER_FRAME, 2);
873     } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
874         q->fmt_conv.float_to_int16_interleave(samples_s16,
875                                               (const float **)q->outSamples,
876                                               SAMPLES_PER_FRAME, q->channels);
877     }
878     *data_size = out_size;
879
880     return avctx->block_align;
881 }
882
883
884 /**
885  * Atrac3 initialization
886  *
887  * @param avctx     pointer to the AVCodecContext
888  */
889
890 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
891 {
892     int i, ret;
893     const uint8_t *edata_ptr = avctx->extradata;
894     ATRAC3Context *q = avctx->priv_data;
895     static VLC_TYPE atrac3_vlc_table[4096][2];
896     static int vlcs_initialized = 0;
897
898     /* Take data from the AVCodecContext (RM container). */
899     q->sample_rate = avctx->sample_rate;
900     q->channels = avctx->channels;
901     q->bit_rate = avctx->bit_rate;
902     q->bits_per_frame = avctx->block_align * 8;
903     q->bytes_per_frame = avctx->block_align;
904
905     /* Take care of the codec-specific extradata. */
906     if (avctx->extradata_size == 14) {
907         /* Parse the extradata, WAV format */
908         av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown value always 1
909         q->samples_per_channel = bytestream_get_le32(&edata_ptr);
910         q->codingMode = bytestream_get_le16(&edata_ptr);
911         av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
912         q->frame_factor = bytestream_get_le16(&edata_ptr);  //Unknown always 1
913         av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown always 0
914
915         /* setup */
916         q->samples_per_frame = SAMPLES_PER_FRAME * q->channels;
917         q->atrac3version = 4;
918         q->delay = 0x88E;
919         if (q->codingMode)
920             q->codingMode = JOINT_STEREO;
921         else
922             q->codingMode = STEREO;
923
924         q->scrambled_stream = 0;
925
926         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)) {
927         } else {
928             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);
929             return AVERROR_INVALIDDATA;
930         }
931
932     } else if (avctx->extradata_size == 10) {
933         /* Parse the extradata, RM format. */
934         q->atrac3version = bytestream_get_be32(&edata_ptr);
935         q->samples_per_frame = bytestream_get_be16(&edata_ptr);
936         q->delay = bytestream_get_be16(&edata_ptr);
937         q->codingMode = bytestream_get_be16(&edata_ptr);
938
939         q->samples_per_channel = q->samples_per_frame / q->channels;
940         q->scrambled_stream = 1;
941
942     } else {
943         av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
944     }
945     /* Check the extradata. */
946
947     if (q->atrac3version != 4) {
948         av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
949         return AVERROR_INVALIDDATA;
950     }
951
952     if (q->samples_per_frame != SAMPLES_PER_FRAME && q->samples_per_frame != SAMPLES_PER_FRAME*2) {
953         av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
954         return AVERROR_INVALIDDATA;
955     }
956
957     if (q->delay != 0x88E) {
958         av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
959         return AVERROR_INVALIDDATA;
960     }
961
962     if (q->codingMode == STEREO) {
963         av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
964     } else if (q->codingMode == JOINT_STEREO) {
965         av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
966     } else {
967         av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
968         return AVERROR_INVALIDDATA;
969     }
970
971     if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
972         av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
973         return AVERROR(EINVAL);
974     }
975
976
977     if(avctx->block_align >= UINT_MAX/2)
978         return AVERROR(EINVAL);
979
980     /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
981      * this is for the bitstream reader. */
982     if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)))  == NULL)
983         return AVERROR(ENOMEM);
984
985
986     /* Initialize the VLC tables. */
987     if (!vlcs_initialized) {
988         for (i=0 ; i<7 ; i++) {
989             spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
990             spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
991             init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
992                 huff_bits[i], 1, 1,
993                 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
994         }
995         vlcs_initialized = 1;
996     }
997
998     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
999         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
1000     else
1001         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1002
1003     if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
1004         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
1005         av_freep(&q->decoded_bytes_buffer);
1006         return ret;
1007     }
1008
1009     atrac_generate_tables();
1010
1011     /* Generate gain tables. */
1012     for (i=0 ; i<16 ; i++)
1013         gain_tab1[i] = powf (2.0, (4 - i));
1014
1015     for (i=-15 ; i<16 ; i++)
1016         gain_tab2[i+15] = powf (2.0, i * -0.125);
1017
1018     /* init the joint-stereo decoding data */
1019     q->weighting_delay[0] = 0;
1020     q->weighting_delay[1] = 7;
1021     q->weighting_delay[2] = 0;
1022     q->weighting_delay[3] = 7;
1023     q->weighting_delay[4] = 0;
1024     q->weighting_delay[5] = 7;
1025
1026     for (i=0; i<4; i++) {
1027         q->matrix_coeff_index_prev[i] = 3;
1028         q->matrix_coeff_index_now[i] = 3;
1029         q->matrix_coeff_index_next[i] = 3;
1030     }
1031
1032     dsputil_init(&dsp, avctx);
1033     ff_fmt_convert_init(&q->fmt_conv, avctx);
1034
1035     q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
1036     if (!q->pUnits) {
1037         atrac3_decode_close(avctx);
1038         return AVERROR(ENOMEM);
1039     }
1040
1041     if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
1042         q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
1043         q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
1044         if (!q->outSamples[0]) {
1045             atrac3_decode_close(avctx);
1046             return AVERROR(ENOMEM);
1047         }
1048     }
1049
1050     return 0;
1051 }
1052
1053
1054 AVCodec ff_atrac3_decoder =
1055 {
1056     .name = "atrac3",
1057     .type = AVMEDIA_TYPE_AUDIO,
1058     .id = CODEC_ID_ATRAC3,
1059     .priv_data_size = sizeof(ATRAC3Context),
1060     .init = atrac3_decode_init,
1061     .close = atrac3_decode_close,
1062     .decode = atrac3_decode_frame,
1063     .capabilities = CODEC_CAP_SUBFRAMES,
1064     .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1065 };