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.

1734 lines
64KB

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