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.

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