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.

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