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.

2064 lines
72KB

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