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.

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