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.

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