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.

953 lines
31KB

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