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.

2107 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 "cbrt_tablegen.h"
  85. #include "sbr.h"
  86. #include "aacsbr.h"
  87. #include "mpeg4audio.h"
  88. #include "aac_parser.h"
  89. #include <assert.h>
  90. #include <errno.h>
  91. #include <math.h>
  92. #include <string.h>
  93. #if ARCH_ARM
  94. # include "arm/aac.h"
  95. #endif
  96. union float754 {
  97. float f;
  98. uint32_t i;
  99. };
  100. static VLC vlc_scalefactors;
  101. static VLC vlc_spectral[11];
  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. cbrt_tableinit();
  509. return 0;
  510. }
  511. /**
  512. * Skip data_stream_element; reference: table 4.10.
  513. */
  514. static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
  515. {
  516. int byte_align = get_bits1(gb);
  517. int count = get_bits(gb, 8);
  518. if (count == 255)
  519. count += get_bits(gb, 8);
  520. if (byte_align)
  521. align_get_bits(gb);
  522. if (get_bits_left(gb) < 8 * count) {
  523. av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
  524. return -1;
  525. }
  526. skip_bits_long(gb, 8 * count);
  527. return 0;
  528. }
  529. static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
  530. GetBitContext *gb)
  531. {
  532. int sfb;
  533. if (get_bits1(gb)) {
  534. ics->predictor_reset_group = get_bits(gb, 5);
  535. if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
  536. av_log(ac->avccontext, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
  537. return -1;
  538. }
  539. }
  540. for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
  541. ics->prediction_used[sfb] = get_bits1(gb);
  542. }
  543. return 0;
  544. }
  545. /**
  546. * Decode Individual Channel Stream info; reference: table 4.6.
  547. *
  548. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  549. */
  550. static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
  551. GetBitContext *gb, int common_window)
  552. {
  553. if (get_bits1(gb)) {
  554. av_log(ac->avccontext, AV_LOG_ERROR, "Reserved bit set.\n");
  555. memset(ics, 0, sizeof(IndividualChannelStream));
  556. return -1;
  557. }
  558. ics->window_sequence[1] = ics->window_sequence[0];
  559. ics->window_sequence[0] = get_bits(gb, 2);
  560. ics->use_kb_window[1] = ics->use_kb_window[0];
  561. ics->use_kb_window[0] = get_bits1(gb);
  562. ics->num_window_groups = 1;
  563. ics->group_len[0] = 1;
  564. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  565. int i;
  566. ics->max_sfb = get_bits(gb, 4);
  567. for (i = 0; i < 7; i++) {
  568. if (get_bits1(gb)) {
  569. ics->group_len[ics->num_window_groups - 1]++;
  570. } else {
  571. ics->num_window_groups++;
  572. ics->group_len[ics->num_window_groups - 1] = 1;
  573. }
  574. }
  575. ics->num_windows = 8;
  576. ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
  577. ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
  578. ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
  579. ics->predictor_present = 0;
  580. } else {
  581. ics->max_sfb = get_bits(gb, 6);
  582. ics->num_windows = 1;
  583. ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
  584. ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
  585. ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
  586. ics->predictor_present = get_bits1(gb);
  587. ics->predictor_reset_group = 0;
  588. if (ics->predictor_present) {
  589. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  590. if (decode_prediction(ac, ics, gb)) {
  591. memset(ics, 0, sizeof(IndividualChannelStream));
  592. return -1;
  593. }
  594. } else if (ac->m4ac.object_type == AOT_AAC_LC) {
  595. av_log(ac->avccontext, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
  596. memset(ics, 0, sizeof(IndividualChannelStream));
  597. return -1;
  598. } else {
  599. av_log_missing_feature(ac->avccontext, "Predictor bit set but LTP is", 1);
  600. memset(ics, 0, sizeof(IndividualChannelStream));
  601. return -1;
  602. }
  603. }
  604. }
  605. if (ics->max_sfb > ics->num_swb) {
  606. av_log(ac->avccontext, AV_LOG_ERROR,
  607. "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
  608. ics->max_sfb, ics->num_swb);
  609. memset(ics, 0, sizeof(IndividualChannelStream));
  610. return -1;
  611. }
  612. return 0;
  613. }
  614. /**
  615. * Decode band types (section_data payload); reference: table 4.46.
  616. *
  617. * @param band_type array of the used band type
  618. * @param band_type_run_end array of the last scalefactor band of a band type run
  619. *
  620. * @return Returns error status. 0 - OK, !0 - error
  621. */
  622. static int decode_band_types(AACContext *ac, enum BandType band_type[120],
  623. int band_type_run_end[120], GetBitContext *gb,
  624. IndividualChannelStream *ics)
  625. {
  626. int g, idx = 0;
  627. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  628. for (g = 0; g < ics->num_window_groups; g++) {
  629. int k = 0;
  630. while (k < ics->max_sfb) {
  631. uint8_t sect_end = k;
  632. int sect_len_incr;
  633. int sect_band_type = get_bits(gb, 4);
  634. if (sect_band_type == 12) {
  635. av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
  636. return -1;
  637. }
  638. while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
  639. sect_end += sect_len_incr;
  640. sect_end += sect_len_incr;
  641. if (get_bits_left(gb) < 0) {
  642. av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
  643. return -1;
  644. }
  645. if (sect_end > ics->max_sfb) {
  646. av_log(ac->avccontext, AV_LOG_ERROR,
  647. "Number of bands (%d) exceeds limit (%d).\n",
  648. sect_end, ics->max_sfb);
  649. return -1;
  650. }
  651. for (; k < sect_end; k++) {
  652. band_type [idx] = sect_band_type;
  653. band_type_run_end[idx++] = sect_end;
  654. }
  655. }
  656. }
  657. return 0;
  658. }
  659. /**
  660. * Decode scalefactors; reference: table 4.47.
  661. *
  662. * @param global_gain first scalefactor value as scalefactors are differentially coded
  663. * @param band_type array of the used band type
  664. * @param band_type_run_end array of the last scalefactor band of a band type run
  665. * @param sf array of scalefactors or intensity stereo positions
  666. *
  667. * @return Returns error status. 0 - OK, !0 - error
  668. */
  669. static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
  670. unsigned int global_gain,
  671. IndividualChannelStream *ics,
  672. enum BandType band_type[120],
  673. int band_type_run_end[120])
  674. {
  675. const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
  676. int g, i, idx = 0;
  677. int offset[3] = { global_gain, global_gain - 90, 100 };
  678. int noise_flag = 1;
  679. static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
  680. for (g = 0; g < ics->num_window_groups; g++) {
  681. for (i = 0; i < ics->max_sfb;) {
  682. int run_end = band_type_run_end[idx];
  683. if (band_type[idx] == ZERO_BT) {
  684. for (; i < run_end; i++, idx++)
  685. sf[idx] = 0.;
  686. } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
  687. for (; i < run_end; i++, idx++) {
  688. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  689. if (offset[2] > 255U) {
  690. av_log(ac->avccontext, AV_LOG_ERROR,
  691. "%s (%d) out of range.\n", sf_str[2], offset[2]);
  692. return -1;
  693. }
  694. sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
  695. }
  696. } else if (band_type[idx] == NOISE_BT) {
  697. for (; i < run_end; i++, idx++) {
  698. if (noise_flag-- > 0)
  699. offset[1] += get_bits(gb, 9) - 256;
  700. else
  701. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  702. if (offset[1] > 255U) {
  703. av_log(ac->avccontext, AV_LOG_ERROR,
  704. "%s (%d) out of range.\n", sf_str[1], offset[1]);
  705. return -1;
  706. }
  707. sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
  708. }
  709. } else {
  710. for (; i < run_end; i++, idx++) {
  711. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  712. if (offset[0] > 255U) {
  713. av_log(ac->avccontext, AV_LOG_ERROR,
  714. "%s (%d) out of range.\n", sf_str[0], offset[0]);
  715. return -1;
  716. }
  717. sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
  718. }
  719. }
  720. }
  721. }
  722. return 0;
  723. }
  724. /**
  725. * Decode pulse data; reference: table 4.7.
  726. */
  727. static int decode_pulses(Pulse *pulse, GetBitContext *gb,
  728. const uint16_t *swb_offset, int num_swb)
  729. {
  730. int i, pulse_swb;
  731. pulse->num_pulse = get_bits(gb, 2) + 1;
  732. pulse_swb = get_bits(gb, 6);
  733. if (pulse_swb >= num_swb)
  734. return -1;
  735. pulse->pos[0] = swb_offset[pulse_swb];
  736. pulse->pos[0] += get_bits(gb, 5);
  737. if (pulse->pos[0] > 1023)
  738. return -1;
  739. pulse->amp[0] = get_bits(gb, 4);
  740. for (i = 1; i < pulse->num_pulse; i++) {
  741. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
  742. if (pulse->pos[i] > 1023)
  743. return -1;
  744. pulse->amp[i] = get_bits(gb, 4);
  745. }
  746. return 0;
  747. }
  748. /**
  749. * Decode Temporal Noise Shaping data; reference: table 4.48.
  750. *
  751. * @return Returns error status. 0 - OK, !0 - error
  752. */
  753. static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
  754. GetBitContext *gb, const IndividualChannelStream *ics)
  755. {
  756. int w, filt, i, coef_len, coef_res, coef_compress;
  757. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  758. const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  759. for (w = 0; w < ics->num_windows; w++) {
  760. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  761. coef_res = get_bits1(gb);
  762. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  763. int tmp2_idx;
  764. tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
  765. if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
  766. av_log(ac->avccontext, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.\n",
  767. tns->order[w][filt], tns_max_order);
  768. tns->order[w][filt] = 0;
  769. return -1;
  770. }
  771. if (tns->order[w][filt]) {
  772. tns->direction[w][filt] = get_bits1(gb);
  773. coef_compress = get_bits1(gb);
  774. coef_len = coef_res + 3 - coef_compress;
  775. tmp2_idx = 2 * coef_compress + coef_res;
  776. for (i = 0; i < tns->order[w][filt]; i++)
  777. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  778. }
  779. }
  780. }
  781. }
  782. return 0;
  783. }
  784. /**
  785. * Decode Mid/Side data; reference: table 4.54.
  786. *
  787. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  788. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  789. * [3] reserved for scalable AAC
  790. */
  791. static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
  792. int ms_present)
  793. {
  794. int idx;
  795. if (ms_present == 1) {
  796. for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
  797. cpe->ms_mask[idx] = get_bits1(gb);
  798. } else if (ms_present == 2) {
  799. memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
  800. }
  801. }
  802. #ifndef VMUL2
  803. static inline float *VMUL2(float *dst, const float *v, unsigned idx,
  804. const float *scale)
  805. {
  806. float s = *scale;
  807. *dst++ = v[idx & 15] * s;
  808. *dst++ = v[idx>>4 & 15] * s;
  809. return dst;
  810. }
  811. #endif
  812. #ifndef VMUL4
  813. static inline float *VMUL4(float *dst, const float *v, unsigned idx,
  814. const float *scale)
  815. {
  816. float s = *scale;
  817. *dst++ = v[idx & 3] * s;
  818. *dst++ = v[idx>>2 & 3] * s;
  819. *dst++ = v[idx>>4 & 3] * s;
  820. *dst++ = v[idx>>6 & 3] * s;
  821. return dst;
  822. }
  823. #endif
  824. #ifndef VMUL2S
  825. static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
  826. unsigned sign, const float *scale)
  827. {
  828. union float754 s0, s1;
  829. s0.f = s1.f = *scale;
  830. s0.i ^= sign >> 1 << 31;
  831. s1.i ^= sign << 31;
  832. *dst++ = v[idx & 15] * s0.f;
  833. *dst++ = v[idx>>4 & 15] * s1.f;
  834. return dst;
  835. }
  836. #endif
  837. #ifndef VMUL4S
  838. static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
  839. unsigned sign, const float *scale)
  840. {
  841. unsigned nz = idx >> 12;
  842. union float754 s = { .f = *scale };
  843. union float754 t;
  844. t.i = s.i ^ (sign & 1<<31);
  845. *dst++ = v[idx & 3] * t.f;
  846. sign <<= nz & 1; nz >>= 1;
  847. t.i = s.i ^ (sign & 1<<31);
  848. *dst++ = v[idx>>2 & 3] * t.f;
  849. sign <<= nz & 1; nz >>= 1;
  850. t.i = s.i ^ (sign & 1<<31);
  851. *dst++ = v[idx>>4 & 3] * t.f;
  852. sign <<= nz & 1; nz >>= 1;
  853. t.i = s.i ^ (sign & 1<<31);
  854. *dst++ = v[idx>>6 & 3] * t.f;
  855. return dst;
  856. }
  857. #endif
  858. /**
  859. * Decode spectral data; reference: table 4.50.
  860. * Dequantize and scale spectral data; reference: 4.6.3.3.
  861. *
  862. * @param coef array of dequantized, scaled spectral data
  863. * @param sf array of scalefactors or intensity stereo positions
  864. * @param pulse_present set if pulses are present
  865. * @param pulse pointer to pulse data struct
  866. * @param band_type array of the used band type
  867. *
  868. * @return Returns error status. 0 - OK, !0 - error
  869. */
  870. static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
  871. GetBitContext *gb, const float sf[120],
  872. int pulse_present, const Pulse *pulse,
  873. const IndividualChannelStream *ics,
  874. enum BandType band_type[120])
  875. {
  876. int i, k, g, idx = 0;
  877. const int c = 1024 / ics->num_windows;
  878. const uint16_t *offsets = ics->swb_offset;
  879. float *coef_base = coef;
  880. int err_idx;
  881. for (g = 0; g < ics->num_windows; g++)
  882. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
  883. for (g = 0; g < ics->num_window_groups; g++) {
  884. unsigned g_len = ics->group_len[g];
  885. for (i = 0; i < ics->max_sfb; i++, idx++) {
  886. const unsigned cbt_m1 = band_type[idx] - 1;
  887. float *cfo = coef + offsets[i];
  888. int off_len = offsets[i + 1] - offsets[i];
  889. int group;
  890. if (cbt_m1 >= INTENSITY_BT2 - 1) {
  891. for (group = 0; group < g_len; group++, cfo+=128) {
  892. memset(cfo, 0, off_len * sizeof(float));
  893. }
  894. } else if (cbt_m1 == NOISE_BT - 1) {
  895. for (group = 0; group < g_len; group++, cfo+=128) {
  896. float scale;
  897. float band_energy;
  898. for (k = 0; k < off_len; k++) {
  899. ac->random_state = lcg_random(ac->random_state);
  900. cfo[k] = ac->random_state;
  901. }
  902. band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
  903. scale = sf[idx] / sqrtf(band_energy);
  904. ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
  905. }
  906. } else {
  907. const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
  908. const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
  909. VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
  910. const int cb_size = ff_aac_spectral_sizes[cbt_m1];
  911. OPEN_READER(re, gb);
  912. switch (cbt_m1 >> 1) {
  913. case 0:
  914. for (group = 0; group < g_len; group++, cfo+=128) {
  915. float *cf = cfo;
  916. int len = off_len;
  917. do {
  918. int code;
  919. unsigned cb_idx;
  920. UPDATE_CACHE(re, gb);
  921. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  922. if (code >= cb_size) {
  923. err_idx = code;
  924. goto err_cb_overflow;
  925. }
  926. cb_idx = cb_vector_idx[code];
  927. cf = VMUL4(cf, vq, cb_idx, sf + idx);
  928. } while (len -= 4);
  929. }
  930. break;
  931. case 1:
  932. for (group = 0; group < g_len; group++, cfo+=128) {
  933. float *cf = cfo;
  934. int len = off_len;
  935. do {
  936. int code;
  937. unsigned nnz;
  938. unsigned cb_idx;
  939. uint32_t bits;
  940. UPDATE_CACHE(re, gb);
  941. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  942. if (code >= cb_size) {
  943. err_idx = code;
  944. goto err_cb_overflow;
  945. }
  946. #if MIN_CACHE_BITS < 20
  947. UPDATE_CACHE(re, gb);
  948. #endif
  949. cb_idx = cb_vector_idx[code];
  950. nnz = cb_idx >> 8 & 15;
  951. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  952. LAST_SKIP_BITS(re, gb, nnz);
  953. cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
  954. } while (len -= 4);
  955. }
  956. break;
  957. case 2:
  958. for (group = 0; group < g_len; group++, cfo+=128) {
  959. float *cf = cfo;
  960. int len = off_len;
  961. do {
  962. int code;
  963. unsigned cb_idx;
  964. UPDATE_CACHE(re, gb);
  965. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  966. if (code >= cb_size) {
  967. err_idx = code;
  968. goto err_cb_overflow;
  969. }
  970. cb_idx = cb_vector_idx[code];
  971. cf = VMUL2(cf, vq, cb_idx, sf + idx);
  972. } while (len -= 2);
  973. }
  974. break;
  975. case 3:
  976. case 4:
  977. for (group = 0; group < g_len; group++, cfo+=128) {
  978. float *cf = cfo;
  979. int len = off_len;
  980. do {
  981. int code;
  982. unsigned nnz;
  983. unsigned cb_idx;
  984. unsigned sign;
  985. UPDATE_CACHE(re, gb);
  986. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  987. if (code >= cb_size) {
  988. err_idx = code;
  989. goto err_cb_overflow;
  990. }
  991. cb_idx = cb_vector_idx[code];
  992. nnz = cb_idx >> 8 & 15;
  993. sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
  994. LAST_SKIP_BITS(re, gb, nnz);
  995. cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
  996. } while (len -= 2);
  997. }
  998. break;
  999. default:
  1000. for (group = 0; group < g_len; group++, cfo+=128) {
  1001. float *cf = cfo;
  1002. uint32_t *icf = (uint32_t *) cf;
  1003. int len = off_len;
  1004. do {
  1005. int code;
  1006. unsigned nzt, nnz;
  1007. unsigned cb_idx;
  1008. uint32_t bits;
  1009. int j;
  1010. UPDATE_CACHE(re, gb);
  1011. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1012. if (!code) {
  1013. *icf++ = 0;
  1014. *icf++ = 0;
  1015. continue;
  1016. }
  1017. if (code >= cb_size) {
  1018. err_idx = code;
  1019. goto err_cb_overflow;
  1020. }
  1021. cb_idx = cb_vector_idx[code];
  1022. nnz = cb_idx >> 12;
  1023. nzt = cb_idx >> 8;
  1024. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  1025. LAST_SKIP_BITS(re, gb, nnz);
  1026. for (j = 0; j < 2; j++) {
  1027. if (nzt & 1<<j) {
  1028. uint32_t b;
  1029. int n;
  1030. /* The total length of escape_sequence must be < 22 bits according
  1031. to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
  1032. UPDATE_CACHE(re, gb);
  1033. b = GET_CACHE(re, gb);
  1034. b = 31 - av_log2(~b);
  1035. if (b > 8) {
  1036. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  1037. return -1;
  1038. }
  1039. #if MIN_CACHE_BITS < 21
  1040. LAST_SKIP_BITS(re, gb, b + 1);
  1041. UPDATE_CACHE(re, gb);
  1042. #else
  1043. SKIP_BITS(re, gb, b + 1);
  1044. #endif
  1045. b += 4;
  1046. n = (1 << b) + SHOW_UBITS(re, gb, b);
  1047. LAST_SKIP_BITS(re, gb, b);
  1048. *icf++ = cbrt_tab[n] | (bits & 1<<31);
  1049. bits <<= 1;
  1050. } else {
  1051. unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
  1052. *icf++ = (bits & 1<<31) | v;
  1053. bits <<= !!v;
  1054. }
  1055. cb_idx >>= 4;
  1056. }
  1057. } while (len -= 2);
  1058. ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
  1059. }
  1060. }
  1061. CLOSE_READER(re, gb);
  1062. }
  1063. }
  1064. coef += g_len << 7;
  1065. }
  1066. if (pulse_present) {
  1067. idx = 0;
  1068. for (i = 0; i < pulse->num_pulse; i++) {
  1069. float co = coef_base[ pulse->pos[i] ];
  1070. while (offsets[idx + 1] <= pulse->pos[i])
  1071. idx++;
  1072. if (band_type[idx] != NOISE_BT && sf[idx]) {
  1073. float ico = -pulse->amp[i];
  1074. if (co) {
  1075. co /= sf[idx];
  1076. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  1077. }
  1078. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  1079. }
  1080. }
  1081. }
  1082. return 0;
  1083. err_cb_overflow:
  1084. av_log(ac->avccontext, AV_LOG_ERROR,
  1085. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  1086. band_type[idx], err_idx, ff_aac_spectral_sizes[band_type[idx]]);
  1087. return -1;
  1088. }
  1089. static av_always_inline float flt16_round(float pf)
  1090. {
  1091. union float754 tmp;
  1092. tmp.f = pf;
  1093. tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
  1094. return tmp.f;
  1095. }
  1096. static av_always_inline float flt16_even(float pf)
  1097. {
  1098. union float754 tmp;
  1099. tmp.f = pf;
  1100. tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
  1101. return tmp.f;
  1102. }
  1103. static av_always_inline float flt16_trunc(float pf)
  1104. {
  1105. union float754 pun;
  1106. pun.f = pf;
  1107. pun.i &= 0xFFFF0000U;
  1108. return pun.f;
  1109. }
  1110. static av_always_inline void predict(AACContext *ac, PredictorState *ps, float *coef,
  1111. int output_enable)
  1112. {
  1113. const float a = 0.953125; // 61.0 / 64
  1114. const float alpha = 0.90625; // 29.0 / 32
  1115. float e0, e1;
  1116. float pv;
  1117. float k1, k2;
  1118. k1 = ps->var0 > 1 ? ps->cor0 * flt16_even(a / ps->var0) : 0;
  1119. k2 = ps->var1 > 1 ? ps->cor1 * flt16_even(a / ps->var1) : 0;
  1120. pv = flt16_round(k1 * ps->r0 + k2 * ps->r1);
  1121. if (output_enable)
  1122. *coef += pv * ac->sf_scale;
  1123. e0 = *coef / ac->sf_scale;
  1124. e1 = e0 - k1 * ps->r0;
  1125. ps->cor1 = flt16_trunc(alpha * ps->cor1 + ps->r1 * e1);
  1126. ps->var1 = flt16_trunc(alpha * ps->var1 + 0.5 * (ps->r1 * ps->r1 + e1 * e1));
  1127. ps->cor0 = flt16_trunc(alpha * ps->cor0 + ps->r0 * e0);
  1128. ps->var0 = flt16_trunc(alpha * ps->var0 + 0.5 * (ps->r0 * ps->r0 + e0 * e0));
  1129. ps->r1 = flt16_trunc(a * (ps->r0 - k1 * e0));
  1130. ps->r0 = flt16_trunc(a * e0);
  1131. }
  1132. /**
  1133. * Apply AAC-Main style frequency domain prediction.
  1134. */
  1135. static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
  1136. {
  1137. int sfb, k;
  1138. if (!sce->ics.predictor_initialized) {
  1139. reset_all_predictors(sce->predictor_state);
  1140. sce->ics.predictor_initialized = 1;
  1141. }
  1142. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  1143. for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
  1144. for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
  1145. predict(ac, &sce->predictor_state[k], &sce->coeffs[k],
  1146. sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
  1147. }
  1148. }
  1149. if (sce->ics.predictor_reset_group)
  1150. reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
  1151. } else
  1152. reset_all_predictors(sce->predictor_state);
  1153. }
  1154. /**
  1155. * Decode an individual_channel_stream payload; reference: table 4.44.
  1156. *
  1157. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  1158. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  1159. *
  1160. * @return Returns error status. 0 - OK, !0 - error
  1161. */
  1162. static int decode_ics(AACContext *ac, SingleChannelElement *sce,
  1163. GetBitContext *gb, int common_window, int scale_flag)
  1164. {
  1165. Pulse pulse;
  1166. TemporalNoiseShaping *tns = &sce->tns;
  1167. IndividualChannelStream *ics = &sce->ics;
  1168. float *out = sce->coeffs;
  1169. int global_gain, pulse_present = 0;
  1170. /* This assignment is to silence a GCC warning about the variable being used
  1171. * uninitialized when in fact it always is.
  1172. */
  1173. pulse.num_pulse = 0;
  1174. global_gain = get_bits(gb, 8);
  1175. if (!common_window && !scale_flag) {
  1176. if (decode_ics_info(ac, ics, gb, 0) < 0)
  1177. return -1;
  1178. }
  1179. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  1180. return -1;
  1181. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  1182. return -1;
  1183. pulse_present = 0;
  1184. if (!scale_flag) {
  1185. if ((pulse_present = get_bits1(gb))) {
  1186. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1187. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  1188. return -1;
  1189. }
  1190. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  1191. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
  1192. return -1;
  1193. }
  1194. }
  1195. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  1196. return -1;
  1197. if (get_bits1(gb)) {
  1198. av_log_missing_feature(ac->avccontext, "SSR", 1);
  1199. return -1;
  1200. }
  1201. }
  1202. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  1203. return -1;
  1204. if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
  1205. apply_prediction(ac, sce);
  1206. return 0;
  1207. }
  1208. /**
  1209. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  1210. */
  1211. static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
  1212. {
  1213. const IndividualChannelStream *ics = &cpe->ch[0].ics;
  1214. float *ch0 = cpe->ch[0].coeffs;
  1215. float *ch1 = cpe->ch[1].coeffs;
  1216. int g, i, group, idx = 0;
  1217. const uint16_t *offsets = ics->swb_offset;
  1218. for (g = 0; g < ics->num_window_groups; g++) {
  1219. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1220. if (cpe->ms_mask[idx] &&
  1221. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  1222. for (group = 0; group < ics->group_len[g]; group++) {
  1223. ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
  1224. ch1 + group * 128 + offsets[i],
  1225. offsets[i+1] - offsets[i]);
  1226. }
  1227. }
  1228. }
  1229. ch0 += ics->group_len[g] * 128;
  1230. ch1 += ics->group_len[g] * 128;
  1231. }
  1232. }
  1233. /**
  1234. * intensity stereo decoding; reference: 4.6.8.2.3
  1235. *
  1236. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1237. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1238. * [3] reserved for scalable AAC
  1239. */
  1240. static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
  1241. {
  1242. const IndividualChannelStream *ics = &cpe->ch[1].ics;
  1243. SingleChannelElement *sce1 = &cpe->ch[1];
  1244. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  1245. const uint16_t *offsets = ics->swb_offset;
  1246. int g, group, i, k, idx = 0;
  1247. int c;
  1248. float scale;
  1249. for (g = 0; g < ics->num_window_groups; g++) {
  1250. for (i = 0; i < ics->max_sfb;) {
  1251. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  1252. const int bt_run_end = sce1->band_type_run_end[idx];
  1253. for (; i < bt_run_end; i++, idx++) {
  1254. c = -1 + 2 * (sce1->band_type[idx] - 14);
  1255. if (ms_present)
  1256. c *= 1 - 2 * cpe->ms_mask[idx];
  1257. scale = c * sce1->sf[idx];
  1258. for (group = 0; group < ics->group_len[g]; group++)
  1259. for (k = offsets[i]; k < offsets[i + 1]; k++)
  1260. coef1[group * 128 + k] = scale * coef0[group * 128 + k];
  1261. }
  1262. } else {
  1263. int bt_run_end = sce1->band_type_run_end[idx];
  1264. idx += bt_run_end - i;
  1265. i = bt_run_end;
  1266. }
  1267. }
  1268. coef0 += ics->group_len[g] * 128;
  1269. coef1 += ics->group_len[g] * 128;
  1270. }
  1271. }
  1272. /**
  1273. * Decode a channel_pair_element; reference: table 4.4.
  1274. *
  1275. * @param elem_id Identifies the instance of a syntax element.
  1276. *
  1277. * @return Returns error status. 0 - OK, !0 - error
  1278. */
  1279. static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
  1280. {
  1281. int i, ret, common_window, ms_present = 0;
  1282. common_window = get_bits1(gb);
  1283. if (common_window) {
  1284. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  1285. return -1;
  1286. i = cpe->ch[1].ics.use_kb_window[0];
  1287. cpe->ch[1].ics = cpe->ch[0].ics;
  1288. cpe->ch[1].ics.use_kb_window[1] = i;
  1289. ms_present = get_bits(gb, 2);
  1290. if (ms_present == 3) {
  1291. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  1292. return -1;
  1293. } else if (ms_present)
  1294. decode_mid_side_stereo(cpe, gb, ms_present);
  1295. }
  1296. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  1297. return ret;
  1298. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  1299. return ret;
  1300. if (common_window) {
  1301. if (ms_present)
  1302. apply_mid_side_stereo(ac, cpe);
  1303. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  1304. apply_prediction(ac, &cpe->ch[0]);
  1305. apply_prediction(ac, &cpe->ch[1]);
  1306. }
  1307. }
  1308. apply_intensity_stereo(cpe, ms_present);
  1309. return 0;
  1310. }
  1311. /**
  1312. * Decode coupling_channel_element; reference: table 4.8.
  1313. *
  1314. * @param elem_id Identifies the instance of a syntax element.
  1315. *
  1316. * @return Returns error status. 0 - OK, !0 - error
  1317. */
  1318. static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
  1319. {
  1320. int num_gain = 0;
  1321. int c, g, sfb, ret;
  1322. int sign;
  1323. float scale;
  1324. SingleChannelElement *sce = &che->ch[0];
  1325. ChannelCoupling *coup = &che->coup;
  1326. coup->coupling_point = 2 * get_bits1(gb);
  1327. coup->num_coupled = get_bits(gb, 3);
  1328. for (c = 0; c <= coup->num_coupled; c++) {
  1329. num_gain++;
  1330. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1331. coup->id_select[c] = get_bits(gb, 4);
  1332. if (coup->type[c] == TYPE_CPE) {
  1333. coup->ch_select[c] = get_bits(gb, 2);
  1334. if (coup->ch_select[c] == 3)
  1335. num_gain++;
  1336. } else
  1337. coup->ch_select[c] = 2;
  1338. }
  1339. coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
  1340. sign = get_bits(gb, 1);
  1341. scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
  1342. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1343. return ret;
  1344. for (c = 0; c < num_gain; c++) {
  1345. int idx = 0;
  1346. int cge = 1;
  1347. int gain = 0;
  1348. float gain_cache = 1.;
  1349. if (c) {
  1350. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1351. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1352. gain_cache = pow(scale, -gain);
  1353. }
  1354. if (coup->coupling_point == AFTER_IMDCT) {
  1355. coup->gain[c][0] = gain_cache;
  1356. } else {
  1357. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1358. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1359. if (sce->band_type[idx] != ZERO_BT) {
  1360. if (!cge) {
  1361. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1362. if (t) {
  1363. int s = 1;
  1364. t = gain += t;
  1365. if (sign) {
  1366. s -= 2 * (t & 0x1);
  1367. t >>= 1;
  1368. }
  1369. gain_cache = pow(scale, -t) * s;
  1370. }
  1371. }
  1372. coup->gain[c][idx] = gain_cache;
  1373. }
  1374. }
  1375. }
  1376. }
  1377. }
  1378. return 0;
  1379. }
  1380. /**
  1381. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  1382. *
  1383. * @return Returns number of bytes consumed.
  1384. */
  1385. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
  1386. GetBitContext *gb)
  1387. {
  1388. int i;
  1389. int num_excl_chan = 0;
  1390. do {
  1391. for (i = 0; i < 7; i++)
  1392. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  1393. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  1394. return num_excl_chan / 7;
  1395. }
  1396. /**
  1397. * Decode dynamic range information; reference: table 4.52.
  1398. *
  1399. * @param cnt length of TYPE_FIL syntactic element in bytes
  1400. *
  1401. * @return Returns number of bytes consumed.
  1402. */
  1403. static int decode_dynamic_range(DynamicRangeControl *che_drc,
  1404. GetBitContext *gb, int cnt)
  1405. {
  1406. int n = 1;
  1407. int drc_num_bands = 1;
  1408. int i;
  1409. /* pce_tag_present? */
  1410. if (get_bits1(gb)) {
  1411. che_drc->pce_instance_tag = get_bits(gb, 4);
  1412. skip_bits(gb, 4); // tag_reserved_bits
  1413. n++;
  1414. }
  1415. /* excluded_chns_present? */
  1416. if (get_bits1(gb)) {
  1417. n += decode_drc_channel_exclusions(che_drc, gb);
  1418. }
  1419. /* drc_bands_present? */
  1420. if (get_bits1(gb)) {
  1421. che_drc->band_incr = get_bits(gb, 4);
  1422. che_drc->interpolation_scheme = get_bits(gb, 4);
  1423. n++;
  1424. drc_num_bands += che_drc->band_incr;
  1425. for (i = 0; i < drc_num_bands; i++) {
  1426. che_drc->band_top[i] = get_bits(gb, 8);
  1427. n++;
  1428. }
  1429. }
  1430. /* prog_ref_level_present? */
  1431. if (get_bits1(gb)) {
  1432. che_drc->prog_ref_level = get_bits(gb, 7);
  1433. skip_bits1(gb); // prog_ref_level_reserved_bits
  1434. n++;
  1435. }
  1436. for (i = 0; i < drc_num_bands; i++) {
  1437. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  1438. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  1439. n++;
  1440. }
  1441. return n;
  1442. }
  1443. /**
  1444. * Decode extension data (incomplete); reference: table 4.51.
  1445. *
  1446. * @param cnt length of TYPE_FIL syntactic element in bytes
  1447. *
  1448. * @return Returns number of bytes consumed
  1449. */
  1450. static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
  1451. ChannelElement *che, enum RawDataBlockType elem_type)
  1452. {
  1453. int crc_flag = 0;
  1454. int res = cnt;
  1455. switch (get_bits(gb, 4)) { // extension type
  1456. case EXT_SBR_DATA_CRC:
  1457. crc_flag++;
  1458. case EXT_SBR_DATA:
  1459. if (!che) {
  1460. av_log(ac->avccontext, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
  1461. return res;
  1462. } else if (!ac->m4ac.sbr) {
  1463. av_log(ac->avccontext, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
  1464. skip_bits_long(gb, 8 * cnt - 4);
  1465. return res;
  1466. } else if (ac->m4ac.sbr == -1 && ac->output_configured == OC_LOCKED) {
  1467. av_log(ac->avccontext, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
  1468. skip_bits_long(gb, 8 * cnt - 4);
  1469. return res;
  1470. } else {
  1471. ac->m4ac.sbr = 1;
  1472. }
  1473. res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
  1474. break;
  1475. case EXT_DYNAMIC_RANGE:
  1476. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  1477. break;
  1478. case EXT_FILL:
  1479. case EXT_FILL_DATA:
  1480. case EXT_DATA_ELEMENT:
  1481. default:
  1482. skip_bits_long(gb, 8 * cnt - 4);
  1483. break;
  1484. };
  1485. return res;
  1486. }
  1487. /**
  1488. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  1489. *
  1490. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  1491. * @param coef spectral coefficients
  1492. */
  1493. static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
  1494. IndividualChannelStream *ics, int decode)
  1495. {
  1496. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  1497. int w, filt, m, i;
  1498. int bottom, top, order, start, end, size, inc;
  1499. float lpc[TNS_MAX_ORDER];
  1500. for (w = 0; w < ics->num_windows; w++) {
  1501. bottom = ics->num_swb;
  1502. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1503. top = bottom;
  1504. bottom = FFMAX(0, top - tns->length[w][filt]);
  1505. order = tns->order[w][filt];
  1506. if (order == 0)
  1507. continue;
  1508. // tns_decode_coef
  1509. compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
  1510. start = ics->swb_offset[FFMIN(bottom, mmm)];
  1511. end = ics->swb_offset[FFMIN( top, mmm)];
  1512. if ((size = end - start) <= 0)
  1513. continue;
  1514. if (tns->direction[w][filt]) {
  1515. inc = -1;
  1516. start = end - 1;
  1517. } else {
  1518. inc = 1;
  1519. }
  1520. start += w * 128;
  1521. // ar filter
  1522. for (m = 0; m < size; m++, start += inc)
  1523. for (i = 1; i <= FFMIN(m, order); i++)
  1524. coef[start] -= coef[start - i * inc] * lpc[i - 1];
  1525. }
  1526. }
  1527. }
  1528. /**
  1529. * Conduct IMDCT and windowing.
  1530. */
  1531. static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce, float bias)
  1532. {
  1533. IndividualChannelStream *ics = &sce->ics;
  1534. float *in = sce->coeffs;
  1535. float *out = sce->ret;
  1536. float *saved = sce->saved;
  1537. const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  1538. const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  1539. const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  1540. float *buf = ac->buf_mdct;
  1541. float *temp = ac->temp;
  1542. int i;
  1543. // imdct
  1544. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1545. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  1546. av_log(ac->avccontext, AV_LOG_WARNING,
  1547. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  1548. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  1549. for (i = 0; i < 1024; i += 128)
  1550. ff_imdct_half(&ac->mdct_small, buf + i, in + i);
  1551. } else
  1552. ff_imdct_half(&ac->mdct, buf, in);
  1553. /* window overlapping
  1554. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  1555. * and long to short transitions are considered to be short to short
  1556. * transitions. This leaves just two cases (long to long and short to short)
  1557. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  1558. */
  1559. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  1560. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  1561. ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, bias, 512);
  1562. } else {
  1563. for (i = 0; i < 448; i++)
  1564. out[i] = saved[i] + bias;
  1565. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1566. ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, bias, 64);
  1567. ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, bias, 64);
  1568. ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, bias, 64);
  1569. ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, bias, 64);
  1570. ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, bias, 64);
  1571. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  1572. } else {
  1573. ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, bias, 64);
  1574. for (i = 576; i < 1024; i++)
  1575. out[i] = buf[i-512] + bias;
  1576. }
  1577. }
  1578. // buffer update
  1579. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1580. for (i = 0; i < 64; i++)
  1581. saved[i] = temp[64 + i] - bias;
  1582. ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
  1583. ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
  1584. ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
  1585. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1586. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1587. memcpy( saved, buf + 512, 448 * sizeof(float));
  1588. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1589. } else { // LONG_STOP or ONLY_LONG
  1590. memcpy( saved, buf + 512, 512 * sizeof(float));
  1591. }
  1592. }
  1593. /**
  1594. * Apply dependent channel coupling (applied before IMDCT).
  1595. *
  1596. * @param index index into coupling gain array
  1597. */
  1598. static void apply_dependent_coupling(AACContext *ac,
  1599. SingleChannelElement *target,
  1600. ChannelElement *cce, int index)
  1601. {
  1602. IndividualChannelStream *ics = &cce->ch[0].ics;
  1603. const uint16_t *offsets = ics->swb_offset;
  1604. float *dest = target->coeffs;
  1605. const float *src = cce->ch[0].coeffs;
  1606. int g, i, group, k, idx = 0;
  1607. if (ac->m4ac.object_type == AOT_AAC_LTP) {
  1608. av_log(ac->avccontext, AV_LOG_ERROR,
  1609. "Dependent coupling is not supported together with LTP\n");
  1610. return;
  1611. }
  1612. for (g = 0; g < ics->num_window_groups; g++) {
  1613. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1614. if (cce->ch[0].band_type[idx] != ZERO_BT) {
  1615. const float gain = cce->coup.gain[index][idx];
  1616. for (group = 0; group < ics->group_len[g]; group++) {
  1617. for (k = offsets[i]; k < offsets[i + 1]; k++) {
  1618. // XXX dsputil-ize
  1619. dest[group * 128 + k] += gain * src[group * 128 + k];
  1620. }
  1621. }
  1622. }
  1623. }
  1624. dest += ics->group_len[g] * 128;
  1625. src += ics->group_len[g] * 128;
  1626. }
  1627. }
  1628. /**
  1629. * Apply independent channel coupling (applied after IMDCT).
  1630. *
  1631. * @param index index into coupling gain array
  1632. */
  1633. static void apply_independent_coupling(AACContext *ac,
  1634. SingleChannelElement *target,
  1635. ChannelElement *cce, int index)
  1636. {
  1637. int i;
  1638. const float gain = cce->coup.gain[index][0];
  1639. const float bias = ac->add_bias;
  1640. const float *src = cce->ch[0].ret;
  1641. float *dest = target->ret;
  1642. const int len = 1024 << (ac->m4ac.sbr == 1);
  1643. for (i = 0; i < len; i++)
  1644. dest[i] += gain * (src[i] - bias);
  1645. }
  1646. /**
  1647. * channel coupling transformation interface
  1648. *
  1649. * @param index index into coupling gain array
  1650. * @param apply_coupling_method pointer to (in)dependent coupling function
  1651. */
  1652. static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
  1653. enum RawDataBlockType type, int elem_id,
  1654. enum CouplingPoint coupling_point,
  1655. void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
  1656. {
  1657. int i, c;
  1658. for (i = 0; i < MAX_ELEM_ID; i++) {
  1659. ChannelElement *cce = ac->che[TYPE_CCE][i];
  1660. int index = 0;
  1661. if (cce && cce->coup.coupling_point == coupling_point) {
  1662. ChannelCoupling *coup = &cce->coup;
  1663. for (c = 0; c <= coup->num_coupled; c++) {
  1664. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  1665. if (coup->ch_select[c] != 1) {
  1666. apply_coupling_method(ac, &cc->ch[0], cce, index);
  1667. if (coup->ch_select[c] != 0)
  1668. index++;
  1669. }
  1670. if (coup->ch_select[c] != 2)
  1671. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  1672. } else
  1673. index += 1 + (coup->ch_select[c] == 3);
  1674. }
  1675. }
  1676. }
  1677. }
  1678. /**
  1679. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1680. */
  1681. static void spectral_to_sample(AACContext *ac)
  1682. {
  1683. int i, type;
  1684. float imdct_bias = (ac->m4ac.sbr <= 0) ? ac->add_bias : 0.0f;
  1685. for (type = 3; type >= 0; type--) {
  1686. for (i = 0; i < MAX_ELEM_ID; i++) {
  1687. ChannelElement *che = ac->che[type][i];
  1688. if (che) {
  1689. if (type <= TYPE_CPE)
  1690. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
  1691. if (che->ch[0].tns.present)
  1692. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1693. if (che->ch[1].tns.present)
  1694. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1695. if (type <= TYPE_CPE)
  1696. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
  1697. if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
  1698. imdct_and_windowing(ac, &che->ch[0], imdct_bias);
  1699. if (ac->m4ac.sbr > 0) {
  1700. ff_sbr_dequant(ac, &che->sbr, type == TYPE_CPE ? TYPE_CPE : TYPE_SCE);
  1701. ff_sbr_apply(ac, &che->sbr, 0, che->ch[0].ret, che->ch[0].ret);
  1702. }
  1703. }
  1704. if (type == TYPE_CPE) {
  1705. imdct_and_windowing(ac, &che->ch[1], imdct_bias);
  1706. if (ac->m4ac.sbr > 0)
  1707. ff_sbr_apply(ac, &che->sbr, 1, che->ch[1].ret, che->ch[1].ret);
  1708. }
  1709. if (type <= TYPE_CCE)
  1710. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
  1711. }
  1712. }
  1713. }
  1714. }
  1715. static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
  1716. {
  1717. int size;
  1718. AACADTSHeaderInfo hdr_info;
  1719. size = ff_aac_parse_header(gb, &hdr_info);
  1720. if (size > 0) {
  1721. if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
  1722. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1723. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1724. ac->m4ac.chan_config = hdr_info.chan_config;
  1725. if (set_default_channel_config(ac, new_che_pos, hdr_info.chan_config))
  1726. return -7;
  1727. if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
  1728. return -7;
  1729. } else if (ac->output_configured != OC_LOCKED) {
  1730. ac->output_configured = OC_NONE;
  1731. }
  1732. if (ac->output_configured != OC_LOCKED)
  1733. ac->m4ac.sbr = -1;
  1734. ac->m4ac.sample_rate = hdr_info.sample_rate;
  1735. ac->m4ac.sampling_index = hdr_info.sampling_index;
  1736. ac->m4ac.object_type = hdr_info.object_type;
  1737. if (!ac->avccontext->sample_rate)
  1738. ac->avccontext->sample_rate = hdr_info.sample_rate;
  1739. if (hdr_info.num_aac_frames == 1) {
  1740. if (!hdr_info.crc_absent)
  1741. skip_bits(gb, 16);
  1742. } else {
  1743. av_log_missing_feature(ac->avccontext, "More than one AAC RDB per ADTS frame is", 0);
  1744. return -1;
  1745. }
  1746. }
  1747. return size;
  1748. }
  1749. static int aac_decode_frame(AVCodecContext *avccontext, void *data,
  1750. int *data_size, AVPacket *avpkt)
  1751. {
  1752. const uint8_t *buf = avpkt->data;
  1753. int buf_size = avpkt->size;
  1754. AACContext *ac = avccontext->priv_data;
  1755. ChannelElement *che = NULL, *che_prev = NULL;
  1756. GetBitContext gb;
  1757. enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
  1758. int err, elem_id, data_size_tmp;
  1759. int buf_consumed;
  1760. int samples = 1024, multiplier;
  1761. init_get_bits(&gb, buf, buf_size * 8);
  1762. if (show_bits(&gb, 12) == 0xfff) {
  1763. if (parse_adts_frame_header(ac, &gb) < 0) {
  1764. av_log(avccontext, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
  1765. return -1;
  1766. }
  1767. if (ac->m4ac.sampling_index > 12) {
  1768. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  1769. return -1;
  1770. }
  1771. }
  1772. // parse
  1773. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1774. elem_id = get_bits(&gb, 4);
  1775. if (elem_type < TYPE_DSE && !(che=get_che(ac, elem_type, elem_id))) {
  1776. av_log(ac->avccontext, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id);
  1777. return -1;
  1778. }
  1779. switch (elem_type) {
  1780. case TYPE_SCE:
  1781. err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
  1782. break;
  1783. case TYPE_CPE:
  1784. err = decode_cpe(ac, &gb, che);
  1785. break;
  1786. case TYPE_CCE:
  1787. err = decode_cce(ac, &gb, che);
  1788. break;
  1789. case TYPE_LFE:
  1790. err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
  1791. break;
  1792. case TYPE_DSE:
  1793. err = skip_data_stream_element(ac, &gb);
  1794. break;
  1795. case TYPE_PCE: {
  1796. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1797. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1798. if ((err = decode_pce(ac, new_che_pos, &gb)))
  1799. break;
  1800. if (ac->output_configured > OC_TRIAL_PCE)
  1801. av_log(avccontext, AV_LOG_ERROR,
  1802. "Not evaluating a further program_config_element as this construct is dubious at best.\n");
  1803. else
  1804. err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
  1805. break;
  1806. }
  1807. case TYPE_FIL:
  1808. if (elem_id == 15)
  1809. elem_id += get_bits(&gb, 8) - 1;
  1810. if (get_bits_left(&gb) < 8 * elem_id) {
  1811. av_log(avccontext, AV_LOG_ERROR, overread_err);
  1812. return -1;
  1813. }
  1814. while (elem_id > 0)
  1815. elem_id -= decode_extension_payload(ac, &gb, elem_id, che_prev, elem_type_prev);
  1816. err = 0; /* FIXME */
  1817. break;
  1818. default:
  1819. err = -1; /* should not happen, but keeps compiler happy */
  1820. break;
  1821. }
  1822. che_prev = che;
  1823. elem_type_prev = elem_type;
  1824. if (err)
  1825. return err;
  1826. if (get_bits_left(&gb) < 3) {
  1827. av_log(avccontext, AV_LOG_ERROR, overread_err);
  1828. return -1;
  1829. }
  1830. }
  1831. spectral_to_sample(ac);
  1832. multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
  1833. samples <<= multiplier;
  1834. if (ac->output_configured < OC_LOCKED) {
  1835. avccontext->sample_rate = ac->m4ac.sample_rate << multiplier;
  1836. avccontext->frame_size = samples;
  1837. }
  1838. data_size_tmp = samples * avccontext->channels * sizeof(int16_t);
  1839. if (*data_size < data_size_tmp) {
  1840. av_log(avccontext, AV_LOG_ERROR,
  1841. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1842. *data_size, data_size_tmp);
  1843. return -1;
  1844. }
  1845. *data_size = data_size_tmp;
  1846. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avccontext->channels);
  1847. if (ac->output_configured)
  1848. ac->output_configured = OC_LOCKED;
  1849. buf_consumed = (get_bits_count(&gb) + 7) >> 3;
  1850. return buf_size > buf_consumed ? buf_consumed : buf_size;
  1851. }
  1852. static av_cold int aac_decode_close(AVCodecContext *avccontext)
  1853. {
  1854. AACContext *ac = avccontext->priv_data;
  1855. int i, type;
  1856. for (i = 0; i < MAX_ELEM_ID; i++) {
  1857. for (type = 0; type < 4; type++) {
  1858. if (ac->che[type][i])
  1859. ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
  1860. av_freep(&ac->che[type][i]);
  1861. }
  1862. }
  1863. ff_mdct_end(&ac->mdct);
  1864. ff_mdct_end(&ac->mdct_small);
  1865. return 0;
  1866. }
  1867. AVCodec aac_decoder = {
  1868. "aac",
  1869. CODEC_TYPE_AUDIO,
  1870. CODEC_ID_AAC,
  1871. sizeof(AACContext),
  1872. aac_decode_init,
  1873. NULL,
  1874. aac_decode_close,
  1875. aac_decode_frame,
  1876. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1877. .sample_fmts = (const enum SampleFormat[]) {
  1878. SAMPLE_FMT_S16,SAMPLE_FMT_NONE
  1879. },
  1880. .channel_layouts = aac_channel_layout,
  1881. };