atrac3.c 32 KB

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