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