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.

1627 lines
59KB

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