atrac3.c
Go to the documentation of this file.
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 
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 #define SAMPLES_PER_FRAME 1024
53 #define MDCT_SIZE 512
54 
55 /* These structures are needed to store the parsed gain control data. */
56 typedef struct {
58  int levcode[8];
59  int loccode[8];
60 } gain_info;
61 
62 typedef struct {
63  gain_info gBlock[4];
64 } gain_block;
65 
66 typedef struct {
67  int pos;
68  int numCoefs;
69  float coef[8];
71 
72 typedef struct {
75  tonal_component components[64];
76  float prevFrame[SAMPLES_PER_FRAME];
78  gain_block gainBlock[2];
79 
80  DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
81  DECLARE_ALIGNED(32, float, IMDCT_buf)[SAMPLES_PER_FRAME];
82 
83  float delayBuf1[46];
84  float delayBuf2[46];
85  float delayBuf3[46];
86 } channel_unit;
87 
88 typedef struct {
92 
93  int channels;
95  int bit_rate;
99 
102  int pBs;
105 
106 
107  int matrix_coeff_index_prev[4];
108  int matrix_coeff_index_now[4];
109  int matrix_coeff_index_next[4];
110  int weighting_delay[6];
112 
113 
114  float *outSamples[2];
116  float tempBuf[1070];
118 
119 
121  int delay;
125 
128 } ATRAC3Context;
129 
132 static float gain_tab1[16];
133 static float gain_tab2[31];
135 
136 
146 static void IMLT(ATRAC3Context *q, float *pInput, float *pOutput, int odd_band)
147 {
148  int i;
149 
150  if (odd_band) {
160  for (i=0; i<128; i++)
161  FFSWAP(float, pInput[i], pInput[255-i]);
162  }
163 
164  q->mdct_ctx.imdct_calc(&q->mdct_ctx,pOutput,pInput);
165 
166  /* Perform windowing on the output. */
167  dsp.vector_fmul(pOutput, pOutput, mdct_window, MDCT_SIZE);
168 
169 }
170 
171 
180 static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
181  int i, off;
182  uint32_t c;
183  const uint32_t* buf;
184  uint32_t* obuf = (uint32_t*) out;
185 
186  off = (intptr_t)inbuffer & 3;
187  buf = (const uint32_t *)(inbuffer - off);
188  if (off)
189  c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
190  else
191  c = av_be2ne32(0x537F6103U);
192  bytes += 3 + off;
193  for (i = 0; i < bytes/4; i++)
194  obuf[i] = c ^ buf[i];
195 
196  if (off)
197  av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
198 
199  return off;
200 }
201 
202 
203 static av_cold int init_atrac3_transforms(ATRAC3Context *q, int is_float) {
204  float enc_window[256];
205  int i;
206 
207  /* Generate the mdct window, for details see
208  * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
209  for (i=0 ; i<256; i++)
210  enc_window[i] = (sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0) * 0.5;
211 
212  if (!mdct_window[0])
213  for (i=0 ; i<256; i++) {
214  mdct_window[i] = enc_window[i]/(enc_window[i]*enc_window[i] + enc_window[255-i]*enc_window[255-i]);
215  mdct_window[511-i] = mdct_window[i];
216  }
217 
218  /* Initialize the MDCT transform. */
219  return ff_mdct_init(&q->mdct_ctx, 9, 1, is_float ? 1.0 / 32768 : 1.0);
220 }
221 
227 {
228  ATRAC3Context *q = avctx->priv_data;
229 
230  av_free(q->pUnits);
232  av_freep(&q->outSamples[0]);
233 
234  ff_mdct_end(&q->mdct_ctx);
235 
236  return 0;
237 }
238 
249 static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes)
250 {
251  int numBits, cnt, code, huffSymb;
252 
253  if (selector == 1)
254  numCodes /= 2;
255 
256  if (codingFlag != 0) {
257  /* constant length coding (CLC) */
258  numBits = CLCLengthTab[selector];
259 
260  if (selector > 1) {
261  for (cnt = 0; cnt < numCodes; cnt++) {
262  if (numBits)
263  code = get_sbits(gb, numBits);
264  else
265  code = 0;
266  mantissas[cnt] = code;
267  }
268  } else {
269  for (cnt = 0; cnt < numCodes; cnt++) {
270  if (numBits)
271  code = get_bits(gb, numBits); //numBits is always 4 in this case
272  else
273  code = 0;
274  mantissas[cnt*2] = seTab_0[code >> 2];
275  mantissas[cnt*2+1] = seTab_0[code & 3];
276  }
277  }
278  } else {
279  /* variable length coding (VLC) */
280  if (selector != 1) {
281  for (cnt = 0; cnt < numCodes; cnt++) {
282  huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
283  huffSymb += 1;
284  code = huffSymb >> 1;
285  if (huffSymb & 1)
286  code = -code;
287  mantissas[cnt] = code;
288  }
289  } else {
290  for (cnt = 0; cnt < numCodes; cnt++) {
291  huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
292  mantissas[cnt*2] = decTable1[huffSymb*2];
293  mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
294  }
295  }
296  }
297 }
298 
307 static int decodeSpectrum (GetBitContext *gb, float *pOut)
308 {
309  int numSubbands, codingMode, cnt, first, last, subbWidth, *pIn;
310  int subband_vlc_index[32], SF_idxs[32];
311  int mantissas[128];
312  float SF;
313 
314  numSubbands = get_bits(gb, 5); // number of coded subbands
315  codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
316 
317  /* Get the VLC selector table for the subbands, 0 means not coded. */
318  for (cnt = 0; cnt <= numSubbands; cnt++)
319  subband_vlc_index[cnt] = get_bits(gb, 3);
320 
321  /* Read the scale factor indexes from the stream. */
322  for (cnt = 0; cnt <= numSubbands; cnt++) {
323  if (subband_vlc_index[cnt] != 0)
324  SF_idxs[cnt] = get_bits(gb, 6);
325  }
326 
327  for (cnt = 0; cnt <= numSubbands; cnt++) {
328  first = subbandTab[cnt];
329  last = subbandTab[cnt+1];
330 
331  subbWidth = last - first;
332 
333  if (subband_vlc_index[cnt] != 0) {
334  /* Decode spectral coefficients for this subband. */
335  /* TODO: This can be done faster is several blocks share the
336  * same VLC selector (subband_vlc_index) */
337  readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
338 
339  /* Decode the scale factor for this subband. */
340  SF = ff_atrac_sf_table[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
341 
342  /* Inverse quantize the coefficients. */
343  for (pIn=mantissas ; first<last; first++, pIn++)
344  pOut[first] = *pIn * SF;
345  } else {
346  /* This subband was not coded, so zero the entire subband. */
347  memset(pOut+first, 0, subbWidth*sizeof(float));
348  }
349  }
350 
351  /* Clear the subbands that were not coded. */
352  first = subbandTab[cnt];
353  memset(pOut+first, 0, (SAMPLES_PER_FRAME - first) * sizeof(float));
354  return numSubbands;
355 }
356 
365 static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
366 {
367  int i,j,k,cnt;
368  int components, coding_mode_selector, coding_mode, coded_values_per_component;
369  int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
370  int band_flags[4], mantissa[8];
371  float *pCoef;
372  float scalefactor;
373  int component_count = 0;
374 
375  components = get_bits(gb,5);
376 
377  /* no tonal components */
378  if (components == 0)
379  return 0;
380 
381  coding_mode_selector = get_bits(gb,2);
382  if (coding_mode_selector == 2)
383  return AVERROR_INVALIDDATA;
384 
385  coding_mode = coding_mode_selector & 1;
386 
387  for (i = 0; i < components; i++) {
388  for (cnt = 0; cnt <= numBands; cnt++)
389  band_flags[cnt] = get_bits1(gb);
390 
391  coded_values_per_component = get_bits(gb,3);
392 
393  quant_step_index = get_bits(gb,3);
394  if (quant_step_index <= 1)
395  return AVERROR_INVALIDDATA;
396 
397  if (coding_mode_selector == 3)
398  coding_mode = get_bits1(gb);
399 
400  for (j = 0; j < (numBands + 1) * 4; j++) {
401  if (band_flags[j >> 2] == 0)
402  continue;
403 
404  coded_components = get_bits(gb,3);
405 
406  for (k=0; k<coded_components; k++) {
407  sfIndx = get_bits(gb,6);
408  if (component_count >= 64)
409  return AVERROR_INVALIDDATA;
410  pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
411  max_coded_values = SAMPLES_PER_FRAME - pComponent[component_count].pos;
412  coded_values = coded_values_per_component + 1;
413  coded_values = FFMIN(max_coded_values,coded_values);
414 
415  scalefactor = ff_atrac_sf_table[sfIndx] * iMaxQuant[quant_step_index];
416 
417  readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
418 
419  pComponent[component_count].numCoefs = coded_values;
420 
421  /* inverse quant */
422  pCoef = pComponent[component_count].coef;
423  for (cnt = 0; cnt < coded_values; cnt++)
424  pCoef[cnt] = mantissa[cnt] * scalefactor;
425 
426  component_count++;
427  }
428  }
429  }
430 
431  return component_count;
432 }
433 
442 static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
443 {
444  int i, cf, numData;
445  int *pLevel, *pLoc;
446 
447  gain_info *pGain = pGb->gBlock;
448 
449  for (i=0 ; i<=numBands; i++)
450  {
451  numData = get_bits(gb,3);
452  pGain[i].num_gain_data = numData;
453  pLevel = pGain[i].levcode;
454  pLoc = pGain[i].loccode;
455 
456  for (cf = 0; cf < numData; cf++){
457  pLevel[cf]= get_bits(gb,4);
458  pLoc [cf]= get_bits(gb,5);
459  if(cf && pLoc[cf] <= pLoc[cf-1])
460  return AVERROR_INVALIDDATA;
461  }
462  }
463 
464  /* Clear the unused blocks. */
465  for (; i<4 ; i++)
466  pGain[i].num_gain_data = 0;
467 
468  return 0;
469 }
470 
481 static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
482 {
483  /* gain compensation function */
484  float gain1, gain2, gain_inc;
485  int cnt, numdata, nsample, startLoc, endLoc;
486 
487 
488  if (pGain2->num_gain_data == 0)
489  gain1 = 1.0;
490  else
491  gain1 = gain_tab1[pGain2->levcode[0]];
492 
493  if (pGain1->num_gain_data == 0) {
494  for (cnt = 0; cnt < 256; cnt++)
495  pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
496  } else {
497  numdata = pGain1->num_gain_data;
498  pGain1->loccode[numdata] = 32;
499  pGain1->levcode[numdata] = 4;
500 
501  nsample = 0; // current sample = 0
502 
503  for (cnt = 0; cnt < numdata; cnt++) {
504  startLoc = pGain1->loccode[cnt] * 8;
505  endLoc = startLoc + 8;
506 
507  gain2 = gain_tab1[pGain1->levcode[cnt]];
508  gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
509 
510  /* interpolate */
511  for (; nsample < startLoc; nsample++)
512  pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
513 
514  /* interpolation is done over eight samples */
515  for (; nsample < endLoc; nsample++) {
516  pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
517  gain2 *= gain_inc;
518  }
519  }
520 
521  for (; nsample < 256; nsample++)
522  pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
523  }
524 
525  /* Delay for the overlapping part. */
526  memcpy(pPrev, &pIn[256], 256*sizeof(float));
527 }
528 
538 static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
539 {
540  int cnt, i, lastPos = -1;
541  float *pIn, *pOut;
542 
543  for (cnt = 0; cnt < numComponents; cnt++){
544  lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
545  pIn = pComponent[cnt].coef;
546  pOut = &(pSpectrum[pComponent[cnt].pos]);
547 
548  for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
549  pOut[i] += pIn[i];
550  }
551 
552  return lastPos;
553 }
554 
555 
556 #define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
557 
558 static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
559 {
560  int i, band, nsample, s1, s2;
561  float c1, c2;
562  float mc1_l, mc1_r, mc2_l, mc2_r;
563 
564  for (i=0,band = 0; band < 4*256; band+=256,i++) {
565  s1 = pPrevCode[i];
566  s2 = pCurrCode[i];
567  nsample = 0;
568 
569  if (s1 != s2) {
570  /* Selector value changed, interpolation needed. */
571  mc1_l = matrixCoeffs[s1*2];
572  mc1_r = matrixCoeffs[s1*2+1];
573  mc2_l = matrixCoeffs[s2*2];
574  mc2_r = matrixCoeffs[s2*2+1];
575 
576  /* Interpolation is done over the first eight samples. */
577  for(; nsample < 8; nsample++) {
578  c1 = su1[band+nsample];
579  c2 = su2[band+nsample];
580  c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
581  su1[band+nsample] = c2;
582  su2[band+nsample] = c1 * 2.0 - c2;
583  }
584  }
585 
586  /* Apply the matrix without interpolation. */
587  switch (s2) {
588  case 0: /* M/S decoding */
589  for (; nsample < 256; nsample++) {
590  c1 = su1[band+nsample];
591  c2 = su2[band+nsample];
592  su1[band+nsample] = c2 * 2.0;
593  su2[band+nsample] = (c1 - c2) * 2.0;
594  }
595  break;
596 
597  case 1:
598  for (; nsample < 256; nsample++) {
599  c1 = su1[band+nsample];
600  c2 = su2[band+nsample];
601  su1[band+nsample] = (c1 + c2) * 2.0;
602  su2[band+nsample] = c2 * -2.0;
603  }
604  break;
605  case 2:
606  case 3:
607  for (; nsample < 256; nsample++) {
608  c1 = su1[band+nsample];
609  c2 = su2[band+nsample];
610  su1[band+nsample] = c1 + c2;
611  su2[band+nsample] = c1 - c2;
612  }
613  break;
614  default:
615  assert(0);
616  }
617  }
618 }
619 
620 static void getChannelWeights (int indx, int flag, float ch[2]){
621 
622  if (indx == 7) {
623  ch[0] = 1.0;
624  ch[1] = 1.0;
625  } else {
626  ch[0] = (float)(indx & 7) / 7.0;
627  ch[1] = sqrt(2 - ch[0]*ch[0]);
628  if(flag)
629  FFSWAP(float, ch[0], ch[1]);
630  }
631 }
632 
633 static void channelWeighting (float *su1, float *su2, int *p3)
634 {
635  int band, nsample;
636  /* w[x][y] y=0 is left y=1 is right */
637  float w[2][2];
638 
639  if (p3[1] != 7 || p3[3] != 7){
640  getChannelWeights(p3[1], p3[0], w[0]);
641  getChannelWeights(p3[3], p3[2], w[1]);
642 
643  for(band = 1; band < 4; band++) {
644  /* scale the channels by the weights */
645  for(nsample = 0; nsample < 8; nsample++) {
646  su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
647  su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
648  }
649 
650  for(; nsample < 256; nsample++) {
651  su1[band*256+nsample] *= w[1][0];
652  su2[band*256+nsample] *= w[1][1];
653  }
654  }
655  }
656 }
657 
658 
670 static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
671 {
672  int band, result=0, numSubbands, lastTonal, numBands;
673 
674  if (codingMode == JOINT_STEREO && channelNum == 1) {
675  if (get_bits(gb,2) != 3) {
676  av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
677  return AVERROR_INVALIDDATA;
678  }
679  } else {
680  if (get_bits(gb,6) != 0x28) {
681  av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
682  return AVERROR_INVALIDDATA;
683  }
684  }
685 
686  /* number of coded QMF bands */
687  pSnd->bandsCoded = get_bits(gb,2);
688 
689  result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
690  if (result) return result;
691 
692  pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
693  if (pSnd->numComponents < 0)
694  return pSnd->numComponents;
695 
696  numSubbands = decodeSpectrum (gb, pSnd->spectrum);
697 
698  /* Merge the decoded spectrum and tonal components. */
699  lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
700 
701 
702  /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
703  numBands = (subbandTab[numSubbands] - 1) >> 8;
704  if (lastTonal >= 0)
705  numBands = FFMAX((lastTonal + 256) >> 8, numBands);
706 
707 
708  /* Reconstruct time domain samples. */
709  for (band=0; band<4; band++) {
710  /* Perform the IMDCT step without overlapping. */
711  if (band <= numBands) {
712  IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
713  } else
714  memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
715 
716  /* gain compensation and overlapping */
717  gainCompensateAndOverlap(pSnd->IMDCT_buf, &pSnd->prevFrame[band * 256],
718  &pOut[band * 256],
719  &pSnd->gainBlock[1 - pSnd->gcBlkSwitch].gBlock[band],
720  &pSnd->gainBlock[ pSnd->gcBlkSwitch].gBlock[band]);
721  }
722 
723  /* Swap the gain control buffers for the next frame. */
724  pSnd->gcBlkSwitch ^= 1;
725 
726  return 0;
727 }
728 
736 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
737  float **out_samples)
738 {
739  int result, i;
740  float *p1, *p2, *p3, *p4;
741  uint8_t *ptr1;
742 
743  if (q->codingMode == JOINT_STEREO) {
744 
745  /* channel coupling mode */
746  /* decode Sound Unit 1 */
747  init_get_bits(&q->gb,databuf,q->bits_per_frame);
748 
749  result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
750  if (result != 0)
751  return result;
752 
753  /* Framedata of the su2 in the joint-stereo mode is encoded in
754  * reverse byte order so we need to swap it first. */
755  if (databuf == q->decoded_bytes_buffer) {
756  uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
757  ptr1 = q->decoded_bytes_buffer;
758  for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
759  FFSWAP(uint8_t,*ptr1,*ptr2);
760  }
761  } else {
762  const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
763  for (i = 0; i < q->bytes_per_frame; i++)
764  q->decoded_bytes_buffer[i] = *ptr2--;
765  }
766 
767  /* Skip the sync codes (0xF8). */
768  ptr1 = q->decoded_bytes_buffer;
769  for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
770  if (i >= q->bytes_per_frame)
771  return AVERROR_INVALIDDATA;
772  }
773 
774 
775  /* set the bitstream reader at the start of the second Sound Unit*/
776  init_get_bits(&q->gb, ptr1, (q->bytes_per_frame - i) * 8);
777 
778  /* Fill the Weighting coeffs delay buffer */
779  memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
780  q->weighting_delay[4] = get_bits1(&q->gb);
781  q->weighting_delay[5] = get_bits(&q->gb,3);
782 
783  for (i = 0; i < 4; i++) {
786  q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
787  }
788 
789  /* Decode Sound Unit 2. */
790  result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
791  if (result != 0)
792  return result;
793 
794  /* Reconstruct the channel coefficients. */
795  reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
796 
797  channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
798 
799  } else {
800  /* normal stereo mode or mono */
801  /* Decode the channel sound units. */
802  for (i=0 ; i<q->channels ; i++) {
803 
804  /* Set the bitstream reader at the start of a channel sound unit. */
805  init_get_bits(&q->gb,
806  databuf + i * q->bytes_per_frame / q->channels,
807  q->bits_per_frame / q->channels);
808 
809  result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
810  if (result != 0)
811  return result;
812  }
813  }
814 
815  /* Apply the iQMF synthesis filter. */
816  for (i=0 ; i<q->channels ; i++) {
817  p1 = out_samples[i];
818  p2= p1+256;
819  p3= p2+256;
820  p4= p3+256;
821  atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
822  atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
823  atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
824  }
825 
826  return 0;
827 }
828 
829 
836 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
837  int *got_frame_ptr, AVPacket *avpkt)
838 {
839  const uint8_t *buf = avpkt->data;
840  int buf_size = avpkt->size;
841  ATRAC3Context *q = avctx->priv_data;
842  int result;
843  const uint8_t* databuf;
844  float *samples_flt;
845  int16_t *samples_s16;
846 
847  if (buf_size < avctx->block_align) {
848  av_log(avctx, AV_LOG_ERROR,
849  "Frame too small (%d bytes). Truncated file?\n", buf_size);
850  return AVERROR_INVALIDDATA;
851  }
852 
853  /* get output buffer */
855  if ((result = avctx->get_buffer(avctx, &q->frame)) < 0) {
856  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
857  return result;
858  }
859  samples_flt = (float *)q->frame.data[0];
860  samples_s16 = (int16_t *)q->frame.data[0];
861 
862  /* Check if we need to descramble and what buffer to pass on. */
863  if (q->scrambled_stream) {
865  databuf = q->decoded_bytes_buffer;
866  } else {
867  databuf = buf;
868  }
869 
870  if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
871  result = decodeFrame(q, databuf, &samples_flt);
872  else
873  result = decodeFrame(q, databuf, q->outSamples);
874 
875  if (result != 0) {
876  av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
877  return result;
878  }
879 
880  /* interleave */
881  if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
882  q->fmt_conv.float_interleave(samples_flt,
883  (const float **)q->outSamples,
884  SAMPLES_PER_FRAME, 2);
885  } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
886  q->fmt_conv.float_to_int16_interleave(samples_s16,
887  (const float **)q->outSamples,
889  }
890 
891  *got_frame_ptr = 1;
892  *(AVFrame *)data = q->frame;
893 
894  return avctx->block_align;
895 }
896 
897 
905 {
906  int i, ret;
907  const uint8_t *edata_ptr = avctx->extradata;
908  ATRAC3Context *q = avctx->priv_data;
909  static VLC_TYPE atrac3_vlc_table[4096][2];
910  static int vlcs_initialized = 0;
911 
912  /* Take data from the AVCodecContext (RM container). */
913  q->sample_rate = avctx->sample_rate;
914  q->channels = avctx->channels;
915  q->bit_rate = avctx->bit_rate;
916  q->bits_per_frame = avctx->block_align * 8;
917  q->bytes_per_frame = avctx->block_align;
918 
919  /* Take care of the codec-specific extradata. */
920  if (avctx->extradata_size == 14) {
921  /* Parse the extradata, WAV format */
922  av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown value always 1
923  q->samples_per_channel = bytestream_get_le32(&edata_ptr);
924  q->codingMode = bytestream_get_le16(&edata_ptr);
925  av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
926  q->frame_factor = bytestream_get_le16(&edata_ptr); //Unknown always 1
927  av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown always 0
928 
929  /* setup */
931  q->atrac3version = 4;
932  q->delay = 0x88E;
933  if (q->codingMode)
935  else
936  q->codingMode = STEREO;
937 
938  q->scrambled_stream = 0;
939 
940  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)) {
941  } else {
942  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);
943  return AVERROR_INVALIDDATA;
944  }
945 
946  } else if (avctx->extradata_size == 10) {
947  /* Parse the extradata, RM format. */
948  q->atrac3version = bytestream_get_be32(&edata_ptr);
949  q->samples_per_frame = bytestream_get_be16(&edata_ptr);
950  q->delay = bytestream_get_be16(&edata_ptr);
951  q->codingMode = bytestream_get_be16(&edata_ptr);
952 
954  q->scrambled_stream = 1;
955 
956  } else {
957  av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
958  }
959  /* Check the extradata. */
960 
961  if (q->atrac3version != 4) {
962  av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
963  return AVERROR_INVALIDDATA;
964  }
965 
967  av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
968  return AVERROR_INVALIDDATA;
969  }
970 
971  if (q->delay != 0x88E) {
972  av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
973  return AVERROR_INVALIDDATA;
974  }
975 
976  if (q->codingMode == STEREO) {
977  av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
978  } else if (q->codingMode == JOINT_STEREO) {
979  if (avctx->channels != 2)
980  return AVERROR_INVALIDDATA;
981  av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
982  } else {
983  av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
984  return AVERROR_INVALIDDATA;
985  }
986 
987  if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
988  av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
989  return AVERROR(EINVAL);
990  }
991 
992 
993  if(avctx->block_align >= UINT_MAX/2)
994  return AVERROR(EINVAL);
995 
996  /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
997  * this is for the bitstream reader. */
999  return AVERROR(ENOMEM);
1000 
1001 
1002  /* Initialize the VLC tables. */
1003  if (!vlcs_initialized) {
1004  for (i=0 ; i<7 ; i++) {
1005  spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
1006  spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
1007  init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
1008  huff_bits[i], 1, 1,
1010  }
1011  vlcs_initialized = 1;
1012  }
1013 
1014  if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
1015  avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
1016  else
1017  avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1018 
1019  if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
1020  av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
1022  return ret;
1023  }
1024 
1026 
1027  /* Generate gain tables. */
1028  for (i=0 ; i<16 ; i++)
1029  gain_tab1[i] = powf (2.0, (4 - i));
1030 
1031  for (i=-15 ; i<16 ; i++)
1032  gain_tab2[i+15] = powf (2.0, i * -0.125);
1033 
1034  /* init the joint-stereo decoding data */
1035  q->weighting_delay[0] = 0;
1036  q->weighting_delay[1] = 7;
1037  q->weighting_delay[2] = 0;
1038  q->weighting_delay[3] = 7;
1039  q->weighting_delay[4] = 0;
1040  q->weighting_delay[5] = 7;
1041 
1042  for (i=0; i<4; i++) {
1043  q->matrix_coeff_index_prev[i] = 3;
1044  q->matrix_coeff_index_now[i] = 3;
1045  q->matrix_coeff_index_next[i] = 3;
1046  }
1047 
1048  dsputil_init(&dsp, avctx);
1049  ff_fmt_convert_init(&q->fmt_conv, avctx);
1050 
1051  q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
1052  if (!q->pUnits) {
1053  atrac3_decode_close(avctx);
1054  return AVERROR(ENOMEM);
1055  }
1056 
1057  if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
1058  q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
1059  q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
1060  if (!q->outSamples[0]) {
1061  atrac3_decode_close(avctx);
1062  return AVERROR(ENOMEM);
1063  }
1064  }
1065 
1067  avctx->coded_frame = &q->frame;
1068 
1069  return 0;
1070 }
1071 
1072 
1074 {
1075  .name = "atrac3",
1076  .type = AVMEDIA_TYPE_AUDIO,
1077  .id = CODEC_ID_ATRAC3,
1078  .priv_data_size = sizeof(ATRAC3Context),
1082  .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1083  .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1084 };