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.

2084 lines
73KB

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