Submit interim version of FS#10565. Performance optimization of atrac3 decoder for...
[kugel-rb.git] / apps / codecs / libatrac / atrac3.c
blob9ea2be8775891fd7b274b60bd1c410989ebe82cf
1 /*
2 * Atrac 3 compatible decoder
3 * Copyright (c) 2006-2008 Maxim Poliakovski
4 * Copyright (c) 2006-2008 Benjamin Larsson
6 * This file is part of FFmpeg.
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.
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.
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
23 /**
24 * @file libavcodec/atrac3.c
25 * Atrac 3 compatible decoder.
26 * This decoder handles Sony's ATRAC3 data.
28 * Container formats used to store atrac 3 data:
29 * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).
31 * To use this decoder, a calling application must supply the extradata
32 * bytes provided in the containers above.
35 #include <math.h>
36 #include <stddef.h>
37 #include <stdio.h>
39 #include "atrac3.h"
40 #include "atrac3data.h"
41 #include "atrac3data_fixed.h"
42 #include "fixp_math.h"
43 #include "../lib/mdct2.h"
45 #define JOINT_STEREO 0x12
46 #define STEREO 0x2
48 #ifdef ROCKBOX
49 #undef DEBUGF
50 #define DEBUGF(...)
51 #endif /* ROCKBOX */
53 /* FFMAX/MIN/SWAP and av_clip were taken from libavutil/common.h */
54 #define FFMAX(a,b) ((a) > (b) ? (a) : (b))
55 #define FFMIN(a,b) ((a) > (b) ? (b) : (a))
56 #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0)
58 /**
59 * Clips a signed integer value into the -32768,32767 range.
61 static inline int16_t av_clip_int16(int a)
63 if ((a+32768) & ~65535) return (a>>31) ^ 32767;
64 else return a;
67 static int32_t qmf_window[48] IBSS_ATTR;
68 static VLC spectral_coeff_tab[7];
69 static channel_unit channel_units[2];
71 /**
72 * Matrixing within quadrature mirror synthesis filter.
74 * @param p3 output buffer
75 * @param inlo lower part of spectrum
76 * @param inhi higher part of spectrum
77 * @param nIn size of spectrum buffer
80 #if defined(CPU_ARM)
81 extern void
82 atrac3_iqmf_matrixing(int32_t *p3,
83 int32_t *inlo,
84 int32_t *inhi,
85 unsigned int nIn);
86 #else
87 static inline void
88 atrac3_iqmf_matrixing(int32_t *p3,
89 int32_t *inlo,
90 int32_t *inhi,
91 unsigned int nIn)
93 for(i=0; i<nIn; i+=2){
94 p3[2*i+0] = inlo[i ] + inhi[i ];
95 p3[2*i+1] = inlo[i ] - inhi[i ];
96 p3[2*i+2] = inlo[i+1] + inhi[i+1];
97 p3[2*i+3] = inlo[i+1] - inhi[i+1];
100 #endif
103 * Matrixing within quadrature mirror synthesis filter.
105 * @param out output buffer
106 * @param in input buffer
107 * @param win windowing coefficients
108 * @param nIn size of spectrum buffer
111 #if defined(CPU_ARM)
112 extern void
113 atrac3_iqmf_dewindowing(int32_t *out,
114 int32_t *in,
115 int32_t *win,
116 unsigned int nIn);
117 #else
118 static inline void
119 atrac3_iqmf_dewindowing(int32_t *out,
120 int32_t *in,
121 int32_t *win,
122 unsigned int nIn)
124 int32_t i, j, s1, s2;
126 for (j = nIn; j != 0; j--) {
127 /* i=0 */
128 s1 = fixmul31(win[0], in[0]);
129 s2 = fixmul31(win[1], in[1]);
131 /* i=2..46 */
132 for (i = 2; i < 48; i += 2) {
133 s1 += fixmul31(win[i ], in[i ]);
134 s2 += fixmul31(win[i+1], in[i+1]);
137 out[0] = s2;
138 out[1] = s1;
140 in += 2;
141 out += 2;
144 #endif
147 * IMDCT windowing.
149 * @param buffer sample buffer
150 * @param win window coefficients
153 static inline void
154 atrac3_imdct_windowing(int32_t *buffer,
155 const int32_t *win)
157 int32_t i;
158 /* win[0..127] = win[511..384], win[128..383] = 1 */
159 for(i = 0; i<128; i++) {
160 buffer[ i] = fixmul31(win[i], buffer[ i]);
161 buffer[511-i] = fixmul31(win[i], buffer[511-i]);
166 * Quadrature mirror synthesis filter.
168 * @param inlo lower part of spectrum
169 * @param inhi higher part of spectrum
170 * @param nIn size of spectrum buffer
171 * @param pOut out buffer
172 * @param delayBuf delayBuf buffer
173 * @param temp temp buffer
176 static void iqmf (int32_t *inlo, int32_t *inhi, unsigned int nIn, int32_t *pOut, int32_t *delayBuf, int32_t *temp)
178 /* Restore the delay buffer */
179 memcpy(temp, delayBuf, 46*sizeof(int32_t));
181 /* loop1: matrixing */
182 atrac3_iqmf_matrixing(temp + 46, inlo, inhi, nIn);
184 /* loop2: dewindowing */
185 atrac3_iqmf_dewindowing(pOut, temp, qmf_window, nIn);
187 /* Save the delay buffer */
188 memcpy(delayBuf, temp + (nIn << 1), 46*sizeof(int32_t));
192 * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
193 * caused by the reverse spectra of the QMF.
195 * @param pInput float input
196 * @param pOutput float output
197 * @param odd_band 1 if the band is an odd band
200 static void IMLT(int32_t *pInput, int32_t *pOutput, int odd_band)
202 int i;
203 if (odd_band) {
205 * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
206 * or it gives better compression to do it this way.
207 * FIXME: It should be possible to handle this in ff_imdct_calc
208 * for that to happen a modification of the prerotation step of
209 * all SIMD code and C code is needed.
210 * Or fix the functions before so they generate a pre reversed spectrum.
213 for (i=0; i<128; i++)
214 FFSWAP(int32_t, pInput[i], pInput[255-i]);
217 /* Apply the imdct. */
218 mdct_backward(512, pInput, pOutput);
220 /* Windowing. */
221 atrac3_imdct_windowing(pOutput, window_lookup);
226 * Atrac 3 indata descrambling, only used for data coming from the rm container
228 * @param in pointer to 8 bit array of indata
229 * @param bits amount of bits
230 * @param out pointer to 8 bit array of outdata
233 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
234 int i, off;
235 uint32_t c;
236 const uint32_t* buf;
237 uint32_t* obuf = (uint32_t*) out;
239 #if ((defined(TEST) || defined(SIMULATOR)) && !defined(CPU_ARM))
240 off = 0; //no check for memory alignment of inbuffer
241 #else
242 off = (intptr_t)inbuffer & 3;
243 #endif /* TEST */
244 buf = (const uint32_t*) (inbuffer - off);
246 c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
247 bytes += 3 + off;
248 for (i = 0; i < bytes/4; i++)
249 obuf[i] = c ^ buf[i];
251 return off;
255 static void init_atrac3_transforms(void) {
256 int32_t s;
257 int i;
259 /* Generate the mdct window, for details see
260 * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
262 /* mdct window had been generated and saved as a lookup table in atrac3data_fixed.h */
264 /* Generate the QMF window. */
265 for (i=0 ; i<24; i++) {
266 s = qmf_48tap_half_fix[i] << 1;
267 qmf_window[i] = s;
268 qmf_window[47 - i] = s;
273 * Mantissa decoding
275 * @param gb the GetBit context
276 * @param selector what table is the output values coded with
277 * @param codingFlag constant length coding or variable length coding
278 * @param mantissas mantissa output table
279 * @param numCodes amount of values to get
282 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
284 int numBits, cnt, code, huffSymb;
286 if (selector == 1)
287 numCodes /= 2;
289 if (codingFlag != 0) {
290 /* constant length coding (CLC) */
291 numBits = CLCLengthTab[selector];
293 if (selector > 1) {
294 for (cnt = 0; cnt < numCodes; cnt++) {
295 if (numBits)
296 code = get_sbits(gb, numBits);
297 else
298 code = 0;
299 mantissas[cnt] = code;
301 } else {
302 for (cnt = 0; cnt < numCodes; cnt++) {
303 if (numBits)
304 code = get_bits(gb, numBits); //numBits is always 4 in this case
305 else
306 code = 0;
307 mantissas[cnt*2] = seTab_0[code >> 2];
308 mantissas[cnt*2+1] = seTab_0[code & 3];
311 } else {
312 /* variable length coding (VLC) */
313 if (selector != 1) {
314 for (cnt = 0; cnt < numCodes; cnt++) {
315 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
316 huffSymb += 1;
317 code = huffSymb >> 1;
318 if (huffSymb & 1)
319 code = -code;
320 mantissas[cnt] = code;
322 } else {
323 for (cnt = 0; cnt < numCodes; cnt++) {
324 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
325 mantissas[cnt*2] = decTable1[huffSymb*2];
326 mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
333 * Restore the quantized band spectrum coefficients
335 * @param gb the GetBit context
336 * @param pOut decoded band spectrum
337 * @return outSubbands subband counter, fix for broken specification/files
340 static int decodeSpectrum (GetBitContext *gb, int32_t *pOut)
342 int numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
343 int subband_vlc_index[32], SF_idxs[32];
344 int mantissas[128];
345 int32_t SF;
347 numSubbands = get_bits(gb, 5); // number of coded subbands
348 codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
350 /* Get the VLC selector table for the subbands, 0 means not coded. */
351 for (cnt = 0; cnt <= numSubbands; cnt++)
352 subband_vlc_index[cnt] = get_bits(gb, 3);
354 /* Read the scale factor indexes from the stream. */
355 for (cnt = 0; cnt <= numSubbands; cnt++) {
356 if (subband_vlc_index[cnt] != 0)
357 SF_idxs[cnt] = get_bits(gb, 6);
360 for (cnt = 0; cnt <= numSubbands; cnt++) {
361 first = subbandTab[cnt];
362 last = subbandTab[cnt+1];
364 subbWidth = last - first;
366 if (subband_vlc_index[cnt] != 0) {
367 /* Decode spectral coefficients for this subband. */
368 /* TODO: This can be done faster is several blocks share the
369 * same VLC selector (subband_vlc_index) */
370 readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
372 /* Decode the scale factor for this subband. */
373 SF = fixmul31(SFTable_fixed[SF_idxs[cnt]], iMaxQuant_fix[subband_vlc_index[cnt]]);
375 /* Inverse quantize the coefficients. */
376 for (pIn=mantissas ; first<last; first++, pIn++)
377 pOut[first] = fixmul16(*pIn, SF);
378 } else {
379 /* This subband was not coded, so zero the entire subband. */
380 memset(pOut+first, 0, subbWidth*sizeof(int32_t));
384 /* Clear the subbands that were not coded. */
385 first = subbandTab[cnt];
386 memset(pOut+first, 0, (1024 - first) * sizeof(int32_t));
387 return numSubbands;
391 * Restore the quantized tonal components
393 * @param gb the GetBit context
394 * @param pComponent tone component
395 * @param numBands amount of coded bands
398 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
400 int i,j,k,cnt;
401 int components, coding_mode_selector, coding_mode, coded_values_per_component;
402 int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
403 int band_flags[4], mantissa[8];
404 int32_t *pCoef;
405 int32_t scalefactor;
406 int component_count = 0;
408 components = get_bits(gb,5);
410 /* no tonal components */
411 if (components == 0)
412 return 0;
414 coding_mode_selector = get_bits(gb,2);
415 if (coding_mode_selector == 2)
416 return -1;
418 coding_mode = coding_mode_selector & 1;
420 for (i = 0; i < components; i++) {
421 for (cnt = 0; cnt <= numBands; cnt++)
422 band_flags[cnt] = get_bits1(gb);
424 coded_values_per_component = get_bits(gb,3);
426 quant_step_index = get_bits(gb,3);
427 if (quant_step_index <= 1)
428 return -1;
430 if (coding_mode_selector == 3)
431 coding_mode = get_bits1(gb);
433 for (j = 0; j < (numBands + 1) * 4; j++) {
434 if (band_flags[j >> 2] == 0)
435 continue;
437 coded_components = get_bits(gb,3);
439 for (k=0; k<coded_components; k++) {
440 sfIndx = get_bits(gb,6);
441 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
442 max_coded_values = 1024 - pComponent[component_count].pos;
443 coded_values = coded_values_per_component + 1;
444 coded_values = FFMIN(max_coded_values,coded_values);
446 scalefactor = fixmul31(SFTable_fixed[sfIndx], iMaxQuant_fix[quant_step_index]);
448 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
450 pComponent[component_count].numCoefs = coded_values;
452 /* inverse quant */
453 pCoef = pComponent[component_count].coef;
454 for (cnt = 0; cnt < coded_values; cnt++)
455 pCoef[cnt] = fixmul16(mantissa[cnt], scalefactor);
457 component_count++;
462 return component_count;
466 * Decode gain parameters for the coded bands
468 * @param gb the GetBit context
469 * @param pGb the gainblock for the current band
470 * @param numBands amount of coded bands
473 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
475 int i, cf, numData;
476 int *pLevel, *pLoc;
478 gain_info *pGain = pGb->gBlock;
480 for (i=0 ; i<=numBands; i++)
482 numData = get_bits(gb,3);
483 pGain[i].num_gain_data = numData;
484 pLevel = pGain[i].levcode;
485 pLoc = pGain[i].loccode;
487 for (cf = 0; cf < numData; cf++){
488 pLevel[cf]= get_bits(gb,4);
489 pLoc [cf]= get_bits(gb,5);
490 if(cf && pLoc[cf] <= pLoc[cf-1])
491 return -1;
495 /* Clear the unused blocks. */
496 for (; i<4 ; i++)
497 pGain[i].num_gain_data = 0;
499 return 0;
503 * Apply gain parameters and perform the MDCT overlapping part
505 * @param pIn input float buffer
506 * @param pPrev previous float buffer to perform overlap against
507 * @param pOut output float buffer
508 * @param pGain1 current band gain info
509 * @param pGain2 next band gain info
512 static void gainCompensateAndOverlap (int32_t *pIn, int32_t *pPrev, int32_t *pOut, gain_info *pGain1, gain_info *pGain2)
514 /* gain compensation function */
515 int32_t gain1, gain2, gain_inc;
516 int cnt, numdata, nsample, startLoc, endLoc;
519 if (pGain2->num_gain_data == 0)
520 gain1 = ONE_16;
521 else
522 gain1 = gain_tab1[pGain2->levcode[0]];
524 if (pGain1->num_gain_data == 0) {
525 for (cnt = 0; cnt < 256; cnt++)
526 pOut[cnt] = fixmul16(pIn[cnt], gain1) + pPrev[cnt];
527 } else {
528 numdata = pGain1->num_gain_data;
529 pGain1->loccode[numdata] = 32;
530 pGain1->levcode[numdata] = 4;
532 nsample = 0; // current sample = 0
534 for (cnt = 0; cnt < numdata; cnt++) {
535 startLoc = pGain1->loccode[cnt] * 8;
536 endLoc = startLoc + 8;
538 gain2 = gain_tab1[pGain1->levcode[cnt]];
539 gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
541 /* interpolate */
542 for (; nsample < startLoc; nsample++)
543 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]), gain2);
545 /* interpolation is done over eight samples */
546 for (; nsample < endLoc; nsample++) {
547 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]),gain2);
548 gain2 = fixmul16(gain2, gain_inc);
552 for (; nsample < 256; nsample++)
553 pOut[nsample] = fixmul16(pIn[nsample], gain1) + pPrev[nsample];
556 /* Delay for the overlapping part. */
557 memcpy(pPrev, &pIn[256], 256*sizeof(int32_t));
561 * Combine the tonal band spectrum and regular band spectrum
562 * Return position of the last tonal coefficient
565 * @param pSpectrum output spectrum buffer
566 * @param numComponents amount of tonal components
567 * @param pComponent tonal components for this band
570 static int addTonalComponents (int32_t *pSpectrum, int numComponents, tonal_component *pComponent)
572 int cnt, i, lastPos = -1;
573 int32_t *pOut;
574 int32_t *pIn;
576 for (cnt = 0; cnt < numComponents; cnt++){
577 lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
578 pIn = pComponent[cnt].coef;
579 pOut = &(pSpectrum[pComponent[cnt].pos]);
581 for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
582 pOut[i] += pIn[i];
585 return lastPos;
589 #define INTERPOLATE(old,new,nsample) ((old*ONE_16) + fixmul16(((nsample*ONE_16)>>3), (((new) - (old))*ONE_16)))
591 static void reverseMatrixing(int32_t *su1, int32_t *su2, int *pPrevCode, int *pCurrCode)
593 int i, band, nsample, s1, s2;
594 int32_t c1, c2;
595 int32_t mc1_l, mc1_r, mc2_l, mc2_r;
597 for (i=0,band = 0; band < 4*256; band+=256,i++) {
598 s1 = pPrevCode[i];
599 s2 = pCurrCode[i];
600 nsample = 0;
602 if (s1 != s2) {
603 /* Selector value changed, interpolation needed. */
604 mc1_l = matrixCoeffs_fix[s1<<1];
605 mc1_r = matrixCoeffs_fix[(s1<<1)+1];
606 mc2_l = matrixCoeffs_fix[s2<<1];
607 mc2_r = matrixCoeffs_fix[(s2<<1)+1];
609 /* Interpolation is done over the first eight samples. */
610 for(; nsample < 8; nsample++) {
611 c1 = su1[band+nsample];
612 c2 = su2[band+nsample];
613 c2 = fixmul16(c1, INTERPOLATE(mc1_l, mc2_l, nsample)) + fixmul16(c2, INTERPOLATE(mc1_r, mc2_r, nsample));
614 su1[band+nsample] = c2;
615 su2[band+nsample] = (c1 << 1) - c2;
619 /* Apply the matrix without interpolation. */
620 switch (s2) {
621 case 0: /* M/S decoding */
622 for (; nsample < 256; nsample++) {
623 c1 = su1[band+nsample];
624 c2 = su2[band+nsample];
625 su1[band+nsample] = c2 << 1;
626 su2[band+nsample] = (c1 - c2) << 1;
628 break;
630 case 1:
631 for (; nsample < 256; nsample++) {
632 c1 = su1[band+nsample];
633 c2 = su2[band+nsample];
634 su1[band+nsample] = (c1 + c2) << 1;
635 su2[band+nsample] = -1*(c2 << 1);
637 break;
638 case 2:
639 case 3:
640 for (; nsample < 256; nsample++) {
641 c1 = su1[band+nsample];
642 c2 = su2[band+nsample];
643 su1[band+nsample] = c1 + c2;
644 su2[band+nsample] = c1 - c2;
646 break;
647 default:
648 //assert(0);
649 break;
654 static void getChannelWeights (int indx, int flag, int32_t ch[2]){
655 if (indx == 7) {
656 ch[0] = ONE_16;
657 ch[1] = ONE_16;
658 } else {
659 ch[0] = fixdiv16(((indx & 7)*ONE_16), 7*ONE_16);
660 ch[1] = fastSqrt((ONE_16 << 1) - fixmul16(ch[0], ch[0]));
661 if(flag)
662 FFSWAP(int32_t, ch[0], ch[1]);
666 static void channelWeighting (int32_t *su1, int32_t *su2, int *p3)
668 int band, nsample;
669 /* w[x][y] y=0 is left y=1 is right */
670 int32_t w[2][2];
672 if (p3[1] != 7 || p3[3] != 7){
673 getChannelWeights(p3[1], p3[0], w[0]);
674 getChannelWeights(p3[3], p3[2], w[1]);
676 for(band = 1; band < 4; band++) {
677 /* scale the channels by the weights */
678 for(nsample = 0; nsample < 8; nsample++) {
679 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], INTERPOLATE(w[0][0], w[0][1], nsample));
680 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], INTERPOLATE(w[1][0], w[1][1], nsample));
683 for(; nsample < 256; nsample++) {
684 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], w[1][0]);
685 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], w[1][1]);
693 * Decode a Sound Unit
695 * @param gb the GetBit context
696 * @param pSnd the channel unit to be used
697 * @param pOut the decoded samples before IQMF in float representation
698 * @param channelNum channel number
699 * @param codingMode the coding mode (JOINT_STEREO or regular stereo/mono)
703 static int decodeChannelSoundUnit (GetBitContext *gb, channel_unit *pSnd, int32_t *pOut, int channelNum, int codingMode)
705 int band, result=0, numSubbands, lastTonal, numBands;
706 if (codingMode == JOINT_STEREO && channelNum == 1) {
707 if (get_bits(gb,2) != 3) {
708 DEBUGF("JS mono Sound Unit id != 3.\n");
709 return -1;
711 } else {
712 if (get_bits(gb,6) != 0x28) {
713 DEBUGF("Sound Unit id != 0x28.\n");
714 return -1;
718 /* number of coded QMF bands */
719 pSnd->bandsCoded = get_bits(gb,2);
721 result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
722 if (result) return result;
724 pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
725 if (pSnd->numComponents == -1) return -1;
727 numSubbands = decodeSpectrum (gb, pSnd->spectrum);
729 /* Merge the decoded spectrum and tonal components. */
730 lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
733 /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
734 numBands = (subbandTab[numSubbands] - 1) >> 8;
735 if (lastTonal >= 0)
736 numBands = FFMAX((lastTonal + 256) >> 8, numBands);
739 /* Reconstruct time domain samples. */
740 for (band=0; band<4; band++) {
741 /* Perform the IMDCT step without overlapping. */
742 if (band <= numBands) {
743 IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
744 } else
745 memset(pSnd->IMDCT_buf, 0, 512 * sizeof(int32_t));
747 /* gain compensation and overlapping */
748 gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),
749 &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),
750 &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));
753 /* Swap the gain control buffers for the next frame. */
754 pSnd->gcBlkSwitch ^= 1;
756 return 0;
760 * Frame handling
762 * @param q Atrac3 private context
763 * @param databuf the input data
766 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf, int off)
768 int result, i;
769 int32_t *p1, *p2, *p3, *p4;
770 uint8_t *ptr1;
772 if (q->codingMode == JOINT_STEREO) {
774 /* channel coupling mode */
775 /* decode Sound Unit 1 */
776 init_get_bits(&q->gb,databuf,q->bits_per_frame);
778 result = decodeChannelSoundUnit(&q->gb, q->pUnits, q->outSamples, 0, JOINT_STEREO);
779 if (result != 0)
780 return (result);
782 /* Framedata of the su2 in the joint-stereo mode is encoded in
783 * reverse byte order so we need to swap it first. */
784 if (databuf == q->decoded_bytes_buffer) {
785 uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
786 ptr1 = q->decoded_bytes_buffer;
787 for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
788 FFSWAP(uint8_t,*ptr1,*ptr2);
790 } else {
791 const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
792 for (i = 0; i < q->bytes_per_frame; i++)
793 q->decoded_bytes_buffer[i] = *ptr2--;
796 /* Skip the sync codes (0xF8). */
797 ptr1 = q->decoded_bytes_buffer;
798 for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
799 if (i >= q->bytes_per_frame)
800 return -1;
804 /* set the bitstream reader at the start of the second Sound Unit*/
805 init_get_bits(&q->gb,ptr1,q->bits_per_frame);
807 /* Fill the Weighting coeffs delay buffer */
808 memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
809 q->weighting_delay[4] = get_bits1(&q->gb);
810 q->weighting_delay[5] = get_bits(&q->gb,3);
812 for (i = 0; i < 4; i++) {
813 q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
814 q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
815 q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
818 /* Decode Sound Unit 2. */
819 result = decodeChannelSoundUnit(&q->gb, &q->pUnits[1], &q->outSamples[1024], 1, JOINT_STEREO);
820 if (result != 0)
821 return (result);
823 /* Reconstruct the channel coefficients. */
824 reverseMatrixing(q->outSamples, &q->outSamples[1024], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
826 channelWeighting(q->outSamples, &q->outSamples[1024], q->weighting_delay);
828 } else {
829 /* normal stereo mode or mono */
830 /* Decode the channel sound units. */
831 for (i=0 ; i<q->channels ; i++) {
833 /* Set the bitstream reader at the start of a channel sound unit. */
834 init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels)+off, (q->bits_per_frame)/q->channels);
836 result = decodeChannelSoundUnit(&q->gb, &q->pUnits[i], &q->outSamples[i*1024], i, q->codingMode);
837 if (result != 0)
838 return (result);
842 /* Apply the iQMF synthesis filter. */
843 p1= q->outSamples;
844 for (i=0 ; i<q->channels ; i++) {
845 p2= p1+256;
846 p3= p2+256;
847 p4= p3+256;
848 iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
849 iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
850 iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
851 p1 +=1024;
854 return 0;
859 * Atrac frame decoding
861 * @param rmctx pointer to the AVCodecContext
864 int atrac3_decode_frame(RMContext *rmctx, ATRAC3Context *q,
865 void *data, int *data_size,
866 const uint8_t *buf, int buf_size) {
867 int result = 0, off = 0, i;
868 const uint8_t* databuf;
869 int16_t* samples = data;
871 if (buf_size < rmctx->block_align)
872 return buf_size;
874 /* Check if we need to descramble and what buffer to pass on. */
875 if (q->scrambled_stream) {
876 off = decode_bytes(buf, q->decoded_bytes_buffer, rmctx->block_align);
877 databuf = q->decoded_bytes_buffer;
878 } else {
879 databuf = buf;
882 result = decodeFrame(q, databuf, off);
884 if (result != 0) {
885 DEBUGF("Frame decoding error!\n");
886 return -1;
889 if (q->channels == 1) {
890 /* mono */
891 for (i = 0; i<1024; i++)
892 samples[i] = av_clip_int16(q->outSamples[i]);
893 *data_size = 1024 * sizeof(int16_t);
894 } else {
895 /* stereo */
896 for (i = 0; i < 1024; i++) {
897 samples[i*2] = av_clip_int16(q->outSamples[i]);
898 samples[i*2+1] = av_clip_int16(q->outSamples[1024+i]);
900 *data_size = 2048 * sizeof(int16_t);
903 return rmctx->block_align;
908 * Atrac3 initialization
910 * @param rmctx pointer to the RMContext
913 int atrac3_decode_init(ATRAC3Context *q, RMContext *rmctx)
915 int i;
916 uint8_t *edata_ptr = rmctx->codec_extradata;
917 static VLC_TYPE atrac3_vlc_table[4096][2];
918 static int vlcs_initialized = 0;
920 /* Take data from the AVCodecContext (RM container). */
921 q->sample_rate = rmctx->sample_rate;
922 q->channels = rmctx->nb_channels;
923 q->bit_rate = rmctx->bit_rate;
924 q->bits_per_frame = rmctx->block_align * 8;
925 q->bytes_per_frame = rmctx->block_align;
927 /* Take care of the codec-specific extradata. */
928 if (rmctx->extradata_size == 14) {
929 /* Parse the extradata, WAV format */
930 DEBUGF("[0-1] %d\n",rm_get_uint16le(&edata_ptr[0])); //Unknown value always 1
931 q->samples_per_channel = rm_get_uint32le(&edata_ptr[2]);
932 q->codingMode = rm_get_uint16le(&edata_ptr[6]);
933 DEBUGF("[8-9] %d\n",rm_get_uint16le(&edata_ptr[8])); //Dupe of coding mode
934 q->frame_factor = rm_get_uint16le(&edata_ptr[10]); //Unknown always 1
935 DEBUGF("[12-13] %d\n",rm_get_uint16le(&edata_ptr[12])); //Unknown always 0
937 /* setup */
938 q->samples_per_frame = 1024 * q->channels;
939 q->atrac3version = 4;
940 q->delay = 0x88E;
941 if (q->codingMode)
942 q->codingMode = JOINT_STEREO;
943 else
944 q->codingMode = STEREO;
945 q->scrambled_stream = 0;
947 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)) {
948 } else {
949 DEBUGF("Unknown frame/channel/frame_factor configuration %d/%d/%d\n", q->bytes_per_frame, q->channels, q->frame_factor);
950 return -1;
953 } else if (rmctx->extradata_size == 10) {
954 /* Parse the extradata, RM format. */
955 q->atrac3version = rm_get_uint32be(&edata_ptr[0]);
956 q->samples_per_frame = rm_get_uint16be(&edata_ptr[4]);
957 q->delay = rm_get_uint16be(&edata_ptr[6]);
958 q->codingMode = rm_get_uint16be(&edata_ptr[8]);
960 q->samples_per_channel = q->samples_per_frame / q->channels;
961 q->scrambled_stream = 1;
963 } else {
964 DEBUGF("Unknown extradata size %d.\n",rmctx->extradata_size);
966 /* Check the extradata. */
968 if (q->atrac3version != 4) {
969 DEBUGF("Version %d != 4.\n",q->atrac3version);
970 return -1;
973 if (q->samples_per_frame != 1024 && q->samples_per_frame != 2048) {
974 DEBUGF("Unknown amount of samples per frame %d.\n",q->samples_per_frame);
975 return -1;
978 if (q->delay != 0x88E) {
979 DEBUGF("Unknown amount of delay %x != 0x88E.\n",q->delay);
980 return -1;
983 if (q->codingMode == STEREO) {
984 DEBUGF("Normal stereo detected.\n");
985 } else if (q->codingMode == JOINT_STEREO) {
986 DEBUGF("Joint stereo detected.\n");
987 } else {
988 DEBUGF("Unknown channel coding mode %x!\n",q->codingMode);
989 return -1;
992 if (rmctx->nb_channels <= 0 || rmctx->nb_channels > 2 /*|| ((rmctx->channels * 1024) != q->samples_per_frame)*/) {
993 DEBUGF("Channel configuration error!\n");
994 return -1;
998 if(rmctx->block_align >= UINT16_MAX/2)
999 return -1;
1002 /* Initialize the VLC tables. */
1003 if (!vlcs_initialized) {
1004 for (i=0 ; i<7 ; i++) {
1005 spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
1006 spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
1007 init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
1008 huff_bits[i], 1, 1,
1009 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
1012 vlcs_initialized = 1;
1016 init_atrac3_transforms();
1018 /* init the joint-stereo decoding data */
1019 q->weighting_delay[0] = 0;
1020 q->weighting_delay[1] = 7;
1021 q->weighting_delay[2] = 0;
1022 q->weighting_delay[3] = 7;
1023 q->weighting_delay[4] = 0;
1024 q->weighting_delay[5] = 7;
1026 for (i=0; i<4; i++) {
1027 q->matrix_coeff_index_prev[i] = 3;
1028 q->matrix_coeff_index_now[i] = 3;
1029 q->matrix_coeff_index_next[i] = 3;
1032 q->pUnits = channel_units;
1034 return 0;