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.

1854 lines
66KB

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