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.

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