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.

1359 lines
50KB

  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 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. * N 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 "bitstream.h"
  77. #include "dsputil.h"
  78. #include "aac.h"
  79. #include "aactab.h"
  80. #include "aacdectab.h"
  81. #include "mpeg4audio.h"
  82. #include <assert.h>
  83. #include <errno.h>
  84. #include <math.h>
  85. #include <string.h>
  86. static VLC vlc_scalefactors;
  87. static VLC vlc_spectral[11];
  88. /**
  89. * Configure output channel order based on the current program configuration element.
  90. *
  91. * @param che_pos current channel position configuration
  92. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  93. *
  94. * @return Returns error status. 0 - OK, !0 - error
  95. */
  96. static int output_configure(AACContext *ac, enum ChannelPosition che_pos[4][MAX_ELEM_ID],
  97. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID]) {
  98. AVCodecContext *avctx = ac->avccontext;
  99. int i, type, channels = 0;
  100. if(!memcmp(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0])))
  101. return 0; /* no change */
  102. memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  103. /* Allocate or free elements depending on if they are in the
  104. * current program configuration.
  105. *
  106. * Set up default 1:1 output mapping.
  107. *
  108. * For a 5.1 stream the output order will be:
  109. * [ Front Left ] [ Front Right ] [ Center ] [ LFE ] [ Surround Left ] [ Surround Right ]
  110. */
  111. for(i = 0; i < MAX_ELEM_ID; i++) {
  112. for(type = 0; type < 4; type++) {
  113. if(che_pos[type][i]) {
  114. if(!ac->che[type][i] && !(ac->che[type][i] = av_mallocz(sizeof(ChannelElement))))
  115. return AVERROR(ENOMEM);
  116. if(type != TYPE_CCE) {
  117. ac->output_data[channels++] = ac->che[type][i]->ch[0].ret;
  118. if(type == TYPE_CPE) {
  119. ac->output_data[channels++] = ac->che[type][i]->ch[1].ret;
  120. }
  121. }
  122. } else
  123. av_freep(&ac->che[type][i]);
  124. }
  125. }
  126. avctx->channels = channels;
  127. return 0;
  128. }
  129. /**
  130. * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
  131. *
  132. * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
  133. * @param sce_map mono (Single Channel Element) map
  134. * @param type speaker type/position for these channels
  135. */
  136. static void decode_channel_map(enum ChannelPosition *cpe_map,
  137. enum ChannelPosition *sce_map, enum ChannelPosition type, GetBitContext * gb, int n) {
  138. while(n--) {
  139. enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
  140. map[get_bits(gb, 4)] = type;
  141. }
  142. }
  143. /**
  144. * Decode program configuration element; reference: table 4.2.
  145. *
  146. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  147. *
  148. * @return Returns error status. 0 - OK, !0 - error
  149. */
  150. static int decode_pce(AACContext * ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  151. GetBitContext * gb) {
  152. int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;
  153. skip_bits(gb, 2); // object_type
  154. ac->m4ac.sampling_index = get_bits(gb, 4);
  155. if(ac->m4ac.sampling_index > 11) {
  156. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  157. return -1;
  158. }
  159. ac->m4ac.sample_rate = ff_mpeg4audio_sample_rates[ac->m4ac.sampling_index];
  160. num_front = get_bits(gb, 4);
  161. num_side = get_bits(gb, 4);
  162. num_back = get_bits(gb, 4);
  163. num_lfe = get_bits(gb, 2);
  164. num_assoc_data = get_bits(gb, 3);
  165. num_cc = get_bits(gb, 4);
  166. if (get_bits1(gb))
  167. skip_bits(gb, 4); // mono_mixdown_tag
  168. if (get_bits1(gb))
  169. skip_bits(gb, 4); // stereo_mixdown_tag
  170. if (get_bits1(gb))
  171. skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
  172. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
  173. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
  174. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
  175. decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
  176. skip_bits_long(gb, 4 * num_assoc_data);
  177. decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
  178. align_get_bits(gb);
  179. /* comment field, first byte is length */
  180. skip_bits_long(gb, 8 * get_bits(gb, 8));
  181. return 0;
  182. }
  183. /**
  184. * Set up channel positions based on a default channel configuration
  185. * as specified in table 1.17.
  186. *
  187. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  188. *
  189. * @return Returns error status. 0 - OK, !0 - error
  190. */
  191. static int set_default_channel_config(AACContext *ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  192. int channel_config)
  193. {
  194. if(channel_config < 1 || channel_config > 7) {
  195. av_log(ac->avccontext, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
  196. channel_config);
  197. return -1;
  198. }
  199. /* default channel configurations:
  200. *
  201. * 1ch : front center (mono)
  202. * 2ch : L + R (stereo)
  203. * 3ch : front center + L + R
  204. * 4ch : front center + L + R + back center
  205. * 5ch : front center + L + R + back stereo
  206. * 6ch : front center + L + R + back stereo + LFE
  207. * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
  208. */
  209. if(channel_config != 2)
  210. new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
  211. if(channel_config > 1)
  212. new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
  213. if(channel_config == 4)
  214. new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
  215. if(channel_config > 4)
  216. new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
  217. = AAC_CHANNEL_BACK; // back stereo
  218. if(channel_config > 5)
  219. new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
  220. if(channel_config == 7)
  221. new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
  222. return 0;
  223. }
  224. /**
  225. * Decode GA "General Audio" specific configuration; reference: table 4.1.
  226. *
  227. * @return Returns error status. 0 - OK, !0 - error
  228. */
  229. static int decode_ga_specific_config(AACContext * ac, GetBitContext * gb, int channel_config) {
  230. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  231. int extension_flag, ret;
  232. if(get_bits1(gb)) { // frameLengthFlag
  233. av_log_missing_feature(ac->avccontext, "960/120 MDCT window is", 1);
  234. return -1;
  235. }
  236. if (get_bits1(gb)) // dependsOnCoreCoder
  237. skip_bits(gb, 14); // coreCoderDelay
  238. extension_flag = get_bits1(gb);
  239. if(ac->m4ac.object_type == AOT_AAC_SCALABLE ||
  240. ac->m4ac.object_type == AOT_ER_AAC_SCALABLE)
  241. skip_bits(gb, 3); // layerNr
  242. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  243. if (channel_config == 0) {
  244. skip_bits(gb, 4); // element_instance_tag
  245. if((ret = decode_pce(ac, new_che_pos, gb)))
  246. return ret;
  247. } else {
  248. if((ret = set_default_channel_config(ac, new_che_pos, channel_config)))
  249. return ret;
  250. }
  251. if((ret = output_configure(ac, ac->che_pos, new_che_pos)))
  252. return ret;
  253. if (extension_flag) {
  254. switch (ac->m4ac.object_type) {
  255. case AOT_ER_BSAC:
  256. skip_bits(gb, 5); // numOfSubFrame
  257. skip_bits(gb, 11); // layer_length
  258. break;
  259. case AOT_ER_AAC_LC:
  260. case AOT_ER_AAC_LTP:
  261. case AOT_ER_AAC_SCALABLE:
  262. case AOT_ER_AAC_LD:
  263. skip_bits(gb, 3); /* aacSectionDataResilienceFlag
  264. * aacScalefactorDataResilienceFlag
  265. * aacSpectralDataResilienceFlag
  266. */
  267. break;
  268. }
  269. skip_bits1(gb); // extensionFlag3 (TBD in version 3)
  270. }
  271. return 0;
  272. }
  273. /**
  274. * Decode audio specific configuration; reference: table 1.13.
  275. *
  276. * @param data pointer to AVCodecContext extradata
  277. * @param data_size size of AVCCodecContext extradata
  278. *
  279. * @return Returns error status. 0 - OK, !0 - error
  280. */
  281. static int decode_audio_specific_config(AACContext * ac, void *data, int data_size) {
  282. GetBitContext gb;
  283. int i;
  284. init_get_bits(&gb, data, data_size * 8);
  285. if((i = ff_mpeg4audio_get_config(&ac->m4ac, data, data_size)) < 0)
  286. return -1;
  287. if(ac->m4ac.sampling_index > 11) {
  288. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  289. return -1;
  290. }
  291. skip_bits_long(&gb, i);
  292. switch (ac->m4ac.object_type) {
  293. case AOT_AAC_LC:
  294. if (decode_ga_specific_config(ac, &gb, ac->m4ac.chan_config))
  295. return -1;
  296. break;
  297. default:
  298. av_log(ac->avccontext, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
  299. ac->m4ac.sbr == 1? "SBR+" : "", ac->m4ac.object_type);
  300. return -1;
  301. }
  302. return 0;
  303. }
  304. /**
  305. * linear congruential pseudorandom number generator
  306. *
  307. * @param previous_val pointer to the current state of the generator
  308. *
  309. * @return Returns a 32-bit pseudorandom integer
  310. */
  311. static av_always_inline int lcg_random(int previous_val) {
  312. return previous_val * 1664525 + 1013904223;
  313. }
  314. static av_cold int aac_decode_init(AVCodecContext * avccontext) {
  315. AACContext * ac = avccontext->priv_data;
  316. int i;
  317. ac->avccontext = avccontext;
  318. if (avccontext->extradata_size <= 0 ||
  319. decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))
  320. return -1;
  321. avccontext->sample_fmt = SAMPLE_FMT_S16;
  322. avccontext->sample_rate = ac->m4ac.sample_rate;
  323. avccontext->frame_size = 1024;
  324. AAC_INIT_VLC_STATIC( 0, 144);
  325. AAC_INIT_VLC_STATIC( 1, 114);
  326. AAC_INIT_VLC_STATIC( 2, 188);
  327. AAC_INIT_VLC_STATIC( 3, 180);
  328. AAC_INIT_VLC_STATIC( 4, 172);
  329. AAC_INIT_VLC_STATIC( 5, 140);
  330. AAC_INIT_VLC_STATIC( 6, 168);
  331. AAC_INIT_VLC_STATIC( 7, 114);
  332. AAC_INIT_VLC_STATIC( 8, 262);
  333. AAC_INIT_VLC_STATIC( 9, 248);
  334. AAC_INIT_VLC_STATIC(10, 384);
  335. dsputil_init(&ac->dsp, avccontext);
  336. ac->random_state = 0x1f2e3d4c;
  337. // -1024 - Compensate wrong IMDCT method.
  338. // 32768 - Required to scale values to the correct range for the bias method
  339. // for float to int16 conversion.
  340. if(ac->dsp.float_to_int16 == ff_float_to_int16_c) {
  341. ac->add_bias = 385.0f;
  342. ac->sf_scale = 1. / (-1024. * 32768.);
  343. ac->sf_offset = 0;
  344. } else {
  345. ac->add_bias = 0.0f;
  346. ac->sf_scale = 1. / -1024.;
  347. ac->sf_offset = 60;
  348. }
  349. #ifndef CONFIG_HARDCODED_TABLES
  350. for (i = 0; i < 316; i++)
  351. ff_aac_pow2sf_tab[i] = pow(2, (i - 200)/4.);
  352. #endif /* CONFIG_HARDCODED_TABLES */
  353. INIT_VLC_STATIC(&vlc_scalefactors, 7, sizeof(ff_aac_scalefactor_code)/sizeof(ff_aac_scalefactor_code[0]),
  354. ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
  355. ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
  356. 352);
  357. ff_mdct_init(&ac->mdct, 11, 1);
  358. ff_mdct_init(&ac->mdct_small, 8, 1);
  359. // window initialization
  360. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  361. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  362. ff_sine_window_init(ff_sine_1024, 1024);
  363. ff_sine_window_init(ff_sine_128, 128);
  364. return 0;
  365. }
  366. /**
  367. * Skip data_stream_element; reference: table 4.10.
  368. */
  369. static void skip_data_stream_element(GetBitContext * gb) {
  370. int byte_align = get_bits1(gb);
  371. int count = get_bits(gb, 8);
  372. if (count == 255)
  373. count += get_bits(gb, 8);
  374. if (byte_align)
  375. align_get_bits(gb);
  376. skip_bits_long(gb, 8 * count);
  377. }
  378. /**
  379. * Decode Individual Channel Stream info; reference: table 4.6.
  380. *
  381. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  382. */
  383. static int decode_ics_info(AACContext * ac, IndividualChannelStream * ics, GetBitContext * gb, int common_window) {
  384. if (get_bits1(gb)) {
  385. av_log(ac->avccontext, AV_LOG_ERROR, "Reserved bit set.\n");
  386. memset(ics, 0, sizeof(IndividualChannelStream));
  387. return -1;
  388. }
  389. ics->window_sequence[1] = ics->window_sequence[0];
  390. ics->window_sequence[0] = get_bits(gb, 2);
  391. ics->use_kb_window[1] = ics->use_kb_window[0];
  392. ics->use_kb_window[0] = get_bits1(gb);
  393. ics->num_window_groups = 1;
  394. ics->group_len[0] = 1;
  395. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  396. int i;
  397. ics->max_sfb = get_bits(gb, 4);
  398. for (i = 0; i < 7; i++) {
  399. if (get_bits1(gb)) {
  400. ics->group_len[ics->num_window_groups-1]++;
  401. } else {
  402. ics->num_window_groups++;
  403. ics->group_len[ics->num_window_groups-1] = 1;
  404. }
  405. }
  406. ics->num_windows = 8;
  407. ics->swb_offset = swb_offset_128[ac->m4ac.sampling_index];
  408. ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
  409. ics->tns_max_bands = tns_max_bands_128[ac->m4ac.sampling_index];
  410. } else {
  411. ics->max_sfb = get_bits(gb, 6);
  412. ics->num_windows = 1;
  413. ics->swb_offset = swb_offset_1024[ac->m4ac.sampling_index];
  414. ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
  415. ics->tns_max_bands = tns_max_bands_1024[ac->m4ac.sampling_index];
  416. if (get_bits1(gb)) {
  417. av_log_missing_feature(ac->avccontext, "Predictor bit set but LTP is", 1);
  418. memset(ics, 0, sizeof(IndividualChannelStream));
  419. return -1;
  420. }
  421. }
  422. if(ics->max_sfb > ics->num_swb) {
  423. av_log(ac->avccontext, AV_LOG_ERROR,
  424. "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
  425. ics->max_sfb, ics->num_swb);
  426. memset(ics, 0, sizeof(IndividualChannelStream));
  427. return -1;
  428. }
  429. return 0;
  430. }
  431. /**
  432. * Decode band types (section_data payload); reference: table 4.46.
  433. *
  434. * @param band_type array of the used band type
  435. * @param band_type_run_end array of the last scalefactor band of a band type run
  436. *
  437. * @return Returns error status. 0 - OK, !0 - error
  438. */
  439. static int decode_band_types(AACContext * ac, enum BandType band_type[120],
  440. int band_type_run_end[120], GetBitContext * gb, IndividualChannelStream * ics) {
  441. int g, idx = 0;
  442. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  443. for (g = 0; g < ics->num_window_groups; g++) {
  444. int k = 0;
  445. while (k < ics->max_sfb) {
  446. uint8_t sect_len = k;
  447. int sect_len_incr;
  448. int sect_band_type = get_bits(gb, 4);
  449. if (sect_band_type == 12) {
  450. av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
  451. return -1;
  452. }
  453. while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits)-1)
  454. sect_len += sect_len_incr;
  455. sect_len += sect_len_incr;
  456. if (sect_len > ics->max_sfb) {
  457. av_log(ac->avccontext, AV_LOG_ERROR,
  458. "Number of bands (%d) exceeds limit (%d).\n",
  459. sect_len, ics->max_sfb);
  460. return -1;
  461. }
  462. for (; k < sect_len; k++) {
  463. band_type [idx] = sect_band_type;
  464. band_type_run_end[idx++] = sect_len;
  465. }
  466. }
  467. }
  468. return 0;
  469. }
  470. /**
  471. * Decode scalefactors; reference: table 4.47.
  472. *
  473. * @param global_gain first scalefactor value as scalefactors are differentially coded
  474. * @param band_type array of the used band type
  475. * @param band_type_run_end array of the last scalefactor band of a band type run
  476. * @param sf array of scalefactors or intensity stereo positions
  477. *
  478. * @return Returns error status. 0 - OK, !0 - error
  479. */
  480. static int decode_scalefactors(AACContext * ac, float sf[120], GetBitContext * gb,
  481. unsigned int global_gain, IndividualChannelStream * ics,
  482. enum BandType band_type[120], int band_type_run_end[120]) {
  483. const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
  484. int g, i, idx = 0;
  485. int offset[3] = { global_gain, global_gain - 90, 100 };
  486. int noise_flag = 1;
  487. static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
  488. for (g = 0; g < ics->num_window_groups; g++) {
  489. for (i = 0; i < ics->max_sfb;) {
  490. int run_end = band_type_run_end[idx];
  491. if (band_type[idx] == ZERO_BT) {
  492. for(; i < run_end; i++, idx++)
  493. sf[idx] = 0.;
  494. }else if((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
  495. for(; i < run_end; i++, idx++) {
  496. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  497. if(offset[2] > 255U) {
  498. av_log(ac->avccontext, AV_LOG_ERROR,
  499. "%s (%d) out of range.\n", sf_str[2], offset[2]);
  500. return -1;
  501. }
  502. sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
  503. }
  504. }else if(band_type[idx] == NOISE_BT) {
  505. for(; i < run_end; i++, idx++) {
  506. if(noise_flag-- > 0)
  507. offset[1] += get_bits(gb, 9) - 256;
  508. else
  509. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  510. if(offset[1] > 255U) {
  511. av_log(ac->avccontext, AV_LOG_ERROR,
  512. "%s (%d) out of range.\n", sf_str[1], offset[1]);
  513. return -1;
  514. }
  515. sf[idx] = -ff_aac_pow2sf_tab[ offset[1] + sf_offset];
  516. }
  517. }else {
  518. for(; i < run_end; i++, idx++) {
  519. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  520. if(offset[0] > 255U) {
  521. av_log(ac->avccontext, AV_LOG_ERROR,
  522. "%s (%d) out of range.\n", sf_str[0], offset[0]);
  523. return -1;
  524. }
  525. sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
  526. }
  527. }
  528. }
  529. }
  530. return 0;
  531. }
  532. /**
  533. * Decode pulse data; reference: table 4.7.
  534. */
  535. static void decode_pulses(Pulse * pulse, GetBitContext * gb, const uint16_t * swb_offset) {
  536. int i;
  537. pulse->num_pulse = get_bits(gb, 2) + 1;
  538. pulse->pos[0] = get_bits(gb, 5) + swb_offset[get_bits(gb, 6)];
  539. pulse->amp[0] = get_bits(gb, 4);
  540. for (i = 1; i < pulse->num_pulse; i++) {
  541. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i-1];
  542. pulse->amp[i] = get_bits(gb, 4);
  543. }
  544. }
  545. /**
  546. * Decode Mid/Side data; reference: table 4.54.
  547. *
  548. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  549. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  550. * [3] reserved for scalable AAC
  551. */
  552. static void decode_mid_side_stereo(ChannelElement * cpe, GetBitContext * gb,
  553. int ms_present) {
  554. int idx;
  555. if (ms_present == 1) {
  556. for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
  557. cpe->ms_mask[idx] = get_bits1(gb);
  558. } else if (ms_present == 2) {
  559. memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
  560. }
  561. }
  562. /**
  563. * Decode spectral data; reference: table 4.50.
  564. * Dequantize and scale spectral data; reference: 4.6.3.3.
  565. *
  566. * @param coef array of dequantized, scaled spectral data
  567. * @param sf array of scalefactors or intensity stereo positions
  568. * @param pulse_present set if pulses are present
  569. * @param pulse pointer to pulse data struct
  570. * @param band_type array of the used band type
  571. *
  572. * @return Returns error status. 0 - OK, !0 - error
  573. */
  574. static int decode_spectrum_and_dequant(AACContext * ac, float coef[1024], GetBitContext * gb, float sf[120],
  575. int pulse_present, const Pulse * pulse, const IndividualChannelStream * ics, enum BandType band_type[120]) {
  576. int i, k, g, idx = 0;
  577. const int c = 1024/ics->num_windows;
  578. const uint16_t * offsets = ics->swb_offset;
  579. float *coef_base = coef;
  580. for (g = 0; g < ics->num_windows; g++)
  581. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float)*(c - offsets[ics->max_sfb]));
  582. for (g = 0; g < ics->num_window_groups; g++) {
  583. for (i = 0; i < ics->max_sfb; i++, idx++) {
  584. const int cur_band_type = band_type[idx];
  585. const int dim = cur_band_type >= FIRST_PAIR_BT ? 2 : 4;
  586. const int is_cb_unsigned = IS_CODEBOOK_UNSIGNED(cur_band_type);
  587. int group;
  588. if (cur_band_type == ZERO_BT) {
  589. for (group = 0; group < ics->group_len[g]; group++) {
  590. memset(coef + group * 128 + offsets[i], 0, (offsets[i+1] - offsets[i])*sizeof(float));
  591. }
  592. }else if (cur_band_type == NOISE_BT) {
  593. const float scale = sf[idx] / ((offsets[i+1] - offsets[i]) * PNS_MEAN_ENERGY);
  594. for (group = 0; group < ics->group_len[g]; group++) {
  595. for (k = offsets[i]; k < offsets[i+1]; k++) {
  596. ac->random_state = lcg_random(ac->random_state);
  597. coef[group*128+k] = ac->random_state * scale;
  598. }
  599. }
  600. }else if (cur_band_type != INTENSITY_BT2 && cur_band_type != INTENSITY_BT) {
  601. for (group = 0; group < ics->group_len[g]; group++) {
  602. for (k = offsets[i]; k < offsets[i+1]; k += dim) {
  603. const int index = get_vlc2(gb, vlc_spectral[cur_band_type - 1].table, 6, 3);
  604. const int coef_tmp_idx = (group << 7) + k;
  605. const float *vq_ptr;
  606. int j;
  607. if(index >= ff_aac_spectral_sizes[cur_band_type - 1]) {
  608. av_log(ac->avccontext, AV_LOG_ERROR,
  609. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  610. cur_band_type - 1, index, ff_aac_spectral_sizes[cur_band_type - 1]);
  611. return -1;
  612. }
  613. vq_ptr = &ff_aac_codebook_vectors[cur_band_type - 1][index * dim];
  614. if (is_cb_unsigned) {
  615. for (j = 0; j < dim; j++)
  616. if (vq_ptr[j])
  617. coef[coef_tmp_idx + j] = 1 - 2*(int)get_bits1(gb);
  618. }else {
  619. for (j = 0; j < dim; j++)
  620. coef[coef_tmp_idx + j] = 1.0f;
  621. }
  622. if (cur_band_type == ESC_BT) {
  623. for (j = 0; j < 2; j++) {
  624. if (vq_ptr[j] == 64.0f) {
  625. int n = 4;
  626. /* The total length of escape_sequence must be < 22 bits according
  627. to the specification (i.e. max is 11111111110xxxxxxxxxx). */
  628. while (get_bits1(gb) && n < 15) n++;
  629. if(n == 15) {
  630. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  631. return -1;
  632. }
  633. n = (1<<n) + get_bits(gb, n);
  634. coef[coef_tmp_idx + j] *= cbrtf(fabsf(n)) * n;
  635. }else
  636. coef[coef_tmp_idx + j] *= vq_ptr[j];
  637. }
  638. }else
  639. for (j = 0; j < dim; j++)
  640. coef[coef_tmp_idx + j] *= vq_ptr[j];
  641. for (j = 0; j < dim; j++)
  642. coef[coef_tmp_idx + j] *= sf[idx];
  643. }
  644. }
  645. }
  646. }
  647. coef += ics->group_len[g]<<7;
  648. }
  649. if (pulse_present) {
  650. for(i = 0; i < pulse->num_pulse; i++){
  651. float co = coef_base[ pulse->pos[i] ];
  652. float ico = co / sqrtf(sqrtf(fabsf(co))) + pulse->amp[i];
  653. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico;
  654. }
  655. }
  656. return 0;
  657. }
  658. /**
  659. * Decode an individual_channel_stream payload; reference: table 4.44.
  660. *
  661. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  662. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  663. *
  664. * @return Returns error status. 0 - OK, !0 - error
  665. */
  666. static int decode_ics(AACContext * ac, SingleChannelElement * sce, GetBitContext * gb, int common_window, int scale_flag) {
  667. Pulse pulse;
  668. TemporalNoiseShaping * tns = &sce->tns;
  669. IndividualChannelStream * ics = &sce->ics;
  670. float * out = sce->coeffs;
  671. int global_gain, pulse_present = 0;
  672. /* This assignment is to silence a GCC warning about the variable being used
  673. * uninitialized when in fact it always is.
  674. */
  675. pulse.num_pulse = 0;
  676. global_gain = get_bits(gb, 8);
  677. if (!common_window && !scale_flag) {
  678. if (decode_ics_info(ac, ics, gb, 0) < 0)
  679. return -1;
  680. }
  681. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  682. return -1;
  683. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  684. return -1;
  685. pulse_present = 0;
  686. if (!scale_flag) {
  687. if ((pulse_present = get_bits1(gb))) {
  688. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  689. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  690. return -1;
  691. }
  692. decode_pulses(&pulse, gb, ics->swb_offset);
  693. }
  694. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  695. return -1;
  696. if (get_bits1(gb)) {
  697. av_log_missing_feature(ac->avccontext, "SSR", 1);
  698. return -1;
  699. }
  700. }
  701. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  702. return -1;
  703. return 0;
  704. }
  705. /**
  706. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  707. */
  708. static void apply_mid_side_stereo(ChannelElement * cpe) {
  709. const IndividualChannelStream * ics = &cpe->ch[0].ics;
  710. float *ch0 = cpe->ch[0].coeffs;
  711. float *ch1 = cpe->ch[1].coeffs;
  712. int g, i, k, group, idx = 0;
  713. const uint16_t * offsets = ics->swb_offset;
  714. for (g = 0; g < ics->num_window_groups; g++) {
  715. for (i = 0; i < ics->max_sfb; i++, idx++) {
  716. if (cpe->ms_mask[idx] &&
  717. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  718. for (group = 0; group < ics->group_len[g]; group++) {
  719. for (k = offsets[i]; k < offsets[i+1]; k++) {
  720. float tmp = ch0[group*128 + k] - ch1[group*128 + k];
  721. ch0[group*128 + k] += ch1[group*128 + k];
  722. ch1[group*128 + k] = tmp;
  723. }
  724. }
  725. }
  726. }
  727. ch0 += ics->group_len[g]*128;
  728. ch1 += ics->group_len[g]*128;
  729. }
  730. }
  731. /**
  732. * intensity stereo decoding; reference: 4.6.8.2.3
  733. *
  734. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  735. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  736. * [3] reserved for scalable AAC
  737. */
  738. static void apply_intensity_stereo(ChannelElement * cpe, int ms_present) {
  739. const IndividualChannelStream * ics = &cpe->ch[1].ics;
  740. SingleChannelElement * sce1 = &cpe->ch[1];
  741. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  742. const uint16_t * offsets = ics->swb_offset;
  743. int g, group, i, k, idx = 0;
  744. int c;
  745. float scale;
  746. for (g = 0; g < ics->num_window_groups; g++) {
  747. for (i = 0; i < ics->max_sfb;) {
  748. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  749. const int bt_run_end = sce1->band_type_run_end[idx];
  750. for (; i < bt_run_end; i++, idx++) {
  751. c = -1 + 2 * (sce1->band_type[idx] - 14);
  752. if (ms_present)
  753. c *= 1 - 2 * cpe->ms_mask[idx];
  754. scale = c * sce1->sf[idx];
  755. for (group = 0; group < ics->group_len[g]; group++)
  756. for (k = offsets[i]; k < offsets[i+1]; k++)
  757. coef1[group*128 + k] = scale * coef0[group*128 + k];
  758. }
  759. } else {
  760. int bt_run_end = sce1->band_type_run_end[idx];
  761. idx += bt_run_end - i;
  762. i = bt_run_end;
  763. }
  764. }
  765. coef0 += ics->group_len[g]*128;
  766. coef1 += ics->group_len[g]*128;
  767. }
  768. }
  769. /**
  770. * Decode a channel_pair_element; reference: table 4.4.
  771. *
  772. * @param elem_id Identifies the instance of a syntax element.
  773. *
  774. * @return Returns error status. 0 - OK, !0 - error
  775. */
  776. static int decode_cpe(AACContext * ac, GetBitContext * gb, int elem_id) {
  777. int i, ret, common_window, ms_present = 0;
  778. ChannelElement * cpe;
  779. cpe = ac->che[TYPE_CPE][elem_id];
  780. common_window = get_bits1(gb);
  781. if (common_window) {
  782. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  783. return -1;
  784. i = cpe->ch[1].ics.use_kb_window[0];
  785. cpe->ch[1].ics = cpe->ch[0].ics;
  786. cpe->ch[1].ics.use_kb_window[1] = i;
  787. ms_present = get_bits(gb, 2);
  788. if(ms_present == 3) {
  789. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  790. return -1;
  791. } else if(ms_present)
  792. decode_mid_side_stereo(cpe, gb, ms_present);
  793. }
  794. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  795. return ret;
  796. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  797. return ret;
  798. if (common_window && ms_present)
  799. apply_mid_side_stereo(cpe);
  800. apply_intensity_stereo(cpe, ms_present);
  801. return 0;
  802. }
  803. /**
  804. * Decode coupling_channel_element; reference: table 4.8.
  805. *
  806. * @param elem_id Identifies the instance of a syntax element.
  807. *
  808. * @return Returns error status. 0 - OK, !0 - error
  809. */
  810. static int decode_cce(AACContext * ac, GetBitContext * gb, ChannelElement * che) {
  811. int num_gain = 0;
  812. int c, g, sfb, ret, idx = 0;
  813. int sign;
  814. float scale;
  815. SingleChannelElement * sce = &che->ch[0];
  816. ChannelCoupling * coup = &che->coup;
  817. coup->coupling_point = 2*get_bits1(gb);
  818. coup->num_coupled = get_bits(gb, 3);
  819. for (c = 0; c <= coup->num_coupled; c++) {
  820. num_gain++;
  821. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  822. coup->id_select[c] = get_bits(gb, 4);
  823. if (coup->type[c] == TYPE_CPE) {
  824. coup->ch_select[c] = get_bits(gb, 2);
  825. if (coup->ch_select[c] == 3)
  826. num_gain++;
  827. } else
  828. coup->ch_select[c] = 1;
  829. }
  830. coup->coupling_point += get_bits1(gb);
  831. if (coup->coupling_point == 2) {
  832. av_log(ac->avccontext, AV_LOG_ERROR,
  833. "Independently switched CCE with 'invalid' domain signalled.\n");
  834. memset(coup, 0, sizeof(ChannelCoupling));
  835. return -1;
  836. }
  837. sign = get_bits(gb, 1);
  838. scale = pow(2., pow(2., get_bits(gb, 2) - 3));
  839. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  840. return ret;
  841. for (c = 0; c < num_gain; c++) {
  842. int cge = 1;
  843. int gain = 0;
  844. float gain_cache = 1.;
  845. if (c) {
  846. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  847. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  848. gain_cache = pow(scale, gain);
  849. }
  850. for (g = 0; g < sce->ics.num_window_groups; g++)
  851. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++)
  852. if (sce->band_type[idx] != ZERO_BT) {
  853. if (!cge) {
  854. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  855. if (t) {
  856. int s = 1;
  857. if (sign) {
  858. s -= 2 * (t & 0x1);
  859. t >>= 1;
  860. }
  861. gain += t;
  862. gain_cache = pow(scale, gain) * s;
  863. }
  864. }
  865. coup->gain[c][idx] = gain_cache;
  866. }
  867. }
  868. return 0;
  869. }
  870. /**
  871. * Decode Spectral Band Replication extension data; reference: table 4.55.
  872. *
  873. * @param crc flag indicating the presence of CRC checksum
  874. * @param cnt length of TYPE_FIL syntactic element in bytes
  875. *
  876. * @return Returns number of bytes consumed from the TYPE_FIL element.
  877. */
  878. static int decode_sbr_extension(AACContext * ac, GetBitContext * gb, int crc, int cnt) {
  879. // TODO : sbr_extension implementation
  880. av_log_missing_feature(ac->avccontext, "SBR", 0);
  881. skip_bits_long(gb, 8*cnt - 4); // -4 due to reading extension type
  882. return cnt;
  883. }
  884. /**
  885. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  886. *
  887. * @return Returns number of bytes consumed.
  888. */
  889. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc, GetBitContext * gb) {
  890. int i;
  891. int num_excl_chan = 0;
  892. do {
  893. for (i = 0; i < 7; i++)
  894. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  895. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  896. return num_excl_chan / 7;
  897. }
  898. /**
  899. * Decode dynamic range information; reference: table 4.52.
  900. *
  901. * @param cnt length of TYPE_FIL syntactic element in bytes
  902. *
  903. * @return Returns number of bytes consumed.
  904. */
  905. static int decode_dynamic_range(DynamicRangeControl *che_drc, GetBitContext * gb, int cnt) {
  906. int n = 1;
  907. int drc_num_bands = 1;
  908. int i;
  909. /* pce_tag_present? */
  910. if(get_bits1(gb)) {
  911. che_drc->pce_instance_tag = get_bits(gb, 4);
  912. skip_bits(gb, 4); // tag_reserved_bits
  913. n++;
  914. }
  915. /* excluded_chns_present? */
  916. if(get_bits1(gb)) {
  917. n += decode_drc_channel_exclusions(che_drc, gb);
  918. }
  919. /* drc_bands_present? */
  920. if (get_bits1(gb)) {
  921. che_drc->band_incr = get_bits(gb, 4);
  922. che_drc->interpolation_scheme = get_bits(gb, 4);
  923. n++;
  924. drc_num_bands += che_drc->band_incr;
  925. for (i = 0; i < drc_num_bands; i++) {
  926. che_drc->band_top[i] = get_bits(gb, 8);
  927. n++;
  928. }
  929. }
  930. /* prog_ref_level_present? */
  931. if (get_bits1(gb)) {
  932. che_drc->prog_ref_level = get_bits(gb, 7);
  933. skip_bits1(gb); // prog_ref_level_reserved_bits
  934. n++;
  935. }
  936. for (i = 0; i < drc_num_bands; i++) {
  937. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  938. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  939. n++;
  940. }
  941. return n;
  942. }
  943. /**
  944. * Decode extension data (incomplete); reference: table 4.51.
  945. *
  946. * @param cnt length of TYPE_FIL syntactic element in bytes
  947. *
  948. * @return Returns number of bytes consumed
  949. */
  950. static int decode_extension_payload(AACContext * ac, GetBitContext * gb, int cnt) {
  951. int crc_flag = 0;
  952. int res = cnt;
  953. switch (get_bits(gb, 4)) { // extension type
  954. case EXT_SBR_DATA_CRC:
  955. crc_flag++;
  956. case EXT_SBR_DATA:
  957. res = decode_sbr_extension(ac, gb, crc_flag, cnt);
  958. break;
  959. case EXT_DYNAMIC_RANGE:
  960. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  961. break;
  962. case EXT_FILL:
  963. case EXT_FILL_DATA:
  964. case EXT_DATA_ELEMENT:
  965. default:
  966. skip_bits_long(gb, 8*cnt - 4);
  967. break;
  968. };
  969. return res;
  970. }
  971. /**
  972. * Conduct IMDCT and windowing.
  973. */
  974. static void imdct_and_windowing(AACContext * ac, SingleChannelElement * sce) {
  975. IndividualChannelStream * ics = &sce->ics;
  976. float * in = sce->coeffs;
  977. float * out = sce->ret;
  978. float * saved = sce->saved;
  979. const float * lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  980. const float * swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  981. const float * lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  982. const float * swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  983. float * buf = ac->buf_mdct;
  984. int i;
  985. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  986. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  987. av_log(ac->avccontext, AV_LOG_WARNING,
  988. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  989. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  990. for (i = 0; i < 2048; i += 256) {
  991. ff_imdct_calc(&ac->mdct_small, buf + i, in + i/2);
  992. ac->dsp.vector_fmul_reverse(ac->revers + i/2, buf + i + 128, swindow, 128);
  993. }
  994. for (i = 0; i < 448; i++) out[i] = saved[i] + ac->add_bias;
  995. ac->dsp.vector_fmul_add_add(out + 448 + 0*128, buf + 0*128, swindow_prev, saved + 448 , ac->add_bias, 128, 1);
  996. ac->dsp.vector_fmul_add_add(out + 448 + 1*128, buf + 2*128, swindow, ac->revers + 0*128, ac->add_bias, 128, 1);
  997. ac->dsp.vector_fmul_add_add(out + 448 + 2*128, buf + 4*128, swindow, ac->revers + 1*128, ac->add_bias, 128, 1);
  998. ac->dsp.vector_fmul_add_add(out + 448 + 3*128, buf + 6*128, swindow, ac->revers + 2*128, ac->add_bias, 128, 1);
  999. ac->dsp.vector_fmul_add_add(out + 448 + 4*128, buf + 8*128, swindow, ac->revers + 3*128, ac->add_bias, 64, 1);
  1000. #if 0
  1001. vector_fmul_add_add_add(&ac->dsp, out + 448 + 1*128, buf + 2*128, swindow, saved + 448 + 1*128, ac->revers + 0*128, ac->add_bias, 128);
  1002. vector_fmul_add_add_add(&ac->dsp, out + 448 + 2*128, buf + 4*128, swindow, saved + 448 + 2*128, ac->revers + 1*128, ac->add_bias, 128);
  1003. vector_fmul_add_add_add(&ac->dsp, out + 448 + 3*128, buf + 6*128, swindow, saved + 448 + 3*128, ac->revers + 2*128, ac->add_bias, 128);
  1004. vector_fmul_add_add_add(&ac->dsp, out + 448 + 4*128, buf + 8*128, swindow, saved + 448 + 4*128, ac->revers + 3*128, ac->add_bias, 64);
  1005. #endif
  1006. ac->dsp.vector_fmul_add_add(saved, buf + 1024 + 64, swindow + 64, ac->revers + 3*128+64, 0, 64, 1);
  1007. ac->dsp.vector_fmul_add_add(saved + 64, buf + 1024 + 2*128, swindow, ac->revers + 4*128, 0, 128, 1);
  1008. ac->dsp.vector_fmul_add_add(saved + 192, buf + 1024 + 4*128, swindow, ac->revers + 5*128, 0, 128, 1);
  1009. ac->dsp.vector_fmul_add_add(saved + 320, buf + 1024 + 6*128, swindow, ac->revers + 6*128, 0, 128, 1);
  1010. memcpy( saved + 448, ac->revers + 7*128, 128 * sizeof(float));
  1011. memset( saved + 576, 0, 448 * sizeof(float));
  1012. } else {
  1013. ff_imdct_calc(&ac->mdct, buf, in);
  1014. if (ics->window_sequence[0] == LONG_STOP_SEQUENCE) {
  1015. for (i = 0; i < 448; i++) out[i] = saved[i] + ac->add_bias;
  1016. ac->dsp.vector_fmul_add_add(out + 448, buf + 448, swindow_prev, saved + 448, ac->add_bias, 128, 1);
  1017. for (i = 576; i < 1024; i++) out[i] = buf[i] + saved[i] + ac->add_bias;
  1018. } else {
  1019. ac->dsp.vector_fmul_add_add(out, buf, lwindow_prev, saved, ac->add_bias, 1024, 1);
  1020. }
  1021. if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1022. memcpy(saved, buf + 1024, 448 * sizeof(float));
  1023. ac->dsp.vector_fmul_reverse(saved + 448, buf + 1024 + 448, swindow, 128);
  1024. memset(saved + 576, 0, 448 * sizeof(float));
  1025. } else {
  1026. ac->dsp.vector_fmul_reverse(saved, buf + 1024, lwindow, 1024);
  1027. }
  1028. }
  1029. }
  1030. /**
  1031. * Apply dependent channel coupling (applied before IMDCT).
  1032. *
  1033. * @param index index into coupling gain array
  1034. */
  1035. static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
  1036. IndividualChannelStream * ics = &cc->ch[0].ics;
  1037. const uint16_t * offsets = ics->swb_offset;
  1038. float * dest = sce->coeffs;
  1039. const float * src = cc->ch[0].coeffs;
  1040. int g, i, group, k, idx = 0;
  1041. if(ac->m4ac.object_type == AOT_AAC_LTP) {
  1042. av_log(ac->avccontext, AV_LOG_ERROR,
  1043. "Dependent coupling is not supported together with LTP\n");
  1044. return;
  1045. }
  1046. for (g = 0; g < ics->num_window_groups; g++) {
  1047. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1048. if (cc->ch[0].band_type[idx] != ZERO_BT) {
  1049. for (group = 0; group < ics->group_len[g]; group++) {
  1050. for (k = offsets[i]; k < offsets[i+1]; k++) {
  1051. // XXX dsputil-ize
  1052. dest[group*128+k] += cc->coup.gain[index][idx] * src[group*128+k];
  1053. }
  1054. }
  1055. }
  1056. }
  1057. dest += ics->group_len[g]*128;
  1058. src += ics->group_len[g]*128;
  1059. }
  1060. }
  1061. /**
  1062. * Apply independent channel coupling (applied after IMDCT).
  1063. *
  1064. * @param index index into coupling gain array
  1065. */
  1066. static void apply_independent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
  1067. int i;
  1068. for (i = 0; i < 1024; i++)
  1069. sce->ret[i] += cc->coup.gain[index][0] * (cc->ch[0].ret[i] - ac->add_bias);
  1070. }
  1071. /**
  1072. * channel coupling transformation interface
  1073. *
  1074. * @param index index into coupling gain array
  1075. * @param apply_coupling_method pointer to (in)dependent coupling function
  1076. */
  1077. static void apply_channel_coupling(AACContext * ac, ChannelElement * cc,
  1078. void (*apply_coupling_method)(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index))
  1079. {
  1080. int c;
  1081. int index = 0;
  1082. ChannelCoupling * coup = &cc->coup;
  1083. for (c = 0; c <= coup->num_coupled; c++) {
  1084. if (ac->che[coup->type[c]][coup->id_select[c]]) {
  1085. if (coup->ch_select[c] != 2) {
  1086. apply_coupling_method(ac, &ac->che[coup->type[c]][coup->id_select[c]]->ch[0], cc, index);
  1087. if (coup->ch_select[c] != 0)
  1088. index++;
  1089. }
  1090. if (coup->ch_select[c] != 1)
  1091. apply_coupling_method(ac, &ac->che[coup->type[c]][coup->id_select[c]]->ch[1], cc, index++);
  1092. } else {
  1093. av_log(ac->avccontext, AV_LOG_ERROR,
  1094. "coupling target %sE[%d] not available\n",
  1095. coup->type[c] == TYPE_CPE ? "CP" : "SC", coup->id_select[c]);
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. /**
  1101. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1102. */
  1103. static void spectral_to_sample(AACContext * ac) {
  1104. int i, type;
  1105. for (i = 0; i < MAX_ELEM_ID; i++) {
  1106. for(type = 0; type < 4; type++) {
  1107. ChannelElement *che = ac->che[type][i];
  1108. if(che) {
  1109. if(che->coup.coupling_point == BEFORE_TNS)
  1110. apply_channel_coupling(ac, che, apply_dependent_coupling);
  1111. if(che->ch[0].tns.present)
  1112. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1113. if(che->ch[1].tns.present)
  1114. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1115. if(che->coup.coupling_point == BETWEEN_TNS_AND_IMDCT)
  1116. apply_channel_coupling(ac, che, apply_dependent_coupling);
  1117. imdct_and_windowing(ac, &che->ch[0]);
  1118. if(type == TYPE_CPE)
  1119. imdct_and_windowing(ac, &che->ch[1]);
  1120. if(che->coup.coupling_point == AFTER_IMDCT)
  1121. apply_channel_coupling(ac, che, apply_independent_coupling);
  1122. }
  1123. }
  1124. }
  1125. }
  1126. static int aac_decode_frame(AVCodecContext * avccontext, void * data, int * data_size, const uint8_t * buf, int buf_size) {
  1127. AACContext * ac = avccontext->priv_data;
  1128. GetBitContext gb;
  1129. enum RawDataBlockType elem_type;
  1130. int err, elem_id, data_size_tmp;
  1131. init_get_bits(&gb, buf, buf_size*8);
  1132. // parse
  1133. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1134. elem_id = get_bits(&gb, 4);
  1135. err = -1;
  1136. if(elem_type == TYPE_SCE && elem_id == 1 &&
  1137. !ac->che[TYPE_SCE][elem_id] && ac->che[TYPE_LFE][0]) {
  1138. /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
  1139. instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
  1140. encountered such a stream, transfer the LFE[0] element to SCE[1] */
  1141. ac->che[TYPE_SCE][elem_id] = ac->che[TYPE_LFE][0];
  1142. ac->che[TYPE_LFE][0] = NULL;
  1143. }
  1144. if(elem_type && elem_type < TYPE_DSE) {
  1145. if(!ac->che[elem_type][elem_id])
  1146. return -1;
  1147. if(elem_type != TYPE_CCE)
  1148. ac->che[elem_type][elem_id]->coup.coupling_point = 4;
  1149. }
  1150. switch (elem_type) {
  1151. case TYPE_SCE:
  1152. err = decode_ics(ac, &ac->che[TYPE_SCE][elem_id]->ch[0], &gb, 0, 0);
  1153. break;
  1154. case TYPE_CPE:
  1155. err = decode_cpe(ac, &gb, elem_id);
  1156. break;
  1157. case TYPE_CCE:
  1158. err = decode_cce(ac, &gb, ac->che[TYPE_SCE][elem_id]);
  1159. break;
  1160. case TYPE_LFE:
  1161. err = decode_ics(ac, &ac->che[TYPE_LFE][elem_id]->ch[0], &gb, 0, 0);
  1162. break;
  1163. case TYPE_DSE:
  1164. skip_data_stream_element(&gb);
  1165. err = 0;
  1166. break;
  1167. case TYPE_PCE:
  1168. {
  1169. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1170. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1171. if((err = decode_pce(ac, new_che_pos, &gb)))
  1172. break;
  1173. err = output_configure(ac, ac->che_pos, new_che_pos);
  1174. break;
  1175. }
  1176. case TYPE_FIL:
  1177. if (elem_id == 15)
  1178. elem_id += get_bits(&gb, 8) - 1;
  1179. while (elem_id > 0)
  1180. elem_id -= decode_extension_payload(ac, &gb, elem_id);
  1181. err = 0; /* FIXME */
  1182. break;
  1183. default:
  1184. err = -1; /* should not happen, but keeps compiler happy */
  1185. break;
  1186. }
  1187. if(err)
  1188. return err;
  1189. }
  1190. spectral_to_sample(ac);
  1191. if (!ac->is_saved) {
  1192. ac->is_saved = 1;
  1193. *data_size = 0;
  1194. return buf_size;
  1195. }
  1196. data_size_tmp = 1024 * avccontext->channels * sizeof(int16_t);
  1197. if(*data_size < data_size_tmp) {
  1198. av_log(avccontext, AV_LOG_ERROR,
  1199. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1200. *data_size, data_size_tmp);
  1201. return -1;
  1202. }
  1203. *data_size = data_size_tmp;
  1204. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, 1024, avccontext->channels);
  1205. return buf_size;
  1206. }
  1207. static av_cold int aac_decode_close(AVCodecContext * avccontext) {
  1208. AACContext * ac = avccontext->priv_data;
  1209. int i, type;
  1210. for (i = 0; i < MAX_ELEM_ID; i++) {
  1211. for(type = 0; type < 4; type++)
  1212. av_freep(&ac->che[type][i]);
  1213. }
  1214. ff_mdct_end(&ac->mdct);
  1215. ff_mdct_end(&ac->mdct_small);
  1216. return 0 ;
  1217. }
  1218. AVCodec aac_decoder = {
  1219. "aac",
  1220. CODEC_TYPE_AUDIO,
  1221. CODEC_ID_AAC,
  1222. sizeof(AACContext),
  1223. aac_decode_init,
  1224. NULL,
  1225. aac_decode_close,
  1226. aac_decode_frame,
  1227. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1228. .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
  1229. };