]> git.sesse.net Git - ffmpeg/blob - libavcodec/atrac3.c
Simplify RGB32 png encoding.
[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 "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     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     float              *outSamples[2];
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 } 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 static DSPContext       dsp;
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     dsp.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, int is_float) {
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, is_float ? 1.0 / 32768 : 1.0);
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     av_freep(&q->outSamples[0]);
230
231     ff_mdct_end(&q->mdct_ctx);
232
233     return 0;
234 }
235
236 /**
237 / * Mantissa decoding
238  *
239  * @param gb            the GetBit context
240  * @param selector      what table is the output values coded with
241  * @param codingFlag    constant length coding or variable length coding
242  * @param mantissas     mantissa output table
243  * @param numCodes      amount of values to get
244  */
245
246 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
247 {
248     int   numBits, cnt, code, huffSymb;
249
250     if (selector == 1)
251         numCodes /= 2;
252
253     if (codingFlag != 0) {
254         /* constant length coding (CLC) */
255         numBits = CLCLengthTab[selector];
256
257         if (selector > 1) {
258             for (cnt = 0; cnt < numCodes; cnt++) {
259                 if (numBits)
260                     code = get_sbits(gb, numBits);
261                 else
262                     code = 0;
263                 mantissas[cnt] = code;
264             }
265         } else {
266             for (cnt = 0; cnt < numCodes; cnt++) {
267                 if (numBits)
268                     code = get_bits(gb, numBits); //numBits is always 4 in this case
269                 else
270                     code = 0;
271                 mantissas[cnt*2] = seTab_0[code >> 2];
272                 mantissas[cnt*2+1] = seTab_0[code & 3];
273             }
274         }
275     } else {
276         /* variable length coding (VLC) */
277         if (selector != 1) {
278             for (cnt = 0; cnt < numCodes; cnt++) {
279                 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
280                 huffSymb += 1;
281                 code = huffSymb >> 1;
282                 if (huffSymb & 1)
283                     code = -code;
284                 mantissas[cnt] = code;
285             }
286         } else {
287             for (cnt = 0; cnt < numCodes; cnt++) {
288                 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
289                 mantissas[cnt*2] = decTable1[huffSymb*2];
290                 mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
291             }
292         }
293     }
294 }
295
296 /**
297  * Restore the quantized band spectrum coefficients
298  *
299  * @param gb            the GetBit context
300  * @param pOut          decoded band spectrum
301  * @return outSubbands   subband counter, fix for broken specification/files
302  */
303
304 static int decodeSpectrum (GetBitContext *gb, float *pOut)
305 {
306     int   numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
307     int   subband_vlc_index[32], SF_idxs[32];
308     int   mantissas[128];
309     float SF;
310
311     numSubbands = get_bits(gb, 5); // number of coded subbands
312     codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
313
314     /* Get the VLC selector table for the subbands, 0 means not coded. */
315     for (cnt = 0; cnt <= numSubbands; cnt++)
316         subband_vlc_index[cnt] = get_bits(gb, 3);
317
318     /* Read the scale factor indexes from the stream. */
319     for (cnt = 0; cnt <= numSubbands; cnt++) {
320         if (subband_vlc_index[cnt] != 0)
321             SF_idxs[cnt] = get_bits(gb, 6);
322     }
323
324     for (cnt = 0; cnt <= numSubbands; cnt++) {
325         first = subbandTab[cnt];
326         last = subbandTab[cnt+1];
327
328         subbWidth = last - first;
329
330         if (subband_vlc_index[cnt] != 0) {
331             /* Decode spectral coefficients for this subband. */
332             /* TODO: This can be done faster is several blocks share the
333              * same VLC selector (subband_vlc_index) */
334             readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
335
336             /* Decode the scale factor for this subband. */
337             SF = ff_atrac_sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
338
339             /* Inverse quantize the coefficients. */
340             for (pIn=mantissas ; first<last; first++, pIn++)
341                 pOut[first] = *pIn * SF;
342         } else {
343             /* This subband was not coded, so zero the entire subband. */
344             memset(pOut+first, 0, subbWidth*sizeof(float));
345         }
346     }
347
348     /* Clear the subbands that were not coded. */
349     first = subbandTab[cnt];
350     memset(pOut+first, 0, (SAMPLES_PER_FRAME - first) * sizeof(float));
351     return numSubbands;
352 }
353
354 /**
355  * Restore the quantized tonal components
356  *
357  * @param gb            the GetBit context
358  * @param pComponent    tone component
359  * @param numBands      amount of coded bands
360  */
361
362 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
363 {
364     int i,j,k,cnt;
365     int   components, coding_mode_selector, coding_mode, coded_values_per_component;
366     int   sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
367     int   band_flags[4], mantissa[8];
368     float  *pCoef;
369     float  scalefactor;
370     int   component_count = 0;
371
372     components = get_bits(gb,5);
373
374     /* no tonal components */
375     if (components == 0)
376         return 0;
377
378     coding_mode_selector = get_bits(gb,2);
379     if (coding_mode_selector == 2)
380         return AVERROR_INVALIDDATA;
381
382     coding_mode = coding_mode_selector & 1;
383
384     for (i = 0; i < components; i++) {
385         for (cnt = 0; cnt <= numBands; cnt++)
386             band_flags[cnt] = get_bits1(gb);
387
388         coded_values_per_component = get_bits(gb,3);
389
390         quant_step_index = get_bits(gb,3);
391         if (quant_step_index <= 1)
392             return AVERROR_INVALIDDATA;
393
394         if (coding_mode_selector == 3)
395             coding_mode = get_bits1(gb);
396
397         for (j = 0; j < (numBands + 1) * 4; j++) {
398             if (band_flags[j >> 2] == 0)
399                 continue;
400
401             coded_components = get_bits(gb,3);
402
403             for (k=0; k<coded_components; k++) {
404                 sfIndx = get_bits(gb,6);
405                 if(component_count>=64)
406                     return AVERROR_INVALIDDATA;
407                 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
408                 max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;
409                 coded_values = coded_values_per_component + 1;
410                 coded_values = FFMIN(max_coded_values,coded_values);
411
412                 scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
413
414                 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
415
416                 pComponent[component_count].numCoefs = coded_values;
417
418                 /* inverse quant */
419                 pCoef = pComponent[component_count].coef;
420                 for (cnt = 0; cnt < coded_values; cnt++)
421                     pCoef[cnt] = mantissa[cnt] * scalefactor;
422
423                 component_count++;
424             }
425         }
426     }
427
428     return component_count;
429 }
430
431 /**
432  * Decode gain parameters for the coded bands
433  *
434  * @param gb            the GetBit context
435  * @param pGb           the gainblock for the current band
436  * @param numBands      amount of coded bands
437  */
438
439 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
440 {
441     int   i, cf, numData;
442     int   *pLevel, *pLoc;
443
444     gain_info   *pGain = pGb->gBlock;
445
446     for (i=0 ; i<=numBands; i++)
447     {
448         numData = get_bits(gb,3);
449         pGain[i].num_gain_data = numData;
450         pLevel = pGain[i].levcode;
451         pLoc = pGain[i].loccode;
452
453         for (cf = 0; cf < numData; cf++){
454             pLevel[cf]= get_bits(gb,4);
455             pLoc  [cf]= get_bits(gb,5);
456             if(cf && pLoc[cf] <= pLoc[cf-1])
457                 return AVERROR_INVALIDDATA;
458         }
459     }
460
461     /* Clear the unused blocks. */
462     for (; i<4 ; i++)
463         pGain[i].num_gain_data = 0;
464
465     return 0;
466 }
467
468 /**
469  * Apply gain parameters and perform the MDCT overlapping part
470  *
471  * @param pIn           input float buffer
472  * @param pPrev         previous float buffer to perform overlap against
473  * @param pOut          output float buffer
474  * @param pGain1        current band gain info
475  * @param pGain2        next band gain info
476  */
477
478 static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
479 {
480     /* gain compensation function */
481     float  gain1, gain2, gain_inc;
482     int   cnt, numdata, nsample, startLoc, endLoc;
483
484
485     if (pGain2->num_gain_data == 0)
486         gain1 = 1.0;
487     else
488         gain1 = gain_tab1[pGain2->levcode[0]];
489
490     if (pGain1->num_gain_data == 0) {
491         for (cnt = 0; cnt < 256; cnt++)
492             pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
493     } else {
494         numdata = pGain1->num_gain_data;
495         pGain1->loccode[numdata] = 32;
496         pGain1->levcode[numdata] = 4;
497
498         nsample = 0; // current sample = 0
499
500         for (cnt = 0; cnt < numdata; cnt++) {
501             startLoc = pGain1->loccode[cnt] * 8;
502             endLoc = startLoc + 8;
503
504             gain2 = gain_tab1[pGain1->levcode[cnt]];
505             gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
506
507             /* interpolate */
508             for (; nsample < startLoc; nsample++)
509                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
510
511             /* interpolation is done over eight samples */
512             for (; nsample < endLoc; nsample++) {
513                 pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
514                 gain2 *= gain_inc;
515             }
516         }
517
518         for (; nsample < 256; nsample++)
519             pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
520     }
521
522     /* Delay for the overlapping part. */
523     memcpy(pPrev, &pIn[256], 256*sizeof(float));
524 }
525
526 /**
527  * Combine the tonal band spectrum and regular band spectrum
528  * Return position of the last tonal coefficient
529  *
530  * @param pSpectrum     output spectrum buffer
531  * @param numComponents amount of tonal components
532  * @param pComponent    tonal components for this band
533  */
534
535 static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
536 {
537     int   cnt, i, lastPos = -1;
538     float   *pIn, *pOut;
539
540     for (cnt = 0; cnt < numComponents; cnt++){
541         lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
542         pIn = pComponent[cnt].coef;
543         pOut = &(pSpectrum[pComponent[cnt].pos]);
544
545         for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
546             pOut[i] += pIn[i];
547     }
548
549     return lastPos;
550 }
551
552
553 #define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
554
555 static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
556 {
557     int    i, band, nsample, s1, s2;
558     float    c1, c2;
559     float    mc1_l, mc1_r, mc2_l, mc2_r;
560
561     for (i=0,band = 0; band < 4*256; band+=256,i++) {
562         s1 = pPrevCode[i];
563         s2 = pCurrCode[i];
564         nsample = 0;
565
566         if (s1 != s2) {
567             /* Selector value changed, interpolation needed. */
568             mc1_l = matrixCoeffs[s1*2];
569             mc1_r = matrixCoeffs[s1*2+1];
570             mc2_l = matrixCoeffs[s2*2];
571             mc2_r = matrixCoeffs[s2*2+1];
572
573             /* Interpolation is done over the first eight samples. */
574             for(; nsample < 8; nsample++) {
575                 c1 = su1[band+nsample];
576                 c2 = su2[band+nsample];
577                 c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
578                 su1[band+nsample] = c2;
579                 su2[band+nsample] = c1 * 2.0 - c2;
580             }
581         }
582
583         /* Apply the matrix without interpolation. */
584         switch (s2) {
585             case 0:     /* M/S decoding */
586                 for (; nsample < 256; nsample++) {
587                     c1 = su1[band+nsample];
588                     c2 = su2[band+nsample];
589                     su1[band+nsample] = c2 * 2.0;
590                     su2[band+nsample] = (c1 - c2) * 2.0;
591                 }
592                 break;
593
594             case 1:
595                 for (; nsample < 256; nsample++) {
596                     c1 = su1[band+nsample];
597                     c2 = su2[band+nsample];
598                     su1[band+nsample] = (c1 + c2) * 2.0;
599                     su2[band+nsample] = c2 * -2.0;
600                 }
601                 break;
602             case 2:
603             case 3:
604                 for (; nsample < 256; nsample++) {
605                     c1 = su1[band+nsample];
606                     c2 = su2[band+nsample];
607                     su1[band+nsample] = c1 + c2;
608                     su2[band+nsample] = c1 - c2;
609                 }
610                 break;
611             default:
612                 assert(0);
613         }
614     }
615 }
616
617 static void getChannelWeights (int indx, int flag, float ch[2]){
618
619     if (indx == 7) {
620         ch[0] = 1.0;
621         ch[1] = 1.0;
622     } else {
623         ch[0] = (float)(indx & 7) / 7.0;
624         ch[1] = sqrt(2 - ch[0]*ch[0]);
625         if(flag)
626             FFSWAP(float, ch[0], ch[1]);
627     }
628 }
629
630 static void channelWeighting (float *su1, float *su2, int *p3)
631 {
632     int   band, nsample;
633     /* w[x][y] y=0 is left y=1 is right */
634     float w[2][2];
635
636     if (p3[1] != 7 || p3[3] != 7){
637         getChannelWeights(p3[1], p3[0], w[0]);
638         getChannelWeights(p3[3], p3[2], w[1]);
639
640         for(band = 1; band < 4; band++) {
641             /* scale the channels by the weights */
642             for(nsample = 0; nsample < 8; nsample++) {
643                 su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
644                 su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
645             }
646
647             for(; nsample < 256; nsample++) {
648                 su1[band*256+nsample] *= w[1][0];
649                 su2[band*256+nsample] *= w[1][1];
650             }
651         }
652     }
653 }
654
655
656 /**
657  * Decode a Sound Unit
658  *
659  * @param gb            the GetBit context
660  * @param pSnd          the channel unit to be used
661  * @param pOut          the decoded samples before IQMF in float representation
662  * @param channelNum    channel number
663  * @param codingMode    the coding mode (JOINT_STEREO or regular stereo/mono)
664  */
665
666
667 static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
668 {
669     int   band, result=0, numSubbands, lastTonal, numBands;
670
671     if (codingMode == JOINT_STEREO && channelNum == 1) {
672         if (get_bits(gb,2) != 3) {
673             av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
674             return AVERROR_INVALIDDATA;
675         }
676     } else {
677         if (get_bits(gb,6) != 0x28) {
678             av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
679             return AVERROR_INVALIDDATA;
680         }
681     }
682
683     /* number of coded QMF bands */
684     pSnd->bandsCoded = get_bits(gb,2);
685
686     result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
687     if (result) return result;
688
689     pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
690     if (pSnd->numComponents == -1) return -1;
691
692     numSubbands = decodeSpectrum (gb, pSnd->spectrum);
693
694     /* Merge the decoded spectrum and tonal components. */
695     lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
696
697
698     /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
699     numBands = (subbandTab[numSubbands] - 1) >> 8;
700     if (lastTonal >= 0)
701         numBands = FFMAX((lastTonal + 256) >> 8, numBands);
702
703
704     /* Reconstruct time domain samples. */
705     for (band=0; band<4; band++) {
706         /* Perform the IMDCT step without overlapping. */
707         if (band <= numBands) {
708             IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
709         } else
710             memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
711
712         /* gain compensation and overlapping */
713         gainCompensateAndOverlap(pSnd->IMDCT_buf, &pSnd->prevFrame[band * 256],
714                                  &pOut[band * 256],
715                                  &pSnd->gainBlock[1 - pSnd->gcBlkSwitch].gBlock[band],
716                                  &pSnd->gainBlock[    pSnd->gcBlkSwitch].gBlock[band]);
717     }
718
719     /* Swap the gain control buffers for the next frame. */
720     pSnd->gcBlkSwitch ^= 1;
721
722     return 0;
723 }
724
725 /**
726  * Frame handling
727  *
728  * @param q             Atrac3 private context
729  * @param databuf       the input data
730  */
731
732 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
733                        float **out_samples)
734 {
735     int   result, i;
736     float   *p1, *p2, *p3, *p4;
737     uint8_t *ptr1;
738
739     if (q->codingMode == JOINT_STEREO) {
740
741         /* channel coupling mode */
742         /* decode Sound Unit 1 */
743         init_get_bits(&q->gb,databuf,q->bits_per_frame);
744
745         result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
746         if (result != 0)
747             return result;
748
749         /* Framedata of the su2 in the joint-stereo mode is encoded in
750          * reverse byte order so we need to swap it first. */
751         if (databuf == q->decoded_bytes_buffer) {
752             uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
753             ptr1 = q->decoded_bytes_buffer;
754             for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
755                 FFSWAP(uint8_t,*ptr1,*ptr2);
756             }
757         } else {
758             const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
759             for (i = 0; i < q->bytes_per_frame; i++)
760                 q->decoded_bytes_buffer[i] = *ptr2--;
761         }
762
763         /* Skip the sync codes (0xF8). */
764         ptr1 = q->decoded_bytes_buffer;
765         for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
766             if (i >= q->bytes_per_frame)
767                 return AVERROR_INVALIDDATA;
768         }
769
770
771         /* set the bitstream reader at the start of the second Sound Unit*/
772         init_get_bits(&q->gb,ptr1,q->bits_per_frame);
773
774         /* Fill the Weighting coeffs delay buffer */
775         memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
776         q->weighting_delay[4] = get_bits1(&q->gb);
777         q->weighting_delay[5] = get_bits(&q->gb,3);
778
779         for (i = 0; i < 4; i++) {
780             q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
781             q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
782             q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
783         }
784
785         /* Decode Sound Unit 2. */
786         result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
787         if (result != 0)
788             return result;
789
790         /* Reconstruct the channel coefficients. */
791         reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
792
793         channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
794
795     } else {
796         /* normal stereo mode or mono */
797         /* Decode the channel sound units. */
798         for (i=0 ; i<q->channels ; i++) {
799
800             /* Set the bitstream reader at the start of a channel sound unit. */
801             init_get_bits(&q->gb,
802                           databuf + i * q->bytes_per_frame / q->channels,
803                           q->bits_per_frame / q->channels);
804
805             result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
806             if (result != 0)
807                 return result;
808         }
809     }
810
811     /* Apply the iQMF synthesis filter. */
812     for (i=0 ; i<q->channels ; i++) {
813         p1 = out_samples[i];
814         p2= p1+256;
815         p3= p2+256;
816         p4= p3+256;
817         atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
818         atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
819         atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
820     }
821
822     return 0;
823 }
824
825
826 /**
827  * Atrac frame decoding
828  *
829  * @param avctx     pointer to the AVCodecContext
830  */
831
832 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
833                                int *got_frame_ptr, AVPacket *avpkt)
834 {
835     const uint8_t *buf = avpkt->data;
836     int buf_size = avpkt->size;
837     ATRAC3Context *q = avctx->priv_data;
838     int result;
839     const uint8_t* databuf;
840     float   *samples_flt;
841     int16_t *samples_s16;
842
843     if (buf_size < avctx->block_align) {
844         av_log(avctx, AV_LOG_ERROR,
845                "Frame too small (%d bytes). Truncated file?\n", buf_size);
846         return AVERROR_INVALIDDATA;
847     }
848
849     /* get output buffer */
850     q->frame.nb_samples = SAMPLES_PER_FRAME;
851     if ((result = avctx->get_buffer(avctx, &q->frame)) < 0) {
852         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
853         return result;
854     }
855     samples_flt = (float   *)q->frame.data[0];
856     samples_s16 = (int16_t *)q->frame.data[0];
857
858     /* Check if we need to descramble and what buffer to pass on. */
859     if (q->scrambled_stream) {
860         decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
861         databuf = q->decoded_bytes_buffer;
862     } else {
863         databuf = buf;
864     }
865
866     if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
867         result = decodeFrame(q, databuf, &samples_flt);
868     else
869         result = decodeFrame(q, databuf, q->outSamples);
870
871     if (result != 0) {
872         av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
873         return result;
874     }
875
876     /* interleave */
877     if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
878         q->fmt_conv.float_interleave(samples_flt,
879                                      (const float **)q->outSamples,
880                                      SAMPLES_PER_FRAME, 2);
881     } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
882         q->fmt_conv.float_to_int16_interleave(samples_s16,
883                                               (const float **)q->outSamples,
884                                               SAMPLES_PER_FRAME, q->channels);
885     }
886
887     *got_frame_ptr   = 1;
888     *(AVFrame *)data = q->frame;
889
890     return avctx->block_align;
891 }
892
893
894 /**
895  * Atrac3 initialization
896  *
897  * @param avctx     pointer to the AVCodecContext
898  */
899
900 static av_cold int atrac3_decode_init(AVCodecContext *avctx)
901 {
902     int i, ret;
903     const uint8_t *edata_ptr = avctx->extradata;
904     ATRAC3Context *q = avctx->priv_data;
905     static VLC_TYPE atrac3_vlc_table[4096][2];
906     static int vlcs_initialized = 0;
907
908     /* Take data from the AVCodecContext (RM container). */
909     q->sample_rate = avctx->sample_rate;
910     q->channels = avctx->channels;
911     q->bit_rate = avctx->bit_rate;
912     q->bits_per_frame = avctx->block_align * 8;
913     q->bytes_per_frame = avctx->block_align;
914
915     /* Take care of the codec-specific extradata. */
916     if (avctx->extradata_size == 14) {
917         /* Parse the extradata, WAV format */
918         av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown value always 1
919         q->samples_per_channel = bytestream_get_le32(&edata_ptr);
920         q->codingMode = bytestream_get_le16(&edata_ptr);
921         av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr));  //Dupe of coding mode
922         q->frame_factor = bytestream_get_le16(&edata_ptr);  //Unknown always 1
923         av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr));  //Unknown always 0
924
925         /* setup */
926         q->samples_per_frame = SAMPLES_PER_FRAME * q->channels;
927         q->atrac3version = 4;
928         q->delay = 0x88E;
929         if (q->codingMode)
930             q->codingMode = JOINT_STEREO;
931         else
932             q->codingMode = STEREO;
933
934         q->scrambled_stream = 0;
935
936         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)) {
937         } else {
938             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);
939             return AVERROR_INVALIDDATA;
940         }
941
942     } else if (avctx->extradata_size == 10) {
943         /* Parse the extradata, RM format. */
944         q->atrac3version = bytestream_get_be32(&edata_ptr);
945         q->samples_per_frame = bytestream_get_be16(&edata_ptr);
946         q->delay = bytestream_get_be16(&edata_ptr);
947         q->codingMode = bytestream_get_be16(&edata_ptr);
948
949         q->samples_per_channel = q->samples_per_frame / q->channels;
950         q->scrambled_stream = 1;
951
952     } else {
953         av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
954     }
955     /* Check the extradata. */
956
957     if (q->atrac3version != 4) {
958         av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
959         return AVERROR_INVALIDDATA;
960     }
961
962     if (q->samples_per_frame != SAMPLES_PER_FRAME && q->samples_per_frame != SAMPLES_PER_FRAME*2) {
963         av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
964         return AVERROR_INVALIDDATA;
965     }
966
967     if (q->delay != 0x88E) {
968         av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
969         return AVERROR_INVALIDDATA;
970     }
971
972     if (q->codingMode == STEREO) {
973         av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
974     } else if (q->codingMode == JOINT_STEREO) {
975         av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
976     } else {
977         av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
978         return AVERROR_INVALIDDATA;
979     }
980
981     if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
982         av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
983         return AVERROR(EINVAL);
984     }
985
986
987     if(avctx->block_align >= UINT_MAX/2)
988         return AVERROR(EINVAL);
989
990     /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
991      * this is for the bitstream reader. */
992     if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)))  == NULL)
993         return AVERROR(ENOMEM);
994
995
996     /* Initialize the VLC tables. */
997     if (!vlcs_initialized) {
998         for (i=0 ; i<7 ; i++) {
999             spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
1000             spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
1001             init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
1002                 huff_bits[i], 1, 1,
1003                 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
1004         }
1005         vlcs_initialized = 1;
1006     }
1007
1008     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
1009         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
1010     else
1011         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1012
1013     if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
1014         av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
1015         av_freep(&q->decoded_bytes_buffer);
1016         return ret;
1017     }
1018
1019     atrac_generate_tables();
1020
1021     /* Generate gain tables. */
1022     for (i=0 ; i<16 ; i++)
1023         gain_tab1[i] = powf (2.0, (4 - i));
1024
1025     for (i=-15 ; i<16 ; i++)
1026         gain_tab2[i+15] = powf (2.0, i * -0.125);
1027
1028     /* init the joint-stereo decoding data */
1029     q->weighting_delay[0] = 0;
1030     q->weighting_delay[1] = 7;
1031     q->weighting_delay[2] = 0;
1032     q->weighting_delay[3] = 7;
1033     q->weighting_delay[4] = 0;
1034     q->weighting_delay[5] = 7;
1035
1036     for (i=0; i<4; i++) {
1037         q->matrix_coeff_index_prev[i] = 3;
1038         q->matrix_coeff_index_now[i] = 3;
1039         q->matrix_coeff_index_next[i] = 3;
1040     }
1041
1042     dsputil_init(&dsp, avctx);
1043     ff_fmt_convert_init(&q->fmt_conv, avctx);
1044
1045     q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
1046     if (!q->pUnits) {
1047         atrac3_decode_close(avctx);
1048         return AVERROR(ENOMEM);
1049     }
1050
1051     if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
1052         q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
1053         q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
1054         if (!q->outSamples[0]) {
1055             atrac3_decode_close(avctx);
1056             return AVERROR(ENOMEM);
1057         }
1058     }
1059
1060     avcodec_get_frame_defaults(&q->frame);
1061     avctx->coded_frame = &q->frame;
1062
1063     return 0;
1064 }
1065
1066
1067 AVCodec ff_atrac3_decoder =
1068 {
1069     .name = "atrac3",
1070     .type = AVMEDIA_TYPE_AUDIO,
1071     .id = CODEC_ID_ATRAC3,
1072     .priv_data_size = sizeof(ATRAC3Context),
1073     .init = atrac3_decode_init,
1074     .close = atrac3_decode_close,
1075     .decode = atrac3_decode_frame,
1076     .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1077     .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1078 };