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.

2015 lines
70KB

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