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 == -1) return -1;
694 
695  numSubbands = decodeSpectrum (gb, pSnd->spectrum);
696 
697  /* Merge the decoded spectrum and tonal components. */
698  lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
699 
700 
701  /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
702  numBands = (subbandTab[numSubbands] - 1) >> 8;
703  if (lastTonal >= 0)
704  numBands = FFMAX((lastTonal + 256) >> 8, numBands);
705 
706 
707  /* Reconstruct time domain samples. */
708  for (band=0; band<4; band++) {
709  /* Perform the IMDCT step without overlapping. */
710  if (band <= numBands) {
711  IMLT(q, &(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);
712  } else
713  memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
714 
715  /* gain compensation and overlapping */
716  gainCompensateAndOverlap(pSnd->IMDCT_buf, &pSnd->prevFrame[band * 256],
717  &pOut[band * 256],
718  &pSnd->gainBlock[1 - pSnd->gcBlkSwitch].gBlock[band],
719  &pSnd->gainBlock[ pSnd->gcBlkSwitch].gBlock[band]);
720  }
721 
722  /* Swap the gain control buffers for the next frame. */
723  pSnd->gcBlkSwitch ^= 1;
724 
725  return 0;
726 }
727 
735 static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
736  float **out_samples)
737 {
738  int result, i;
739  float *p1, *p2, *p3, *p4;
740  uint8_t *ptr1;
741 
742  if (q->codingMode == JOINT_STEREO) {
743 
744  /* channel coupling mode */
745  /* decode Sound Unit 1 */
746  init_get_bits(&q->gb,databuf,q->bits_per_frame);
747 
748  result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
749  if (result != 0)
750  return result;
751 
752  /* Framedata of the su2 in the joint-stereo mode is encoded in
753  * reverse byte order so we need to swap it first. */
754  if (databuf == q->decoded_bytes_buffer) {
755  uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
756  ptr1 = q->decoded_bytes_buffer;
757  for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
758  FFSWAP(uint8_t,*ptr1,*ptr2);
759  }
760  } else {
761  const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
762  for (i = 0; i < q->bytes_per_frame; i++)
763  q->decoded_bytes_buffer[i] = *ptr2--;
764  }
765 
766  /* Skip the sync codes (0xF8). */
767  ptr1 = q->decoded_bytes_buffer;
768  for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
769  if (i >= q->bytes_per_frame)
770  return AVERROR_INVALIDDATA;
771  }
772 
773 
774  /* set the bitstream reader at the start of the second Sound Unit*/
775  init_get_bits(&q->gb,ptr1,q->bits_per_frame);
776 
777  /* Fill the Weighting coeffs delay buffer */
778  memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
779  q->weighting_delay[4] = get_bits1(&q->gb);
780  q->weighting_delay[5] = get_bits(&q->gb,3);
781 
782  for (i = 0; i < 4; i++) {
785  q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
786  }
787 
788  /* Decode Sound Unit 2. */
789  result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
790  if (result != 0)
791  return result;
792 
793  /* Reconstruct the channel coefficients. */
794  reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
795 
796  channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
797 
798  } else {
799  /* normal stereo mode or mono */
800  /* Decode the channel sound units. */
801  for (i=0 ; i<q->channels ; i++) {
802 
803  /* Set the bitstream reader at the start of a channel sound unit. */
804  init_get_bits(&q->gb,
805  databuf + i * q->bytes_per_frame / q->channels,
806  q->bits_per_frame / q->channels);
807 
808  result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
809  if (result != 0)
810  return result;
811  }
812  }
813 
814  /* Apply the iQMF synthesis filter. */
815  for (i=0 ; i<q->channels ; i++) {
816  p1 = out_samples[i];
817  p2= p1+256;
818  p3= p2+256;
819  p4= p3+256;
820  atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
821  atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
822  atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
823  }
824 
825  return 0;
826 }
827 
828 
835 static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
836  int *got_frame_ptr, AVPacket *avpkt)
837 {
838  const uint8_t *buf = avpkt->data;
839  int buf_size = avpkt->size;
840  ATRAC3Context *q = avctx->priv_data;
841  int result;
842  const uint8_t* databuf;
843  float *samples_flt;
844  int16_t *samples_s16;
845 
846  if (buf_size < avctx->block_align) {
847  av_log(avctx, AV_LOG_ERROR,
848  "Frame too small (%d bytes). Truncated file?\n", buf_size);
849  return AVERROR_INVALIDDATA;
850  }
851 
852  /* get output buffer */
854  if ((result = avctx->get_buffer(avctx, &q->frame)) < 0) {
855  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
856  return result;
857  }
858  samples_flt = (float *)q->frame.data[0];
859  samples_s16 = (int16_t *)q->frame.data[0];
860 
861  /* Check if we need to descramble and what buffer to pass on. */
862  if (q->scrambled_stream) {
864  databuf = q->decoded_bytes_buffer;
865  } else {
866  databuf = buf;
867  }
868 
869  if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
870  result = decodeFrame(q, databuf, &samples_flt);
871  else
872  result = decodeFrame(q, databuf, q->outSamples);
873 
874  if (result != 0) {
875  av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
876  return result;
877  }
878 
879  /* interleave */
880  if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
881  q->fmt_conv.float_interleave(samples_flt,
882  (const float **)q->outSamples,
883  SAMPLES_PER_FRAME, 2);
884  } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
885  q->fmt_conv.float_to_int16_interleave(samples_s16,
886  (const float **)q->outSamples,
888  }
889 
890  *got_frame_ptr = 1;
891  *(AVFrame *)data = q->frame;
892 
893  return avctx->block_align;
894 }
895 
896 
904 {
905  int i, ret;
906  const uint8_t *edata_ptr = avctx->extradata;
907  ATRAC3Context *q = avctx->priv_data;
908  static VLC_TYPE atrac3_vlc_table[4096][2];
909  static int vlcs_initialized = 0;
910 
911  /* Take data from the AVCodecContext (RM container). */
912  q->sample_rate = avctx->sample_rate;
913  q->channels = avctx->channels;
914  q->bit_rate = avctx->bit_rate;
915  q->bits_per_frame = avctx->block_align * 8;
916  q->bytes_per_frame = avctx->block_align;
917 
918  /* Take care of the codec-specific extradata. */
919  if (avctx->extradata_size == 14) {
920  /* Parse the extradata, WAV format */
921  av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown value always 1
922  q->samples_per_channel = bytestream_get_le32(&edata_ptr);
923  q->codingMode = bytestream_get_le16(&edata_ptr);
924  av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
925  q->frame_factor = bytestream_get_le16(&edata_ptr); //Unknown always 1
926  av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown always 0
927 
928  /* setup */
930  q->atrac3version = 4;
931  q->delay = 0x88E;
932  if (q->codingMode)
934  else
935  q->codingMode = STEREO;
936 
937  q->scrambled_stream = 0;
938 
939  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)) {
940  } else {
941  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);
942  return AVERROR_INVALIDDATA;
943  }
944 
945  } else if (avctx->extradata_size == 10) {
946  /* Parse the extradata, RM format. */
947  q->atrac3version = bytestream_get_be32(&edata_ptr);
948  q->samples_per_frame = bytestream_get_be16(&edata_ptr);
949  q->delay = bytestream_get_be16(&edata_ptr);
950  q->codingMode = bytestream_get_be16(&edata_ptr);
951 
953  q->scrambled_stream = 1;
954 
955  } else {
956  av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
957  }
958  /* Check the extradata. */
959 
960  if (q->atrac3version != 4) {
961  av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
962  return AVERROR_INVALIDDATA;
963  }
964 
966  av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
967  return AVERROR_INVALIDDATA;
968  }
969 
970  if (q->delay != 0x88E) {
971  av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
972  return AVERROR_INVALIDDATA;
973  }
974 
975  if (q->codingMode == STEREO) {
976  av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
977  } else if (q->codingMode == JOINT_STEREO) {
978  av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
979  } else {
980  av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
981  return AVERROR_INVALIDDATA;
982  }
983 
984  if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
985  av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
986  return AVERROR(EINVAL);
987  }
988 
989 
990  if(avctx->block_align >= UINT_MAX/2)
991  return AVERROR(EINVAL);
992 
993  /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
994  * this is for the bitstream reader. */
996  return AVERROR(ENOMEM);
997 
998 
999  /* Initialize the VLC tables. */
1000  if (!vlcs_initialized) {
1001  for (i=0 ; i<7 ; i++) {
1002  spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
1003  spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
1004  init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
1005  huff_bits[i], 1, 1,
1007  }
1008  vlcs_initialized = 1;
1009  }
1010 
1011  if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
1012  avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
1013  else
1014  avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1015 
1016  if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
1017  av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
1019  return ret;
1020  }
1021 
1023 
1024  /* Generate gain tables. */
1025  for (i=0 ; i<16 ; i++)
1026  gain_tab1[i] = powf (2.0, (4 - i));
1027 
1028  for (i=-15 ; i<16 ; i++)
1029  gain_tab2[i+15] = powf (2.0, i * -0.125);
1030 
1031  /* init the joint-stereo decoding data */
1032  q->weighting_delay[0] = 0;
1033  q->weighting_delay[1] = 7;
1034  q->weighting_delay[2] = 0;
1035  q->weighting_delay[3] = 7;
1036  q->weighting_delay[4] = 0;
1037  q->weighting_delay[5] = 7;
1038 
1039  for (i=0; i<4; i++) {
1040  q->matrix_coeff_index_prev[i] = 3;
1041  q->matrix_coeff_index_now[i] = 3;
1042  q->matrix_coeff_index_next[i] = 3;
1043  }
1044 
1045  dsputil_init(&dsp, avctx);
1046  ff_fmt_convert_init(&q->fmt_conv, avctx);
1047 
1048  q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
1049  if (!q->pUnits) {
1050  atrac3_decode_close(avctx);
1051  return AVERROR(ENOMEM);
1052  }
1053 
1054  if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
1055  q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
1056  q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
1057  if (!q->outSamples[0]) {
1058  atrac3_decode_close(avctx);
1059  return AVERROR(ENOMEM);
1060  }
1061  }
1062 
1064  avctx->coded_frame = &q->frame;
1065 
1066  return 0;
1067 }
1068 
1069 
1071 {
1072  .name = "atrac3",
1073  .type = AVMEDIA_TYPE_AUDIO,
1074  .id = CODEC_ID_ATRAC3,
1075  .priv_data_size = sizeof(ATRAC3Context),
1079  .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1080  .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
1081 };