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.

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