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.

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