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.

1014 lines
32KB

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