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.

1049 lines
33KB

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