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.

1811 lines
65KB

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