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.

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