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