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.

2092 lines
73KB

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