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.

1628 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. static const float sign_lookup[] = { 1.0f, -1.0f };
  674. for (g = 0; g < ics->num_windows; g++)
  675. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float)*(c - offsets[ics->max_sfb]));
  676. for (g = 0; g < ics->num_window_groups; g++) {
  677. for (i = 0; i < ics->max_sfb; i++, idx++) {
  678. const int cur_band_type = band_type[idx];
  679. const int dim = cur_band_type >= FIRST_PAIR_BT ? 2 : 4;
  680. const int is_cb_unsigned = IS_CODEBOOK_UNSIGNED(cur_band_type);
  681. int group;
  682. if (cur_band_type == ZERO_BT) {
  683. for (group = 0; group < ics->group_len[g]; group++) {
  684. memset(coef + group * 128 + offsets[i], 0, (offsets[i+1] - offsets[i])*sizeof(float));
  685. }
  686. }else if (cur_band_type == NOISE_BT) {
  687. for (group = 0; group < ics->group_len[g]; group++) {
  688. float scale;
  689. float band_energy = 0;
  690. for (k = offsets[i]; k < offsets[i+1]; k++) {
  691. ac->random_state = lcg_random(ac->random_state);
  692. coef[group*128+k] = ac->random_state;
  693. band_energy += coef[group*128+k]*coef[group*128+k];
  694. }
  695. scale = sf[idx] / sqrtf(band_energy);
  696. for (k = offsets[i]; k < offsets[i+1]; k++) {
  697. coef[group*128+k] *= scale;
  698. }
  699. }
  700. }else if (cur_band_type != INTENSITY_BT2 && cur_band_type != INTENSITY_BT) {
  701. for (group = 0; group < ics->group_len[g]; group++) {
  702. for (k = offsets[i]; k < offsets[i+1]; k += dim) {
  703. const int index = get_vlc2(gb, vlc_spectral[cur_band_type - 1].table, 6, 3);
  704. const int coef_tmp_idx = (group << 7) + k;
  705. const float *vq_ptr;
  706. int j;
  707. if(index >= ff_aac_spectral_sizes[cur_band_type - 1]) {
  708. av_log(ac->avccontext, AV_LOG_ERROR,
  709. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  710. cur_band_type - 1, index, ff_aac_spectral_sizes[cur_band_type - 1]);
  711. return -1;
  712. }
  713. vq_ptr = &ff_aac_codebook_vectors[cur_band_type - 1][index * dim];
  714. if (is_cb_unsigned) {
  715. if (vq_ptr[0]) coef[coef_tmp_idx ] = sign_lookup[get_bits1(gb)];
  716. if (vq_ptr[1]) coef[coef_tmp_idx + 1] = sign_lookup[get_bits1(gb)];
  717. if (dim == 4) {
  718. if (vq_ptr[2]) coef[coef_tmp_idx + 2] = sign_lookup[get_bits1(gb)];
  719. if (vq_ptr[3]) coef[coef_tmp_idx + 3] = sign_lookup[get_bits1(gb)];
  720. }
  721. }else {
  722. coef[coef_tmp_idx ] = 1.0f;
  723. coef[coef_tmp_idx + 1] = 1.0f;
  724. if (dim == 4) {
  725. coef[coef_tmp_idx + 2] = 1.0f;
  726. coef[coef_tmp_idx + 3] = 1.0f;
  727. }
  728. }
  729. if (cur_band_type == ESC_BT) {
  730. for (j = 0; j < 2; j++) {
  731. if (vq_ptr[j] == 64.0f) {
  732. int n = 4;
  733. /* The total length of escape_sequence must be < 22 bits according
  734. to the specification (i.e. max is 11111111110xxxxxxxxxx). */
  735. while (get_bits1(gb) && n < 15) n++;
  736. if(n == 15) {
  737. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  738. return -1;
  739. }
  740. n = (1<<n) + get_bits(gb, n);
  741. coef[coef_tmp_idx + j] *= cbrtf(n) * n;
  742. }else
  743. coef[coef_tmp_idx + j] *= vq_ptr[j];
  744. }
  745. }else
  746. {
  747. coef[coef_tmp_idx ] *= vq_ptr[0];
  748. coef[coef_tmp_idx + 1] *= vq_ptr[1];
  749. if (dim == 4) {
  750. coef[coef_tmp_idx + 2] *= vq_ptr[2];
  751. coef[coef_tmp_idx + 3] *= vq_ptr[3];
  752. }
  753. }
  754. coef[coef_tmp_idx ] *= sf[idx];
  755. coef[coef_tmp_idx + 1] *= sf[idx];
  756. if (dim == 4) {
  757. coef[coef_tmp_idx + 2] *= sf[idx];
  758. coef[coef_tmp_idx + 3] *= sf[idx];
  759. }
  760. }
  761. }
  762. }
  763. }
  764. coef += ics->group_len[g]<<7;
  765. }
  766. if (pulse_present) {
  767. idx = 0;
  768. for(i = 0; i < pulse->num_pulse; i++){
  769. float co = coef_base[ pulse->pos[i] ];
  770. while(offsets[idx + 1] <= pulse->pos[i])
  771. idx++;
  772. if (band_type[idx] != NOISE_BT && sf[idx]) {
  773. float ico = -pulse->amp[i];
  774. if (co) {
  775. co /= sf[idx];
  776. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  777. }
  778. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  779. }
  780. }
  781. }
  782. return 0;
  783. }
  784. static av_always_inline float flt16_round(float pf) {
  785. int exp;
  786. pf = frexpf(pf, &exp);
  787. pf = ldexpf(roundf(ldexpf(pf, 8)), exp-8);
  788. return pf;
  789. }
  790. static av_always_inline float flt16_even(float pf) {
  791. int exp;
  792. pf = frexpf(pf, &exp);
  793. pf = ldexpf(rintf(ldexpf(pf, 8)), exp-8);
  794. return pf;
  795. }
  796. static av_always_inline float flt16_trunc(float pf) {
  797. int exp;
  798. pf = frexpf(pf, &exp);
  799. pf = ldexpf(truncf(ldexpf(pf, 8)), exp-8);
  800. return pf;
  801. }
  802. static void predict(AACContext * ac, PredictorState * ps, float* coef, int output_enable) {
  803. const float a = 0.953125; // 61.0/64
  804. const float alpha = 0.90625; // 29.0/32
  805. float e0, e1;
  806. float pv;
  807. float k1, k2;
  808. k1 = ps->var0 > 1 ? ps->cor0 * flt16_even(a / ps->var0) : 0;
  809. k2 = ps->var1 > 1 ? ps->cor1 * flt16_even(a / ps->var1) : 0;
  810. pv = flt16_round(k1 * ps->r0 + k2 * ps->r1);
  811. if (output_enable)
  812. *coef += pv * ac->sf_scale;
  813. e0 = *coef / ac->sf_scale;
  814. e1 = e0 - k1 * ps->r0;
  815. ps->cor1 = flt16_trunc(alpha * ps->cor1 + ps->r1 * e1);
  816. ps->var1 = flt16_trunc(alpha * ps->var1 + 0.5 * (ps->r1 * ps->r1 + e1 * e1));
  817. ps->cor0 = flt16_trunc(alpha * ps->cor0 + ps->r0 * e0);
  818. ps->var0 = flt16_trunc(alpha * ps->var0 + 0.5 * (ps->r0 * ps->r0 + e0 * e0));
  819. ps->r1 = flt16_trunc(a * (ps->r0 - k1 * e0));
  820. ps->r0 = flt16_trunc(a * e0);
  821. }
  822. /**
  823. * Apply AAC-Main style frequency domain prediction.
  824. */
  825. static void apply_prediction(AACContext * ac, SingleChannelElement * sce) {
  826. int sfb, k;
  827. if (!sce->ics.predictor_initialized) {
  828. reset_all_predictors(sce->ics.predictor_state);
  829. sce->ics.predictor_initialized = 1;
  830. }
  831. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  832. for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
  833. for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
  834. predict(ac, &sce->ics.predictor_state[k], &sce->coeffs[k],
  835. sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
  836. }
  837. }
  838. if (sce->ics.predictor_reset_group)
  839. reset_predictor_group(sce->ics.predictor_state, sce->ics.predictor_reset_group);
  840. } else
  841. reset_all_predictors(sce->ics.predictor_state);
  842. }
  843. /**
  844. * Decode an individual_channel_stream payload; reference: table 4.44.
  845. *
  846. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  847. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  848. *
  849. * @return Returns error status. 0 - OK, !0 - error
  850. */
  851. static int decode_ics(AACContext * ac, SingleChannelElement * sce, GetBitContext * gb, int common_window, int scale_flag) {
  852. Pulse pulse;
  853. TemporalNoiseShaping * tns = &sce->tns;
  854. IndividualChannelStream * ics = &sce->ics;
  855. float * out = sce->coeffs;
  856. int global_gain, pulse_present = 0;
  857. /* This assignment is to silence a GCC warning about the variable being used
  858. * uninitialized when in fact it always is.
  859. */
  860. pulse.num_pulse = 0;
  861. global_gain = get_bits(gb, 8);
  862. if (!common_window && !scale_flag) {
  863. if (decode_ics_info(ac, ics, gb, 0) < 0)
  864. return -1;
  865. }
  866. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  867. return -1;
  868. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  869. return -1;
  870. pulse_present = 0;
  871. if (!scale_flag) {
  872. if ((pulse_present = get_bits1(gb))) {
  873. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  874. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  875. return -1;
  876. }
  877. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  878. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
  879. return -1;
  880. }
  881. }
  882. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  883. return -1;
  884. if (get_bits1(gb)) {
  885. ff_log_missing_feature(ac->avccontext, "SSR", 1);
  886. return -1;
  887. }
  888. }
  889. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  890. return -1;
  891. if(ac->m4ac.object_type == AOT_AAC_MAIN)
  892. apply_prediction(ac, sce);
  893. return 0;
  894. }
  895. /**
  896. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  897. */
  898. static void apply_mid_side_stereo(ChannelElement * cpe) {
  899. const IndividualChannelStream * ics = &cpe->ch[0].ics;
  900. float *ch0 = cpe->ch[0].coeffs;
  901. float *ch1 = cpe->ch[1].coeffs;
  902. int g, i, k, group, idx = 0;
  903. const uint16_t * offsets = ics->swb_offset;
  904. for (g = 0; g < ics->num_window_groups; g++) {
  905. for (i = 0; i < ics->max_sfb; i++, idx++) {
  906. if (cpe->ms_mask[idx] &&
  907. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  908. for (group = 0; group < ics->group_len[g]; group++) {
  909. for (k = offsets[i]; k < offsets[i+1]; k++) {
  910. float tmp = ch0[group*128 + k] - ch1[group*128 + k];
  911. ch0[group*128 + k] += ch1[group*128 + k];
  912. ch1[group*128 + k] = tmp;
  913. }
  914. }
  915. }
  916. }
  917. ch0 += ics->group_len[g]*128;
  918. ch1 += ics->group_len[g]*128;
  919. }
  920. }
  921. /**
  922. * intensity stereo decoding; reference: 4.6.8.2.3
  923. *
  924. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  925. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  926. * [3] reserved for scalable AAC
  927. */
  928. static void apply_intensity_stereo(ChannelElement * cpe, int ms_present) {
  929. const IndividualChannelStream * ics = &cpe->ch[1].ics;
  930. SingleChannelElement * sce1 = &cpe->ch[1];
  931. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  932. const uint16_t * offsets = ics->swb_offset;
  933. int g, group, i, k, idx = 0;
  934. int c;
  935. float scale;
  936. for (g = 0; g < ics->num_window_groups; g++) {
  937. for (i = 0; i < ics->max_sfb;) {
  938. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  939. const int bt_run_end = sce1->band_type_run_end[idx];
  940. for (; i < bt_run_end; i++, idx++) {
  941. c = -1 + 2 * (sce1->band_type[idx] - 14);
  942. if (ms_present)
  943. c *= 1 - 2 * cpe->ms_mask[idx];
  944. scale = c * sce1->sf[idx];
  945. for (group = 0; group < ics->group_len[g]; group++)
  946. for (k = offsets[i]; k < offsets[i+1]; k++)
  947. coef1[group*128 + k] = scale * coef0[group*128 + k];
  948. }
  949. } else {
  950. int bt_run_end = sce1->band_type_run_end[idx];
  951. idx += bt_run_end - i;
  952. i = bt_run_end;
  953. }
  954. }
  955. coef0 += ics->group_len[g]*128;
  956. coef1 += ics->group_len[g]*128;
  957. }
  958. }
  959. /**
  960. * Decode a channel_pair_element; reference: table 4.4.
  961. *
  962. * @param elem_id Identifies the instance of a syntax element.
  963. *
  964. * @return Returns error status. 0 - OK, !0 - error
  965. */
  966. static int decode_cpe(AACContext * ac, GetBitContext * gb, int elem_id) {
  967. int i, ret, common_window, ms_present = 0;
  968. ChannelElement * cpe;
  969. cpe = ac->che[TYPE_CPE][elem_id];
  970. common_window = get_bits1(gb);
  971. if (common_window) {
  972. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  973. return -1;
  974. i = cpe->ch[1].ics.use_kb_window[0];
  975. cpe->ch[1].ics = cpe->ch[0].ics;
  976. cpe->ch[1].ics.use_kb_window[1] = i;
  977. ms_present = get_bits(gb, 2);
  978. if(ms_present == 3) {
  979. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  980. return -1;
  981. } else if(ms_present)
  982. decode_mid_side_stereo(cpe, gb, ms_present);
  983. }
  984. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  985. return ret;
  986. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  987. return ret;
  988. if (common_window && ms_present)
  989. apply_mid_side_stereo(cpe);
  990. apply_intensity_stereo(cpe, ms_present);
  991. return 0;
  992. }
  993. /**
  994. * Decode coupling_channel_element; reference: table 4.8.
  995. *
  996. * @param elem_id Identifies the instance of a syntax element.
  997. *
  998. * @return Returns error status. 0 - OK, !0 - error
  999. */
  1000. static int decode_cce(AACContext * ac, GetBitContext * gb, ChannelElement * che) {
  1001. int num_gain = 0;
  1002. int c, g, sfb, ret;
  1003. int sign;
  1004. float scale;
  1005. SingleChannelElement * sce = &che->ch[0];
  1006. ChannelCoupling * coup = &che->coup;
  1007. coup->coupling_point = 2*get_bits1(gb);
  1008. coup->num_coupled = get_bits(gb, 3);
  1009. for (c = 0; c <= coup->num_coupled; c++) {
  1010. num_gain++;
  1011. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1012. coup->id_select[c] = get_bits(gb, 4);
  1013. if (coup->type[c] == TYPE_CPE) {
  1014. coup->ch_select[c] = get_bits(gb, 2);
  1015. if (coup->ch_select[c] == 3)
  1016. num_gain++;
  1017. } else
  1018. coup->ch_select[c] = 2;
  1019. }
  1020. coup->coupling_point += get_bits1(gb);
  1021. if (coup->coupling_point == 2) {
  1022. av_log(ac->avccontext, AV_LOG_ERROR,
  1023. "Independently switched CCE with 'invalid' domain signalled.\n");
  1024. memset(coup, 0, sizeof(ChannelCoupling));
  1025. return -1;
  1026. }
  1027. sign = get_bits(gb, 1);
  1028. scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
  1029. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1030. return ret;
  1031. for (c = 0; c < num_gain; c++) {
  1032. int idx = 0;
  1033. int cge = 1;
  1034. int gain = 0;
  1035. float gain_cache = 1.;
  1036. if (c) {
  1037. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1038. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1039. gain_cache = pow(scale, -gain);
  1040. }
  1041. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1042. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1043. if (sce->band_type[idx] != ZERO_BT) {
  1044. if (!cge) {
  1045. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1046. if (t) {
  1047. int s = 1;
  1048. t = gain += t;
  1049. if (sign) {
  1050. s -= 2 * (t & 0x1);
  1051. t >>= 1;
  1052. }
  1053. gain_cache = pow(scale, -t) * s;
  1054. }
  1055. }
  1056. coup->gain[c][idx] = gain_cache;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. return 0;
  1062. }
  1063. /**
  1064. * Decode Spectral Band Replication extension data; reference: table 4.55.
  1065. *
  1066. * @param crc flag indicating the presence of CRC checksum
  1067. * @param cnt length of TYPE_FIL syntactic element in bytes
  1068. *
  1069. * @return Returns number of bytes consumed from the TYPE_FIL element.
  1070. */
  1071. static int decode_sbr_extension(AACContext * ac, GetBitContext * gb, int crc, int cnt) {
  1072. // TODO : sbr_extension implementation
  1073. ff_log_missing_feature(ac->avccontext, "SBR", 0);
  1074. skip_bits_long(gb, 8*cnt - 4); // -4 due to reading extension type
  1075. return cnt;
  1076. }
  1077. /**
  1078. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  1079. *
  1080. * @return Returns number of bytes consumed.
  1081. */
  1082. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc, GetBitContext * gb) {
  1083. int i;
  1084. int num_excl_chan = 0;
  1085. do {
  1086. for (i = 0; i < 7; i++)
  1087. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  1088. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  1089. return num_excl_chan / 7;
  1090. }
  1091. /**
  1092. * Decode dynamic range information; reference: table 4.52.
  1093. *
  1094. * @param cnt length of TYPE_FIL syntactic element in bytes
  1095. *
  1096. * @return Returns number of bytes consumed.
  1097. */
  1098. static int decode_dynamic_range(DynamicRangeControl *che_drc, GetBitContext * gb, int cnt) {
  1099. int n = 1;
  1100. int drc_num_bands = 1;
  1101. int i;
  1102. /* pce_tag_present? */
  1103. if(get_bits1(gb)) {
  1104. che_drc->pce_instance_tag = get_bits(gb, 4);
  1105. skip_bits(gb, 4); // tag_reserved_bits
  1106. n++;
  1107. }
  1108. /* excluded_chns_present? */
  1109. if(get_bits1(gb)) {
  1110. n += decode_drc_channel_exclusions(che_drc, gb);
  1111. }
  1112. /* drc_bands_present? */
  1113. if (get_bits1(gb)) {
  1114. che_drc->band_incr = get_bits(gb, 4);
  1115. che_drc->interpolation_scheme = get_bits(gb, 4);
  1116. n++;
  1117. drc_num_bands += che_drc->band_incr;
  1118. for (i = 0; i < drc_num_bands; i++) {
  1119. che_drc->band_top[i] = get_bits(gb, 8);
  1120. n++;
  1121. }
  1122. }
  1123. /* prog_ref_level_present? */
  1124. if (get_bits1(gb)) {
  1125. che_drc->prog_ref_level = get_bits(gb, 7);
  1126. skip_bits1(gb); // prog_ref_level_reserved_bits
  1127. n++;
  1128. }
  1129. for (i = 0; i < drc_num_bands; i++) {
  1130. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  1131. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  1132. n++;
  1133. }
  1134. return n;
  1135. }
  1136. /**
  1137. * Decode extension data (incomplete); reference: table 4.51.
  1138. *
  1139. * @param cnt length of TYPE_FIL syntactic element in bytes
  1140. *
  1141. * @return Returns number of bytes consumed
  1142. */
  1143. static int decode_extension_payload(AACContext * ac, GetBitContext * gb, int cnt) {
  1144. int crc_flag = 0;
  1145. int res = cnt;
  1146. switch (get_bits(gb, 4)) { // extension type
  1147. case EXT_SBR_DATA_CRC:
  1148. crc_flag++;
  1149. case EXT_SBR_DATA:
  1150. res = decode_sbr_extension(ac, gb, crc_flag, cnt);
  1151. break;
  1152. case EXT_DYNAMIC_RANGE:
  1153. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  1154. break;
  1155. case EXT_FILL:
  1156. case EXT_FILL_DATA:
  1157. case EXT_DATA_ELEMENT:
  1158. default:
  1159. skip_bits_long(gb, 8*cnt - 4);
  1160. break;
  1161. };
  1162. return res;
  1163. }
  1164. /**
  1165. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  1166. *
  1167. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  1168. * @param coef spectral coefficients
  1169. */
  1170. static void apply_tns(float coef[1024], TemporalNoiseShaping * tns, IndividualChannelStream * ics, int decode) {
  1171. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  1172. int w, filt, m, i;
  1173. int bottom, top, order, start, end, size, inc;
  1174. float lpc[TNS_MAX_ORDER];
  1175. for (w = 0; w < ics->num_windows; w++) {
  1176. bottom = ics->num_swb;
  1177. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1178. top = bottom;
  1179. bottom = FFMAX(0, top - tns->length[w][filt]);
  1180. order = tns->order[w][filt];
  1181. if (order == 0)
  1182. continue;
  1183. // tns_decode_coef
  1184. compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
  1185. start = ics->swb_offset[FFMIN(bottom, mmm)];
  1186. end = ics->swb_offset[FFMIN( top, mmm)];
  1187. if ((size = end - start) <= 0)
  1188. continue;
  1189. if (tns->direction[w][filt]) {
  1190. inc = -1; start = end - 1;
  1191. } else {
  1192. inc = 1;
  1193. }
  1194. start += w * 128;
  1195. // ar filter
  1196. for (m = 0; m < size; m++, start += inc)
  1197. for (i = 1; i <= FFMIN(m, order); i++)
  1198. coef[start] -= coef[start - i*inc] * lpc[i-1];
  1199. }
  1200. }
  1201. }
  1202. /**
  1203. * Conduct IMDCT and windowing.
  1204. */
  1205. static void imdct_and_windowing(AACContext * ac, SingleChannelElement * sce) {
  1206. IndividualChannelStream * ics = &sce->ics;
  1207. float * in = sce->coeffs;
  1208. float * out = sce->ret;
  1209. float * saved = sce->saved;
  1210. const float * swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  1211. const float * lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  1212. const float * swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  1213. float * buf = ac->buf_mdct;
  1214. float * temp = ac->temp;
  1215. int i;
  1216. // imdct
  1217. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1218. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  1219. av_log(ac->avccontext, AV_LOG_WARNING,
  1220. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  1221. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  1222. for (i = 0; i < 1024; i += 128)
  1223. ff_imdct_half(&ac->mdct_small, buf + i, in + i);
  1224. } else
  1225. ff_imdct_half(&ac->mdct, buf, in);
  1226. /* window overlapping
  1227. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  1228. * and long to short transitions are considered to be short to short
  1229. * transitions. This leaves just two cases (long to long and short to short)
  1230. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  1231. */
  1232. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  1233. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  1234. ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, ac->add_bias, 512);
  1235. } else {
  1236. for (i = 0; i < 448; i++)
  1237. out[i] = saved[i] + ac->add_bias;
  1238. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1239. ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, ac->add_bias, 64);
  1240. ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, ac->add_bias, 64);
  1241. ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, ac->add_bias, 64);
  1242. ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, ac->add_bias, 64);
  1243. ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, ac->add_bias, 64);
  1244. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  1245. } else {
  1246. ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, ac->add_bias, 64);
  1247. for (i = 576; i < 1024; i++)
  1248. out[i] = buf[i-512] + ac->add_bias;
  1249. }
  1250. }
  1251. // buffer update
  1252. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1253. for (i = 0; i < 64; i++)
  1254. saved[i] = temp[64 + i] - ac->add_bias;
  1255. ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
  1256. ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
  1257. ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
  1258. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1259. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1260. memcpy( saved, buf + 512, 448 * sizeof(float));
  1261. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1262. } else { // LONG_STOP or ONLY_LONG
  1263. memcpy( saved, buf + 512, 512 * sizeof(float));
  1264. }
  1265. }
  1266. /**
  1267. * Apply dependent channel coupling (applied before IMDCT).
  1268. *
  1269. * @param index index into coupling gain array
  1270. */
  1271. static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index) {
  1272. IndividualChannelStream * ics = &cce->ch[0].ics;
  1273. const uint16_t * offsets = ics->swb_offset;
  1274. float * dest = target->coeffs;
  1275. const float * src = cce->ch[0].coeffs;
  1276. int g, i, group, k, idx = 0;
  1277. if(ac->m4ac.object_type == AOT_AAC_LTP) {
  1278. av_log(ac->avccontext, AV_LOG_ERROR,
  1279. "Dependent coupling is not supported together with LTP\n");
  1280. return;
  1281. }
  1282. for (g = 0; g < ics->num_window_groups; g++) {
  1283. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1284. if (cce->ch[0].band_type[idx] != ZERO_BT) {
  1285. for (group = 0; group < ics->group_len[g]; group++) {
  1286. for (k = offsets[i]; k < offsets[i+1]; k++) {
  1287. // XXX dsputil-ize
  1288. dest[group*128+k] += cce->coup.gain[index][idx] * src[group*128+k];
  1289. }
  1290. }
  1291. }
  1292. }
  1293. dest += ics->group_len[g]*128;
  1294. src += ics->group_len[g]*128;
  1295. }
  1296. }
  1297. /**
  1298. * Apply independent channel coupling (applied after IMDCT).
  1299. *
  1300. * @param index index into coupling gain array
  1301. */
  1302. static void apply_independent_coupling(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index) {
  1303. int i;
  1304. for (i = 0; i < 1024; i++)
  1305. target->ret[i] += cce->coup.gain[index][0] * (cce->ch[0].ret[i] - ac->add_bias);
  1306. }
  1307. /**
  1308. * channel coupling transformation interface
  1309. *
  1310. * @param index index into coupling gain array
  1311. * @param apply_coupling_method pointer to (in)dependent coupling function
  1312. */
  1313. static void apply_channel_coupling(AACContext * ac, ChannelElement * cc,
  1314. enum RawDataBlockType type, int elem_id, enum CouplingPoint coupling_point,
  1315. void (*apply_coupling_method)(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index))
  1316. {
  1317. int i, c;
  1318. for (i = 0; i < MAX_ELEM_ID; i++) {
  1319. ChannelElement *cce = ac->che[TYPE_CCE][i];
  1320. int index = 0;
  1321. if (cce && cce->coup.coupling_point == coupling_point) {
  1322. ChannelCoupling * coup = &cce->coup;
  1323. for (c = 0; c <= coup->num_coupled; c++) {
  1324. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  1325. if (coup->ch_select[c] != 1) {
  1326. apply_coupling_method(ac, &cc->ch[0], cce, index);
  1327. if (coup->ch_select[c] != 0)
  1328. index++;
  1329. }
  1330. if (coup->ch_select[c] != 2)
  1331. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  1332. } else
  1333. index += 1 + (coup->ch_select[c] == 3);
  1334. }
  1335. }
  1336. }
  1337. }
  1338. /**
  1339. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1340. */
  1341. static void spectral_to_sample(AACContext * ac) {
  1342. int i, type;
  1343. for(type = 3; type >= 0; type--) {
  1344. for (i = 0; i < MAX_ELEM_ID; i++) {
  1345. ChannelElement *che = ac->che[type][i];
  1346. if(che) {
  1347. if(type <= TYPE_CPE)
  1348. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
  1349. if(che->ch[0].tns.present)
  1350. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1351. if(che->ch[1].tns.present)
  1352. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1353. if(type <= TYPE_CPE)
  1354. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
  1355. if(type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT)
  1356. imdct_and_windowing(ac, &che->ch[0]);
  1357. if(type == TYPE_CPE)
  1358. imdct_and_windowing(ac, &che->ch[1]);
  1359. if(type <= TYPE_CCE)
  1360. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
  1361. }
  1362. }
  1363. }
  1364. }
  1365. static int aac_decode_frame(AVCodecContext * avccontext, void * data, int * data_size, const uint8_t * buf, int buf_size) {
  1366. AACContext * ac = avccontext->priv_data;
  1367. GetBitContext gb;
  1368. enum RawDataBlockType elem_type;
  1369. int err, elem_id, data_size_tmp;
  1370. init_get_bits(&gb, buf, buf_size*8);
  1371. // parse
  1372. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1373. elem_id = get_bits(&gb, 4);
  1374. err = -1;
  1375. if(elem_type == TYPE_SCE && elem_id == 1 &&
  1376. !ac->che[TYPE_SCE][elem_id] && ac->che[TYPE_LFE][0]) {
  1377. /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
  1378. instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
  1379. encountered such a stream, transfer the LFE[0] element to SCE[1] */
  1380. ac->che[TYPE_SCE][elem_id] = ac->che[TYPE_LFE][0];
  1381. ac->che[TYPE_LFE][0] = NULL;
  1382. }
  1383. if(elem_type < TYPE_DSE) {
  1384. if(!ac->che[elem_type][elem_id])
  1385. return -1;
  1386. if(elem_type != TYPE_CCE)
  1387. ac->che[elem_type][elem_id]->coup.coupling_point = 4;
  1388. }
  1389. switch (elem_type) {
  1390. case TYPE_SCE:
  1391. err = decode_ics(ac, &ac->che[TYPE_SCE][elem_id]->ch[0], &gb, 0, 0);
  1392. break;
  1393. case TYPE_CPE:
  1394. err = decode_cpe(ac, &gb, elem_id);
  1395. break;
  1396. case TYPE_CCE:
  1397. err = decode_cce(ac, &gb, ac->che[TYPE_CCE][elem_id]);
  1398. break;
  1399. case TYPE_LFE:
  1400. err = decode_ics(ac, &ac->che[TYPE_LFE][elem_id]->ch[0], &gb, 0, 0);
  1401. break;
  1402. case TYPE_DSE:
  1403. skip_data_stream_element(&gb);
  1404. err = 0;
  1405. break;
  1406. case TYPE_PCE:
  1407. {
  1408. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1409. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1410. if((err = decode_pce(ac, new_che_pos, &gb)))
  1411. break;
  1412. err = output_configure(ac, ac->che_pos, new_che_pos);
  1413. break;
  1414. }
  1415. case TYPE_FIL:
  1416. if (elem_id == 15)
  1417. elem_id += get_bits(&gb, 8) - 1;
  1418. while (elem_id > 0)
  1419. elem_id -= decode_extension_payload(ac, &gb, elem_id);
  1420. err = 0; /* FIXME */
  1421. break;
  1422. default:
  1423. err = -1; /* should not happen, but keeps compiler happy */
  1424. break;
  1425. }
  1426. if(err)
  1427. return err;
  1428. }
  1429. spectral_to_sample(ac);
  1430. if (!ac->is_saved) {
  1431. ac->is_saved = 1;
  1432. *data_size = 0;
  1433. return buf_size;
  1434. }
  1435. data_size_tmp = 1024 * avccontext->channels * sizeof(int16_t);
  1436. if(*data_size < data_size_tmp) {
  1437. av_log(avccontext, AV_LOG_ERROR,
  1438. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1439. *data_size, data_size_tmp);
  1440. return -1;
  1441. }
  1442. *data_size = data_size_tmp;
  1443. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, 1024, avccontext->channels);
  1444. return buf_size;
  1445. }
  1446. static av_cold int aac_decode_close(AVCodecContext * avccontext) {
  1447. AACContext * ac = avccontext->priv_data;
  1448. int i, type;
  1449. for (i = 0; i < MAX_ELEM_ID; i++) {
  1450. for(type = 0; type < 4; type++)
  1451. av_freep(&ac->che[type][i]);
  1452. }
  1453. ff_mdct_end(&ac->mdct);
  1454. ff_mdct_end(&ac->mdct_small);
  1455. return 0 ;
  1456. }
  1457. AVCodec aac_decoder = {
  1458. "aac",
  1459. CODEC_TYPE_AUDIO,
  1460. CODEC_ID_AAC,
  1461. sizeof(AACContext),
  1462. aac_decode_init,
  1463. NULL,
  1464. aac_decode_close,
  1465. aac_decode_frame,
  1466. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1467. .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
  1468. };