FS#10785: Add new context CONTEXT_MORSE_INPUT for keymaps which is used during morse...
[kugel-rb.git] / apps / codecs / libatrac / atrac3.c
blobcd49aec348213991f1b1589373802a0ae50e737b
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 static int32_t qmf_window[48] IBSS_ATTR;
59 static VLC spectral_coeff_tab[7];
60 static channel_unit channel_units[2] IBSS_ATTR_LARGE_IRAM;
62 /**
63 * Matrixing within quadrature mirror synthesis filter.
65 * @param p3 output buffer
66 * @param inlo lower part of spectrum
67 * @param inhi higher part of spectrum
68 * @param nIn size of spectrum buffer
71 #if defined(CPU_ARM)
72 extern void
73 atrac3_iqmf_matrixing(int32_t *p3,
74 int32_t *inlo,
75 int32_t *inhi,
76 unsigned int nIn);
77 #else
78 static inline void
79 atrac3_iqmf_matrixing(int32_t *p3,
80 int32_t *inlo,
81 int32_t *inhi,
82 unsigned int nIn)
84 uint32_t i;
85 for(i=0; i<nIn; i+=2){
86 p3[2*i+0] = inlo[i ] + inhi[i ];
87 p3[2*i+1] = inlo[i ] - inhi[i ];
88 p3[2*i+2] = inlo[i+1] + inhi[i+1];
89 p3[2*i+3] = inlo[i+1] - inhi[i+1];
92 #endif
94 /**
95 * Matrixing within quadrature mirror synthesis filter.
97 * @param out output buffer
98 * @param in input buffer
99 * @param win windowing coefficients
100 * @param nIn size of spectrum buffer
103 #if defined(CPU_ARM)
104 extern void
105 atrac3_iqmf_dewindowing(int32_t *out,
106 int32_t *in,
107 int32_t *win,
108 unsigned int nIn);
109 #else
110 static inline void
111 atrac3_iqmf_dewindowing(int32_t *out,
112 int32_t *in,
113 int32_t *win,
114 unsigned int nIn)
116 int32_t i, j, s1, s2;
118 for (j = nIn; j != 0; j--) {
119 /* i=0 */
120 s1 = fixmul31(win[0], in[0]);
121 s2 = fixmul31(win[1], in[1]);
123 /* i=2..46 */
124 for (i = 2; i < 48; i += 2) {
125 s1 += fixmul31(win[i ], in[i ]);
126 s2 += fixmul31(win[i+1], in[i+1]);
129 out[0] = s2;
130 out[1] = s1;
132 in += 2;
133 out += 2;
136 #endif
139 * IMDCT windowing.
141 * @param buffer sample buffer
142 * @param win window coefficients
145 static inline void
146 atrac3_imdct_windowing(int32_t *buffer,
147 const int32_t *win)
149 int32_t i;
150 /* win[0..127] = win[511..384], win[128..383] = 1 */
151 for(i = 0; i<128; i++) {
152 buffer[ i] = fixmul31(win[i], buffer[ i]);
153 buffer[511-i] = fixmul31(win[i], buffer[511-i]);
158 * Quadrature mirror synthesis filter.
160 * @param inlo lower part of spectrum
161 * @param inhi higher part of spectrum
162 * @param nIn size of spectrum buffer
163 * @param pOut out buffer
164 * @param delayBuf delayBuf buffer
165 * @param temp temp buffer
168 static void iqmf (int32_t *inlo, int32_t *inhi, unsigned int nIn, int32_t *pOut, int32_t *delayBuf, int32_t *temp)
170 /* Restore the delay buffer */
171 memcpy(temp, delayBuf, 46*sizeof(int32_t));
173 /* loop1: matrixing */
174 atrac3_iqmf_matrixing(temp + 46, inlo, inhi, nIn);
176 /* loop2: dewindowing */
177 atrac3_iqmf_dewindowing(pOut, temp, qmf_window, nIn);
179 /* Save the delay buffer */
180 memcpy(delayBuf, temp + (nIn << 1), 46*sizeof(int32_t));
184 * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
185 * caused by the reverse spectra of the QMF.
187 * @param pInput float input
188 * @param pOutput float output
189 * @param odd_band 1 if the band is an odd band
192 static void IMLT(int32_t *pInput, int32_t *pOutput, int odd_band)
194 int i;
195 if (odd_band) {
197 * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
198 * or it gives better compression to do it this way.
199 * FIXME: It should be possible to handle this in ff_imdct_calc
200 * for that to happen a modification of the prerotation step of
201 * all SIMD code and C code is needed.
202 * Or fix the functions before so they generate a pre reversed spectrum.
205 for (i=0; i<128; i++)
206 FFSWAP(int32_t, pInput[i], pInput[255-i]);
209 /* Apply the imdct. */
210 mdct_backward(512, pInput, pOutput);
212 /* Windowing. */
213 atrac3_imdct_windowing(pOutput, window_lookup);
218 * Atrac 3 indata descrambling, only used for data coming from the rm container
220 * @param in pointer to 8 bit array of indata
221 * @param bits amount of bits
222 * @param out pointer to 8 bit array of outdata
225 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
226 int i, off;
227 uint32_t c;
228 const uint32_t* buf;
229 uint32_t* obuf = (uint32_t*) out;
231 #if ((defined(TEST) || defined(SIMULATOR)) && !defined(CPU_ARM))
232 off = 0; //no check for memory alignment of inbuffer
233 #else
234 off = (intptr_t)inbuffer & 3;
235 #endif /* TEST */
236 buf = (const uint32_t*) (inbuffer - off);
238 c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
239 bytes += 3 + off;
240 for (i = 0; i < bytes/4; i++)
241 obuf[i] = c ^ buf[i];
243 return off;
247 static void init_atrac3_transforms(void) {
248 int32_t s;
249 int i;
251 /* Generate the mdct window, for details see
252 * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
254 /* mdct window had been generated and saved as a lookup table in atrac3data_fixed.h */
256 /* Generate the QMF window. */
257 for (i=0 ; i<24; i++) {
258 s = qmf_48tap_half_fix[i] << 1;
259 qmf_window[i] = s;
260 qmf_window[47 - i] = s;
265 * Mantissa decoding
267 * @param gb the GetBit context
268 * @param selector what table is the output values coded with
269 * @param codingFlag constant length coding or variable length coding
270 * @param mantissas mantissa output table
271 * @param numCodes amount of values to get
274 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
276 int numBits, cnt, code, huffSymb;
278 if (selector == 1)
279 numCodes /= 2;
281 if (codingFlag != 0) {
282 /* constant length coding (CLC) */
283 numBits = CLCLengthTab[selector];
285 if (selector > 1) {
286 for (cnt = 0; cnt < numCodes; cnt++) {
287 if (numBits)
288 code = get_sbits(gb, numBits);
289 else
290 code = 0;
291 mantissas[cnt] = code;
293 } else {
294 for (cnt = 0; cnt < numCodes; cnt++) {
295 if (numBits)
296 code = get_bits(gb, numBits); //numBits is always 4 in this case
297 else
298 code = 0;
299 mantissas[cnt*2] = seTab_0[code >> 2];
300 mantissas[cnt*2+1] = seTab_0[code & 3];
303 } else {
304 /* variable length coding (VLC) */
305 if (selector != 1) {
306 for (cnt = 0; cnt < numCodes; cnt++) {
307 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
308 huffSymb += 1;
309 code = huffSymb >> 1;
310 if (huffSymb & 1)
311 code = -code;
312 mantissas[cnt] = code;
314 } else {
315 for (cnt = 0; cnt < numCodes; cnt++) {
316 huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
317 mantissas[cnt*2] = decTable1[huffSymb*2];
318 mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
325 * Restore the quantized band spectrum coefficients
327 * @param gb the GetBit context
328 * @param pOut decoded band spectrum
329 * @return outSubbands subband counter, fix for broken specification/files
332 static int decodeSpectrum (GetBitContext *gb, int32_t *pOut)
334 int numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
335 int subband_vlc_index[32], SF_idxs[32];
336 int mantissas[128];
337 int32_t SF;
339 numSubbands = get_bits(gb, 5); // number of coded subbands
340 codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
342 /* Get the VLC selector table for the subbands, 0 means not coded. */
343 for (cnt = 0; cnt <= numSubbands; cnt++)
344 subband_vlc_index[cnt] = get_bits(gb, 3);
346 /* Read the scale factor indexes from the stream. */
347 for (cnt = 0; cnt <= numSubbands; cnt++) {
348 if (subband_vlc_index[cnt] != 0)
349 SF_idxs[cnt] = get_bits(gb, 6);
352 for (cnt = 0; cnt <= numSubbands; cnt++) {
353 first = subbandTab[cnt];
354 last = subbandTab[cnt+1];
356 subbWidth = last - first;
358 if (subband_vlc_index[cnt] != 0) {
359 /* Decode spectral coefficients for this subband. */
360 /* TODO: This can be done faster is several blocks share the
361 * same VLC selector (subband_vlc_index) */
362 readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
364 /* Decode the scale factor for this subband. */
365 SF = fixmul31(SFTable_fixed[SF_idxs[cnt]], iMaxQuant_fix[subband_vlc_index[cnt]]);
367 /* Inverse quantize the coefficients. */
368 for (pIn=mantissas ; first<last; first++, pIn++)
369 pOut[first] = fixmul16(*pIn, SF);
370 } else {
371 /* This subband was not coded, so zero the entire subband. */
372 memset(pOut+first, 0, subbWidth*sizeof(int32_t));
376 /* Clear the subbands that were not coded. */
377 first = subbandTab[cnt];
378 memset(pOut+first, 0, (1024 - first) * sizeof(int32_t));
379 return numSubbands;
383 * Restore the quantized tonal components
385 * @param gb the GetBit context
386 * @param pComponent tone component
387 * @param numBands amount of coded bands
390 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
392 int i,j,k,cnt;
393 int components, coding_mode_selector, coding_mode, coded_values_per_component;
394 int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
395 int band_flags[4], mantissa[8];
396 int32_t *pCoef;
397 int32_t scalefactor;
398 int component_count = 0;
400 components = get_bits(gb,5);
402 /* no tonal components */
403 if (components == 0)
404 return 0;
406 coding_mode_selector = get_bits(gb,2);
407 if (coding_mode_selector == 2)
408 return -1;
410 coding_mode = coding_mode_selector & 1;
412 for (i = 0; i < components; i++) {
413 for (cnt = 0; cnt <= numBands; cnt++)
414 band_flags[cnt] = get_bits1(gb);
416 coded_values_per_component = get_bits(gb,3);
418 quant_step_index = get_bits(gb,3);
419 if (quant_step_index <= 1)
420 return -1;
422 if (coding_mode_selector == 3)
423 coding_mode = get_bits1(gb);
425 for (j = 0; j < (numBands + 1) * 4; j++) {
426 if (band_flags[j >> 2] == 0)
427 continue;
429 coded_components = get_bits(gb,3);
431 for (k=0; k<coded_components; k++) {
432 sfIndx = get_bits(gb,6);
433 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
434 max_coded_values = 1024 - pComponent[component_count].pos;
435 coded_values = coded_values_per_component + 1;
436 coded_values = FFMIN(max_coded_values,coded_values);
438 scalefactor = fixmul31(SFTable_fixed[sfIndx], iMaxQuant_fix[quant_step_index]);
440 readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
442 pComponent[component_count].numCoefs = coded_values;
444 /* inverse quant */
445 pCoef = pComponent[component_count].coef;
446 for (cnt = 0; cnt < coded_values; cnt++)
447 pCoef[cnt] = fixmul16(mantissa[cnt], scalefactor);
449 component_count++;
454 return component_count;
458 * Decode gain parameters for the coded bands
460 * @param gb the GetBit context
461 * @param pGb the gainblock for the current band
462 * @param numBands amount of coded bands
465 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
467 int i, cf, numData;
468 int *pLevel, *pLoc;
470 gain_info *pGain = pGb->gBlock;
472 for (i=0 ; i<=numBands; i++)
474 numData = get_bits(gb,3);
475 pGain[i].num_gain_data = numData;
476 pLevel = pGain[i].levcode;
477 pLoc = pGain[i].loccode;
479 for (cf = 0; cf < numData; cf++){
480 pLevel[cf]= get_bits(gb,4);
481 pLoc [cf]= get_bits(gb,5);
482 if(cf && pLoc[cf] <= pLoc[cf-1])
483 return -1;
487 /* Clear the unused blocks. */
488 for (; i<4 ; i++)
489 pGain[i].num_gain_data = 0;
491 return 0;
495 * Apply gain parameters and perform the MDCT overlapping part
497 * @param pIn input float buffer
498 * @param pPrev previous float buffer to perform overlap against
499 * @param pOut output float buffer
500 * @param pGain1 current band gain info
501 * @param pGain2 next band gain info
504 static void gainCompensateAndOverlap (int32_t *pIn, int32_t *pPrev, int32_t *pOut, gain_info *pGain1, gain_info *pGain2)
506 /* gain compensation function */
507 int32_t gain1, gain2, gain_inc;
508 int cnt, numdata, nsample, startLoc, endLoc;
510 if (pGain2->num_gain_data == 0)
511 gain1 = ONE_16;
512 else
513 gain1 = gain_tab1[pGain2->levcode[0]];
515 if (pGain1->num_gain_data == 0) {
516 for (cnt = 0; cnt < 256; cnt++)
517 pOut[cnt] = fixmul16(pIn[cnt], gain1) + pPrev[cnt];
518 } else {
519 numdata = pGain1->num_gain_data;
520 pGain1->loccode[numdata] = 32;
521 pGain1->levcode[numdata] = 4;
523 nsample = 0; // current sample = 0
525 for (cnt = 0; cnt < numdata; cnt++) {
526 startLoc = pGain1->loccode[cnt] * 8;
527 endLoc = startLoc + 8;
529 gain2 = gain_tab1[pGain1->levcode[cnt]];
530 gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
532 /* interpolate */
533 for (; nsample < startLoc; nsample++)
534 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]), gain2);
536 /* interpolation is done over eight samples */
537 for (; nsample < endLoc; nsample++) {
538 pOut[nsample] = fixmul16((fixmul16(pIn[nsample], gain1) + pPrev[nsample]),gain2);
539 gain2 = fixmul16(gain2, gain_inc);
543 for (; nsample < 256; nsample++)
544 pOut[nsample] = fixmul16(pIn[nsample], gain1) + pPrev[nsample];
547 /* Delay for the overlapping part. */
548 memcpy(pPrev, &pIn[256], 256*sizeof(int32_t));
552 * Combine the tonal band spectrum and regular band spectrum
553 * Return position of the last tonal coefficient
556 * @param pSpectrum output spectrum buffer
557 * @param numComponents amount of tonal components
558 * @param pComponent tonal components for this band
561 static int addTonalComponents (int32_t *pSpectrum, int numComponents, tonal_component *pComponent)
563 int cnt, i, lastPos = -1;
564 int32_t *pOut;
565 int32_t *pIn;
567 for (cnt = 0; cnt < numComponents; cnt++){
568 lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
569 pIn = pComponent[cnt].coef;
570 pOut = &(pSpectrum[pComponent[cnt].pos]);
572 for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
573 pOut[i] += pIn[i];
576 return lastPos;
580 #define INTERPOLATE(old,new,nsample) ((old*ONE_16) + fixmul16(((nsample*ONE_16)>>3), (((new) - (old))*ONE_16)))
582 static void reverseMatrixing(int32_t *su1, int32_t *su2, int *pPrevCode, int *pCurrCode)
584 int i, band, nsample, s1, s2;
585 int32_t c1, c2;
586 int32_t mc1_l, mc1_r, mc2_l, mc2_r;
588 for (i=0,band = 0; band < 4*256; band+=256,i++) {
589 s1 = pPrevCode[i];
590 s2 = pCurrCode[i];
591 nsample = 0;
593 if (s1 != s2) {
594 /* Selector value changed, interpolation needed. */
595 mc1_l = matrixCoeffs_fix[s1<<1];
596 mc1_r = matrixCoeffs_fix[(s1<<1)+1];
597 mc2_l = matrixCoeffs_fix[s2<<1];
598 mc2_r = matrixCoeffs_fix[(s2<<1)+1];
600 /* Interpolation is done over the first eight samples. */
601 for(; nsample < 8; nsample++) {
602 c1 = su1[band+nsample];
603 c2 = su2[band+nsample];
604 c2 = fixmul16(c1, INTERPOLATE(mc1_l, mc2_l, nsample)) + fixmul16(c2, INTERPOLATE(mc1_r, mc2_r, nsample));
605 su1[band+nsample] = c2;
606 su2[band+nsample] = (c1 << 1) - c2;
610 /* Apply the matrix without interpolation. */
611 switch (s2) {
612 case 0: /* M/S decoding */
613 for (; nsample < 256; nsample++) {
614 c1 = su1[band+nsample];
615 c2 = su2[band+nsample];
616 su1[band+nsample] = c2 << 1;
617 su2[band+nsample] = (c1 - c2) << 1;
619 break;
621 case 1:
622 for (; nsample < 256; nsample++) {
623 c1 = su1[band+nsample];
624 c2 = su2[band+nsample];
625 su1[band+nsample] = (c1 + c2) << 1;
626 su2[band+nsample] = -1*(c2 << 1);
628 break;
629 case 2:
630 case 3:
631 for (; nsample < 256; nsample++) {
632 c1 = su1[band+nsample];
633 c2 = su2[band+nsample];
634 su1[band+nsample] = c1 + c2;
635 su2[band+nsample] = c1 - c2;
637 break;
638 default:
639 //assert(0);
640 break;
645 static void getChannelWeights (int indx, int flag, int32_t ch[2]){
646 if (indx == 7) {
647 ch[0] = ONE_16;
648 ch[1] = ONE_16;
649 } else {
650 ch[0] = fixdiv16(((indx & 7)*ONE_16), 7*ONE_16);
651 ch[1] = fastSqrt((ONE_16 << 1) - fixmul16(ch[0], ch[0]));
652 if(flag)
653 FFSWAP(int32_t, ch[0], ch[1]);
657 static void channelWeighting (int32_t *su1, int32_t *su2, int *p3)
659 int band, nsample;
660 /* w[x][y] y=0 is left y=1 is right */
661 int32_t w[2][2];
663 if (p3[1] != 7 || p3[3] != 7){
664 getChannelWeights(p3[1], p3[0], w[0]);
665 getChannelWeights(p3[3], p3[2], w[1]);
667 for(band = 1; band < 4; band++) {
668 /* scale the channels by the weights */
669 for(nsample = 0; nsample < 8; nsample++) {
670 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], INTERPOLATE(w[0][0], w[0][1], nsample));
671 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], INTERPOLATE(w[1][0], w[1][1], nsample));
674 for(; nsample < 256; nsample++) {
675 su1[band*256+nsample] = fixmul16(su1[band*256+nsample], w[1][0]);
676 su2[band*256+nsample] = fixmul16(su2[band*256+nsample], w[1][1]);
684 * Decode a Sound Unit
686 * @param gb the GetBit context
687 * @param pSnd the channel unit to be used
688 * @param pOut the decoded samples before IQMF in float representation
689 * @param channelNum channel number
690 * @param codingMode the coding mode (JOINT_STEREO or regular stereo/mono)
694 static int decodeChannelSoundUnit (GetBitContext *gb, channel_unit *pSnd, int32_t *pOut, int channelNum, int codingMode)
696 int band, result=0, numSubbands, lastTonal, numBands;
697 if (codingMode == JOINT_STEREO && channelNum == 1) {
698 if (get_bits(gb,2) != 3) {
699 DEBUGF("JS mono Sound Unit id != 3.\n");
700 return -1;
702 } else {
703 if (get_bits(gb,6) != 0x28) {
704 DEBUGF("Sound Unit id != 0x28.\n");
705 return -1;
709 /* number of coded QMF bands */
710 pSnd->bandsCoded = get_bits(gb,2);
712 result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
713 if (result) return result;
715 pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
716 if (pSnd->numComponents == -1) return -1;
718 numSubbands = decodeSpectrum (gb, pSnd->spectrum);
720 /* Merge the decoded spectrum and tonal components. */
721 lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
724 /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
725 numBands = (subbandTab[numSubbands] - 1) >> 8;
726 if (lastTonal >= 0)
727 numBands = FFMAX((lastTonal + 256) >> 8, numBands);
729 /* Remark: Hardcoded hack to add 2 bits (empty) fract part to internal sample
730 * representation. Needed for higher accuracy in internal calculations as
731 * well as for DSP configuration. See also: ../atrac3_rm.c, DSP_SET_SAMPLE_DEPTH
732 * Todo: Check spectral requantisation for using and outputting samples with
733 * fract part. */
734 int32_t i;
735 for (i=0; i<1024; ++i) {
736 pSnd->spectrum[i] <<= 2;
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 int *data_size, const uint8_t *buf, int buf_size) {
866 int result = 0, off = 0;
867 const uint8_t* databuf;
869 if (buf_size < rmctx->block_align)
870 return buf_size;
872 /* Check if we need to descramble and what buffer to pass on. */
873 if (q->scrambled_stream) {
874 off = decode_bytes(buf, q->decoded_bytes_buffer, rmctx->block_align);
875 databuf = q->decoded_bytes_buffer;
876 } else {
877 databuf = buf;
880 result = decodeFrame(q, databuf, off);
882 if (result != 0) {
883 DEBUGF("Frame decoding error!\n");
884 return -1;
887 if (q->channels == 1)
888 *data_size = 1024 * sizeof(int32_t);
889 else
890 *data_size = 2048 * sizeof(int32_t);
892 return rmctx->block_align;
897 * Atrac3 initialization
899 * @param rmctx pointer to the RMContext
902 int atrac3_decode_init(ATRAC3Context *q, RMContext *rmctx)
904 int i;
905 uint8_t *edata_ptr = rmctx->codec_extradata;
906 static VLC_TYPE atrac3_vlc_table[4096][2];
907 static int vlcs_initialized = 0;
909 /* Take data from the AVCodecContext (RM container). */
910 q->sample_rate = rmctx->sample_rate;
911 q->channels = rmctx->nb_channels;
912 q->bit_rate = rmctx->bit_rate;
913 q->bits_per_frame = rmctx->block_align * 8;
914 q->bytes_per_frame = rmctx->block_align;
916 /* Take care of the codec-specific extradata. */
917 if (rmctx->extradata_size == 14) {
918 /* Parse the extradata, WAV format */
919 DEBUGF("[0-1] %d\n",rm_get_uint16le(&edata_ptr[0])); //Unknown value always 1
920 q->samples_per_channel = rm_get_uint32le(&edata_ptr[2]);
921 q->codingMode = rm_get_uint16le(&edata_ptr[6]);
922 DEBUGF("[8-9] %d\n",rm_get_uint16le(&edata_ptr[8])); //Dupe of coding mode
923 q->frame_factor = rm_get_uint16le(&edata_ptr[10]); //Unknown always 1
924 DEBUGF("[12-13] %d\n",rm_get_uint16le(&edata_ptr[12])); //Unknown always 0
926 /* setup */
927 q->samples_per_frame = 1024 * q->channels;
928 q->atrac3version = 4;
929 q->delay = 0x88E;
930 if (q->codingMode)
931 q->codingMode = JOINT_STEREO;
932 else
933 q->codingMode = STEREO;
934 q->scrambled_stream = 0;
936 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)) {
937 } else {
938 DEBUGF("Unknown frame/channel/frame_factor configuration %d/%d/%d\n", q->bytes_per_frame, q->channels, q->frame_factor);
939 return -1;
942 } else if (rmctx->extradata_size == 10) {
943 /* Parse the extradata, RM format. */
944 q->atrac3version = rm_get_uint32be(&edata_ptr[0]);
945 q->samples_per_frame = rm_get_uint16be(&edata_ptr[4]);
946 q->delay = rm_get_uint16be(&edata_ptr[6]);
947 q->codingMode = rm_get_uint16be(&edata_ptr[8]);
949 q->samples_per_channel = q->samples_per_frame / q->channels;
950 q->scrambled_stream = 1;
952 } else {
953 DEBUGF("Unknown extradata size %d.\n",rmctx->extradata_size);
955 /* Check the extradata. */
957 if (q->atrac3version != 4) {
958 DEBUGF("Version %d != 4.\n",q->atrac3version);
959 return -1;
962 if (q->samples_per_frame != 1024 && q->samples_per_frame != 2048) {
963 DEBUGF("Unknown amount of samples per frame %d.\n",q->samples_per_frame);
964 return -1;
967 if (q->delay != 0x88E) {
968 DEBUGF("Unknown amount of delay %x != 0x88E.\n",q->delay);
969 return -1;
972 if (q->codingMode == STEREO) {
973 DEBUGF("Normal stereo detected.\n");
974 } else if (q->codingMode == JOINT_STEREO) {
975 DEBUGF("Joint stereo detected.\n");
976 } else {
977 DEBUGF("Unknown channel coding mode %x!\n",q->codingMode);
978 return -1;
981 if (rmctx->nb_channels <= 0 || rmctx->nb_channels > 2 /*|| ((rmctx->channels * 1024) != q->samples_per_frame)*/) {
982 DEBUGF("Channel configuration error!\n");
983 return -1;
987 if(rmctx->block_align >= UINT16_MAX/2)
988 return -1;
991 /* Initialize the VLC tables. */
992 if (!vlcs_initialized) {
993 for (i=0 ; i<7 ; i++) {
994 spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
995 spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
996 init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
997 huff_bits[i], 1, 1,
998 huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
1001 vlcs_initialized = 1;
1005 init_atrac3_transforms();
1007 /* init the joint-stereo decoding data */
1008 q->weighting_delay[0] = 0;
1009 q->weighting_delay[1] = 7;
1010 q->weighting_delay[2] = 0;
1011 q->weighting_delay[3] = 7;
1012 q->weighting_delay[4] = 0;
1013 q->weighting_delay[5] = 7;
1015 for (i=0; i<4; i++) {
1016 q->matrix_coeff_index_prev[i] = 3;
1017 q->matrix_coeff_index_now[i] = 3;
1018 q->matrix_coeff_index_next[i] = 3;
1021 q->pUnits = channel_units;
1023 return 0;