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.

1035 lines
32KB

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