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.

2113 lines
74KB

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