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.

1727 lines
63KB

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