You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1077 lines
32KB

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