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.

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