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.

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