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.

1635 lines
60KB

  1. /*
  2. * AAC decoder
  3. * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
  4. * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
  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 aac.c
  24. * AAC decoder
  25. * @author Oded Shimon ( ods15 ods15 dyndns org )
  26. * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
  27. */
  28. /*
  29. * supported tools
  30. *
  31. * Support? Name
  32. * N (code in SoC repo) gain control
  33. * Y block switching
  34. * Y window shapes - standard
  35. * N window shapes - Low Delay
  36. * Y filterbank - standard
  37. * N (code in SoC repo) filterbank - Scalable Sample Rate
  38. * Y Temporal Noise Shaping
  39. * N (code in SoC repo) Long Term Prediction
  40. * Y intensity stereo
  41. * Y channel coupling
  42. * Y frequency domain prediction
  43. * Y Perceptual Noise Substitution
  44. * Y Mid/Side stereo
  45. * N Scalable Inverse AAC Quantization
  46. * N Frequency Selective Switch
  47. * N upsampling filter
  48. * Y quantization & coding - AAC
  49. * N quantization & coding - TwinVQ
  50. * N quantization & coding - BSAC
  51. * N AAC Error Resilience tools
  52. * N Error Resilience payload syntax
  53. * N Error Protection tool
  54. * N CELP
  55. * N Silence Compression
  56. * N HVXC
  57. * N HVXC 4kbits/s VR
  58. * N Structured Audio tools
  59. * N Structured Audio Sample Bank Format
  60. * N MIDI
  61. * N Harmonic and Individual Lines plus Noise
  62. * N Text-To-Speech Interface
  63. * N (in progress) Spectral Band Replication
  64. * Y (not in this code) Layer-1
  65. * Y (not in this code) Layer-2
  66. * Y (not in this code) Layer-3
  67. * N SinuSoidal Coding (Transient, Sinusoid, Noise)
  68. * N (planned) Parametric Stereo
  69. * N Direct Stream Transfer
  70. *
  71. * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
  72. * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
  73. Parametric Stereo.
  74. */
  75. #include "avcodec.h"
  76. #include "internal.h"
  77. #include "bitstream.h"
  78. #include "dsputil.h"
  79. #include "lpc.h"
  80. #include "aac.h"
  81. #include "aactab.h"
  82. #include "aacdectab.h"
  83. #include "mpeg4audio.h"
  84. #include <assert.h>
  85. #include <errno.h>
  86. #include <math.h>
  87. #include <string.h>
  88. static VLC vlc_scalefactors;
  89. static VLC vlc_spectral[11];
  90. /**
  91. * Configure output channel order based on the current program configuration element.
  92. *
  93. * @param che_pos current channel position configuration
  94. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  95. *
  96. * @return Returns error status. 0 - OK, !0 - error
  97. */
  98. static int output_configure(AACContext *ac, enum ChannelPosition che_pos[4][MAX_ELEM_ID],
  99. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID]) {
  100. AVCodecContext *avctx = ac->avccontext;
  101. int i, type, channels = 0;
  102. if(!memcmp(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0])))
  103. return 0; /* no change */
  104. memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  105. /* Allocate or free elements depending on if they are in the
  106. * current program configuration.
  107. *
  108. * Set up default 1:1 output mapping.
  109. *
  110. * For a 5.1 stream the output order will be:
  111. * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
  112. */
  113. for(i = 0; i < MAX_ELEM_ID; i++) {
  114. for(type = 0; type < 4; type++) {
  115. if(che_pos[type][i]) {
  116. if(!ac->che[type][i] && !(ac->che[type][i] = av_mallocz(sizeof(ChannelElement))))
  117. return AVERROR(ENOMEM);
  118. if(type != TYPE_CCE) {
  119. ac->output_data[channels++] = ac->che[type][i]->ch[0].ret;
  120. if(type == TYPE_CPE) {
  121. ac->output_data[channels++] = ac->che[type][i]->ch[1].ret;
  122. }
  123. }
  124. } else
  125. av_freep(&ac->che[type][i]);
  126. }
  127. }
  128. avctx->channels = channels;
  129. return 0;
  130. }
  131. /**
  132. * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
  133. *
  134. * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
  135. * @param sce_map mono (Single Channel Element) map
  136. * @param type speaker type/position for these channels
  137. */
  138. static void decode_channel_map(enum ChannelPosition *cpe_map,
  139. enum ChannelPosition *sce_map, enum ChannelPosition type, GetBitContext * gb, int n) {
  140. while(n--) {
  141. enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
  142. map[get_bits(gb, 4)] = type;
  143. }
  144. }
  145. /**
  146. * Decode program configuration element; reference: table 4.2.
  147. *
  148. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  149. *
  150. * @return Returns error status. 0 - OK, !0 - error
  151. */
  152. static int decode_pce(AACContext * ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  153. GetBitContext * gb) {
  154. int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
  155. skip_bits(gb, 2); // object_type
  156. sampling_index = get_bits(gb, 4);
  157. if(sampling_index > 11) {
  158. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  159. return -1;
  160. }
  161. ac->m4ac.sampling_index = sampling_index;
  162. ac->m4ac.sample_rate = ff_mpeg4audio_sample_rates[ac->m4ac.sampling_index];
  163. num_front = get_bits(gb, 4);
  164. num_side = get_bits(gb, 4);
  165. num_back = get_bits(gb, 4);
  166. num_lfe = get_bits(gb, 2);
  167. num_assoc_data = get_bits(gb, 3);
  168. num_cc = get_bits(gb, 4);
  169. if (get_bits1(gb))
  170. skip_bits(gb, 4); // mono_mixdown_tag
  171. if (get_bits1(gb))
  172. skip_bits(gb, 4); // stereo_mixdown_tag
  173. if (get_bits1(gb))
  174. skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
  175. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
  176. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
  177. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
  178. decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
  179. skip_bits_long(gb, 4 * num_assoc_data);
  180. decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
  181. align_get_bits(gb);
  182. /* comment field, first byte is length */
  183. skip_bits_long(gb, 8 * get_bits(gb, 8));
  184. return 0;
  185. }
  186. /**
  187. * Set up channel positions based on a default channel configuration
  188. * as specified in table 1.17.
  189. *
  190. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  191. *
  192. * @return Returns error status. 0 - OK, !0 - error
  193. */
  194. static int set_default_channel_config(AACContext *ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  195. int channel_config)
  196. {
  197. if(channel_config < 1 || channel_config > 7) {
  198. av_log(ac->avccontext, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
  199. channel_config);
  200. return -1;
  201. }
  202. /* default channel configurations:
  203. *
  204. * 1ch : front center (mono)
  205. * 2ch : L + R (stereo)
  206. * 3ch : front center + L + R
  207. * 4ch : front center + L + R + back center
  208. * 5ch : front center + L + R + back stereo
  209. * 6ch : front center + L + R + back stereo + LFE
  210. * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
  211. */
  212. if(channel_config != 2)
  213. new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
  214. if(channel_config > 1)
  215. new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
  216. if(channel_config == 4)
  217. new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
  218. if(channel_config > 4)
  219. new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
  220. = AAC_CHANNEL_BACK; // back stereo
  221. if(channel_config > 5)
  222. new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
  223. if(channel_config == 7)
  224. new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
  225. return 0;
  226. }
  227. /**
  228. * Decode GA "General Audio" specific configuration; reference: table 4.1.
  229. *
  230. * @return Returns error status. 0 - OK, !0 - error
  231. */
  232. static int decode_ga_specific_config(AACContext * ac, GetBitContext * gb, int channel_config) {
  233. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  234. int extension_flag, ret;
  235. if(get_bits1(gb)) { // frameLengthFlag
  236. ff_log_missing_feature(ac->avccontext, "960/120 MDCT window is", 1);
  237. return -1;
  238. }
  239. if (get_bits1(gb)) // dependsOnCoreCoder
  240. skip_bits(gb, 14); // coreCoderDelay
  241. extension_flag = get_bits1(gb);
  242. if(ac->m4ac.object_type == AOT_AAC_SCALABLE ||
  243. ac->m4ac.object_type == AOT_ER_AAC_SCALABLE)
  244. skip_bits(gb, 3); // layerNr
  245. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  246. if (channel_config == 0) {
  247. skip_bits(gb, 4); // element_instance_tag
  248. if((ret = decode_pce(ac, new_che_pos, gb)))
  249. return ret;
  250. } else {
  251. if((ret = set_default_channel_config(ac, new_che_pos, channel_config)))
  252. return ret;
  253. }
  254. if((ret = output_configure(ac, ac->che_pos, new_che_pos)))
  255. return ret;
  256. if (extension_flag) {
  257. switch (ac->m4ac.object_type) {
  258. case AOT_ER_BSAC:
  259. skip_bits(gb, 5); // numOfSubFrame
  260. skip_bits(gb, 11); // layer_length
  261. break;
  262. case AOT_ER_AAC_LC:
  263. case AOT_ER_AAC_LTP:
  264. case AOT_ER_AAC_SCALABLE:
  265. case AOT_ER_AAC_LD:
  266. skip_bits(gb, 3); /* aacSectionDataResilienceFlag
  267. * aacScalefactorDataResilienceFlag
  268. * aacSpectralDataResilienceFlag
  269. */
  270. break;
  271. }
  272. skip_bits1(gb); // extensionFlag3 (TBD in version 3)
  273. }
  274. return 0;
  275. }
  276. /**
  277. * Decode audio specific configuration; reference: table 1.13.
  278. *
  279. * @param data pointer to AVCodecContext extradata
  280. * @param data_size size of AVCCodecContext extradata
  281. *
  282. * @return Returns error status. 0 - OK, !0 - error
  283. */
  284. static int decode_audio_specific_config(AACContext * ac, void *data, int data_size) {
  285. GetBitContext gb;
  286. int i;
  287. init_get_bits(&gb, data, data_size * 8);
  288. if((i = ff_mpeg4audio_get_config(&ac->m4ac, data, data_size)) < 0)
  289. return -1;
  290. if(ac->m4ac.sampling_index > 11) {
  291. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  292. return -1;
  293. }
  294. skip_bits_long(&gb, i);
  295. switch (ac->m4ac.object_type) {
  296. case AOT_AAC_MAIN:
  297. case AOT_AAC_LC:
  298. if (decode_ga_specific_config(ac, &gb, ac->m4ac.chan_config))
  299. return -1;
  300. break;
  301. default:
  302. av_log(ac->avccontext, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
  303. ac->m4ac.sbr == 1? "SBR+" : "", ac->m4ac.object_type);
  304. return -1;
  305. }
  306. return 0;
  307. }
  308. /**
  309. * linear congruential pseudorandom number generator
  310. *
  311. * @param previous_val pointer to the current state of the generator
  312. *
  313. * @return Returns a 32-bit pseudorandom integer
  314. */
  315. static av_always_inline int lcg_random(int previous_val) {
  316. return previous_val * 1664525 + 1013904223;
  317. }
  318. static void reset_predict_state(PredictorState * ps) {
  319. ps->r0 = 0.0f;
  320. ps->r1 = 0.0f;
  321. ps->cor0 = 0.0f;
  322. ps->cor1 = 0.0f;
  323. ps->var0 = 1.0f;
  324. ps->var1 = 1.0f;
  325. }
  326. static void reset_all_predictors(PredictorState * ps) {
  327. int i;
  328. for (i = 0; i < MAX_PREDICTORS; i++)
  329. reset_predict_state(&ps[i]);
  330. }
  331. static void reset_predictor_group(PredictorState * ps, int group_num) {
  332. int i;
  333. for (i = group_num-1; i < MAX_PREDICTORS; i+=30)
  334. reset_predict_state(&ps[i]);
  335. }
  336. static av_cold int aac_decode_init(AVCodecContext * avccontext) {
  337. AACContext * ac = avccontext->priv_data;
  338. int i;
  339. ac->avccontext = avccontext;
  340. if (avccontext->extradata_size <= 0 ||
  341. decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))
  342. return -1;
  343. avccontext->sample_fmt = SAMPLE_FMT_S16;
  344. avccontext->sample_rate = ac->m4ac.sample_rate;
  345. avccontext->frame_size = 1024;
  346. AAC_INIT_VLC_STATIC( 0, 144);
  347. AAC_INIT_VLC_STATIC( 1, 114);
  348. AAC_INIT_VLC_STATIC( 2, 188);
  349. AAC_INIT_VLC_STATIC( 3, 180);
  350. AAC_INIT_VLC_STATIC( 4, 172);
  351. AAC_INIT_VLC_STATIC( 5, 140);
  352. AAC_INIT_VLC_STATIC( 6, 168);
  353. AAC_INIT_VLC_STATIC( 7, 114);
  354. AAC_INIT_VLC_STATIC( 8, 262);
  355. AAC_INIT_VLC_STATIC( 9, 248);
  356. AAC_INIT_VLC_STATIC(10, 384);
  357. dsputil_init(&ac->dsp, avccontext);
  358. ac->random_state = 0x1f2e3d4c;
  359. // -1024 - Compensate wrong IMDCT method.
  360. // 32768 - Required to scale values to the correct range for the bias method
  361. // for float to int16 conversion.
  362. if(ac->dsp.float_to_int16 == ff_float_to_int16_c) {
  363. ac->add_bias = 385.0f;
  364. ac->sf_scale = 1. / (-1024. * 32768.);
  365. ac->sf_offset = 0;
  366. } else {
  367. ac->add_bias = 0.0f;
  368. ac->sf_scale = 1. / -1024.;
  369. ac->sf_offset = 60;
  370. }
  371. #ifndef CONFIG_HARDCODED_TABLES
  372. for (i = 0; i < 428; i++)
  373. ff_aac_pow2sf_tab[i] = pow(2, (i - 200)/4.);
  374. #endif /* CONFIG_HARDCODED_TABLES */
  375. INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
  376. ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
  377. ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
  378. 352);
  379. ff_mdct_init(&ac->mdct, 11, 1);
  380. ff_mdct_init(&ac->mdct_small, 8, 1);
  381. // window initialization
  382. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  383. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  384. ff_sine_window_init(ff_sine_1024, 1024);
  385. ff_sine_window_init(ff_sine_128, 128);
  386. return 0;
  387. }
  388. /**
  389. * Skip data_stream_element; reference: table 4.10.
  390. */
  391. static void skip_data_stream_element(GetBitContext * gb) {
  392. int byte_align = get_bits1(gb);
  393. int count = get_bits(gb, 8);
  394. if (count == 255)
  395. count += get_bits(gb, 8);
  396. if (byte_align)
  397. align_get_bits(gb);
  398. skip_bits_long(gb, 8 * count);
  399. }
  400. static int decode_prediction(AACContext * ac, IndividualChannelStream * ics, GetBitContext * gb) {
  401. int sfb;
  402. if (get_bits1(gb)) {
  403. ics->predictor_reset_group = get_bits(gb, 5);
  404. if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
  405. av_log(ac->avccontext, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
  406. return -1;
  407. }
  408. }
  409. for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
  410. ics->prediction_used[sfb] = get_bits1(gb);
  411. }
  412. return 0;
  413. }
  414. /**
  415. * Decode Individual Channel Stream info; reference: table 4.6.
  416. *
  417. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  418. */
  419. static int decode_ics_info(AACContext * ac, IndividualChannelStream * ics, GetBitContext * gb, int common_window) {
  420. if (get_bits1(gb)) {
  421. av_log(ac->avccontext, AV_LOG_ERROR, "Reserved bit set.\n");
  422. memset(ics, 0, sizeof(IndividualChannelStream));
  423. return -1;
  424. }
  425. ics->window_sequence[1] = ics->window_sequence[0];
  426. ics->window_sequence[0] = get_bits(gb, 2);
  427. ics->use_kb_window[1] = ics->use_kb_window[0];
  428. ics->use_kb_window[0] = get_bits1(gb);
  429. ics->num_window_groups = 1;
  430. ics->group_len[0] = 1;
  431. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  432. int i;
  433. ics->max_sfb = get_bits(gb, 4);
  434. for (i = 0; i < 7; i++) {
  435. if (get_bits1(gb)) {
  436. ics->group_len[ics->num_window_groups-1]++;
  437. } else {
  438. ics->num_window_groups++;
  439. ics->group_len[ics->num_window_groups-1] = 1;
  440. }
  441. }
  442. ics->num_windows = 8;
  443. ics->swb_offset = swb_offset_128[ac->m4ac.sampling_index];
  444. ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
  445. ics->tns_max_bands = tns_max_bands_128[ac->m4ac.sampling_index];
  446. ics->predictor_present = 0;
  447. } else {
  448. ics->max_sfb = get_bits(gb, 6);
  449. ics->num_windows = 1;
  450. ics->swb_offset = swb_offset_1024[ac->m4ac.sampling_index];
  451. ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
  452. ics->tns_max_bands = tns_max_bands_1024[ac->m4ac.sampling_index];
  453. ics->predictor_present = get_bits1(gb);
  454. ics->predictor_reset_group = 0;
  455. if (ics->predictor_present) {
  456. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  457. if (decode_prediction(ac, ics, gb)) {
  458. memset(ics, 0, sizeof(IndividualChannelStream));
  459. return -1;
  460. }
  461. } else if (ac->m4ac.object_type == AOT_AAC_LC) {
  462. av_log(ac->avccontext, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
  463. memset(ics, 0, sizeof(IndividualChannelStream));
  464. return -1;
  465. } else {
  466. ff_log_missing_feature(ac->avccontext, "Predictor bit set but LTP is", 1);
  467. memset(ics, 0, sizeof(IndividualChannelStream));
  468. return -1;
  469. }
  470. }
  471. }
  472. if(ics->max_sfb > ics->num_swb) {
  473. av_log(ac->avccontext, AV_LOG_ERROR,
  474. "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
  475. ics->max_sfb, ics->num_swb);
  476. memset(ics, 0, sizeof(IndividualChannelStream));
  477. return -1;
  478. }
  479. return 0;
  480. }
  481. /**
  482. * Decode band types (section_data payload); reference: table 4.46.
  483. *
  484. * @param band_type array of the used band type
  485. * @param band_type_run_end array of the last scalefactor band of a band type run
  486. *
  487. * @return Returns error status. 0 - OK, !0 - error
  488. */
  489. static int decode_band_types(AACContext * ac, enum BandType band_type[120],
  490. int band_type_run_end[120], GetBitContext * gb, IndividualChannelStream * ics) {
  491. int g, idx = 0;
  492. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  493. for (g = 0; g < ics->num_window_groups; g++) {
  494. int k = 0;
  495. while (k < ics->max_sfb) {
  496. uint8_t sect_len = k;
  497. int sect_len_incr;
  498. int sect_band_type = get_bits(gb, 4);
  499. if (sect_band_type == 12) {
  500. av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
  501. return -1;
  502. }
  503. while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits)-1)
  504. sect_len += sect_len_incr;
  505. sect_len += sect_len_incr;
  506. if (sect_len > ics->max_sfb) {
  507. av_log(ac->avccontext, AV_LOG_ERROR,
  508. "Number of bands (%d) exceeds limit (%d).\n",
  509. sect_len, ics->max_sfb);
  510. return -1;
  511. }
  512. for (; k < sect_len; k++) {
  513. band_type [idx] = sect_band_type;
  514. band_type_run_end[idx++] = sect_len;
  515. }
  516. }
  517. }
  518. return 0;
  519. }
  520. /**
  521. * Decode scalefactors; reference: table 4.47.
  522. *
  523. * @param global_gain first scalefactor value as scalefactors are differentially coded
  524. * @param band_type array of the used band type
  525. * @param band_type_run_end array of the last scalefactor band of a band type run
  526. * @param sf array of scalefactors or intensity stereo positions
  527. *
  528. * @return Returns error status. 0 - OK, !0 - error
  529. */
  530. static int decode_scalefactors(AACContext * ac, float sf[120], GetBitContext * gb,
  531. unsigned int global_gain, IndividualChannelStream * ics,
  532. enum BandType band_type[120], int band_type_run_end[120]) {
  533. const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
  534. int g, i, idx = 0;
  535. int offset[3] = { global_gain, global_gain - 90, 100 };
  536. int noise_flag = 1;
  537. static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
  538. for (g = 0; g < ics->num_window_groups; g++) {
  539. for (i = 0; i < ics->max_sfb;) {
  540. int run_end = band_type_run_end[idx];
  541. if (band_type[idx] == ZERO_BT) {
  542. for(; i < run_end; i++, idx++)
  543. sf[idx] = 0.;
  544. }else if((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
  545. for(; i < run_end; i++, idx++) {
  546. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  547. if(offset[2] > 255U) {
  548. av_log(ac->avccontext, AV_LOG_ERROR,
  549. "%s (%d) out of range.\n", sf_str[2], offset[2]);
  550. return -1;
  551. }
  552. sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
  553. }
  554. }else if(band_type[idx] == NOISE_BT) {
  555. for(; i < run_end; i++, idx++) {
  556. if(noise_flag-- > 0)
  557. offset[1] += get_bits(gb, 9) - 256;
  558. else
  559. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  560. if(offset[1] > 255U) {
  561. av_log(ac->avccontext, AV_LOG_ERROR,
  562. "%s (%d) out of range.\n", sf_str[1], offset[1]);
  563. return -1;
  564. }
  565. sf[idx] = -ff_aac_pow2sf_tab[ offset[1] + sf_offset + 100];
  566. }
  567. }else {
  568. for(; i < run_end; i++, idx++) {
  569. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  570. if(offset[0] > 255U) {
  571. av_log(ac->avccontext, AV_LOG_ERROR,
  572. "%s (%d) out of range.\n", sf_str[0], offset[0]);
  573. return -1;
  574. }
  575. sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
  576. }
  577. }
  578. }
  579. }
  580. return 0;
  581. }
  582. /**
  583. * Decode pulse data; reference: table 4.7.
  584. */
  585. static int decode_pulses(Pulse * pulse, GetBitContext * gb, const uint16_t * swb_offset, int num_swb) {
  586. int i, pulse_swb;
  587. pulse->num_pulse = get_bits(gb, 2) + 1;
  588. pulse_swb = get_bits(gb, 6);
  589. if (pulse_swb >= num_swb)
  590. return -1;
  591. pulse->pos[0] = swb_offset[pulse_swb];
  592. pulse->pos[0] += get_bits(gb, 5);
  593. if (pulse->pos[0] > 1023)
  594. return -1;
  595. pulse->amp[0] = get_bits(gb, 4);
  596. for (i = 1; i < pulse->num_pulse; i++) {
  597. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i-1];
  598. if (pulse->pos[i] > 1023)
  599. return -1;
  600. pulse->amp[i] = get_bits(gb, 4);
  601. }
  602. return 0;
  603. }
  604. /**
  605. * Decode Temporal Noise Shaping data; reference: table 4.48.
  606. *
  607. * @return Returns error status. 0 - OK, !0 - error
  608. */
  609. static int decode_tns(AACContext * ac, TemporalNoiseShaping * tns,
  610. GetBitContext * gb, const IndividualChannelStream * ics) {
  611. int w, filt, i, coef_len, coef_res, coef_compress;
  612. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  613. const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  614. for (w = 0; w < ics->num_windows; w++) {
  615. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  616. coef_res = get_bits1(gb);
  617. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  618. int tmp2_idx;
  619. tns->length[w][filt] = get_bits(gb, 6 - 2*is8);
  620. if ((tns->order[w][filt] = get_bits(gb, 5 - 2*is8)) > tns_max_order) {
  621. av_log(ac->avccontext, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.",
  622. tns->order[w][filt], tns_max_order);
  623. tns->order[w][filt] = 0;
  624. return -1;
  625. }
  626. if (tns->order[w][filt]) {
  627. tns->direction[w][filt] = get_bits1(gb);
  628. coef_compress = get_bits1(gb);
  629. coef_len = coef_res + 3 - coef_compress;
  630. tmp2_idx = 2*coef_compress + coef_res;
  631. for (i = 0; i < tns->order[w][filt]; i++)
  632. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  633. }
  634. }
  635. }
  636. }
  637. return 0;
  638. }
  639. /**
  640. * Decode Mid/Side data; reference: table 4.54.
  641. *
  642. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  643. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  644. * [3] reserved for scalable AAC
  645. */
  646. static void decode_mid_side_stereo(ChannelElement * cpe, GetBitContext * gb,
  647. int ms_present) {
  648. int idx;
  649. if (ms_present == 1) {
  650. for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
  651. cpe->ms_mask[idx] = get_bits1(gb);
  652. } else if (ms_present == 2) {
  653. memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
  654. }
  655. }
  656. /**
  657. * Decode spectral data; reference: table 4.50.
  658. * Dequantize and scale spectral data; reference: 4.6.3.3.
  659. *
  660. * @param coef array of dequantized, scaled spectral data
  661. * @param sf array of scalefactors or intensity stereo positions
  662. * @param pulse_present set if pulses are present
  663. * @param pulse pointer to pulse data struct
  664. * @param band_type array of the used band type
  665. *
  666. * @return Returns error status. 0 - OK, !0 - error
  667. */
  668. static int decode_spectrum_and_dequant(AACContext * ac, float coef[1024], GetBitContext * gb, float sf[120],
  669. int pulse_present, const Pulse * pulse, const IndividualChannelStream * ics, enum BandType band_type[120]) {
  670. int i, k, g, idx = 0;
  671. const int c = 1024/ics->num_windows;
  672. const uint16_t * offsets = ics->swb_offset;
  673. float *coef_base = coef;
  674. static const float sign_lookup[] = { 1.0f, -1.0f };
  675. for (g = 0; g < ics->num_windows; g++)
  676. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float)*(c - offsets[ics->max_sfb]));
  677. for (g = 0; g < ics->num_window_groups; g++) {
  678. for (i = 0; i < ics->max_sfb; i++, idx++) {
  679. const int cur_band_type = band_type[idx];
  680. const int dim = cur_band_type >= FIRST_PAIR_BT ? 2 : 4;
  681. const int is_cb_unsigned = IS_CODEBOOK_UNSIGNED(cur_band_type);
  682. int group;
  683. if (cur_band_type == ZERO_BT || cur_band_type == INTENSITY_BT2 || cur_band_type == INTENSITY_BT) {
  684. for (group = 0; group < ics->group_len[g]; group++) {
  685. memset(coef + group * 128 + offsets[i], 0, (offsets[i+1] - offsets[i])*sizeof(float));
  686. }
  687. }else if (cur_band_type == NOISE_BT) {
  688. for (group = 0; group < ics->group_len[g]; group++) {
  689. float scale;
  690. float band_energy = 0;
  691. for (k = offsets[i]; k < offsets[i+1]; k++) {
  692. ac->random_state = lcg_random(ac->random_state);
  693. coef[group*128+k] = ac->random_state;
  694. band_energy += coef[group*128+k]*coef[group*128+k];
  695. }
  696. scale = sf[idx] / sqrtf(band_energy);
  697. for (k = offsets[i]; k < offsets[i+1]; k++) {
  698. coef[group*128+k] *= scale;
  699. }
  700. }
  701. }else {
  702. for (group = 0; group < ics->group_len[g]; group++) {
  703. for (k = offsets[i]; k < offsets[i+1]; k += dim) {
  704. const int index = get_vlc2(gb, vlc_spectral[cur_band_type - 1].table, 6, 3);
  705. const int coef_tmp_idx = (group << 7) + k;
  706. const float *vq_ptr;
  707. int j;
  708. if(index >= ff_aac_spectral_sizes[cur_band_type - 1]) {
  709. av_log(ac->avccontext, AV_LOG_ERROR,
  710. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  711. cur_band_type - 1, index, ff_aac_spectral_sizes[cur_band_type - 1]);
  712. return -1;
  713. }
  714. vq_ptr = &ff_aac_codebook_vectors[cur_band_type - 1][index * dim];
  715. if (is_cb_unsigned) {
  716. if (vq_ptr[0]) coef[coef_tmp_idx ] = sign_lookup[get_bits1(gb)];
  717. if (vq_ptr[1]) coef[coef_tmp_idx + 1] = sign_lookup[get_bits1(gb)];
  718. if (dim == 4) {
  719. if (vq_ptr[2]) coef[coef_tmp_idx + 2] = sign_lookup[get_bits1(gb)];
  720. if (vq_ptr[3]) coef[coef_tmp_idx + 3] = sign_lookup[get_bits1(gb)];
  721. }
  722. }else {
  723. coef[coef_tmp_idx ] = 1.0f;
  724. coef[coef_tmp_idx + 1] = 1.0f;
  725. if (dim == 4) {
  726. coef[coef_tmp_idx + 2] = 1.0f;
  727. coef[coef_tmp_idx + 3] = 1.0f;
  728. }
  729. }
  730. if (cur_band_type == ESC_BT) {
  731. for (j = 0; j < 2; j++) {
  732. if (vq_ptr[j] == 64.0f) {
  733. int n = 4;
  734. /* The total length of escape_sequence must be < 22 bits according
  735. to the specification (i.e. max is 11111111110xxxxxxxxxx). */
  736. while (get_bits1(gb) && n < 15) n++;
  737. if(n == 15) {
  738. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  739. return -1;
  740. }
  741. n = (1<<n) + get_bits(gb, n);
  742. coef[coef_tmp_idx + j] *= cbrtf(n) * n;
  743. }else
  744. coef[coef_tmp_idx + j] *= vq_ptr[j];
  745. }
  746. }else
  747. {
  748. coef[coef_tmp_idx ] *= vq_ptr[0];
  749. coef[coef_tmp_idx + 1] *= vq_ptr[1];
  750. if (dim == 4) {
  751. coef[coef_tmp_idx + 2] *= vq_ptr[2];
  752. coef[coef_tmp_idx + 3] *= vq_ptr[3];
  753. }
  754. }
  755. coef[coef_tmp_idx ] *= sf[idx];
  756. coef[coef_tmp_idx + 1] *= sf[idx];
  757. if (dim == 4) {
  758. coef[coef_tmp_idx + 2] *= sf[idx];
  759. coef[coef_tmp_idx + 3] *= sf[idx];
  760. }
  761. }
  762. }
  763. }
  764. }
  765. coef += ics->group_len[g]<<7;
  766. }
  767. if (pulse_present) {
  768. idx = 0;
  769. for(i = 0; i < pulse->num_pulse; i++){
  770. float co = coef_base[ pulse->pos[i] ];
  771. while(offsets[idx + 1] <= pulse->pos[i])
  772. idx++;
  773. if (band_type[idx] != NOISE_BT && sf[idx]) {
  774. float ico = -pulse->amp[i];
  775. if (co) {
  776. co /= sf[idx];
  777. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  778. }
  779. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  780. }
  781. }
  782. }
  783. return 0;
  784. }
  785. static av_always_inline float flt16_round(float pf) {
  786. int exp;
  787. pf = frexpf(pf, &exp);
  788. pf = ldexpf(roundf(ldexpf(pf, 8)), exp-8);
  789. return pf;
  790. }
  791. static av_always_inline float flt16_even(float pf) {
  792. int exp;
  793. pf = frexpf(pf, &exp);
  794. pf = ldexpf(rintf(ldexpf(pf, 8)), exp-8);
  795. return pf;
  796. }
  797. static av_always_inline float flt16_trunc(float pf) {
  798. int exp;
  799. pf = frexpf(pf, &exp);
  800. pf = ldexpf(truncf(ldexpf(pf, 8)), exp-8);
  801. return pf;
  802. }
  803. static void predict(AACContext * ac, PredictorState * ps, float* coef, int output_enable) {
  804. const float a = 0.953125; // 61.0/64
  805. const float alpha = 0.90625; // 29.0/32
  806. float e0, e1;
  807. float pv;
  808. float k1, k2;
  809. k1 = ps->var0 > 1 ? ps->cor0 * flt16_even(a / ps->var0) : 0;
  810. k2 = ps->var1 > 1 ? ps->cor1 * flt16_even(a / ps->var1) : 0;
  811. pv = flt16_round(k1 * ps->r0 + k2 * ps->r1);
  812. if (output_enable)
  813. *coef += pv * ac->sf_scale;
  814. e0 = *coef / ac->sf_scale;
  815. e1 = e0 - k1 * ps->r0;
  816. ps->cor1 = flt16_trunc(alpha * ps->cor1 + ps->r1 * e1);
  817. ps->var1 = flt16_trunc(alpha * ps->var1 + 0.5 * (ps->r1 * ps->r1 + e1 * e1));
  818. ps->cor0 = flt16_trunc(alpha * ps->cor0 + ps->r0 * e0);
  819. ps->var0 = flt16_trunc(alpha * ps->var0 + 0.5 * (ps->r0 * ps->r0 + e0 * e0));
  820. ps->r1 = flt16_trunc(a * (ps->r0 - k1 * e0));
  821. ps->r0 = flt16_trunc(a * e0);
  822. }
  823. /**
  824. * Apply AAC-Main style frequency domain prediction.
  825. */
  826. static void apply_prediction(AACContext * ac, SingleChannelElement * sce) {
  827. int sfb, k;
  828. if (!sce->ics.predictor_initialized) {
  829. reset_all_predictors(sce->predictor_state);
  830. sce->ics.predictor_initialized = 1;
  831. }
  832. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  833. for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
  834. for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
  835. predict(ac, &sce->predictor_state[k], &sce->coeffs[k],
  836. sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
  837. }
  838. }
  839. if (sce->ics.predictor_reset_group)
  840. reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
  841. } else
  842. reset_all_predictors(sce->predictor_state);
  843. }
  844. /**
  845. * Decode an individual_channel_stream payload; reference: table 4.44.
  846. *
  847. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  848. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  849. *
  850. * @return Returns error status. 0 - OK, !0 - error
  851. */
  852. static int decode_ics(AACContext * ac, SingleChannelElement * sce, GetBitContext * gb, int common_window, int scale_flag) {
  853. Pulse pulse;
  854. TemporalNoiseShaping * tns = &sce->tns;
  855. IndividualChannelStream * ics = &sce->ics;
  856. float * out = sce->coeffs;
  857. int global_gain, pulse_present = 0;
  858. /* This assignment is to silence a GCC warning about the variable being used
  859. * uninitialized when in fact it always is.
  860. */
  861. pulse.num_pulse = 0;
  862. global_gain = get_bits(gb, 8);
  863. if (!common_window && !scale_flag) {
  864. if (decode_ics_info(ac, ics, gb, 0) < 0)
  865. return -1;
  866. }
  867. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  868. return -1;
  869. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  870. return -1;
  871. pulse_present = 0;
  872. if (!scale_flag) {
  873. if ((pulse_present = get_bits1(gb))) {
  874. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  875. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  876. return -1;
  877. }
  878. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  879. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
  880. return -1;
  881. }
  882. }
  883. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  884. return -1;
  885. if (get_bits1(gb)) {
  886. ff_log_missing_feature(ac->avccontext, "SSR", 1);
  887. return -1;
  888. }
  889. }
  890. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  891. return -1;
  892. if(ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
  893. apply_prediction(ac, sce);
  894. return 0;
  895. }
  896. /**
  897. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  898. */
  899. static void apply_mid_side_stereo(ChannelElement * cpe) {
  900. const IndividualChannelStream * ics = &cpe->ch[0].ics;
  901. float *ch0 = cpe->ch[0].coeffs;
  902. float *ch1 = cpe->ch[1].coeffs;
  903. int g, i, k, group, idx = 0;
  904. const uint16_t * offsets = ics->swb_offset;
  905. for (g = 0; g < ics->num_window_groups; g++) {
  906. for (i = 0; i < ics->max_sfb; i++, idx++) {
  907. if (cpe->ms_mask[idx] &&
  908. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  909. for (group = 0; group < ics->group_len[g]; group++) {
  910. for (k = offsets[i]; k < offsets[i+1]; k++) {
  911. float tmp = ch0[group*128 + k] - ch1[group*128 + k];
  912. ch0[group*128 + k] += ch1[group*128 + k];
  913. ch1[group*128 + k] = tmp;
  914. }
  915. }
  916. }
  917. }
  918. ch0 += ics->group_len[g]*128;
  919. ch1 += ics->group_len[g]*128;
  920. }
  921. }
  922. /**
  923. * intensity stereo decoding; reference: 4.6.8.2.3
  924. *
  925. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  926. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  927. * [3] reserved for scalable AAC
  928. */
  929. static void apply_intensity_stereo(ChannelElement * cpe, int ms_present) {
  930. const IndividualChannelStream * ics = &cpe->ch[1].ics;
  931. SingleChannelElement * sce1 = &cpe->ch[1];
  932. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  933. const uint16_t * offsets = ics->swb_offset;
  934. int g, group, i, k, idx = 0;
  935. int c;
  936. float scale;
  937. for (g = 0; g < ics->num_window_groups; g++) {
  938. for (i = 0; i < ics->max_sfb;) {
  939. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  940. const int bt_run_end = sce1->band_type_run_end[idx];
  941. for (; i < bt_run_end; i++, idx++) {
  942. c = -1 + 2 * (sce1->band_type[idx] - 14);
  943. if (ms_present)
  944. c *= 1 - 2 * cpe->ms_mask[idx];
  945. scale = c * sce1->sf[idx];
  946. for (group = 0; group < ics->group_len[g]; group++)
  947. for (k = offsets[i]; k < offsets[i+1]; k++)
  948. coef1[group*128 + k] = scale * coef0[group*128 + k];
  949. }
  950. } else {
  951. int bt_run_end = sce1->band_type_run_end[idx];
  952. idx += bt_run_end - i;
  953. i = bt_run_end;
  954. }
  955. }
  956. coef0 += ics->group_len[g]*128;
  957. coef1 += ics->group_len[g]*128;
  958. }
  959. }
  960. /**
  961. * Decode a channel_pair_element; reference: table 4.4.
  962. *
  963. * @param elem_id Identifies the instance of a syntax element.
  964. *
  965. * @return Returns error status. 0 - OK, !0 - error
  966. */
  967. static int decode_cpe(AACContext * ac, GetBitContext * gb, int elem_id) {
  968. int i, ret, common_window, ms_present = 0;
  969. ChannelElement * cpe;
  970. cpe = ac->che[TYPE_CPE][elem_id];
  971. common_window = get_bits1(gb);
  972. if (common_window) {
  973. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  974. return -1;
  975. i = cpe->ch[1].ics.use_kb_window[0];
  976. cpe->ch[1].ics = cpe->ch[0].ics;
  977. cpe->ch[1].ics.use_kb_window[1] = i;
  978. ms_present = get_bits(gb, 2);
  979. if(ms_present == 3) {
  980. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  981. return -1;
  982. } else if(ms_present)
  983. decode_mid_side_stereo(cpe, gb, ms_present);
  984. }
  985. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  986. return ret;
  987. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  988. return ret;
  989. if (common_window) {
  990. if (ms_present)
  991. apply_mid_side_stereo(cpe);
  992. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  993. apply_prediction(ac, &cpe->ch[0]);
  994. apply_prediction(ac, &cpe->ch[1]);
  995. }
  996. }
  997. apply_intensity_stereo(cpe, ms_present);
  998. return 0;
  999. }
  1000. /**
  1001. * Decode coupling_channel_element; reference: table 4.8.
  1002. *
  1003. * @param elem_id Identifies the instance of a syntax element.
  1004. *
  1005. * @return Returns error status. 0 - OK, !0 - error
  1006. */
  1007. static int decode_cce(AACContext * ac, GetBitContext * gb, ChannelElement * che) {
  1008. int num_gain = 0;
  1009. int c, g, sfb, ret;
  1010. int sign;
  1011. float scale;
  1012. SingleChannelElement * sce = &che->ch[0];
  1013. ChannelCoupling * coup = &che->coup;
  1014. coup->coupling_point = 2*get_bits1(gb);
  1015. coup->num_coupled = get_bits(gb, 3);
  1016. for (c = 0; c <= coup->num_coupled; c++) {
  1017. num_gain++;
  1018. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1019. coup->id_select[c] = get_bits(gb, 4);
  1020. if (coup->type[c] == TYPE_CPE) {
  1021. coup->ch_select[c] = get_bits(gb, 2);
  1022. if (coup->ch_select[c] == 3)
  1023. num_gain++;
  1024. } else
  1025. coup->ch_select[c] = 2;
  1026. }
  1027. coup->coupling_point += get_bits1(gb);
  1028. if (coup->coupling_point == 2) {
  1029. av_log(ac->avccontext, AV_LOG_ERROR,
  1030. "Independently switched CCE with 'invalid' domain signalled.\n");
  1031. memset(coup, 0, sizeof(ChannelCoupling));
  1032. return -1;
  1033. }
  1034. sign = get_bits(gb, 1);
  1035. scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
  1036. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1037. return ret;
  1038. for (c = 0; c < num_gain; c++) {
  1039. int idx = 0;
  1040. int cge = 1;
  1041. int gain = 0;
  1042. float gain_cache = 1.;
  1043. if (c) {
  1044. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1045. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1046. gain_cache = pow(scale, -gain);
  1047. }
  1048. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1049. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1050. if (sce->band_type[idx] != ZERO_BT) {
  1051. if (!cge) {
  1052. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1053. if (t) {
  1054. int s = 1;
  1055. t = gain += t;
  1056. if (sign) {
  1057. s -= 2 * (t & 0x1);
  1058. t >>= 1;
  1059. }
  1060. gain_cache = pow(scale, -t) * s;
  1061. }
  1062. }
  1063. coup->gain[c][idx] = gain_cache;
  1064. }
  1065. }
  1066. }
  1067. }
  1068. return 0;
  1069. }
  1070. /**
  1071. * Decode Spectral Band Replication extension data; reference: table 4.55.
  1072. *
  1073. * @param crc flag indicating the presence of CRC checksum
  1074. * @param cnt length of TYPE_FIL syntactic element in bytes
  1075. *
  1076. * @return Returns number of bytes consumed from the TYPE_FIL element.
  1077. */
  1078. static int decode_sbr_extension(AACContext * ac, GetBitContext * gb, int crc, int cnt) {
  1079. // TODO : sbr_extension implementation
  1080. ff_log_missing_feature(ac->avccontext, "SBR", 0);
  1081. skip_bits_long(gb, 8*cnt - 4); // -4 due to reading extension type
  1082. return cnt;
  1083. }
  1084. /**
  1085. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  1086. *
  1087. * @return Returns number of bytes consumed.
  1088. */
  1089. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc, GetBitContext * gb) {
  1090. int i;
  1091. int num_excl_chan = 0;
  1092. do {
  1093. for (i = 0; i < 7; i++)
  1094. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  1095. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  1096. return num_excl_chan / 7;
  1097. }
  1098. /**
  1099. * Decode dynamic range information; reference: table 4.52.
  1100. *
  1101. * @param cnt length of TYPE_FIL syntactic element in bytes
  1102. *
  1103. * @return Returns number of bytes consumed.
  1104. */
  1105. static int decode_dynamic_range(DynamicRangeControl *che_drc, GetBitContext * gb, int cnt) {
  1106. int n = 1;
  1107. int drc_num_bands = 1;
  1108. int i;
  1109. /* pce_tag_present? */
  1110. if(get_bits1(gb)) {
  1111. che_drc->pce_instance_tag = get_bits(gb, 4);
  1112. skip_bits(gb, 4); // tag_reserved_bits
  1113. n++;
  1114. }
  1115. /* excluded_chns_present? */
  1116. if(get_bits1(gb)) {
  1117. n += decode_drc_channel_exclusions(che_drc, gb);
  1118. }
  1119. /* drc_bands_present? */
  1120. if (get_bits1(gb)) {
  1121. che_drc->band_incr = get_bits(gb, 4);
  1122. che_drc->interpolation_scheme = get_bits(gb, 4);
  1123. n++;
  1124. drc_num_bands += che_drc->band_incr;
  1125. for (i = 0; i < drc_num_bands; i++) {
  1126. che_drc->band_top[i] = get_bits(gb, 8);
  1127. n++;
  1128. }
  1129. }
  1130. /* prog_ref_level_present? */
  1131. if (get_bits1(gb)) {
  1132. che_drc->prog_ref_level = get_bits(gb, 7);
  1133. skip_bits1(gb); // prog_ref_level_reserved_bits
  1134. n++;
  1135. }
  1136. for (i = 0; i < drc_num_bands; i++) {
  1137. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  1138. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  1139. n++;
  1140. }
  1141. return n;
  1142. }
  1143. /**
  1144. * Decode extension data (incomplete); reference: table 4.51.
  1145. *
  1146. * @param cnt length of TYPE_FIL syntactic element in bytes
  1147. *
  1148. * @return Returns number of bytes consumed
  1149. */
  1150. static int decode_extension_payload(AACContext * ac, GetBitContext * gb, int cnt) {
  1151. int crc_flag = 0;
  1152. int res = cnt;
  1153. switch (get_bits(gb, 4)) { // extension type
  1154. case EXT_SBR_DATA_CRC:
  1155. crc_flag++;
  1156. case EXT_SBR_DATA:
  1157. res = decode_sbr_extension(ac, gb, crc_flag, cnt);
  1158. break;
  1159. case EXT_DYNAMIC_RANGE:
  1160. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  1161. break;
  1162. case EXT_FILL:
  1163. case EXT_FILL_DATA:
  1164. case EXT_DATA_ELEMENT:
  1165. default:
  1166. skip_bits_long(gb, 8*cnt - 4);
  1167. break;
  1168. };
  1169. return res;
  1170. }
  1171. /**
  1172. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  1173. *
  1174. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  1175. * @param coef spectral coefficients
  1176. */
  1177. static void apply_tns(float coef[1024], TemporalNoiseShaping * tns, IndividualChannelStream * ics, int decode) {
  1178. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  1179. int w, filt, m, i;
  1180. int bottom, top, order, start, end, size, inc;
  1181. float lpc[TNS_MAX_ORDER];
  1182. for (w = 0; w < ics->num_windows; w++) {
  1183. bottom = ics->num_swb;
  1184. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1185. top = bottom;
  1186. bottom = FFMAX(0, top - tns->length[w][filt]);
  1187. order = tns->order[w][filt];
  1188. if (order == 0)
  1189. continue;
  1190. // tns_decode_coef
  1191. compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
  1192. start = ics->swb_offset[FFMIN(bottom, mmm)];
  1193. end = ics->swb_offset[FFMIN( top, mmm)];
  1194. if ((size = end - start) <= 0)
  1195. continue;
  1196. if (tns->direction[w][filt]) {
  1197. inc = -1; start = end - 1;
  1198. } else {
  1199. inc = 1;
  1200. }
  1201. start += w * 128;
  1202. // ar filter
  1203. for (m = 0; m < size; m++, start += inc)
  1204. for (i = 1; i <= FFMIN(m, order); i++)
  1205. coef[start] -= coef[start - i*inc] * lpc[i-1];
  1206. }
  1207. }
  1208. }
  1209. /**
  1210. * Conduct IMDCT and windowing.
  1211. */
  1212. static void imdct_and_windowing(AACContext * ac, SingleChannelElement * sce) {
  1213. IndividualChannelStream * ics = &sce->ics;
  1214. float * in = sce->coeffs;
  1215. float * out = sce->ret;
  1216. float * saved = sce->saved;
  1217. const float * swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  1218. const float * lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  1219. const float * swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  1220. float * buf = ac->buf_mdct;
  1221. float * temp = ac->temp;
  1222. int i;
  1223. // imdct
  1224. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1225. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  1226. av_log(ac->avccontext, AV_LOG_WARNING,
  1227. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  1228. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  1229. for (i = 0; i < 1024; i += 128)
  1230. ff_imdct_half(&ac->mdct_small, buf + i, in + i);
  1231. } else
  1232. ff_imdct_half(&ac->mdct, buf, in);
  1233. /* window overlapping
  1234. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  1235. * and long to short transitions are considered to be short to short
  1236. * transitions. This leaves just two cases (long to long and short to short)
  1237. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  1238. */
  1239. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  1240. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  1241. ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, ac->add_bias, 512);
  1242. } else {
  1243. for (i = 0; i < 448; i++)
  1244. out[i] = saved[i] + ac->add_bias;
  1245. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1246. ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, ac->add_bias, 64);
  1247. ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, ac->add_bias, 64);
  1248. ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, ac->add_bias, 64);
  1249. ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, ac->add_bias, 64);
  1250. ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, ac->add_bias, 64);
  1251. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  1252. } else {
  1253. ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, ac->add_bias, 64);
  1254. for (i = 576; i < 1024; i++)
  1255. out[i] = buf[i-512] + ac->add_bias;
  1256. }
  1257. }
  1258. // buffer update
  1259. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1260. for (i = 0; i < 64; i++)
  1261. saved[i] = temp[64 + i] - ac->add_bias;
  1262. ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
  1263. ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
  1264. ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
  1265. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1266. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1267. memcpy( saved, buf + 512, 448 * sizeof(float));
  1268. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1269. } else { // LONG_STOP or ONLY_LONG
  1270. memcpy( saved, buf + 512, 512 * sizeof(float));
  1271. }
  1272. }
  1273. /**
  1274. * Apply dependent channel coupling (applied before IMDCT).
  1275. *
  1276. * @param index index into coupling gain array
  1277. */
  1278. static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index) {
  1279. IndividualChannelStream * ics = &cce->ch[0].ics;
  1280. const uint16_t * offsets = ics->swb_offset;
  1281. float * dest = target->coeffs;
  1282. const float * src = cce->ch[0].coeffs;
  1283. int g, i, group, k, idx = 0;
  1284. if(ac->m4ac.object_type == AOT_AAC_LTP) {
  1285. av_log(ac->avccontext, AV_LOG_ERROR,
  1286. "Dependent coupling is not supported together with LTP\n");
  1287. return;
  1288. }
  1289. for (g = 0; g < ics->num_window_groups; g++) {
  1290. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1291. if (cce->ch[0].band_type[idx] != ZERO_BT) {
  1292. for (group = 0; group < ics->group_len[g]; group++) {
  1293. for (k = offsets[i]; k < offsets[i+1]; k++) {
  1294. // XXX dsputil-ize
  1295. dest[group*128+k] += cce->coup.gain[index][idx] * src[group*128+k];
  1296. }
  1297. }
  1298. }
  1299. }
  1300. dest += ics->group_len[g]*128;
  1301. src += ics->group_len[g]*128;
  1302. }
  1303. }
  1304. /**
  1305. * Apply independent channel coupling (applied after IMDCT).
  1306. *
  1307. * @param index index into coupling gain array
  1308. */
  1309. static void apply_independent_coupling(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index) {
  1310. int i;
  1311. for (i = 0; i < 1024; i++)
  1312. target->ret[i] += cce->coup.gain[index][0] * (cce->ch[0].ret[i] - ac->add_bias);
  1313. }
  1314. /**
  1315. * channel coupling transformation interface
  1316. *
  1317. * @param index index into coupling gain array
  1318. * @param apply_coupling_method pointer to (in)dependent coupling function
  1319. */
  1320. static void apply_channel_coupling(AACContext * ac, ChannelElement * cc,
  1321. enum RawDataBlockType type, int elem_id, enum CouplingPoint coupling_point,
  1322. void (*apply_coupling_method)(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index))
  1323. {
  1324. int i, c;
  1325. for (i = 0; i < MAX_ELEM_ID; i++) {
  1326. ChannelElement *cce = ac->che[TYPE_CCE][i];
  1327. int index = 0;
  1328. if (cce && cce->coup.coupling_point == coupling_point) {
  1329. ChannelCoupling * coup = &cce->coup;
  1330. for (c = 0; c <= coup->num_coupled; c++) {
  1331. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  1332. if (coup->ch_select[c] != 1) {
  1333. apply_coupling_method(ac, &cc->ch[0], cce, index);
  1334. if (coup->ch_select[c] != 0)
  1335. index++;
  1336. }
  1337. if (coup->ch_select[c] != 2)
  1338. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  1339. } else
  1340. index += 1 + (coup->ch_select[c] == 3);
  1341. }
  1342. }
  1343. }
  1344. }
  1345. /**
  1346. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1347. */
  1348. static void spectral_to_sample(AACContext * ac) {
  1349. int i, type;
  1350. for(type = 3; type >= 0; type--) {
  1351. for (i = 0; i < MAX_ELEM_ID; i++) {
  1352. ChannelElement *che = ac->che[type][i];
  1353. if(che) {
  1354. if(type <= TYPE_CPE)
  1355. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
  1356. if(che->ch[0].tns.present)
  1357. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1358. if(che->ch[1].tns.present)
  1359. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1360. if(type <= TYPE_CPE)
  1361. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
  1362. if(type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT)
  1363. imdct_and_windowing(ac, &che->ch[0]);
  1364. if(type == TYPE_CPE)
  1365. imdct_and_windowing(ac, &che->ch[1]);
  1366. if(type <= TYPE_CCE)
  1367. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. static int aac_decode_frame(AVCodecContext * avccontext, void * data, int * data_size, const uint8_t * buf, int buf_size) {
  1373. AACContext * ac = avccontext->priv_data;
  1374. GetBitContext gb;
  1375. enum RawDataBlockType elem_type;
  1376. int err, elem_id, data_size_tmp;
  1377. init_get_bits(&gb, buf, buf_size*8);
  1378. // parse
  1379. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1380. elem_id = get_bits(&gb, 4);
  1381. err = -1;
  1382. if(elem_type == TYPE_SCE && elem_id == 1 &&
  1383. !ac->che[TYPE_SCE][elem_id] && ac->che[TYPE_LFE][0]) {
  1384. /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
  1385. instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
  1386. encountered such a stream, transfer the LFE[0] element to SCE[1] */
  1387. ac->che[TYPE_SCE][elem_id] = ac->che[TYPE_LFE][0];
  1388. ac->che[TYPE_LFE][0] = NULL;
  1389. }
  1390. if(elem_type < TYPE_DSE) {
  1391. if(!ac->che[elem_type][elem_id])
  1392. return -1;
  1393. if(elem_type != TYPE_CCE)
  1394. ac->che[elem_type][elem_id]->coup.coupling_point = 4;
  1395. }
  1396. switch (elem_type) {
  1397. case TYPE_SCE:
  1398. err = decode_ics(ac, &ac->che[TYPE_SCE][elem_id]->ch[0], &gb, 0, 0);
  1399. break;
  1400. case TYPE_CPE:
  1401. err = decode_cpe(ac, &gb, elem_id);
  1402. break;
  1403. case TYPE_CCE:
  1404. err = decode_cce(ac, &gb, ac->che[TYPE_CCE][elem_id]);
  1405. break;
  1406. case TYPE_LFE:
  1407. err = decode_ics(ac, &ac->che[TYPE_LFE][elem_id]->ch[0], &gb, 0, 0);
  1408. break;
  1409. case TYPE_DSE:
  1410. skip_data_stream_element(&gb);
  1411. err = 0;
  1412. break;
  1413. case TYPE_PCE:
  1414. {
  1415. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1416. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1417. if((err = decode_pce(ac, new_che_pos, &gb)))
  1418. break;
  1419. err = output_configure(ac, ac->che_pos, new_che_pos);
  1420. break;
  1421. }
  1422. case TYPE_FIL:
  1423. if (elem_id == 15)
  1424. elem_id += get_bits(&gb, 8) - 1;
  1425. while (elem_id > 0)
  1426. elem_id -= decode_extension_payload(ac, &gb, elem_id);
  1427. err = 0; /* FIXME */
  1428. break;
  1429. default:
  1430. err = -1; /* should not happen, but keeps compiler happy */
  1431. break;
  1432. }
  1433. if(err)
  1434. return err;
  1435. }
  1436. spectral_to_sample(ac);
  1437. if (!ac->is_saved) {
  1438. ac->is_saved = 1;
  1439. *data_size = 0;
  1440. return buf_size;
  1441. }
  1442. data_size_tmp = 1024 * avccontext->channels * sizeof(int16_t);
  1443. if(*data_size < data_size_tmp) {
  1444. av_log(avccontext, AV_LOG_ERROR,
  1445. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1446. *data_size, data_size_tmp);
  1447. return -1;
  1448. }
  1449. *data_size = data_size_tmp;
  1450. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, 1024, avccontext->channels);
  1451. return buf_size;
  1452. }
  1453. static av_cold int aac_decode_close(AVCodecContext * avccontext) {
  1454. AACContext * ac = avccontext->priv_data;
  1455. int i, type;
  1456. for (i = 0; i < MAX_ELEM_ID; i++) {
  1457. for(type = 0; type < 4; type++)
  1458. av_freep(&ac->che[type][i]);
  1459. }
  1460. ff_mdct_end(&ac->mdct);
  1461. ff_mdct_end(&ac->mdct_small);
  1462. return 0 ;
  1463. }
  1464. AVCodec aac_decoder = {
  1465. "aac",
  1466. CODEC_TYPE_AUDIO,
  1467. CODEC_ID_AAC,
  1468. sizeof(AACContext),
  1469. aac_decode_init,
  1470. NULL,
  1471. aac_decode_close,
  1472. aac_decode_frame,
  1473. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1474. .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
  1475. };