FS#8961 - Anti-Aliased Fonts.
[kugel-rb/myfork.git] / apps / codecs / libatrac / atrac3.c
blob47a63cae30f4555fbdf5a05e1c721388c851d29e
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];
70 /**
71 * Quadrature mirror synthesis filter.
73 * @param inlo lower part of spectrum
74 * @param inhi higher part of spectrum
75 * @param nIn size of spectrum buffer
76 * @param pOut out buffer
77 * @param delayBuf delayBuf buffer
78 * @param temp temp buffer
80 static void iqmf (int32_t *inlo, int32_t *inhi, unsigned int nIn, int32_t *pOut, int32_t *delayBuf, int32_t *temp)
82 unsigned int i, j;
83 int32_t *p1, *p3;
85 memcpy(temp, delayBuf, 46*sizeof(int32_t));
87 p3 = temp + 46;
89 /* loop1 */
90 for(i=0; i<nIn; i+=2){
91 p3[2*i+0] = inlo[i ] + inhi[i ];
92 p3[2*i+1] = inlo[i ] - inhi[i ];
93 p3[2*i+2] = inlo[i+1] + inhi[i+1];
94 p3[2*i+3] = inlo[i+1] - inhi[i+1];
97 /* loop2 */
98 p1 = temp;
99 for (j = nIn; j != 0; j--) {
100 int32_t s1 = 0;
101 int32_t s2 = 0;
103 for (i = 0; i < 48; i += 2) {
104 s1 += fixmul31(p1[i], qmf_window[i]);
105 s2 += fixmul31(p1[i+1], qmf_window[i+1]);
108 pOut[0] = s2;
109 pOut[1] = s1;
111 p1 += 2;
112 pOut += 2;
115 /* Update the delay buffer. */
116 memcpy(delayBuf, temp + (nIn << 1), 46*sizeof(int32_t));
120 * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
121 * caused by the reverse spectra of the QMF.
123 * @param pInput float input
124 * @param pOutput float output
125 * @param odd_band 1 if the band is an odd band
128 static void IMLT(int32_t *pInput, int32_t *pOutput, int odd_band)
130 int i;
131 if (odd_band) {
133 * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
134 * or it gives better compression to do it this way.
135 * FIXME: It should be possible to handle this in ff_imdct_calc
136 * for that to happen a modification of the prerotation step of
137 * all SIMD code and C code is needed.
138 * Or fix the functions before so they generate a pre reversed spectrum.
141 for (i=0; i<128; i++)
142 FFSWAP(int32_t, pInput[i], pInput[255-i]);
145 /* Apply the imdct. */
146 mdct_backward(512, pInput, pOutput);
148 /* Windowing. */
149 for(i = 0; i<512; i++)
150 pOutput[i] = fixmul31(pOutput[i], window_lookup[i]);
156 * Atrac 3 indata descrambling, only used for data coming from the rm container
158 * @param in pointer to 8 bit array of indata
159 * @param bits amount of bits
160 * @param out pointer to 8 bit array of outdata
163 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
164 int i, off;
165 uint32_t c;
166 const uint32_t* buf;
167 uint32_t* obuf = (uint32_t*) out;
169 #if ((defined(TEST) || defined(SIMULATOR)) && !defined(CPU_ARM))
170 off = 0; //no check for memory alignment of inbuffer
171 #else
172 off = (intptr_t)inbuffer & 3;
173 #endif /* TEST */
174 buf = (const uint32_t*) (inbuffer - off);
176 c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
177 bytes += 3 + off;
178 for (i = 0; i < bytes/4; i++)
179 obuf[i] = c ^ buf[i];
181 return off;
185 static void init_atrac3_transforms(void) {
186 int32_t s;
187 int i;
189 /* Generate the mdct window, for details see
190 * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
192 /* mdct window had been generated and saved as a lookup table in atrac3data_fixed.h */
194 /* Generate the QMF window. */
195 for (i=0 ; i<24; i++) {
196 s = qmf_48tap_half_fix[i] << 1;
197 qmf_window[i] = s;
198 qmf_window[47 - i] = s;
203 * Mantissa decoding
205 * @param gb the GetBit context
206 * @param selector what table is the output values coded with
207 * @param codingFlag constant length coding or variable length coding
208 * @param mantissas mantissa output table
209 * @param numCodes amount of values to get
212 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
214 int numBits, cnt, code, huffSymb;
216 if (selector == 1)
217 numCodes /= 2;
219 if (codingFlag != 0) {
220 /* constant length coding (CLC) */
221 numBits = CLCLengthTab[selector];
223 if (selector > 1) {
224 for (cnt = 0; cnt < numCodes; cnt++) {
225 if (numBits)
226 code = get_sbits(gb, numBits);
227 else
228 code = 0;
229 mantissas[cnt] = code;
231 } else {
232 for (cnt = 0; cnt < numCodes; cnt++) {
233 if (numBits)
234 code = get_bits(gb, numBits); //numBits is always 4 in this case
235 else
236 code = 0;
237 mantissas[cnt*2] = seTab_0[code >> 2];
238 mantissas[cnt*2+1] = seTab_0[code & 3];
241 } else {
242 /* variable length coding (VLC) */
243 if (selector != 1) {
244 for (cnt = 0; cnt < numCodes; cnt++) {
245 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
246 huffSymb += 1;
247 code = huffSymb >> 1;
248 if (huffSymb & 1)
249 code = -code;
250 mantissas[cnt] = code;
252 } else {
253 for (cnt = 0; cnt < numCodes; cnt++) {
254 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
255 mantissas[cnt*2] = decTable1[huffSymb*2];
256 mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
263 * Restore the quantized band spectrum coefficients
265 * @param gb the GetBit context
266 * @param pOut decoded band spectrum
267 * @return outSubbands subband counter, fix for broken specification/files
270 static int decodeSpectrum (GetBitContext *gb, int32_t *pOut)
272 int numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
273 int subband_vlc_index[32], SF_idxs[32];
274 int mantissas[128];
275 int32_t SF;
277 numSubbands = get_bits(gb, 5); // number of coded subbands
278 codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
280 /* Get the VLC selector table for the subbands, 0 means not coded. */
281 for (cnt = 0; cnt <= numSubbands; cnt++)
282 subband_vlc_index[cnt] = get_bits(gb, 3);
284 /* Read the scale factor indexes from the stream. */
285 for (cnt = 0; cnt <= numSubbands; cnt++) {
286 if (subband_vlc_index[cnt] != 0)
287 SF_idxs[cnt] = get_bits(gb, 6);
290 for (cnt = 0; cnt <= numSubbands; cnt++) {
291 first = subbandTab[cnt];
292 last = subbandTab[cnt+1];
294 subbWidth = last - first;
296 if (subband_vlc_index[cnt] != 0) {
297 /* Decode spectral coefficients for this subband. */
298 /* TODO: This can be done faster is several blocks share the
299 * same VLC selector (subband_vlc_index) */
300 readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
302 /* Decode the scale factor for this subband. */
303 SF = fixmul31(SFTable_fixed[SF_idxs[cnt]], iMaxQuant_fix[subband_vlc_index[cnt]]);
305 /* Inverse quantize the coefficients. */
306 for (pIn=mantissas ; first<last; first++, pIn++)
307 pOut[first] = fixmul16(*pIn, SF);
308 } else {
309 /* This subband was not coded, so zero the entire subband. */
310 memset(pOut+first, 0, subbWidth*sizeof(int32_t));
314 /* Clear the subbands that were not coded. */
315 first = subbandTab[cnt];
316 memset(pOut+first, 0, (1024 - first) * sizeof(int32_t));
317 return numSubbands;
321 * Restore the quantized tonal components
323 * @param gb the GetBit context
324 * @param pComponent tone component
325 * @param numBands amount of coded bands
328 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
330 int i,j,k,cnt;
331 int components, coding_mode_selector, coding_mode, coded_values_per_component;
332 int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
333 int band_flags[4], mantissa[8];
334 int32_t *pCoef;
335 int32_t scalefactor;
336 int component_count = 0;
338 components = get_bits(gb,5);
340 /* no tonal components */
341 if (components == 0)
342 return 0;
344 coding_mode_selector = get_bits(gb,2);
345 if (coding_mode_selector == 2)
346 return -1;
348 coding_mode = coding_mode_selector & 1;
350 for (i = 0; i < components; i++) {
351 for (cnt = 0; cnt <= numBands; cnt++)
352 band_flags[cnt] = get_bits1(gb);
354 coded_values_per_component = get_bits(gb,3);
356 quant_step_index = get_bits(gb,3);
357 if (quant_step_index <= 1)
358 return -1;
360 if (coding_mode_selector == 3)
361 coding_mode = get_bits1(gb);
363 for (j = 0; j < (numBands + 1) * 4; j++) {
364 if (band_flags[j >> 2] == 0)
365 continue;
367 coded_components = get_bits(gb,3);
369 for (k=0; k<coded_components; k++) {
370 sfIndx = get_bits(gb,6);
371 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
372 max_coded_values = 1024 - pComponent[component_count].pos;
373 coded_values = coded_values_per_component + 1;
374 coded_values = FFMIN(max_coded_values,coded_values);
376 scalefactor = fixmul31(SFTable_fixed[sfIndx], iMaxQuant_fix[quant_step_index]);
378 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
380 pComponent[component_count].numCoefs = coded_values;
382 /* inverse quant */
383 pCoef = pComponent[component_count].coef;
384 for (cnt = 0; cnt < coded_values; cnt++)
385 pCoef[cnt] = fixmul16(mantissa[cnt], scalefactor);
387 component_count++;
392 return component_count;
396 * Decode gain parameters for the coded bands
398 * @param gb the GetBit context
399 * @param pGb the gainblock for the current band
400 * @param numBands amount of coded bands
403 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
405 int i, cf, numData;
406 int *pLevel, *pLoc;
408 gain_info *pGain = pGb->gBlock;
410 for (i=0 ; i<=numBands; i++)
412 numData = get_bits(gb,3);
413 pGain[i].num_gain_data = numData;
414 pLevel = pGain[i].levcode;
415 pLoc = pGain[i].loccode;
417 for (cf = 0; cf < numData; cf++){
418 pLevel[cf]= get_bits(gb,4);
419 pLoc [cf]= get_bits(gb,5);
420 if(cf && pLoc[cf] <= pLoc[cf-1])
421 return -1;
425 /* Clear the unused blocks. */
426 for (; i<4 ; i++)
427 pGain[i].num_gain_data = 0;
429 return 0;
433 * Apply gain parameters and perform the MDCT overlapping part
435 * @param pIn input float buffer
436 * @param pPrev previous float buffer to perform overlap against
437 * @param pOut output float buffer
438 * @param pGain1 current band gain info
439 * @param pGain2 next band gain info
442 static void gainCompensateAndOverlap (int32_t *pIn, int32_t *pPrev, int32_t *pOut, gain_info *pGain1, gain_info *pGain2)
444 /* gain compensation function */
445 int32_t gain1, gain2, gain_inc;
446 int cnt, numdata, nsample, startLoc, endLoc;
449 if (pGain2->num_gain_data == 0)
450 gain1 = ONE_16;
451 else
452 gain1 = gain_tab1[pGain2->levcode[0]];
454 if (pGain1->num_gain_data == 0) {
455 for (cnt = 0; cnt < 256; cnt++)
456 pOut[cnt] = fixmul16(pIn[cnt], gain1) + pPrev[cnt];
457 } else {
458 numdata = pGain1->num_gain_data;
459 pGain1->loccode[numdata] = 32;
460 pGain1->levcode[numdata] = 4;
462 nsample = 0; // current sample = 0
464 for (cnt = 0; cnt < numdata; cnt++) {
465 startLoc = pGain1->loccode[cnt] * 8;
466 endLoc = startLoc + 8;
468 gain2 = gain_tab1[pGain1->levcode[cnt]];
469 gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
471 /* interpolate */
472 for (; nsample < startLoc; nsample++)
473 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]), gain2);
475 /* interpolation is done over eight samples */
476 for (; nsample < endLoc; nsample++) {
477 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]),gain2);
478 gain2 = fixmul16(gain2, gain_inc);
482 for (; nsample < 256; nsample++)
483 pOut[nsample] = fixmul16(pIn[nsample], gain1) + pPrev[nsample];
486 /* Delay for the overlapping part. */
487 memcpy(pPrev, &pIn[256], 256*sizeof(int32_t));
491 * Combine the tonal band spectrum and regular band spectrum
492 * Return position of the last tonal coefficient
495 * @param pSpectrum output spectrum buffer
496 * @param numComponents amount of tonal components
497 * @param pComponent tonal components for this band
500 static int addTonalComponents (int32_t *pSpectrum, int numComponents, tonal_component *pComponent)
502 int cnt, i, lastPos = -1;
503 int32_t *pOut;
504 int32_t *pIn;
506 for (cnt = 0; cnt < numComponents; cnt++){
507 lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
508 pIn = pComponent[cnt].coef;
509 pOut = &(pSpectrum[pComponent[cnt].pos]);
511 for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
512 pOut[i] += pIn[i];
515 return lastPos;
519 #define INTERPOLATE(old,new,nsample) ((old*ONE_16) + fixmul16(((nsample*ONE_16)>>3), (((new) - (old))*ONE_16)))
521 static void reverseMatrixing(int32_t *su1, int32_t *su2, int *pPrevCode, int *pCurrCode)
523 int i, band, nsample, s1, s2;
524 int32_t c1, c2;
525 int32_t mc1_l, mc1_r, mc2_l, mc2_r;
527 for (i=0,band = 0; band < 4*256; band+=256,i++) {
528 s1 = pPrevCode[i];
529 s2 = pCurrCode[i];
530 nsample = 0;
532 if (s1 != s2) {
533 /* Selector value changed, interpolation needed. */
534 mc1_l = matrixCoeffs_fix[s1<<1];
535 mc1_r = matrixCoeffs_fix[(s1<<1)+1];
536 mc2_l = matrixCoeffs_fix[s2<<1];
537 mc2_r = matrixCoeffs_fix[(s2<<1)+1];
539 /* Interpolation is done over the first eight samples. */
540 for(; nsample < 8; nsample++) {
541 c1 = su1[band+nsample];
542 c2 = su2[band+nsample];
543 c2 = fixmul16(c1, INTERPOLATE(mc1_l, mc2_l, nsample)) + fixmul16(c2, INTERPOLATE(mc1_r, mc2_r, nsample));
544 su1[band+nsample] = c2;
545 su2[band+nsample] = (c1 << 1) - c2;
549 /* Apply the matrix without interpolation. */
550 switch (s2) {
551 case 0: /* M/S decoding */
552 for (; nsample < 256; nsample++) {
553 c1 = su1[band+nsample];
554 c2 = su2[band+nsample];
555 su1[band+nsample] = c2 << 1;
556 su2[band+nsample] = (c1 - c2) << 1;
558 break;
560 case 1:
561 for (; nsample < 256; nsample++) {
562 c1 = su1[band+nsample];
563 c2 = su2[band+nsample];
564 su1[band+nsample] = (c1 + c2) << 1;
565 su2[band+nsample] = -1*(c2 << 1);
567 break;
568 case 2:
569 case 3:
570 for (; nsample < 256; nsample++) {
571 c1 = su1[band+nsample];
572 c2 = su2[band+nsample];
573 su1[band+nsample] = c1 + c2;
574 su2[band+nsample] = c1 - c2;
576 break;
577 default:
578 //assert(0);
579 break;
584 static void getChannelWeights (int indx, int flag, int32_t ch[2]){
585 if (indx == 7) {
586 ch[0] = ONE_16;
587 ch[1] = ONE_16;
588 } else {
589 ch[0] = fixdiv16(((indx & 7)*ONE_16), 7*ONE_16);
590 ch[1] = fastSqrt((ONE_16 << 1) - fixmul16(ch[0], ch[0]));
591 if(flag)
592 FFSWAP(int32_t, ch[0], ch[1]);
596 static void channelWeighting (int32_t *su1, int32_t *su2, int *p3)
598 int band, nsample;
599 /* w[x][y] y=0 is left y=1 is right */
600 int32_t w[2][2];
602 if (p3[1] != 7 || p3[3] != 7){
603 getChannelWeights(p3[1], p3[0], w[0]);
604 getChannelWeights(p3[3], p3[2], w[1]);
606 for(band = 1; band < 4; band++) {
607 /* scale the channels by the weights */
608 for(nsample = 0; nsample < 8; nsample++) {
609 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], INTERPOLATE(w[0][0], w[0][1], nsample));
610 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], INTERPOLATE(w[1][0], w[1][1], nsample));
613 for(; nsample < 256; nsample++) {
614 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], w[1][0]);
615 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], w[1][1]);
623 * Decode a Sound Unit
625 * @param gb the GetBit context
626 * @param pSnd the channel unit to be used
627 * @param pOut the decoded samples before IQMF in float representation
628 * @param channelNum channel number
629 * @param codingMode the coding mode (JOINT_STEREO or regular stereo/mono)
633 static int decodeChannelSoundUnit (GetBitContext *gb, channel_unit *pSnd, int32_t *pOut, int channelNum, int codingMode)
635 int band, result=0, numSubbands, lastTonal, numBands;
636 if (codingMode == JOINT_STEREO && channelNum == 1) {
637 if (get_bits(gb,2) != 3) {
638 DEBUGF("JS mono Sound Unit id != 3.\n");
639 return -1;
641 } else {
642 if (get_bits(gb,6) != 0x28) {
643 DEBUGF("Sound Unit id != 0x28.\n");
644 return -1;
648 /* number of coded QMF bands */
649 pSnd->bandsCoded = get_bits(gb,2);
651 result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
652 if (result) return result;
654 pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
655 if (pSnd->numComponents == -1) return -1;
657 numSubbands = decodeSpectrum (gb, pSnd->spectrum);
659 /* Merge the decoded spectrum and tonal components. */
660 lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
663 /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
664 numBands = (subbandTab[numSubbands] - 1) >> 8;
665 if (lastTonal >= 0)
666 numBands = FFMAX((lastTonal + 256) >> 8, numBands);
669 /* Reconstruct time domain samples. */
670 for (band=0; band<4; band++) {
671 /* Perform the IMDCT step without overlapping. */
672 if (band <= numBands) {
673 IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
674 } else
675 memset(pSnd->IMDCT_buf, 0, 512 * sizeof(int32_t));
677 /* gain compensation and overlapping */
678 gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),
679 &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),
680 &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));
683 /* Swap the gain control buffers for the next frame. */
684 pSnd->gcBlkSwitch ^= 1;
686 return 0;
690 * Frame handling
692 * @param q Atrac3 private context
693 * @param databuf the input data
696 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf, int off)
698 int result, i;
699 int32_t *p1, *p2, *p3, *p4;
700 uint8_t *ptr1;
702 if (q->codingMode == JOINT_STEREO) {
704 /* channel coupling mode */
705 /* decode Sound Unit 1 */
706 init_get_bits(&q->gb,databuf,q->bits_per_frame);
708 result = decodeChannelSoundUnit(&q->gb, q->pUnits, q->outSamples, 0, JOINT_STEREO);
709 if (result != 0)
710 return (result);
712 /* Framedata of the su2 in the joint-stereo mode is encoded in
713 * reverse byte order so we need to swap it first. */
714 if (databuf == q->decoded_bytes_buffer) {
715 uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
716 ptr1 = q->decoded_bytes_buffer;
717 for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
718 FFSWAP(uint8_t,*ptr1,*ptr2);
720 } else {
721 const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
722 for (i = 0; i < q->bytes_per_frame; i++)
723 q->decoded_bytes_buffer[i] = *ptr2--;
726 /* Skip the sync codes (0xF8). */
727 ptr1 = q->decoded_bytes_buffer;
728 for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
729 if (i >= q->bytes_per_frame)
730 return -1;
734 /* set the bitstream reader at the start of the second Sound Unit*/
735 init_get_bits(&q->gb,ptr1,q->bits_per_frame);
737 /* Fill the Weighting coeffs delay buffer */
738 memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
739 q->weighting_delay[4] = get_bits1(&q->gb);
740 q->weighting_delay[5] = get_bits(&q->gb,3);
742 for (i = 0; i < 4; i++) {
743 q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
744 q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
745 q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
748 /* Decode Sound Unit 2. */
749 result = decodeChannelSoundUnit(&q->gb, &q->pUnits[1], &q->outSamples[1024], 1, JOINT_STEREO);
750 if (result != 0)
751 return (result);
753 /* Reconstruct the channel coefficients. */
754 reverseMatrixing(q->outSamples, &q->outSamples[1024], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
756 channelWeighting(q->outSamples, &q->outSamples[1024], q->weighting_delay);
758 } else {
759 /* normal stereo mode or mono */
760 /* Decode the channel sound units. */
761 for (i=0 ; i<q->channels ; i++) {
763 /* Set the bitstream reader at the start of a channel sound unit. */
764 init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels)+off, (q->bits_per_frame)/q->channels);
766 result = decodeChannelSoundUnit(&q->gb, &q->pUnits[i], &q->outSamples[i*1024], i, q->codingMode);
767 if (result != 0)
768 return (result);
772 /* Apply the iQMF synthesis filter. */
773 p1= q->outSamples;
774 for (i=0 ; i<q->channels ; i++) {
775 p2= p1+256;
776 p3= p2+256;
777 p4= p3+256;
778 iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
779 iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
780 iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
781 p1 +=1024;
784 return 0;
789 * Atrac frame decoding
791 * @param rmctx pointer to the AVCodecContext
794 int atrac3_decode_frame(RMContext *rmctx, ATRAC3Context *q,
795 void *data, int *data_size,
796 const uint8_t *buf, int buf_size) {
797 int result = 0, off = 0, i;
798 const uint8_t* databuf;
799 int16_t* samples = data;
801 if (buf_size < rmctx->block_align)
802 return buf_size;
804 /* Check if we need to descramble and what buffer to pass on. */
805 if (q->scrambled_stream) {
806 off = decode_bytes(buf, q->decoded_bytes_buffer, rmctx->block_align);
807 databuf = q->decoded_bytes_buffer;
808 } else {
809 databuf = buf;
812 result = decodeFrame(q, databuf, off);
814 if (result != 0) {
815 DEBUGF("Frame decoding error!\n");
816 return -1;
819 if (q->channels == 1) {
820 /* mono */
821 for (i = 0; i<1024; i++)
822 samples[i] = av_clip_int16(q->outSamples[i]);
823 *data_size = 1024 * sizeof(int16_t);
824 } else {
825 /* stereo */
826 for (i = 0; i < 1024; i++) {
827 samples[i*2] = av_clip_int16(q->outSamples[i]);
828 samples[i*2+1] = av_clip_int16(q->outSamples[1024+i]);
830 *data_size = 2048 * sizeof(int16_t);
833 return rmctx->block_align;
838 * Atrac3 initialization
840 * @param rmctx pointer to the RMContext
843 int atrac3_decode_init(ATRAC3Context *q, RMContext *rmctx)
845 int i;
846 uint8_t *edata_ptr = rmctx->codec_extradata;
847 static VLC_TYPE atrac3_vlc_table[4096][2];
848 static int vlcs_initialized = 0;
850 /* Take data from the AVCodecContext (RM container). */
851 q->sample_rate = rmctx->sample_rate;
852 q->channels = rmctx->nb_channels;
853 q->bit_rate = rmctx->bit_rate;
854 q->bits_per_frame = rmctx->block_align * 8;
855 q->bytes_per_frame = rmctx->block_align;
857 /* Take care of the codec-specific extradata. */
858 if (rmctx->extradata_size == 14) {
859 /* Parse the extradata, WAV format */
860 DEBUGF("[0-1] %d\n",rm_get_uint16le(&edata_ptr[0])); //Unknown value always 1
861 q->samples_per_channel = rm_get_uint32le(&edata_ptr[2]);
862 q->codingMode = rm_get_uint16le(&edata_ptr[6]);
863 DEBUGF("[8-9] %d\n",rm_get_uint16le(&edata_ptr[8])); //Dupe of coding mode
864 q->frame_factor = rm_get_uint16le(&edata_ptr[10]); //Unknown always 1
865 DEBUGF("[12-13] %d\n",rm_get_uint16le(&edata_ptr[12])); //Unknown always 0
867 /* setup */
868 q->samples_per_frame = 1024 * q->channels;
869 q->atrac3version = 4;
870 q->delay = 0x88E;
871 if (q->codingMode)
872 q->codingMode = JOINT_STEREO;
873 else
874 q->codingMode = STEREO;
875 q->scrambled_stream = 0;
877 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)) {
878 } else {
879 DEBUGF("Unknown frame/channel/frame_factor configuration %d/%d/%d\n", q->bytes_per_frame, q->channels, q->frame_factor);
880 return -1;
883 } else if (rmctx->extradata_size == 10) {
884 /* Parse the extradata, RM format. */
885 q->atrac3version = rm_get_uint32be(&edata_ptr[0]);
886 q->samples_per_frame = rm_get_uint16be(&edata_ptr[4]);
887 q->delay = rm_get_uint16be(&edata_ptr[6]);
888 q->codingMode = rm_get_uint16be(&edata_ptr[8]);
890 q->samples_per_channel = q->samples_per_frame / q->channels;
891 q->scrambled_stream = 1;
893 } else {
894 DEBUGF("Unknown extradata size %d.\n",rmctx->extradata_size);
896 /* Check the extradata. */
898 if (q->atrac3version != 4) {
899 DEBUGF("Version %d != 4.\n",q->atrac3version);
900 return -1;
903 if (q->samples_per_frame != 1024 && q->samples_per_frame != 2048) {
904 DEBUGF("Unknown amount of samples per frame %d.\n",q->samples_per_frame);
905 return -1;
908 if (q->delay != 0x88E) {
909 DEBUGF("Unknown amount of delay %x != 0x88E.\n",q->delay);
910 return -1;
913 if (q->codingMode == STEREO) {
914 DEBUGF("Normal stereo detected.\n");
915 } else if (q->codingMode == JOINT_STEREO) {
916 DEBUGF("Joint stereo detected.\n");
917 } else {
918 DEBUGF("Unknown channel coding mode %x!\n",q->codingMode);
919 return -1;
922 if (rmctx->nb_channels <= 0 || rmctx->nb_channels > 2 /*|| ((rmctx->channels * 1024) != q->samples_per_frame)*/) {
923 DEBUGF("Channel configuration error!\n");
924 return -1;
928 if(rmctx->block_align >= UINT16_MAX/2)
929 return -1;
932 /* Initialize the VLC tables. */
933 if (!vlcs_initialized) {
934 for (i=0 ; i<7 ; i++) {
935 spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
936 spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
937 init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
938 huff_bits[i], 1, 1,
939 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
942 vlcs_initialized = 1;
946 init_atrac3_transforms();
948 /* init the joint-stereo decoding data */
949 q->weighting_delay[0] = 0;
950 q->weighting_delay[1] = 7;
951 q->weighting_delay[2] = 0;
952 q->weighting_delay[3] = 7;
953 q->weighting_delay[4] = 0;
954 q->weighting_delay[5] = 7;
956 for (i=0; i<4; i++) {
957 q->matrix_coeff_index_prev[i] = 3;
958 q->matrix_coeff_index_now[i] = 3;
959 q->matrix_coeff_index_next[i] = 3;
962 q->pUnits = channel_units;
964 return 0;