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.

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