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.

2080 lines
72KB

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