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.

1009 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 "internal.h"
  43. #include "atrac.h"
  44. #include "atrac3data.h"
  45. #define JOINT_STEREO 0x12
  46. #define STEREO 0x2
  47. #define SAMPLES_PER_FRAME 1024
  48. #define MDCT_SIZE 512
  49. typedef struct GainInfo {
  50. int num_gain_data;
  51. int lev_code[8];
  52. int loc_code[8];
  53. } GainInfo;
  54. typedef struct GainBlock {
  55. GainInfo g_block[4];
  56. } GainBlock;
  57. typedef struct TonalComponent {
  58. int pos;
  59. int num_coefs;
  60. float coef[8];
  61. } TonalComponent;
  62. typedef struct ChannelUnit {
  63. int bands_coded;
  64. int num_components;
  65. float prev_frame[SAMPLES_PER_FRAME];
  66. int gc_blk_switch;
  67. TonalComponent components[64];
  68. GainBlock gain_block[2];
  69. DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];
  70. DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];
  71. float delay_buf1[46]; ///<qmf delay buffers
  72. float delay_buf2[46];
  73. float delay_buf3[46];
  74. } ChannelUnit;
  75. typedef struct ATRAC3Context {
  76. AVFrame frame;
  77. GetBitContext gb;
  78. //@{
  79. /** stream data */
  80. int coding_mode;
  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. 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 i, cf, num_data;
  349. int *level, *loc;
  350. GainInfo *gain = block->g_block;
  351. for (i = 0; i <= num_bands; i++) {
  352. num_data = get_bits(gb, 3);
  353. gain[i].num_gain_data = num_data;
  354. level = gain[i].lev_code;
  355. loc = gain[i].loc_code;
  356. for (cf = 0; cf < gain[i].num_gain_data; cf++) {
  357. level[cf] = get_bits(gb, 4);
  358. loc [cf] = get_bits(gb, 5);
  359. if (cf && loc[cf] <= loc[cf - 1])
  360. return AVERROR_INVALIDDATA;
  361. }
  362. }
  363. /* Clear the unused blocks. */
  364. for (; i < 4 ; i++)
  365. gain[i].num_gain_data = 0;
  366. return 0;
  367. }
  368. /*
  369. * Apply gain parameters and perform the MDCT overlapping part
  370. *
  371. * @param input input buffer
  372. * @param prev previous buffer to perform overlap against
  373. * @param output output buffer
  374. * @param gain1 current band gain info
  375. * @param gain2 next band gain info
  376. */
  377. static void gain_compensate_and_overlap(float *input, float *prev,
  378. float *output, GainInfo *gain1,
  379. GainInfo *gain2)
  380. {
  381. float g1, g2, gain_inc;
  382. int i, j, num_data, start_loc, end_loc;
  383. if (gain2->num_gain_data == 0)
  384. g1 = 1.0;
  385. else
  386. g1 = gain_tab1[gain2->lev_code[0]];
  387. if (gain1->num_gain_data == 0) {
  388. for (i = 0; i < 256; i++)
  389. output[i] = input[i] * g1 + prev[i];
  390. } else {
  391. num_data = gain1->num_gain_data;
  392. gain1->loc_code[num_data] = 32;
  393. gain1->lev_code[num_data] = 4;
  394. for (i = 0, j = 0; i < num_data; i++) {
  395. start_loc = gain1->loc_code[i] * 8;
  396. end_loc = start_loc + 8;
  397. g2 = gain_tab1[gain1->lev_code[i]];
  398. gain_inc = gain_tab2[gain1->lev_code[i + 1] -
  399. gain1->lev_code[i ] + 15];
  400. /* interpolate */
  401. for (; j < start_loc; j++)
  402. output[j] = (input[j] * g1 + prev[j]) * g2;
  403. /* interpolation is done over eight samples */
  404. for (; j < end_loc; j++) {
  405. output[j] = (input[j] * g1 + prev[j]) * g2;
  406. g2 *= gain_inc;
  407. }
  408. }
  409. for (; j < 256; j++)
  410. output[j] = input[j] * g1 + prev[j];
  411. }
  412. /* Delay for the overlapping part. */
  413. memcpy(prev, &input[256], 256 * sizeof(*prev));
  414. }
  415. /*
  416. * Combine the tonal band spectrum and regular band spectrum
  417. *
  418. * @param spectrum output spectrum buffer
  419. * @param num_components number of tonal components
  420. * @param components tonal components for this band
  421. * @return position of the last tonal coefficient
  422. */
  423. static int add_tonal_components(float *spectrum, int num_components,
  424. TonalComponent *components)
  425. {
  426. int i, j, last_pos = -1;
  427. float *input, *output;
  428. for (i = 0; i < num_components; i++) {
  429. last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);
  430. input = components[i].coef;
  431. output = &spectrum[components[i].pos];
  432. for (j = 0; j < components[i].num_coefs; j++)
  433. output[i] += input[i];
  434. }
  435. return last_pos;
  436. }
  437. #define INTERPOLATE(old, new, nsample) \
  438. ((old) + (nsample) * 0.125 * ((new) - (old)))
  439. static void reverse_matrixing(float *su1, float *su2, int *prev_code,
  440. int *curr_code)
  441. {
  442. int i, nsample, band;
  443. float mc1_l, mc1_r, mc2_l, mc2_r;
  444. for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {
  445. int s1 = prev_code[i];
  446. int s2 = curr_code[i];
  447. nsample = band;
  448. if (s1 != s2) {
  449. /* Selector value changed, interpolation needed. */
  450. mc1_l = matrix_coeffs[s1 * 2 ];
  451. mc1_r = matrix_coeffs[s1 * 2 + 1];
  452. mc2_l = matrix_coeffs[s2 * 2 ];
  453. mc2_r = matrix_coeffs[s2 * 2 + 1];
  454. /* Interpolation is done over the first eight samples. */
  455. for (; nsample < band + 8; nsample++) {
  456. float c1 = su1[nsample];
  457. float c2 = su2[nsample];
  458. c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +
  459. c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);
  460. su1[nsample] = c2;
  461. su2[nsample] = c1 * 2.0 - c2;
  462. }
  463. }
  464. /* Apply the matrix without interpolation. */
  465. switch (s2) {
  466. case 0: /* M/S decoding */
  467. for (; nsample < band + 256; nsample++) {
  468. float c1 = su1[nsample];
  469. float c2 = su2[nsample];
  470. su1[nsample] = c2 * 2.0;
  471. su2[nsample] = (c1 - c2) * 2.0;
  472. }
  473. break;
  474. case 1:
  475. for (; nsample < band + 256; nsample++) {
  476. float c1 = su1[nsample];
  477. float c2 = su2[nsample];
  478. su1[nsample] = (c1 + c2) * 2.0;
  479. su2[nsample] = c2 * -2.0;
  480. }
  481. break;
  482. case 2:
  483. case 3:
  484. for (; nsample < band + 256; nsample++) {
  485. float c1 = su1[nsample];
  486. float c2 = su2[nsample];
  487. su1[nsample] = c1 + c2;
  488. su2[nsample] = c1 - c2;
  489. }
  490. break;
  491. default:
  492. assert(0);
  493. }
  494. }
  495. }
  496. static void get_channel_weights(int index, int flag, float ch[2])
  497. {
  498. if (index == 7) {
  499. ch[0] = 1.0;
  500. ch[1] = 1.0;
  501. } else {
  502. ch[0] = (index & 7) / 7.0;
  503. ch[1] = sqrt(2 - ch[0] * ch[0]);
  504. if (flag)
  505. FFSWAP(float, ch[0], ch[1]);
  506. }
  507. }
  508. static void channel_weighting(float *su1, float *su2, int *p3)
  509. {
  510. int band, nsample;
  511. /* w[x][y] y=0 is left y=1 is right */
  512. float w[2][2];
  513. if (p3[1] != 7 || p3[3] != 7) {
  514. get_channel_weights(p3[1], p3[0], w[0]);
  515. get_channel_weights(p3[3], p3[2], w[1]);
  516. for (band = 256; band < 4 * 256; band += 256) {
  517. for (nsample = band; nsample < band + 8; nsample++) {
  518. su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);
  519. su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);
  520. }
  521. for(; nsample < band + 256; nsample++) {
  522. su1[nsample] *= w[1][0];
  523. su2[nsample] *= w[1][1];
  524. }
  525. }
  526. }
  527. }
  528. /*
  529. * Decode a Sound Unit
  530. *
  531. * @param snd the channel unit to be used
  532. * @param output the decoded samples before IQMF in float representation
  533. * @param channel_num channel number
  534. * @param coding_mode the coding mode (JOINT_STEREO or regular stereo/mono)
  535. */
  536. static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,
  537. ChannelUnit *snd, float *output,
  538. int channel_num, int coding_mode)
  539. {
  540. int band, ret, num_subbands, last_tonal, num_bands;
  541. GainBlock *gain1 = &snd->gain_block[ snd->gc_blk_switch];
  542. GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];
  543. if (coding_mode == JOINT_STEREO && channel_num == 1) {
  544. if (get_bits(gb, 2) != 3) {
  545. av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");
  546. return AVERROR_INVALIDDATA;
  547. }
  548. } else {
  549. if (get_bits(gb, 6) != 0x28) {
  550. av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");
  551. return AVERROR_INVALIDDATA;
  552. }
  553. }
  554. /* number of coded QMF bands */
  555. snd->bands_coded = get_bits(gb, 2);
  556. ret = decode_gain_control(gb, gain2, snd->bands_coded);
  557. if (ret)
  558. return ret;
  559. snd->num_components = decode_tonal_components(gb, snd->components,
  560. snd->bands_coded);
  561. if (snd->num_components == -1)
  562. return -1;
  563. num_subbands = decode_spectrum(gb, snd->spectrum);
  564. /* Merge the decoded spectrum and tonal components. */
  565. last_tonal = add_tonal_components(snd->spectrum, snd->num_components,
  566. snd->components);
  567. /* calculate number of used MLT/QMF bands according to the amount of coded
  568. spectral lines */
  569. num_bands = (subband_tab[num_subbands] - 1) >> 8;
  570. if (last_tonal >= 0)
  571. num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);
  572. /* Reconstruct time domain samples. */
  573. for (band = 0; band < 4; band++) {
  574. /* Perform the IMDCT step without overlapping. */
  575. if (band <= num_bands)
  576. imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);
  577. else
  578. memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));
  579. /* gain compensation and overlapping */
  580. gain_compensate_and_overlap(snd->imdct_buf,
  581. &snd->prev_frame[band * 256],
  582. &output[band * 256],
  583. &gain1->g_block[band],
  584. &gain2->g_block[band]);
  585. }
  586. /* Swap the gain control buffers for the next frame. */
  587. snd->gc_blk_switch ^= 1;
  588. return 0;
  589. }
  590. static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,
  591. float **out_samples)
  592. {
  593. ATRAC3Context *q = avctx->priv_data;
  594. int ret, i;
  595. uint8_t *ptr1;
  596. if (q->coding_mode == JOINT_STEREO) {
  597. /* channel coupling mode */
  598. /* decode Sound Unit 1 */
  599. init_get_bits(&q->gb, databuf, avctx->block_align * 8);
  600. ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,
  601. JOINT_STEREO);
  602. if (ret != 0)
  603. return ret;
  604. /* Framedata of the su2 in the joint-stereo mode is encoded in
  605. * reverse byte order so we need to swap it first. */
  606. if (databuf == q->decoded_bytes_buffer) {
  607. uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;
  608. ptr1 = q->decoded_bytes_buffer;
  609. for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)
  610. FFSWAP(uint8_t, *ptr1, *ptr2);
  611. } else {
  612. const uint8_t *ptr2 = databuf + avctx->block_align - 1;
  613. for (i = 0; i < avctx->block_align; i++)
  614. q->decoded_bytes_buffer[i] = *ptr2--;
  615. }
  616. /* Skip the sync codes (0xF8). */
  617. ptr1 = q->decoded_bytes_buffer;
  618. for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {
  619. if (i >= avctx->block_align)
  620. return AVERROR_INVALIDDATA;
  621. }
  622. /* set the bitstream reader at the start of the second Sound Unit*/
  623. init_get_bits(&q->gb, ptr1, avctx->block_align * 8);
  624. /* Fill the Weighting coeffs delay buffer */
  625. memmove(q->weighting_delay, &q->weighting_delay[2],
  626. 4 * sizeof(*q->weighting_delay));
  627. q->weighting_delay[4] = get_bits1(&q->gb);
  628. q->weighting_delay[5] = get_bits(&q->gb, 3);
  629. for (i = 0; i < 4; i++) {
  630. q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];
  631. q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];
  632. q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);
  633. }
  634. /* Decode Sound Unit 2. */
  635. ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],
  636. out_samples[1], 1, JOINT_STEREO);
  637. if (ret != 0)
  638. return ret;
  639. /* Reconstruct the channel coefficients. */
  640. reverse_matrixing(out_samples[0], out_samples[1],
  641. q->matrix_coeff_index_prev,
  642. q->matrix_coeff_index_now);
  643. channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);
  644. } else {
  645. /* normal stereo mode or mono */
  646. /* Decode the channel sound units. */
  647. for (i = 0; i < avctx->channels; i++) {
  648. /* Set the bitstream reader at the start of a channel sound unit. */
  649. init_get_bits(&q->gb,
  650. databuf + i * avctx->block_align / avctx->channels,
  651. avctx->block_align * 8 / avctx->channels);
  652. ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],
  653. out_samples[i], i, q->coding_mode);
  654. if (ret != 0)
  655. return ret;
  656. }
  657. }
  658. /* Apply the iQMF synthesis filter. */
  659. for (i = 0; i < avctx->channels; i++) {
  660. float *p1 = out_samples[i];
  661. float *p2 = p1 + 256;
  662. float *p3 = p2 + 256;
  663. float *p4 = p3 + 256;
  664. ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);
  665. ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);
  666. ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);
  667. }
  668. return 0;
  669. }
  670. static int atrac3_decode_frame(AVCodecContext *avctx, void *data,
  671. int *got_frame_ptr, AVPacket *avpkt)
  672. {
  673. const uint8_t *buf = avpkt->data;
  674. int buf_size = avpkt->size;
  675. ATRAC3Context *q = avctx->priv_data;
  676. int ret;
  677. const uint8_t *databuf;
  678. if (buf_size < avctx->block_align) {
  679. av_log(avctx, AV_LOG_ERROR,
  680. "Frame too small (%d bytes). Truncated file?\n", buf_size);
  681. return AVERROR_INVALIDDATA;
  682. }
  683. /* get output buffer */
  684. q->frame.nb_samples = SAMPLES_PER_FRAME;
  685. if ((ret = ff_get_buffer(avctx, &q->frame)) < 0) {
  686. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  687. return ret;
  688. }
  689. /* Check if we need to descramble and what buffer to pass on. */
  690. if (q->scrambled_stream) {
  691. decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);
  692. databuf = q->decoded_bytes_buffer;
  693. } else {
  694. databuf = buf;
  695. }
  696. ret = decode_frame(avctx, databuf, (float **)q->frame.extended_data);
  697. if (ret) {
  698. av_log(NULL, AV_LOG_ERROR, "Frame decoding error!\n");
  699. return ret;
  700. }
  701. *got_frame_ptr = 1;
  702. *(AVFrame *)data = q->frame;
  703. return avctx->block_align;
  704. }
  705. static void atrac3_init_static_data(AVCodec *codec)
  706. {
  707. int i;
  708. init_atrac3_window();
  709. ff_atrac_generate_tables();
  710. /* Initialize the VLC tables. */
  711. for (i = 0; i < 7; i++) {
  712. spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];
  713. spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -
  714. atrac3_vlc_offs[i ];
  715. init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],
  716. huff_bits[i], 1, 1,
  717. huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);
  718. }
  719. /* Generate gain tables */
  720. for (i = 0; i < 16; i++)
  721. gain_tab1[i] = powf(2.0, (4 - i));
  722. for (i = -15; i < 16; i++)
  723. gain_tab2[i + 15] = powf(2.0, i * -0.125);
  724. }
  725. static av_cold int atrac3_decode_init(AVCodecContext *avctx)
  726. {
  727. int i, ret;
  728. int version, delay, samples_per_frame, frame_factor;
  729. const uint8_t *edata_ptr = avctx->extradata;
  730. ATRAC3Context *q = avctx->priv_data;
  731. if (avctx->channels <= 0 || avctx->channels > 2) {
  732. av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");
  733. return AVERROR(EINVAL);
  734. }
  735. /* Take care of the codec-specific extradata. */
  736. if (avctx->extradata_size == 14) {
  737. /* Parse the extradata, WAV format */
  738. av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",
  739. bytestream_get_le16(&edata_ptr)); // Unknown value always 1
  740. edata_ptr += 4; // samples per channel
  741. q->coding_mode = bytestream_get_le16(&edata_ptr);
  742. av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",
  743. bytestream_get_le16(&edata_ptr)); //Dupe of coding mode
  744. frame_factor = bytestream_get_le16(&edata_ptr); // Unknown always 1
  745. av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",
  746. bytestream_get_le16(&edata_ptr)); // Unknown always 0
  747. /* setup */
  748. samples_per_frame = SAMPLES_PER_FRAME * avctx->channels;
  749. version = 4;
  750. delay = 0x88E;
  751. q->coding_mode = q->coding_mode ? JOINT_STEREO : STEREO;
  752. q->scrambled_stream = 0;
  753. if (avctx->block_align != 96 * avctx->channels * frame_factor &&
  754. avctx->block_align != 152 * avctx->channels * frame_factor &&
  755. avctx->block_align != 192 * avctx->channels * frame_factor) {
  756. av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "
  757. "configuration %d/%d/%d\n", avctx->block_align,
  758. avctx->channels, frame_factor);
  759. return AVERROR_INVALIDDATA;
  760. }
  761. } else if (avctx->extradata_size == 10) {
  762. /* Parse the extradata, RM format. */
  763. version = bytestream_get_be32(&edata_ptr);
  764. samples_per_frame = bytestream_get_be16(&edata_ptr);
  765. delay = bytestream_get_be16(&edata_ptr);
  766. q->coding_mode = bytestream_get_be16(&edata_ptr);
  767. q->scrambled_stream = 1;
  768. } else {
  769. av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",
  770. avctx->extradata_size);
  771. return AVERROR(EINVAL);
  772. }
  773. /* Check the extradata */
  774. if (version != 4) {
  775. av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);
  776. return AVERROR_INVALIDDATA;
  777. }
  778. if (samples_per_frame != SAMPLES_PER_FRAME &&
  779. samples_per_frame != SAMPLES_PER_FRAME * 2) {
  780. av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",
  781. samples_per_frame);
  782. return AVERROR_INVALIDDATA;
  783. }
  784. if (delay != 0x88E) {
  785. av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",
  786. delay);
  787. return AVERROR_INVALIDDATA;
  788. }
  789. if (q->coding_mode == STEREO)
  790. av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");
  791. else if (q->coding_mode == JOINT_STEREO)
  792. av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");
  793. else {
  794. av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",
  795. q->coding_mode);
  796. return AVERROR_INVALIDDATA;
  797. }
  798. if (avctx->block_align >= UINT_MAX / 2)
  799. return AVERROR(EINVAL);
  800. q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +
  801. FF_INPUT_BUFFER_PADDING_SIZE);
  802. if (q->decoded_bytes_buffer == NULL)
  803. return AVERROR(ENOMEM);
  804. avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
  805. /* initialize the MDCT transform */
  806. if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {
  807. av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
  808. av_freep(&q->decoded_bytes_buffer);
  809. return ret;
  810. }
  811. /* init the joint-stereo decoding data */
  812. q->weighting_delay[0] = 0;
  813. q->weighting_delay[1] = 7;
  814. q->weighting_delay[2] = 0;
  815. q->weighting_delay[3] = 7;
  816. q->weighting_delay[4] = 0;
  817. q->weighting_delay[5] = 7;
  818. for (i = 0; i < 4; i++) {
  819. q->matrix_coeff_index_prev[i] = 3;
  820. q->matrix_coeff_index_now[i] = 3;
  821. q->matrix_coeff_index_next[i] = 3;
  822. }
  823. avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);
  824. ff_fmt_convert_init(&q->fmt_conv, avctx);
  825. q->units = av_mallocz(sizeof(*q->units) * avctx->channels);
  826. if (!q->units) {
  827. atrac3_decode_close(avctx);
  828. return AVERROR(ENOMEM);
  829. }
  830. avcodec_get_frame_defaults(&q->frame);
  831. avctx->coded_frame = &q->frame;
  832. return 0;
  833. }
  834. AVCodec ff_atrac3_decoder = {
  835. .name = "atrac3",
  836. .type = AVMEDIA_TYPE_AUDIO,
  837. .id = AV_CODEC_ID_ATRAC3,
  838. .priv_data_size = sizeof(ATRAC3Context),
  839. .init = atrac3_decode_init,
  840. .init_static_data = atrac3_init_static_data,
  841. .close = atrac3_decode_close,
  842. .decode = atrac3_decode_frame,
  843. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
  844. .long_name = NULL_IF_CONFIG_SMALL("Atrac 3 (Adaptive TRansform Acoustic Coding 3)"),
  845. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
  846. AV_SAMPLE_FMT_NONE },
  847. };