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.

1046 lines
34KB

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