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.

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