atrac3.c 33 KB

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