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