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.

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