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.

1080 lines
34KB

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