atrac3.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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 "fmtconvert.h"
  42. #include "atrac.h"
  43. #include "atrac3data.h"
  44. #define JOINT_STEREO 0x12
  45. #define STEREO 0x2
  46. #define SAMPLES_PER_FRAME 1024
  47. #define MDCT_SIZE 512
  48. /* These structures are needed to store the parsed gain control data. */
  49. typedef struct {
  50. int num_gain_data;
  51. int levcode[8];
  52. int loccode[8];
  53. } gain_info;
  54. typedef struct {
  55. gain_info gBlock[4];
  56. } gain_block;
  57. typedef struct {
  58. int pos;
  59. int numCoefs;
  60. float coef[8];
  61. } tonal_component;
  62. typedef struct {
  63. int bandsCoded;
  64. int numComponents;
  65. tonal_component components[64];
  66. float prevFrame[SAMPLES_PER_FRAME];
  67. int gcBlkSwitch;
  68. gain_block gainBlock[2];
  69. DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
  70. DECLARE_ALIGNED(32, float, IMDCT_buf)[SAMPLES_PER_FRAME];
  71. float delayBuf1[46]; ///<qmf delay buffers
  72. float delayBuf2[46];
  73. float delayBuf3[46];
  74. } channel_unit;
  75. typedef struct {
  76. GetBitContext gb;
  77. //@{
  78. /** stream data */
  79. int channels;
  80. int codingMode;
  81. int bit_rate;
  82. int sample_rate;
  83. int samples_per_channel;
  84. int samples_per_frame;
  85. int bits_per_frame;
  86. int bytes_per_frame;
  87. int pBs;
  88. channel_unit* pUnits;
  89. //@}
  90. //@{
  91. /** joint-stereo related variables */
  92. int matrix_coeff_index_prev[4];
  93. int matrix_coeff_index_now[4];
  94. int matrix_coeff_index_next[4];
  95. int weighting_delay[6];
  96. //@}
  97. //@{
  98. /** data buffers */
  99. float *outSamples[2];
  100. uint8_t* decoded_bytes_buffer;
  101. float tempBuf[1070];
  102. //@}
  103. //@{
  104. /** extradata */
  105. int atrac3version;
  106. int delay;
  107. int scrambled_stream;
  108. int frame_factor;
  109. //@}
  110. FFTContext mdct_ctx;
  111. FmtConvertContext fmt_conv;
  112. } ATRAC3Context;
  113. static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
  114. static VLC spectral_coeff_tab[7];
  115. static float gain_tab1[16];
  116. static float gain_tab2[31];
  117. static DSPContext dsp;
  118. /**
  119. * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands
  120. * caused by the reverse spectra of the QMF.
  121. *
  122. * @param pInput float input
  123. * @param pOutput float output
  124. * @param odd_band 1 if the band is an odd band
  125. */
  126. static void IMLT(ATRAC3Context *q, float *pInput, float *pOutput, int odd_band)
  127. {
  128. int i;
  129. if (odd_band) {
  130. /**
  131. * Reverse the odd bands before IMDCT, this is an effect of the QMF transform
  132. * or it gives better compression to do it this way.
  133. * FIXME: It should be possible to handle this in imdct_calc
  134. * for that to happen a modification of the prerotation step of
  135. * all SIMD code and C code is needed.
  136. * Or fix the functions before so they generate a pre reversed spectrum.
  137. */
  138. for (i=0; i<128; i++)
  139. FFSWAP(float, pInput[i], pInput[255-i]);
  140. }
  141. q->mdct_ctx.imdct_calc(&q->mdct_ctx,pOutput,pInput);
  142. /* Perform windowing on the output. */
  143. dsp.vector_fmul(pOutput, pOutput, mdct_window, MDCT_SIZE);
  144. }
  145. /**
  146. * Atrac 3 indata descrambling, only used for data coming from the rm container
  147. *
  148. * @param inbuffer pointer to 8 bit array of indata
  149. * @param out pointer to 8 bit array of outdata
  150. * @param bytes amount of bytes
  151. */
  152. static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
  153. int i, off;
  154. uint32_t c;
  155. const uint32_t* buf;
  156. uint32_t* obuf = (uint32_t*) out;
  157. off = (intptr_t)inbuffer & 3;
  158. buf = (const uint32_t*) (inbuffer - off);
  159. c = av_be2ne32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
  160. bytes += 3 + off;
  161. for (i = 0; i < bytes/4; i++)
  162. obuf[i] = c ^ buf[i];
  163. if (off)
  164. av_log_ask_for_sample(NULL, "Offset of %d not handled.\n", off);
  165. return off;
  166. }
  167. static av_cold int init_atrac3_transforms(ATRAC3Context *q, int is_float) {
  168. float enc_window[256];
  169. int i;
  170. /* Generate the mdct window, for details see
  171. * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
  172. for (i=0 ; i<256; i++)
  173. enc_window[i] = (sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0) * 0.5;
  174. if (!mdct_window[0])
  175. for (i=0 ; i<256; i++) {
  176. mdct_window[i] = enc_window[i]/(enc_window[i]*enc_window[i] + enc_window[255-i]*enc_window[255-i]);
  177. mdct_window[511-i] = mdct_window[i];
  178. }
  179. /* Initialize the MDCT transform. */
  180. return ff_mdct_init(&q->mdct_ctx, 9, 1, is_float ? 1.0 / 32768 : 1.0);
  181. }
  182. /**
  183. * Atrac3 uninit, free all allocated memory
  184. */
  185. static av_cold int atrac3_decode_close(AVCodecContext *avctx)
  186. {
  187. ATRAC3Context *q = avctx->priv_data;
  188. av_free(q->pUnits);
  189. av_free(q->decoded_bytes_buffer);
  190. av_freep(&q->outSamples[0]);
  191. ff_mdct_end(&q->mdct_ctx);
  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 = ff_atrac_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, (SAMPLES_PER_FRAME - 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 AVERROR_INVALIDDATA;
  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 AVERROR_INVALIDDATA;
  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 = SAMPLES_PER_FRAME - pComponent[component_count].pos;
  337. coded_values = coded_values_per_component + 1;
  338. coded_values = FFMIN(max_coded_values,coded_values);
  339. scalefactor = ff_atrac_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 AVERROR_INVALIDDATA;
  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 AVERROR_INVALIDDATA;
  554. }
  555. } else {
  556. if (get_bits(gb,6) != 0x28) {
  557. av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
  558. return AVERROR_INVALIDDATA;
  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(q, &(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. float **out_samples)
  598. {
  599. int result, i;
  600. float *p1, *p2, *p3, *p4;
  601. uint8_t *ptr1;
  602. if (q->codingMode == JOINT_STEREO) {
  603. /* channel coupling mode */
  604. /* decode Sound Unit 1 */
  605. init_get_bits(&q->gb,databuf,q->bits_per_frame);
  606. result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
  607. if (result != 0)
  608. return (result);
  609. /* Framedata of the su2 in the joint-stereo mode is encoded in
  610. * reverse byte order so we need to swap it first. */
  611. if (databuf == q->decoded_bytes_buffer) {
  612. uint8_t *ptr2 = q->decoded_bytes_buffer+q->bytes_per_frame-1;
  613. ptr1 = q->decoded_bytes_buffer;
  614. for (i = 0; i < (q->bytes_per_frame/2); i++, ptr1++, ptr2--) {
  615. FFSWAP(uint8_t,*ptr1,*ptr2);
  616. }
  617. } else {
  618. const uint8_t *ptr2 = databuf+q->bytes_per_frame-1;
  619. for (i = 0; i < q->bytes_per_frame; i++)
  620. q->decoded_bytes_buffer[i] = *ptr2--;
  621. }
  622. /* Skip the sync codes (0xF8). */
  623. ptr1 = q->decoded_bytes_buffer;
  624. for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
  625. if (i >= q->bytes_per_frame)
  626. return AVERROR_INVALIDDATA;
  627. }
  628. /* set the bitstream reader at the start of the second Sound Unit*/
  629. init_get_bits(&q->gb,ptr1,q->bits_per_frame);
  630. /* Fill the Weighting coeffs delay buffer */
  631. memmove(q->weighting_delay,&(q->weighting_delay[2]),4*sizeof(int));
  632. q->weighting_delay[4] = get_bits1(&q->gb);
  633. q->weighting_delay[5] = get_bits(&q->gb,3);
  634. for (i = 0; i < 4; i++) {
  635. q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
  636. q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
  637. q->matrix_coeff_index_next[i] = get_bits(&q->gb,2);
  638. }
  639. /* Decode Sound Unit 2. */
  640. result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
  641. if (result != 0)
  642. return (result);
  643. /* Reconstruct the channel coefficients. */
  644. reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
  645. channelWeighting(out_samples[0], out_samples[1], q->weighting_delay);
  646. } else {
  647. /* normal stereo mode or mono */
  648. /* Decode the channel sound units. */
  649. for (i=0 ; i<q->channels ; i++) {
  650. /* Set the bitstream reader at the start of a channel sound unit. */
  651. init_get_bits(&q->gb, databuf+((i*q->bytes_per_frame)/q->channels), (q->bits_per_frame)/q->channels);
  652. result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
  653. if (result != 0)
  654. return (result);
  655. }
  656. }
  657. /* Apply the iQMF synthesis filter. */
  658. for (i=0 ; i<q->channels ; i++) {
  659. p1 = out_samples[i];
  660. p2= p1+256;
  661. p3= p2+256;
  662. p4= p3+256;
  663. atrac_iqmf (p1, p2, 256, p1, q->pUnits[i].delayBuf1, q->tempBuf);
  664. atrac_iqmf (p4, p3, 256, p3, q->pUnits[i].delayBuf2, q->tempBuf);
  665. atrac_iqmf (p1, p3, 512, p1, q->pUnits[i].delayBuf3, q->tempBuf);
  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, out_size;
  681. const uint8_t* databuf;
  682. float *samples_flt = data;
  683. int16_t *samples_s16 = data;
  684. if (buf_size < avctx->block_align) {
  685. av_log(avctx, AV_LOG_ERROR,
  686. "Frame too small (%d bytes). Truncated file?\n", buf_size);
  687. return AVERROR_INVALIDDATA;
  688. }
  689. out_size = SAMPLES_PER_FRAME * q->channels *
  690. av_get_bytes_per_sample(avctx->sample_fmt);
  691. if (*data_size < out_size) {
  692. av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
  693. return AVERROR(EINVAL);
  694. }
  695. /* Check if we need to descramble and what buffer to pass on. */
  696. if (q->scrambled_stream) {
  697. decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
  698. databuf = q->decoded_bytes_buffer;
  699. } else {
  700. databuf = buf;
  701. }
  702. if (q->channels == 1 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT)
  703. result = decodeFrame(q, databuf, &samples_flt);
  704. else
  705. result = decodeFrame(q, databuf, q->outSamples);
  706. if (result != 0) {
  707. av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");
  708. return result;
  709. }
  710. /* interleave */
  711. if (q->channels == 2 && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
  712. q->fmt_conv.float_interleave(samples_flt,
  713. (const float **)q->outSamples,
  714. SAMPLES_PER_FRAME, 2);
  715. } else if (avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
  716. q->fmt_conv.float_to_int16_interleave(samples_s16,
  717. (const float **)q->outSamples,
  718. SAMPLES_PER_FRAME, q->channels);
  719. }
  720. *data_size = out_size;
  721. return avctx->block_align;
  722. }
  723. /**
  724. * Atrac3 initialization
  725. *
  726. * @param avctx pointer to the AVCodecContext
  727. */
  728. static av_cold int atrac3_decode_init(AVCodecContext *avctx)
  729. {
  730. int i, ret;
  731. const uint8_t *edata_ptr = avctx->extradata;
  732. ATRAC3Context *q = avctx->priv_data;
  733. static VLC_TYPE atrac3_vlc_table[4096][2];
  734. static int vlcs_initialized = 0;
  735. /* Take data from the AVCodecContext (RM container). */
  736. q->sample_rate = avctx->sample_rate;
  737. q->channels = avctx->channels;
  738. q->bit_rate = avctx->bit_rate;
  739. q->bits_per_frame = avctx->block_align * 8;
  740. q->bytes_per_frame = avctx->block_align;
  741. /* Take care of the codec-specific extradata. */
  742. if (avctx->extradata_size == 14) {
  743. /* Parse the extradata, WAV format */
  744. av_log(avctx,AV_LOG_DEBUG,"[0-1] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown value always 1
  745. q->samples_per_channel = bytestream_get_le32(&edata_ptr);
  746. q->codingMode = bytestream_get_le16(&edata_ptr);
  747. av_log(avctx,AV_LOG_DEBUG,"[8-9] %d\n",bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
  748. q->frame_factor = bytestream_get_le16(&edata_ptr); //Unknown always 1
  749. av_log(avctx,AV_LOG_DEBUG,"[12-13] %d\n",bytestream_get_le16(&edata_ptr)); //Unknown always 0
  750. /* setup */
  751. q->samples_per_frame = SAMPLES_PER_FRAME * q->channels;
  752. q->atrac3version = 4;
  753. q->delay = 0x88E;
  754. if (q->codingMode)
  755. q->codingMode = JOINT_STEREO;
  756. else
  757. q->codingMode = STEREO;
  758. q->scrambled_stream = 0;
  759. 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)) {
  760. } else {
  761. 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);
  762. return AVERROR_INVALIDDATA;
  763. }
  764. } else if (avctx->extradata_size == 10) {
  765. /* Parse the extradata, RM format. */
  766. q->atrac3version = bytestream_get_be32(&edata_ptr);
  767. q->samples_per_frame = bytestream_get_be16(&edata_ptr);
  768. q->delay = bytestream_get_be16(&edata_ptr);
  769. q->codingMode = bytestream_get_be16(&edata_ptr);
  770. q->samples_per_channel = q->samples_per_frame / q->channels;
  771. q->scrambled_stream = 1;
  772. } else {
  773. av_log(NULL,AV_LOG_ERROR,"Unknown extradata size %d.\n",avctx->extradata_size);
  774. }
  775. /* Check the extradata. */
  776. if (q->atrac3version != 4) {
  777. av_log(avctx,AV_LOG_ERROR,"Version %d != 4.\n",q->atrac3version);
  778. return AVERROR_INVALIDDATA;
  779. }
  780. if (q->samples_per_frame != SAMPLES_PER_FRAME && q->samples_per_frame != SAMPLES_PER_FRAME*2) {
  781. av_log(avctx,AV_LOG_ERROR,"Unknown amount of samples per frame %d.\n",q->samples_per_frame);
  782. return AVERROR_INVALIDDATA;
  783. }
  784. if (q->delay != 0x88E) {
  785. av_log(avctx,AV_LOG_ERROR,"Unknown amount of delay %x != 0x88E.\n",q->delay);
  786. return AVERROR_INVALIDDATA;
  787. }
  788. if (q->codingMode == STEREO) {
  789. av_log(avctx,AV_LOG_DEBUG,"Normal stereo detected.\n");
  790. } else if (q->codingMode == JOINT_STEREO) {
  791. av_log(avctx,AV_LOG_DEBUG,"Joint stereo detected.\n");
  792. } else {
  793. av_log(avctx,AV_LOG_ERROR,"Unknown channel coding mode %x!\n",q->codingMode);
  794. return AVERROR_INVALIDDATA;
  795. }
  796. if (avctx->channels <= 0 || avctx->channels > 2 /*|| ((avctx->channels * 1024) != q->samples_per_frame)*/) {
  797. av_log(avctx,AV_LOG_ERROR,"Channel configuration error!\n");
  798. return AVERROR(EINVAL);
  799. }
  800. if(avctx->block_align >= UINT_MAX/2)
  801. return AVERROR(EINVAL);
  802. /* Pad the data buffer with FF_INPUT_BUFFER_PADDING_SIZE,
  803. * this is for the bitstream reader. */
  804. if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE))) == NULL)
  805. return AVERROR(ENOMEM);
  806. /* Initialize the VLC tables. */
  807. if (!vlcs_initialized) {
  808. for (i=0 ; i<7 ; i++) {
  809. spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
  810. spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] - atrac3_vlc_offs[i];
  811. init_vlc (&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
  812. huff_bits[i], 1, 1,
  813. huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
  814. }
  815. vlcs_initialized = 1;
  816. }
  817. if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT)
  818. avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  819. else
  820. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  821. if ((ret = init_atrac3_transforms(q, avctx->sample_fmt == AV_SAMPLE_FMT_FLT))) {
  822. av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
  823. av_freep(&q->decoded_bytes_buffer);
  824. return ret;
  825. }
  826. atrac_generate_tables();
  827. /* Generate gain tables. */
  828. for (i=0 ; i<16 ; i++)
  829. gain_tab1[i] = powf (2.0, (4 - i));
  830. for (i=-15 ; i<16 ; i++)
  831. gain_tab2[i+15] = powf (2.0, i * -0.125);
  832. /* init the joint-stereo decoding data */
  833. q->weighting_delay[0] = 0;
  834. q->weighting_delay[1] = 7;
  835. q->weighting_delay[2] = 0;
  836. q->weighting_delay[3] = 7;
  837. q->weighting_delay[4] = 0;
  838. q->weighting_delay[5] = 7;
  839. for (i=0; i<4; i++) {
  840. q->matrix_coeff_index_prev[i] = 3;
  841. q->matrix_coeff_index_now[i] = 3;
  842. q->matrix_coeff_index_next[i] = 3;
  843. }
  844. dsputil_init(&dsp, avctx);
  845. ff_fmt_convert_init(&q->fmt_conv, avctx);
  846. q->pUnits = av_mallocz(sizeof(channel_unit)*q->channels);
  847. if (!q->pUnits) {
  848. atrac3_decode_close(avctx);
  849. return AVERROR(ENOMEM);
  850. }
  851. if (avctx->channels > 1 || avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
  852. q->outSamples[0] = av_mallocz(SAMPLES_PER_FRAME * avctx->channels * sizeof(*q->outSamples[0]));
  853. q->outSamples[1] = q->outSamples[0] + SAMPLES_PER_FRAME;
  854. if (!q->outSamples[0]) {
  855. atrac3_decode_close(avctx);
  856. return AVERROR(ENOMEM);
  857. }
  858. }
  859. return 0;
  860. }
  861. AVCodec ff_atrac3_decoder =
  862. {
  863. .name = "atrac3",
  864. .type = AVMEDIA_TYPE_AUDIO,
  865. .id = CODEC_ID_ATRAC3,
  866. .priv_data_size = sizeof(ATRAC3Context),
  867. .init = atrac3_decode_init,
  868. .close = atrac3_decode_close,
  869. .decode = atrac3_decode_frame,
  870. .capabilities = CODEC_CAP_SUBFRAMES,
  871. .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
  872. };