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