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