You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

936 lines
30KB

  1. /*
  2. * ATRAC3 compatible decoder
  3. * Copyright (c) 2006-2008 Maxim Poliakovski
  4. * Copyright (c) 2006-2008 Benjamin Larsson
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; 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. * ATRAC3 compatible decoder.
  25. * This decoder handles Sony's ATRAC3 data.
  26. *
  27. * Container formats used to store ATRAC3 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 "libavutil/attributes.h"
  37. #include "libavutil/float_dsp.h"
  38. #include "avcodec.h"
  39. #include "bitstream.h"
  40. #include "bytestream.h"
  41. #include "fft.h"
  42. #include "internal.h"
  43. #include "atrac.h"
  44. #include "atrac3data.h"
  45. #define JOINT_STEREO 0x12
  46. #define STEREO 0x2
  47. #define SAMPLES_PER_FRAME 1024
  48. #define MDCT_SIZE 512
  49. typedef struct GainBlock {
  50. AtracGainInfo g_block[4];
  51. } GainBlock;
  52. typedef struct TonalComponent {
  53. int pos;
  54. int num_coefs;
  55. float coef[8];
  56. } TonalComponent;
  57. typedef struct ChannelUnit {
  58. int bands_coded;
  59. int num_components;
  60. float prev_frame[SAMPLES_PER_FRAME];
  61. int gc_blk_switch;
  62. TonalComponent components[64];
  63. GainBlock gain_block[2];
  64. DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
  65. DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
  66. float delay_buf1[46]; ///<qmf delay buffers
  67. float delay_buf2[46];
  68. float delay_buf3[46];
  69. } ChannelUnit;
  70. typedef struct ATRAC3Context {
  71. BitstreamContext bc;
  72. //@{
  73. /** stream data */
  74. int coding_mode;
  75. ChannelUnit *units;
  76. //@}
  77. //@{
  78. /** joint-stereo related variables */
  79. int matrix_coeff_index_prev[4];
  80. int matrix_coeff_index_now[4];
  81. int matrix_coeff_index_next[4];
  82. int weighting_delay[6];
  83. //@}
  84. //@{
  85. /** data buffers */
  86. uint8_t *decoded_bytes_buffer;
  87. float temp_buf[1070];
  88. //@}
  89. //@{
  90. /** extradata */
  91. int scrambled_stream;
  92. //@}
  93. AtracGCContext gainc_ctx;
  94. FFTContext mdct_ctx;
  95. AVFloatDSPContext fdsp;
  96. } ATRAC3Context;
  97. static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];
  98. static VLC_TYPE atrac3_vlc_table[4096][2];
  99. static VLC spectral_coeff_tab[7];
  100. /**
  101. * Regular 512 points IMDCT without overlapping, with the exception of the
  102. * swapping of odd bands caused by the reverse spectra of the QMF.
  103. *
  104. * @param odd_band 1 if the band is an odd band
  105. */
  106. static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)
  107. {
  108. int i;
  109. if (odd_band) {
  110. /**
  111. * Reverse the odd bands before IMDCT, this is an effect of the QMF
  112. * transform or it gives better compression to do it this way.
  113. * FIXME: It should be possible to handle this in imdct_calc
  114. * for that to happen a modification of the prerotation step of
  115. * all SIMD code and C code is needed.
  116. * Or fix the functions before so they generate a pre reversed spectrum.
  117. */
  118. for (i = 0; i < 128; i++)
  119. FFSWAP(float, input[i], input[255 - i]);
  120. }
  121. q->mdct_ctx.imdct_calc(&q->mdct_ctx, output, input);
  122. /* Perform windowing on the output. */
  123. q->fdsp.vector_fmul(output, output, mdct_window, MDCT_SIZE);
  124. }
  125. /*
  126. * indata descrambling, only used for data coming from the rm container
  127. */
  128. static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)
  129. {
  130. int i, off;
  131. uint32_t c;
  132. const uint32_t *buf;
  133. uint32_t *output = (uint32_t *)out;
  134. off = (intptr_t)input & 3;
  135. buf = (const uint32_t *)(input - off);
  136. if (off)
  137. c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));
  138. else
  139. c = av_be2ne32(0x537F6103U);
  140. bytes += 3 + off;
  141. for (i = 0; i < bytes / 4; i++)
  142. output[i] = c ^ buf[i];
  143. if (off)
  144. avpriv_request_sample(NULL, "Offset of %d", off);
  145. return off;
  146. }
  147. static av_cold void init_imdct_window(void)
  148. {
  149. int i, j;
  150. /* generate the mdct window, for details see
  151. * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */
  152. for (i = 0, j = 255; i < 128; i++, j--) {
  153. float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
  154. float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;
  155. float w = 0.5 * (wi * wi + wj * wj);
  156. mdct_window[i] = mdct_window[511 - i] = wi / w;
  157. mdct_window[j] = mdct_window[511 - j] = wj / w;
  158. }
  159. }
  160. static av_cold int atrac3_decode_close(AVCodecContext *avctx)
  161. {
  162. ATRAC3Context *q = avctx->priv_data;
  163. av_free(q->units);
  164. av_free(q->decoded_bytes_buffer);
  165. ff_mdct_end(&q->mdct_ctx);
  166. return 0;
  167. }
  168. /**
  169. * Mantissa decoding
  170. *
  171. * @param selector which table the output values are coded with
  172. * @param coding_flag constant length coding or variable length coding
  173. * @param mantissas mantissa output table
  174. * @param num_codes number of values to get
  175. */
  176. static void read_quant_spectral_coeffs(BitstreamContext *bc, int selector,
  177. int coding_flag, int *mantissas,
  178. int num_codes)
  179. {
  180. int i, code, huff_symb;
  181. if (selector == 1)
  182. num_codes /= 2;
  183. if (coding_flag != 0) {
  184. /* constant length coding (CLC) */
  185. int num_bits = clc_length_tab[selector];
  186. if (selector > 1) {
  187. for (i = 0; i < num_codes; i++) {
  188. if (num_bits)
  189. code = bitstream_read_signed(bc, num_bits);
  190. else
  191. code = 0;
  192. mantissas[i] = code;
  193. }
  194. } else {
  195. for (i = 0; i < num_codes; i++) {
  196. if (num_bits)
  197. code = bitstream_read(bc, num_bits); // num_bits is always 4 in this case
  198. else
  199. code = 0;
  200. mantissas[i * 2 ] = mantissa_clc_tab[code >> 2];
  201. mantissas[i * 2 + 1] = mantissa_clc_tab[code & 3];
  202. }
  203. }
  204. } else {
  205. /* variable length coding (VLC) */
  206. if (selector != 1) {
  207. for (i = 0; i < num_codes; i++) {
  208. huff_symb = bitstream_read_vlc(bc, spectral_coeff_tab[selector-1].table,
  209. spectral_coeff_tab[selector-1].bits, 3);
  210. huff_symb += 1;
  211. code = huff_symb >> 1;
  212. if (huff_symb & 1)
  213. code = -code;
  214. mantissas[i] = code;
  215. }
  216. } else {
  217. for (i = 0; i < num_codes; i++) {
  218. huff_symb = bitstream_read_vlc(bc, spectral_coeff_tab[selector - 1].table,
  219. spectral_coeff_tab[selector - 1].bits, 3);
  220. mantissas[i * 2 ] = mantissa_vlc_tab[huff_symb * 2 ];
  221. mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * Restore the quantized band spectrum coefficients
  228. *
  229. * @return subband count, fix for broken specification/files
  230. */
  231. static int decode_spectrum(BitstreamContext *bc, float *output)
  232. {
  233. int num_subbands, coding_mode, i, j, first, last, subband_size;
  234. int subband_vlc_index[32], sf_index[32];
  235. int mantissas[128];
  236. float scale_factor;
  237. num_subbands = bitstream_read(bc, 5); // number of coded subbands
  238. coding_mode = bitstream_read_bit(bc); // coding Mode: 0 - VLC/ 1 - CLC
  239. /* get the VLC selector table for the subbands, 0 means not coded */
  240. for (i = 0; i <= num_subbands; i++)
  241. subband_vlc_index[i] = bitstream_read(bc, 3);
  242. /* read the scale factor indexes from the stream */
  243. for (i = 0; i <= num_subbands; i++) {
  244. if (subband_vlc_index[i] != 0)
  245. sf_index[i] = bitstream_read(bc, 6);
  246. }
  247. for (i = 0; i <= num_subbands; i++) {
  248. first = subband_tab[i ];
  249. last = subband_tab[i + 1];
  250. subband_size = last - first;
  251. if (subband_vlc_index[i] != 0) {
  252. /* decode spectral coefficients for this subband */
  253. /* TODO: This can be done faster is several blocks share the
  254. * same VLC selector (subband_vlc_index) */
  255. read_quant_spectral_coeffs(bc, subband_vlc_index[i], coding_mode,
  256. mantissas, subband_size);
  257. /* decode the scale factor for this subband */
  258. scale_factor = ff_atrac_sf_table[sf_index[i]] *
  259. inv_max_quant[subband_vlc_index[i]];
  260. /* inverse quantize the coefficients */
  261. for (j = 0; first < last; first++, j++)
  262. output[first] = mantissas[j] * scale_factor;
  263. } else {
  264. /* this subband was not coded, so zero the entire subband */
  265. memset(output + first, 0, subband_size * sizeof(*output));
  266. }
  267. }
  268. /* clear the subbands that were not coded */
  269. first = subband_tab[i];
  270. memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));
  271. return num_subbands;
  272. }
  273. /**
  274. * Restore the quantized tonal components
  275. *
  276. * @param components tonal components
  277. * @param num_bands number of coded bands
  278. */
  279. static int decode_tonal_components(BitstreamContext *bc,
  280. TonalComponent *components, int num_bands)
  281. {
  282. int i, b, c, m;
  283. int nb_components, coding_mode_selector, coding_mode;
  284. int band_flags[4], mantissa[8];
  285. int component_count = 0;
  286. nb_components = bitstream_read(bc, 5);
  287. /* no tonal components */
  288. if (nb_components == 0)
  289. return 0;
  290. coding_mode_selector = bitstream_read(bc, 2);
  291. if (coding_mode_selector == 2)
  292. return AVERROR_INVALIDDATA;
  293. coding_mode = coding_mode_selector & 1;
  294. for (i = 0; i < nb_components; i++) {
  295. int coded_values_per_component, quant_step_index;
  296. for (b = 0; b <= num_bands; b++)
  297. band_flags[b] = bitstream_read_bit(bc);
  298. coded_values_per_component = bitstream_read(bc, 3);
  299. quant_step_index = bitstream_read(bc, 3);
  300. if (quant_step_index <= 1)
  301. return AVERROR_INVALIDDATA;
  302. if (coding_mode_selector == 3)
  303. coding_mode = bitstream_read_bit(bc);
  304. for (b = 0; b < (num_bands + 1) * 4; b++) {
  305. int coded_components;
  306. if (band_flags[b >> 2] == 0)
  307. continue;
  308. coded_components = bitstream_read(bc, 3);
  309. for (c = 0; c < coded_components; c++) {
  310. TonalComponent *cmp = &components[component_count];
  311. int sf_index, coded_values, max_coded_values;
  312. float scale_factor;
  313. sf_index = bitstream_read(bc, 6);
  314. if (component_count >= 64)
  315. return AVERROR_INVALIDDATA;
  316. cmp->pos = b * 64 + bitstream_read(bc, 6);
  317. max_coded_values = SAMPLES_PER_FRAME - cmp->pos;
  318. coded_values = coded_values_per_component + 1;
  319. coded_values = FFMIN(max_coded_values, coded_values);
  320. scale_factor = ff_atrac_sf_table[sf_index] *
  321. inv_max_quant[quant_step_index];
  322. read_quant_spectral_coeffs(bc, quant_step_index, coding_mode,
  323. mantissa, coded_values);
  324. cmp->num_coefs = coded_values;
  325. /* inverse quant */
  326. for (m = 0; m < coded_values; m++)
  327. cmp->coef[m] = mantissa[m] * scale_factor;
  328. component_count++;
  329. }
  330. }
  331. }
  332. return component_count;
  333. }
  334. /**
  335. * Decode gain parameters for the coded bands
  336. *
  337. * @param block the gainblock for the current band
  338. * @param num_bands amount of coded bands
  339. */
  340. static int decode_gain_control(BitstreamContext *bc, GainBlock *block,
  341. int num_bands)
  342. {
  343. int i, j;
  344. int *level, *loc;
  345. AtracGainInfo *gain = block->g_block;
  346. for (i = 0; i <= num_bands; i++) {
  347. gain[i].num_points = bitstream_read(bc, 3);
  348. level = gain[i].lev_code;
  349. loc = gain[i].loc_code;
  350. for (j = 0; j < gain[i].num_points; j++) {
  351. level[j] = bitstream_read(bc, 4);
  352. loc[j] = bitstream_read(bc, 5);
  353. if (j && loc[j] <= loc[j - 1])
  354. return AVERROR_INVALIDDATA;
  355. }
  356. }
  357. /* Clear the unused blocks. */
  358. for (; i < 4 ; i++)
  359. gain[i].num_points = 0;
  360. return 0;
  361. }
  362. /**
  363. * Combine the tonal band spectrum and regular band spectrum
  364. *
  365. * @param spectrum output spectrum buffer
  366. * @param num_components number of tonal components
  367. * @param components tonal components for this band
  368. * @return position of the last tonal coefficient
  369. */
  370. static int add_tonal_components(float *spectrum, int num_components,
  371. TonalComponent *components)
  372. {
  373. int i, j, last_pos = -1;
  374. float *input, *output;
  375. for (i = 0; i < num_components; i++) {
  376. last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
  377. input = components[i].coef;
  378. output = &spectrum[components[i].pos];
  379. for (j = 0; j < components[i].num_coefs; j++)
  380. output[j] += input[j];
  381. }
  382. return last_pos;
  383. }
  384. #define INTERPOLATE(old, new, nsample) \
  385. ((old) + (nsample) * 0.125 * ((new) - (old)))
  386. static void reverse_matrixing(float *su1, float *su2, int *prev_code,
  387. int *curr_code)
  388. {
  389. int i, nsample, band;
  390. float mc1_l, mc1_r, mc2_l, mc2_r;
  391. for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
  392. int s1 = prev_code[i];
  393. int s2 = curr_code[i];
  394. nsample = band;
  395. if (s1 != s2) {
  396. /* Selector value changed, interpolation needed. */
  397. mc1_l = matrix_coeffs[s1 * 2 ];
  398. mc1_r = matrix_coeffs[s1 * 2 + 1];
  399. mc2_l = matrix_coeffs[s2 * 2 ];
  400. mc2_r = matrix_coeffs[s2 * 2 + 1];
  401. /* Interpolation is done over the first eight samples. */
  402. for (; nsample < band + 8; nsample++) {
  403. float c1 = su1[nsample];
  404. float c2 = su2[nsample];
  405. c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
  406. c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
  407. su1[nsample] = c2;
  408. su2[nsample] = c1 * 2.0 - c2;
  409. }
  410. }
  411. /* Apply the matrix without interpolation. */
  412. switch (s2) {
  413. case 0: /* M/S decoding */
  414. for (; nsample < band + 256; nsample++) {
  415. float c1 = su1[nsample];
  416. float c2 = su2[nsample];
  417. su1[nsample] = c2 * 2.0;
  418. su2[nsample] = (c1 - c2) * 2.0;
  419. }
  420. break;
  421. case 1:
  422. for (; nsample < band + 256; nsample++) {
  423. float c1 = su1[nsample];
  424. float c2 = su2[nsample];
  425. su1[nsample] = (c1 + c2) * 2.0;
  426. su2[nsample] = c2 * -2.0;
  427. }
  428. break;
  429. case 2:
  430. case 3:
  431. for (; nsample < band + 256; nsample++) {
  432. float c1 = su1[nsample];
  433. float c2 = su2[nsample];
  434. su1[nsample] = c1 + c2;
  435. su2[nsample] = c1 - c2;
  436. }
  437. break;
  438. default:
  439. assert(0);
  440. }
  441. }
  442. }
  443. static void get_channel_weights(int index, int flag, float ch[2])
  444. {
  445. if (index == 7) {
  446. ch[0] = 1.0;
  447. ch[1] = 1.0;
  448. } else {
  449. ch[0] = (index & 7) / 7.0;
  450. ch[1] = sqrt(2 - ch[0] * ch[0]);
  451. if (flag)
  452. FFSWAP(float, ch[0], ch[1]);
  453. }
  454. }
  455. static void channel_weighting(float *su1, float *su2, int *p3)
  456. {
  457. int band, nsample;
  458. /* w[x][y] y=0 is left y=1 is right */
  459. float w[2][2];
  460. if (p3[1] != 7 || p3[3] != 7) {
  461. get_channel_weights(p3[1], p3[0], w[0]);
  462. get_channel_weights(p3[3], p3[2], w[1]);
  463. for (band = 256; band < 4 * 256; band += 256) {
  464. for (nsample = band; nsample < band + 8; nsample++) {
  465. su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
  466. su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
  467. }
  468. for(; nsample < band + 256; nsample++) {
  469. su1[nsample] *= w[1][0];
  470. su2[nsample] *= w[1][1];
  471. }
  472. }
  473. }
  474. }
  475. /**
  476. * Decode a Sound Unit
  477. *
  478. * @param snd the channel unit to be used
  479. * @param output the decoded samples before IQMF in float representation
  480. * @param channel_num channel number
  481. * @param coding_mode the coding mode (JOINT_STEREO or regular stereo/mono)
  482. */
  483. static int decode_channel_sound_unit(ATRAC3Context *q, BitstreamContext *bc,
  484. ChannelUnit *snd, float *output,
  485. int channel_num, int coding_mode)
  486. {
  487. int band, ret, num_subbands, last_tonal, num_bands;
  488. GainBlock *gain1 = &snd->gain_block[ snd->gc_blk_switch];
  489. GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
  490. if (coding_mode == JOINT_STEREO && channel_num == 1) {
  491. if (bitstream_read(bc, 2) != 3) {
  492. av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
  493. return AVERROR_INVALIDDATA;
  494. }
  495. } else {
  496. if (bitstream_read(bc, 6) != 0x28) {
  497. av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
  498. return AVERROR_INVALIDDATA;
  499. }
  500. }
  501. /* number of coded QMF bands */
  502. snd->bands_coded = bitstream_read(bc, 2);
  503. ret = decode_gain_control(bc, gain2, snd->bands_coded);
  504. if (ret)
  505. return ret;
  506. snd->num_components = decode_tonal_components(bc, snd->components,
  507. snd->bands_coded);
  508. if (snd->num_components < 0)
  509. return snd->num_components;
  510. num_subbands = decode_spectrum(bc, snd->spectrum);
  511. /* Merge the decoded spectrum and tonal components. */
  512. last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
  513. snd->components);
  514. /* calculate number of used MLT/QMF bands according to the amount of coded
  515. spectral lines */
  516. num_bands = (subband_tab[num_subbands] - 1) >> 8;
  517. if (last_tonal >= 0)
  518. num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
  519. /* Reconstruct time domain samples. */
  520. for (band = 0; band < 4; band++) {
  521. /* Perform the IMDCT step without overlapping. */
  522. if (band <= num_bands)
  523. imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
  524. else
  525. memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
  526. /* gain compensation and overlapping */
  527. ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,
  528. &snd->prev_frame[band * 256],
  529. &gain1->g_block[band], &gain2->g_block[band],
  530. 256, &output[band * 256]);
  531. }
  532. /* Swap the gain control buffers for the next frame. */
  533. snd->gc_blk_switch ^= 1;
  534. return 0;
  535. }
  536. static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
  537. float **out_samples)
  538. {
  539. ATRAC3Context *q = avctx->priv_data;
  540. int ret, i;
  541. uint8_t *ptr1;
  542. if (q->coding_mode == JOINT_STEREO) {
  543. /* channel coupling mode */
  544. /* decode Sound Unit 1 */
  545. bitstream_init8(&q->bc, databuf, avctx->block_align);
  546. ret = decode_channel_sound_unit(q, &q->bc, q->units, out_samples[0], 0,
  547. JOINT_STEREO);
  548. if (ret != 0)
  549. return ret;
  550. /* Framedata of the su2 in the joint-stereo mode is encoded in
  551. * reverse byte order so we need to swap it first. */
  552. if (databuf == q->decoded_bytes_buffer) {
  553. uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
  554. ptr1 = q->decoded_bytes_buffer;
  555. for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
  556. FFSWAP(uint8_t, *ptr1, *ptr2);
  557. } else {
  558. const uint8_t *ptr2 = databuf + avctx->block_align - 1;
  559. for (i = 0; i < avctx->block_align; i++)
  560. q->decoded_bytes_buffer[i] = *ptr2--;
  561. }
  562. /* Skip the sync codes (0xF8). */
  563. ptr1 = q->decoded_bytes_buffer;
  564. for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
  565. if (i >= avctx->block_align)
  566. return AVERROR_INVALIDDATA;
  567. }
  568. /* set the bitstream reader at the start of the second Sound Unit*/
  569. bitstream_init8(&q->bc, ptr1, avctx->block_align - i);
  570. /* Fill the Weighting coeffs delay buffer */
  571. memmove(q->weighting_delay, &q->weighting_delay[2],
  572. 4 * sizeof(*q->weighting_delay));
  573. q->weighting_delay[4] = bitstream_read_bit(&q->bc);
  574. q->weighting_delay[5] = bitstream_read(&q->bc, 3);
  575. for (i = 0; i < 4; i++) {
  576. q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
  577. q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
  578. q->matrix_coeff_index_next[i] = bitstream_read(&q->bc, 2);
  579. }
  580. /* Decode Sound Unit 2. */
  581. ret = decode_channel_sound_unit(q, &q->bc, &q->units[1],
  582. out_samples[1], 1, JOINT_STEREO);
  583. if (ret != 0)
  584. return ret;
  585. /* Reconstruct the channel coefficients. */
  586. reverse_matrixing(out_samples[0], out_samples[1],
  587. q->matrix_coeff_index_prev,
  588. q->matrix_coeff_index_now);
  589. channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
  590. } else {
  591. /* normal stereo mode or mono */
  592. /* Decode the channel sound units. */
  593. for (i = 0; i < avctx->channels; i++) {
  594. /* Set the bitstream reader at the start of a channel sound unit. */
  595. bitstream_init8(&q->bc,
  596. databuf + i * avctx->block_align / avctx->channels,
  597. avctx->block_align / avctx->channels);
  598. ret = decode_channel_sound_unit(q, &q->bc, &q->units[i],
  599. out_samples[i], i, q->coding_mode);
  600. if (ret != 0)
  601. return ret;
  602. }
  603. }
  604. /* Apply the iQMF synthesis filter. */
  605. for (i = 0; i < avctx->channels; i++) {
  606. float *p1 = out_samples[i];
  607. float *p2 = p1 + 256;
  608. float *p3 = p2 + 256;
  609. float *p4 = p3 + 256;
  610. ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
  611. ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
  612. ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
  613. }
  614. return 0;
  615. }
  616. static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
  617. int *got_frame_ptr, AVPacket *avpkt)
  618. {
  619. AVFrame *frame = data;
  620. const uint8_t *buf = avpkt->data;
  621. int buf_size = avpkt->size;
  622. ATRAC3Context *q = avctx->priv_data;
  623. int ret;
  624. const uint8_t *databuf;
  625. if (buf_size < avctx->block_align) {
  626. av_log(avctx, AV_LOG_ERROR,
  627. "Frame too small (%d bytes). Truncated file?\n", buf_size);
  628. return AVERROR_INVALIDDATA;
  629. }
  630. /* get output buffer */
  631. frame->nb_samples = SAMPLES_PER_FRAME;
  632. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
  633. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  634. return ret;
  635. }
  636. /* Check if we need to descramble and what buffer to pass on. */
  637. if (q->scrambled_stream) {
  638. decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
  639. databuf = q->decoded_bytes_buffer;
  640. } else {
  641. databuf = buf;
  642. }
  643. ret = decode_frame(avctx, databuf, (float **)frame->extended_data);
  644. if (ret) {
  645. av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
  646. return ret;
  647. }
  648. *got_frame_ptr = 1;
  649. return avctx->block_align;
  650. }
  651. static av_cold void atrac3_init_static_data(AVCodec *codec)
  652. {
  653. int i;
  654. init_imdct_window();
  655. ff_atrac_generate_tables();
  656. /* Initialize the VLC tables. */
  657. for (i = 0; i < 7; i++) {
  658. spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
  659. spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
  660. atrac3_vlc_offs[i ];
  661. init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
  662. huff_bits[i], 1, 1,
  663. huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
  664. }
  665. }
  666. static av_cold int atrac3_decode_init(AVCodecContext *avctx)
  667. {
  668. int i, ret;
  669. int version, delay, samples_per_frame, frame_factor;
  670. const uint8_t *edata_ptr = avctx->extradata;
  671. ATRAC3Context *q = avctx->priv_data;
  672. if (avctx->channels <= 0 || avctx->channels > 2) {
  673. av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
  674. return AVERROR(EINVAL);
  675. }
  676. /* Take care of the codec-specific extradata. */
  677. if (avctx->extradata_size == 14) {
  678. /* Parse the extradata, WAV format */
  679. av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
  680. bytestream_get_le16(&edata_ptr)); // Unknown value always 1
  681. edata_ptr += 4; // samples per channel
  682. q->coding_mode = bytestream_get_le16(&edata_ptr);
  683. av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
  684. bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
  685. frame_factor = bytestream_get_le16(&edata_ptr); // Unknown always 1
  686. av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
  687. bytestream_get_le16(&edata_ptr)); // Unknown always 0
  688. /* setup */
  689. samples_per_frame = SAMPLES_PER_FRAME * avctx->channels;
  690. version = 4;
  691. delay = 0x88E;
  692. q->coding_mode = q->coding_mode ? JOINT_STEREO : STEREO;
  693. q->scrambled_stream = 0;
  694. if (avctx->block_align != 96 * avctx->channels * frame_factor &&
  695. avctx->block_align != 152 * avctx->channels * frame_factor &&
  696. avctx->block_align != 192 * avctx->channels * frame_factor) {
  697. av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
  698. "configuration %d/%d/%d\n", avctx->block_align,
  699. avctx->channels, frame_factor);
  700. return AVERROR_INVALIDDATA;
  701. }
  702. } else if (avctx->extradata_size == 10) {
  703. /* Parse the extradata, RM format. */
  704. version = bytestream_get_be32(&edata_ptr);
  705. samples_per_frame = bytestream_get_be16(&edata_ptr);
  706. delay = bytestream_get_be16(&edata_ptr);
  707. q->coding_mode = bytestream_get_be16(&edata_ptr);
  708. q->scrambled_stream = 1;
  709. } else {
  710. av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
  711. avctx->extradata_size);
  712. return AVERROR(EINVAL);
  713. }
  714. /* Check the extradata */
  715. if (version != 4) {
  716. av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
  717. return AVERROR_INVALIDDATA;
  718. }
  719. if (samples_per_frame != SAMPLES_PER_FRAME &&
  720. samples_per_frame != SAMPLES_PER_FRAME * 2) {
  721. av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
  722. samples_per_frame);
  723. return AVERROR_INVALIDDATA;
  724. }
  725. if (delay != 0x88E) {
  726. av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
  727. delay);
  728. return AVERROR_INVALIDDATA;
  729. }
  730. if (q->coding_mode == STEREO)
  731. av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
  732. else if (q->coding_mode == JOINT_STEREO) {
  733. if (avctx->channels != 2)
  734. return AVERROR_INVALIDDATA;
  735. av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
  736. } else {
  737. av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
  738. q->coding_mode);
  739. return AVERROR_INVALIDDATA;
  740. }
  741. if (avctx->block_align >= UINT_MAX / 2)
  742. return AVERROR(EINVAL);
  743. q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
  744. AV_INPUT_BUFFER_PADDING_SIZE);
  745. if (!q->decoded_bytes_buffer)
  746. return AVERROR(ENOMEM);
  747. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  748. /* initialize the MDCT transform */
  749. if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
  750. av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
  751. av_freep(&q->decoded_bytes_buffer);
  752. return ret;
  753. }
  754. /* init the joint-stereo decoding data */
  755. q->weighting_delay[0] = 0;
  756. q->weighting_delay[1] = 7;
  757. q->weighting_delay[2] = 0;
  758. q->weighting_delay[3] = 7;
  759. q->weighting_delay[4] = 0;
  760. q->weighting_delay[5] = 7;
  761. for (i = 0; i < 4; i++) {
  762. q->matrix_coeff_index_prev[i] = 3;
  763. q->matrix_coeff_index_now[i] = 3;
  764. q->matrix_coeff_index_next[i] = 3;
  765. }
  766. ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);
  767. avpriv_float_dsp_init(&q->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
  768. q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
  769. if (!q->units) {
  770. atrac3_decode_close(avctx);
  771. return AVERROR(ENOMEM);
  772. }
  773. return 0;
  774. }
  775. AVCodec ff_atrac3_decoder = {
  776. .name = "atrac3",
  777. .long_name = NULL_IF_CONFIG_SMALL("ATRAC3 (Adaptive TRansform Acoustic Coding 3)"),
  778. .type = AVMEDIA_TYPE_AUDIO,
  779. .id = AV_CODEC_ID_ATRAC3,
  780. .priv_data_size = sizeof(ATRAC3Context),
  781. .init = atrac3_decode_init,
  782. .init_static_data = atrac3_init_static_data,
  783. .close = atrac3_decode_close,
  784. .decode = atrac3_decode_frame,
  785. .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
  786. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  787. AV_SAMPLE_FMT_NONE },
  788. };