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.

1011 lines
32KB

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