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