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.

1076 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. numBits = CLCLengthTab[selector];
  255. if (selector > 1) {
  256. for (cnt = 0; cnt < numCodes; cnt++) {
  257. if (numBits)
  258. code = get_sbits(gb, numBits);
  259. else
  260. code = 0;
  261. mantissas[cnt] = code;
  262. }
  263. } else {
  264. for (cnt = 0; cnt < numCodes; cnt++) {
  265. if (numBits)
  266. code = get_bits(gb, numBits); //numBits is always 4 in this case
  267. else
  268. code = 0;
  269. mantissas[cnt*2] = seTab_0[code >> 2];
  270. mantissas[cnt*2+1] = seTab_0[code & 3];
  271. }
  272. }
  273. } else {
  274. /* variable length coding (VLC) */
  275. if (selector != 1) {
  276. for (cnt = 0; cnt < numCodes; cnt++) {
  277. huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
  278. huffSymb += 1;
  279. code = huffSymb >> 1;
  280. if (huffSymb & 1)
  281. code = -code;
  282. mantissas[cnt] = code;
  283. }
  284. } else {
  285. for (cnt = 0; cnt < numCodes; cnt++) {
  286. huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3);
  287. mantissas[cnt*2] = decTable1[huffSymb*2];
  288. mantissas[cnt*2+1] = decTable1[huffSymb*2+1];
  289. }
  290. }
  291. }
  292. }
  293. /**
  294. * Restore the quantized band spectrum coefficients
  295. *
  296. * @param gb the GetBit context
  297. * @param pOut decoded band spectrum
  298. * @return outSubbands subband counter, fix for broken specification/files
  299. */
  300. static 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. numSubbands = get_bits(gb, 5); // number of coded subbands
  307. codingMode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC
  308. /* Get the VLC selector table for the subbands, 0 means not coded. */
  309. for (cnt = 0; cnt <= numSubbands; cnt++)
  310. subband_vlc_index[cnt] = get_bits(gb, 3);
  311. /* Read the scale factor indexes from the stream. */
  312. for (cnt = 0; cnt <= numSubbands; cnt++) {
  313. if (subband_vlc_index[cnt] != 0)
  314. SF_idxs[cnt] = get_bits(gb, 6);
  315. }
  316. for (cnt = 0; cnt <= numSubbands; cnt++) {
  317. first = subbandTab[cnt];
  318. last = subbandTab[cnt+1];
  319. subbWidth = last - first;
  320. if (subband_vlc_index[cnt] != 0) {
  321. /* Decode spectral coefficients for this subband. */
  322. /* TODO: This can be done faster is several blocks share the
  323. * same VLC selector (subband_vlc_index) */
  324. readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth);
  325. /* Decode the scale factor for this subband. */
  326. SF = SFTable[SF_idxs[cnt]] * iMaxQuant[subband_vlc_index[cnt]];
  327. /* Inverse quantize the coefficients. */
  328. for (pIn=mantissas ; first<last; first++, pIn++)
  329. pOut[first] = *pIn * SF;
  330. } else {
  331. /* This subband was not coded, so zero the entire subband. */
  332. memset(pOut+first, 0, subbWidth*sizeof(float));
  333. }
  334. }
  335. /* Clear the subbands that were not coded. */
  336. first = subbandTab[cnt];
  337. memset(pOut+first, 0, (1024 - first) * sizeof(float));
  338. return numSubbands;
  339. }
  340. /**
  341. * Restore the quantized tonal components
  342. *
  343. * @param gb the GetBit context
  344. * @param pComponent tone component
  345. * @param numBands amount of coded bands
  346. */
  347. static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands)
  348. {
  349. int i,j,k,cnt;
  350. int components, coding_mode_selector, coding_mode, coded_values_per_component;
  351. int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components;
  352. int band_flags[4], mantissa[8];
  353. float *pCoef;
  354. float scalefactor;
  355. int component_count = 0;
  356. components = get_bits(gb,5);
  357. /* no tonal components */
  358. if (components == 0)
  359. return 0;
  360. coding_mode_selector = get_bits(gb,2);
  361. if (coding_mode_selector == 2)
  362. return -1;
  363. coding_mode = coding_mode_selector & 1;
  364. for (i = 0; i < components; i++) {
  365. for (cnt = 0; cnt <= numBands; cnt++)
  366. band_flags[cnt] = get_bits1(gb);
  367. coded_values_per_component = get_bits(gb,3);
  368. quant_step_index = get_bits(gb,3);
  369. if (quant_step_index <= 1)
  370. return -1;
  371. if (coding_mode_selector == 3)
  372. coding_mode = get_bits1(gb);
  373. for (j = 0; j < (numBands + 1) * 4; j++) {
  374. if (band_flags[j >> 2] == 0)
  375. continue;
  376. coded_components = get_bits(gb,3);
  377. for (k=0; k<coded_components; k++) {
  378. sfIndx = get_bits(gb,6);
  379. pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
  380. max_coded_values = 1024 - pComponent[component_count].pos;
  381. coded_values = coded_values_per_component + 1;
  382. coded_values = FFMIN(max_coded_values,coded_values);
  383. scalefactor = SFTable[sfIndx] * iMaxQuant[quant_step_index];
  384. readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values);
  385. pComponent[component_count].numCoefs = coded_values;
  386. /* inverse quant */
  387. pCoef = pComponent[component_count].coef;
  388. for (cnt = 0; cnt < coded_values; cnt++)
  389. pCoef[cnt] = mantissa[cnt] * scalefactor;
  390. component_count++;
  391. }
  392. }
  393. }
  394. return component_count;
  395. }
  396. /**
  397. * Decode gain parameters for the coded bands
  398. *
  399. * @param gb the GetBit context
  400. * @param pGb the gainblock for the current band
  401. * @param numBands amount of coded bands
  402. */
  403. static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands)
  404. {
  405. int i, cf, numData;
  406. int *pLevel, *pLoc;
  407. gain_info *pGain = pGb->gBlock;
  408. for (i=0 ; i<=numBands; i++)
  409. {
  410. numData = get_bits(gb,3);
  411. pGain[i].num_gain_data = numData;
  412. pLevel = pGain[i].levcode;
  413. pLoc = pGain[i].loccode;
  414. for (cf = 0; cf < numData; cf++){
  415. pLevel[cf]= get_bits(gb,4);
  416. pLoc [cf]= get_bits(gb,5);
  417. if(cf && pLoc[cf] <= pLoc[cf-1])
  418. return -1;
  419. }
  420. }
  421. /* Clear the unused blocks. */
  422. for (; i<4 ; i++)
  423. pGain[i].num_gain_data = 0;
  424. return 0;
  425. }
  426. /**
  427. * Apply gain parameters and perform the MDCT overlapping part
  428. *
  429. * @param pIn input float buffer
  430. * @param pPrev previous float buffer to perform overlap against
  431. * @param pOut output float buffer
  432. * @param pGain1 current band gain info
  433. * @param pGain2 next band gain info
  434. */
  435. static void gainCompensateAndOverlap (float *pIn, float *pPrev, float *pOut, gain_info *pGain1, gain_info *pGain2)
  436. {
  437. /* gain compensation function */
  438. float gain1, gain2, gain_inc;
  439. int cnt, numdata, nsample, startLoc, endLoc;
  440. if (pGain2->num_gain_data == 0)
  441. gain1 = 1.0;
  442. else
  443. gain1 = gain_tab1[pGain2->levcode[0]];
  444. if (pGain1->num_gain_data == 0) {
  445. for (cnt = 0; cnt < 256; cnt++)
  446. pOut[cnt] = pIn[cnt] * gain1 + pPrev[cnt];
  447. } else {
  448. numdata = pGain1->num_gain_data;
  449. pGain1->loccode[numdata] = 32;
  450. pGain1->levcode[numdata] = 4;
  451. nsample = 0; // current sample = 0
  452. for (cnt = 0; cnt < numdata; cnt++) {
  453. startLoc = pGain1->loccode[cnt] * 8;
  454. endLoc = startLoc + 8;
  455. gain2 = gain_tab1[pGain1->levcode[cnt]];
  456. gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15];
  457. /* interpolate */
  458. for (; nsample < startLoc; nsample++)
  459. pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
  460. /* interpolation is done over eight samples */
  461. for (; nsample < endLoc; nsample++) {
  462. pOut[nsample] = (pIn[nsample] * gain1 + pPrev[nsample]) * gain2;
  463. gain2 *= gain_inc;
  464. }
  465. }
  466. for (; nsample < 256; nsample++)
  467. pOut[nsample] = (pIn[nsample] * gain1) + pPrev[nsample];
  468. }
  469. /* Delay for the overlapping part. */
  470. memcpy(pPrev, &pIn[256], 256*sizeof(float));
  471. }
  472. /**
  473. * Combine the tonal band spectrum and regular band spectrum
  474. * Return position of the last tonal coefficient
  475. *
  476. * @param pSpectrum output spectrum buffer
  477. * @param numComponents amount of tonal components
  478. * @param pComponent tonal components for this band
  479. */
  480. static int addTonalComponents (float *pSpectrum, int numComponents, tonal_component *pComponent)
  481. {
  482. int cnt, i, lastPos = -1;
  483. float *pIn, *pOut;
  484. for (cnt = 0; cnt < numComponents; cnt++){
  485. lastPos = FFMAX(pComponent[cnt].pos + pComponent[cnt].numCoefs, lastPos);
  486. pIn = pComponent[cnt].coef;
  487. pOut = &(pSpectrum[pComponent[cnt].pos]);
  488. for (i=0 ; i<pComponent[cnt].numCoefs ; i++)
  489. pOut[i] += pIn[i];
  490. }
  491. return lastPos;
  492. }
  493. #define INTERPOLATE(old,new,nsample) ((old) + (nsample)*0.125*((new)-(old)))
  494. static void reverseMatrixing(float *su1, float *su2, int *pPrevCode, int *pCurrCode)
  495. {
  496. int i, band, nsample, s1, s2;
  497. float c1, c2;
  498. float mc1_l, mc1_r, mc2_l, mc2_r;
  499. for (i=0,band = 0; band < 4*256; band+=256,i++) {
  500. s1 = pPrevCode[i];
  501. s2 = pCurrCode[i];
  502. nsample = 0;
  503. if (s1 != s2) {
  504. /* Selector value changed, interpolation needed. */
  505. mc1_l = matrixCoeffs[s1*2];
  506. mc1_r = matrixCoeffs[s1*2+1];
  507. mc2_l = matrixCoeffs[s2*2];
  508. mc2_r = matrixCoeffs[s2*2+1];
  509. /* Interpolation is done over the first eight samples. */
  510. for(; nsample < 8; nsample++) {
  511. c1 = su1[band+nsample];
  512. c2 = su2[band+nsample];
  513. c2 = c1 * INTERPOLATE(mc1_l,mc2_l,nsample) + c2 * INTERPOLATE(mc1_r,mc2_r,nsample);
  514. su1[band+nsample] = c2;
  515. su2[band+nsample] = c1 * 2.0 - c2;
  516. }
  517. }
  518. /* Apply the matrix without interpolation. */
  519. switch (s2) {
  520. case 0: /* M/S decoding */
  521. for (; nsample < 256; nsample++) {
  522. c1 = su1[band+nsample];
  523. c2 = su2[band+nsample];
  524. su1[band+nsample] = c2 * 2.0;
  525. su2[band+nsample] = (c1 - c2) * 2.0;
  526. }
  527. break;
  528. case 1:
  529. for (; nsample < 256; nsample++) {
  530. c1 = su1[band+nsample];
  531. c2 = su2[band+nsample];
  532. su1[band+nsample] = (c1 + c2) * 2.0;
  533. su2[band+nsample] = c2 * -2.0;
  534. }
  535. break;
  536. case 2:
  537. case 3:
  538. for (; nsample < 256; nsample++) {
  539. c1 = su1[band+nsample];
  540. c2 = su2[band+nsample];
  541. su1[band+nsample] = c1 + c2;
  542. su2[band+nsample] = c1 - c2;
  543. }
  544. break;
  545. default:
  546. assert(0);
  547. }
  548. }
  549. }
  550. static void getChannelWeights (int indx, int flag, float ch[2]){
  551. if (indx == 7) {
  552. ch[0] = 1.0;
  553. ch[1] = 1.0;
  554. } else {
  555. ch[0] = (float)(indx & 7) / 7.0;
  556. ch[1] = sqrt(2 - ch[0]*ch[0]);
  557. if(flag)
  558. FFSWAP(float, ch[0], ch[1]);
  559. }
  560. }
  561. static void channelWeighting (float *su1, float *su2, int *p3)
  562. {
  563. int band, nsample;
  564. /* w[x][y] y=0 is left y=1 is right */
  565. float w[2][2];
  566. if (p3[1] != 7 || p3[3] != 7){
  567. getChannelWeights(p3[1], p3[0], w[0]);
  568. getChannelWeights(p3[3], p3[2], w[1]);
  569. for(band = 1; band < 4; band++) {
  570. /* scale the channels by the weights */
  571. for(nsample = 0; nsample < 8; nsample++) {
  572. su1[band*256+nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample);
  573. su2[band*256+nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample);
  574. }
  575. for(; nsample < 256; nsample++) {
  576. su1[band*256+nsample] *= w[1][0];
  577. su2[band*256+nsample] *= w[1][1];
  578. }
  579. }
  580. }
  581. }
  582. /**
  583. * Decode a Sound Unit
  584. *
  585. * @param gb the GetBit context
  586. * @param pSnd the channel unit to be used
  587. * @param pOut the decoded samples before IQMF in float representation
  588. * @param channelNum channel number
  589. * @param codingMode the coding mode (JOINT_STEREO or regular stereo/mono)
  590. */
  591. static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)
  592. {
  593. int band, result=0, numSubbands, lastTonal, numBands;
  594. if (codingMode == JOINT_STEREO && channelNum == 1) {
  595. if (get_bits(gb,2) != 3) {
  596. av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
  597. return -1;
  598. }
  599. } else {
  600. if (get_bits(gb,6) != 0x28) {
  601. av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
  602. return -1;
  603. }
  604. }
  605. /* number of coded QMF bands */
  606. pSnd->bandsCoded = get_bits(gb,2);
  607. result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);
  608. if (result) return result;
  609. pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);
  610. if (pSnd->numComponents == -1) return -1;
  611. numSubbands = decodeSpectrum (gb, pSnd->spectrum);
  612. /* Merge the decoded spectrum and tonal components. */
  613. lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);
  614. /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */
  615. numBands = (subbandTab[numSubbands] - 1) >> 8;
  616. if (lastTonal >= 0)
  617. numBands = FFMAX((lastTonal + 256) >> 8, numBands);
  618. /* Reconstruct time domain samples. */
  619. for (band=0; band<4; band++) {
  620. /* Perform the IMDCT step without overlapping. */
  621. if (band <= numBands) {
  622. IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1,q->mdct_tmp);
  623. } else
  624. memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));
  625. /* gain compensation and overlapping */
  626. gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),
  627. &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),
  628. &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));
  629. }
  630. /* Swap the gain control buffers for the next frame. */
  631. pSnd->gcBlkSwitch ^= 1;
  632. return 0;
  633. }
  634. /**
  635. * Frame handling
  636. *
  637. * @param q Atrac3 private context
  638. * @param databuf the input data
  639. */
  640. static int decodeFrame(ATRAC3Context *q, uint8_t* databuf)
  641. {
  642. int result, i;
  643. float *p1, *p2, *p3, *p4;
  644. uint8_t *ptr1, *ptr2;
  645. if (q->codingMode == JOINT_STEREO) {
  646. /* channel coupling mode */
  647. /* decode Sound Unit 1 */
  648. init_get_bits(&q->gb,databuf,q->bits_per_frame);
  649. result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, q->outSamples, 0, JOINT_STEREO);
  650. if (result != 0)
  651. return (result);
  652. /* Framedata of the su2 in the joint-stereo mode is encoded in
  653. * reverse byte order so we need to swap it first. */
  654. ptr1 = databuf;
  655. ptr2 = databuf+q->bytes_per_frame-1;
  656. for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
  657. FFSWAP(uint8_t,*ptr1,*ptr2);
  658. }
  659. /* Skip the sync codes (0xF8). */
  660. ptr1 = databuf;
  661. for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
  662. if (i >= q->bytes_per_frame)
  663. return -1;
  664. }
  665. /* set the bitstream reader at the start of the second Sound Unit*/
  666. init_get_bits(&q->gb,ptr1,q->bits_per_frame);
  667. /* Fill the Weighting coeffs delay buffer */
  668. memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
  669. q->weighting_delay[4] = get_bits1(&q->gb);
  670. q->weighting_delay[5] = get_bits(&q->gb,3);
  671. for (i = 0; i < 4; i++) {
  672. q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
  673. q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
  674. q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
  675. }
  676. /* Decode Sound Unit 2. */
  677. result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], &q->outSamples[1024], 1, JOINT_STEREO);
  678. if (result != 0)
  679. return (result);
  680. /* Reconstruct the channel coefficients. */
  681. reverseMatrixing(q->outSamples, &q->outSamples[1024], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
  682. channelWeighting(q->outSamples, &q->outSamples[1024], q->weighting_delay);
  683. } else {
  684. /* normal stereo mode or mono */
  685. /* Decode the channel sound units. */
  686. for (i=0 ; i<q->channels ; i++) {
  687. /* Set the bitstream reader at the start of a channel sound unit. */
  688. init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels), (q->bits_per_frame)/q->channels);
  689. result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], &q->outSamples[i*1024], i, q->codingMode);
  690. if (result != 0)
  691. return (result);
  692. }
  693. }
  694. /* Apply the iQMF synthesis filter. */
  695. p1= q->outSamples;
  696. for (i=0 ; i<q->channels ; i++) {
  697. p2= p1+256;
  698. p3= p2+256;
  699. p4= p3+256;
  700. iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
  701. iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
  702. iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
  703. p1 +=1024;
  704. }
  705. return 0;
  706. }
  707. /**
  708. * Atrac frame decoding
  709. *
  710. * @param avctx pointer to the AVCodecContext
  711. */
  712. static int atrac3_decode_frame(AVCodecContext *avctx,
  713. void *data, int *data_size,
  714. const uint8_t *buf, int buf_size) {
  715. ATRAC3Context *q = avctx->priv_data;
  716. int result = 0, i;
  717. uint8_t* databuf;
  718. int16_t* samples = data;
  719. if (buf_size < avctx->block_align)
  720. return buf_size;
  721. /* Check if we need to descramble and what buffer to pass on. */
  722. if (q->scrambled_stream) {
  723. decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
  724. databuf = q->decoded_bytes_buffer;
  725. } else {
  726. databuf = buf;
  727. }
  728. result = decodeFrame(q, databuf);
  729. if (result != 0) {
  730. av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
  731. return -1;
  732. }
  733. if (q->channels == 1) {
  734. /* mono */
  735. for (i = 0; i<1024; i++)
  736. samples[i] = av_clip_int16(round(q->outSamples[i]));
  737. *data_size = 1024 * sizeof(int16_t);
  738. } else {
  739. /* stereo */
  740. for (i = 0; i < 1024; i++) {
  741. samples[i*2] = av_clip_int16(round(q->outSamples[i]));
  742. samples[i*2+1] = av_clip_int16(round(q->outSamples[1024+i]));
  743. }
  744. *data_size = 2048 * sizeof(int16_t);
  745. }
  746. return avctx->block_align;
  747. }
  748. /**
  749. * Atrac3 initialization
  750. *
  751. * @param avctx pointer to the AVCodecContext
  752. */
  753. static int atrac3_decode_init(AVCodecContext *avctx)
  754. {
  755. int i;
  756. const uint8_t *edata_ptr = avctx->extradata;
  757. ATRAC3Context *q = avctx->priv_data;
  758. /* Take data from the AVCodecContext (RM container). */
  759. q->sample_rate = avctx->sample_rate;
  760. q->channels = avctx->channels;
  761. q->bit_rate = avctx->bit_rate;
  762. q->bits_per_frame = avctx->block_align * 8;
  763. q->bytes_per_frame = avctx->block_align;
  764. /* Take care of the codec-specific extradata. */
  765. if (avctx->extradata_size == 14) {
  766. /* Parse the extradata, WAV format */
  767. av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown value always 1
  768. q->samples_per_channel = bytestream_get_le32(&edata_ptr);
  769. q->codingMode = bytestream_get_le16(&edata_ptr);
  770. av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
  771. q->frame_factor = bytestream_get_le16(&edata_ptr); //Unknown always 1
  772. av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown always 0
  773. /* setup */
  774. q->samples_per_frame = 1024 * q->channels;
  775. q->atrac3version = 4;
  776. q->delay = 0x88E;
  777. if (q->codingMode)
  778. q->codingMode = JOINT_STEREO;
  779. else
  780. q->codingMode = STEREO;
  781. q->scrambled_stream = 0;
  782. 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)) {
  783. } else {
  784. 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);
  785. return -1;
  786. }
  787. } else if (avctx->extradata_size == 10) {
  788. /* Parse the extradata, RM format. */
  789. q->atrac3version = bytestream_get_be32(&edata_ptr);
  790. q->samples_per_frame = bytestream_get_be16(&edata_ptr);
  791. q->delay = bytestream_get_be16(&edata_ptr);
  792. q->codingMode = bytestream_get_be16(&edata_ptr);
  793. q->samples_per_channel = q->samples_per_frame / q->channels;
  794. q->scrambled_stream = 1;
  795. } else {
  796. av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
  797. }
  798. /* Check the extradata. */
  799. if (q->atrac3version != 4) {
  800. av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
  801. return -1;
  802. }
  803. if (q->samples_per_frame != 1024 && q->samples_per_frame != 2048) {
  804. av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
  805. return -1;
  806. }
  807. if (q->delay != 0x88E) {
  808. av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
  809. return -1;
  810. }
  811. if (q->codingMode == STEREO) {
  812. av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
  813. } else if (q->codingMode == JOINT_STEREO) {
  814. av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
  815. } else {
  816. av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
  817. return -1;
  818. }
  819. if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
  820. av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
  821. return -1;
  822. }
  823. if(avctx->block_align >= UINT_MAX/2)
  824. return -1;
  825. /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
  826. * this is for the bitstream reader. */
  827. if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE))) == NULL)
  828. return AVERROR(ENOMEM);
  829. /* Initialize the VLC tables. */
  830. for (i=0 ; i<7 ; i++) {
  831. init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
  832. huff_bits[i], 1, 1,
  833. huff_codes[i], 1, 1, INIT_VLC_USE_STATIC);
  834. }
  835. init_atrac3_transforms(q);
  836. /* Generate the scale factors. */
  837. for (i=0 ; i<64 ; i++)
  838. SFTable[i] = pow(2.0, (i - 15) / 3.0);
  839. /* Generate gain tables. */
  840. for (i=0 ; i<16 ; i++)
  841. gain_tab1[i] = powf (2.0, (4 - i));
  842. for (i=-15 ; i<16 ; i++)
  843. gain_tab2[i+15] = powf (2.0, i * -0.125);
  844. /* init the joint-stereo decoding data */
  845. q->weighting_delay[0] = 0;
  846. q->weighting_delay[1] = 7;
  847. q->weighting_delay[2] = 0;
  848. q->weighting_delay[3] = 7;
  849. q->weighting_delay[4] = 0;
  850. q->weighting_delay[5] = 7;
  851. for (i=0; i<4; i++) {
  852. q->matrix_coeff_index_prev[i] = 3;
  853. q->matrix_coeff_index_now[i] = 3;
  854. q->matrix_coeff_index_next[i] = 3;
  855. }
  856. dsputil_init(&dsp, avctx);
  857. q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
  858. if (!q->pUnits) {
  859. av_free(q->decoded_bytes_buffer);
  860. return AVERROR(ENOMEM);
  861. }
  862. return 0;
  863. }
  864. AVCodec atrac3_decoder =
  865. {
  866. .name = "atrac3",
  867. .type = CODEC_TYPE_AUDIO,
  868. .id = CODEC_ID_ATRAC3,
  869. .priv_data_size = sizeof(ATRAC3Context),
  870. .init = atrac3_decode_init,
  871. .close = atrac3_decode_close,
  872. .decode = atrac3_decode_frame,
  873. .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
  874. };