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.

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