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.

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