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.

1456 lines
54KB

  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. * [ Center ] [ Front Left ] [ Front Right ] [ 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 Temporal Noise Shaping data; reference: table 4.48.
  547. *
  548. * @return Returns error status. 0 - OK, !0 - error
  549. */
  550. static int decode_tns(AACContext * ac, TemporalNoiseShaping * tns,
  551. GetBitContext * gb, const IndividualChannelStream * ics) {
  552. int w, filt, i, coef_len, coef_res, coef_compress;
  553. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  554. const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  555. for (w = 0; w < ics->num_windows; w++) {
  556. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  557. coef_res = get_bits1(gb);
  558. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  559. int tmp2_idx;
  560. tns->length[w][filt] = get_bits(gb, 6 - 2*is8);
  561. if ((tns->order[w][filt] = get_bits(gb, 5 - 2*is8)) > tns_max_order) {
  562. av_log(ac->avccontext, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.",
  563. tns->order[w][filt], tns_max_order);
  564. tns->order[w][filt] = 0;
  565. return -1;
  566. }
  567. tns->direction[w][filt] = get_bits1(gb);
  568. coef_compress = get_bits1(gb);
  569. coef_len = coef_res + 3 - coef_compress;
  570. tmp2_idx = 2*coef_compress + coef_res;
  571. for (i = 0; i < tns->order[w][filt]; i++)
  572. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  573. }
  574. }
  575. }
  576. return 0;
  577. }
  578. /**
  579. * Decode Mid/Side data; reference: table 4.54.
  580. *
  581. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  582. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  583. * [3] reserved for scalable AAC
  584. */
  585. static void decode_mid_side_stereo(ChannelElement * cpe, GetBitContext * gb,
  586. int ms_present) {
  587. int idx;
  588. if (ms_present == 1) {
  589. for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
  590. cpe->ms_mask[idx] = get_bits1(gb);
  591. } else if (ms_present == 2) {
  592. memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
  593. }
  594. }
  595. /**
  596. * Decode spectral data; reference: table 4.50.
  597. * Dequantize and scale spectral data; reference: 4.6.3.3.
  598. *
  599. * @param coef array of dequantized, scaled spectral data
  600. * @param sf array of scalefactors or intensity stereo positions
  601. * @param pulse_present set if pulses are present
  602. * @param pulse pointer to pulse data struct
  603. * @param band_type array of the used band type
  604. *
  605. * @return Returns error status. 0 - OK, !0 - error
  606. */
  607. static int decode_spectrum_and_dequant(AACContext * ac, float coef[1024], GetBitContext * gb, float sf[120],
  608. int pulse_present, const Pulse * pulse, const IndividualChannelStream * ics, enum BandType band_type[120]) {
  609. int i, k, g, idx = 0;
  610. const int c = 1024/ics->num_windows;
  611. const uint16_t * offsets = ics->swb_offset;
  612. float *coef_base = coef;
  613. for (g = 0; g < ics->num_windows; g++)
  614. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float)*(c - offsets[ics->max_sfb]));
  615. for (g = 0; g < ics->num_window_groups; g++) {
  616. for (i = 0; i < ics->max_sfb; i++, idx++) {
  617. const int cur_band_type = band_type[idx];
  618. const int dim = cur_band_type >= FIRST_PAIR_BT ? 2 : 4;
  619. const int is_cb_unsigned = IS_CODEBOOK_UNSIGNED(cur_band_type);
  620. int group;
  621. if (cur_band_type == ZERO_BT) {
  622. for (group = 0; group < ics->group_len[g]; group++) {
  623. memset(coef + group * 128 + offsets[i], 0, (offsets[i+1] - offsets[i])*sizeof(float));
  624. }
  625. }else if (cur_band_type == NOISE_BT) {
  626. const float scale = sf[idx] / ((offsets[i+1] - offsets[i]) * PNS_MEAN_ENERGY);
  627. for (group = 0; group < ics->group_len[g]; group++) {
  628. for (k = offsets[i]; k < offsets[i+1]; k++) {
  629. ac->random_state = lcg_random(ac->random_state);
  630. coef[group*128+k] = ac->random_state * scale;
  631. }
  632. }
  633. }else if (cur_band_type != INTENSITY_BT2 && cur_band_type != INTENSITY_BT) {
  634. for (group = 0; group < ics->group_len[g]; group++) {
  635. for (k = offsets[i]; k < offsets[i+1]; k += dim) {
  636. const int index = get_vlc2(gb, vlc_spectral[cur_band_type - 1].table, 6, 3);
  637. const int coef_tmp_idx = (group << 7) + k;
  638. const float *vq_ptr;
  639. int j;
  640. if(index >= ff_aac_spectral_sizes[cur_band_type - 1]) {
  641. av_log(ac->avccontext, AV_LOG_ERROR,
  642. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  643. cur_band_type - 1, index, ff_aac_spectral_sizes[cur_band_type - 1]);
  644. return -1;
  645. }
  646. vq_ptr = &ff_aac_codebook_vectors[cur_band_type - 1][index * dim];
  647. if (is_cb_unsigned) {
  648. for (j = 0; j < dim; j++)
  649. if (vq_ptr[j])
  650. coef[coef_tmp_idx + j] = 1 - 2*(int)get_bits1(gb);
  651. }else {
  652. for (j = 0; j < dim; j++)
  653. coef[coef_tmp_idx + j] = 1.0f;
  654. }
  655. if (cur_band_type == ESC_BT) {
  656. for (j = 0; j < 2; j++) {
  657. if (vq_ptr[j] == 64.0f) {
  658. int n = 4;
  659. /* The total length of escape_sequence must be < 22 bits according
  660. to the specification (i.e. max is 11111111110xxxxxxxxxx). */
  661. while (get_bits1(gb) && n < 15) n++;
  662. if(n == 15) {
  663. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  664. return -1;
  665. }
  666. n = (1<<n) + get_bits(gb, n);
  667. coef[coef_tmp_idx + j] *= cbrtf(fabsf(n)) * n;
  668. }else
  669. coef[coef_tmp_idx + j] *= vq_ptr[j];
  670. }
  671. }else
  672. for (j = 0; j < dim; j++)
  673. coef[coef_tmp_idx + j] *= vq_ptr[j];
  674. for (j = 0; j < dim; j++)
  675. coef[coef_tmp_idx + j] *= sf[idx];
  676. }
  677. }
  678. }
  679. }
  680. coef += ics->group_len[g]<<7;
  681. }
  682. if (pulse_present) {
  683. for(i = 0; i < pulse->num_pulse; i++){
  684. float co = coef_base[ pulse->pos[i] ];
  685. float ico = co / sqrtf(sqrtf(fabsf(co))) + pulse->amp[i];
  686. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico;
  687. }
  688. }
  689. return 0;
  690. }
  691. /**
  692. * Decode an individual_channel_stream payload; reference: table 4.44.
  693. *
  694. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  695. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  696. *
  697. * @return Returns error status. 0 - OK, !0 - error
  698. */
  699. static int decode_ics(AACContext * ac, SingleChannelElement * sce, GetBitContext * gb, int common_window, int scale_flag) {
  700. Pulse pulse;
  701. TemporalNoiseShaping * tns = &sce->tns;
  702. IndividualChannelStream * ics = &sce->ics;
  703. float * out = sce->coeffs;
  704. int global_gain, pulse_present = 0;
  705. /* This assignment is to silence a GCC warning about the variable being used
  706. * uninitialized when in fact it always is.
  707. */
  708. pulse.num_pulse = 0;
  709. global_gain = get_bits(gb, 8);
  710. if (!common_window && !scale_flag) {
  711. if (decode_ics_info(ac, ics, gb, 0) < 0)
  712. return -1;
  713. }
  714. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  715. return -1;
  716. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  717. return -1;
  718. pulse_present = 0;
  719. if (!scale_flag) {
  720. if ((pulse_present = get_bits1(gb))) {
  721. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  722. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  723. return -1;
  724. }
  725. decode_pulses(&pulse, gb, ics->swb_offset);
  726. }
  727. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  728. return -1;
  729. if (get_bits1(gb)) {
  730. av_log_missing_feature(ac->avccontext, "SSR", 1);
  731. return -1;
  732. }
  733. }
  734. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  735. return -1;
  736. return 0;
  737. }
  738. /**
  739. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  740. */
  741. static void apply_mid_side_stereo(ChannelElement * cpe) {
  742. const IndividualChannelStream * ics = &cpe->ch[0].ics;
  743. float *ch0 = cpe->ch[0].coeffs;
  744. float *ch1 = cpe->ch[1].coeffs;
  745. int g, i, k, group, idx = 0;
  746. const uint16_t * offsets = ics->swb_offset;
  747. for (g = 0; g < ics->num_window_groups; g++) {
  748. for (i = 0; i < ics->max_sfb; i++, idx++) {
  749. if (cpe->ms_mask[idx] &&
  750. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  751. for (group = 0; group < ics->group_len[g]; group++) {
  752. for (k = offsets[i]; k < offsets[i+1]; k++) {
  753. float tmp = ch0[group*128 + k] - ch1[group*128 + k];
  754. ch0[group*128 + k] += ch1[group*128 + k];
  755. ch1[group*128 + k] = tmp;
  756. }
  757. }
  758. }
  759. }
  760. ch0 += ics->group_len[g]*128;
  761. ch1 += ics->group_len[g]*128;
  762. }
  763. }
  764. /**
  765. * intensity stereo decoding; reference: 4.6.8.2.3
  766. *
  767. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  768. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  769. * [3] reserved for scalable AAC
  770. */
  771. static void apply_intensity_stereo(ChannelElement * cpe, int ms_present) {
  772. const IndividualChannelStream * ics = &cpe->ch[1].ics;
  773. SingleChannelElement * sce1 = &cpe->ch[1];
  774. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  775. const uint16_t * offsets = ics->swb_offset;
  776. int g, group, i, k, idx = 0;
  777. int c;
  778. float scale;
  779. for (g = 0; g < ics->num_window_groups; g++) {
  780. for (i = 0; i < ics->max_sfb;) {
  781. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  782. const int bt_run_end = sce1->band_type_run_end[idx];
  783. for (; i < bt_run_end; i++, idx++) {
  784. c = -1 + 2 * (sce1->band_type[idx] - 14);
  785. if (ms_present)
  786. c *= 1 - 2 * cpe->ms_mask[idx];
  787. scale = c * sce1->sf[idx];
  788. for (group = 0; group < ics->group_len[g]; group++)
  789. for (k = offsets[i]; k < offsets[i+1]; k++)
  790. coef1[group*128 + k] = scale * coef0[group*128 + k];
  791. }
  792. } else {
  793. int bt_run_end = sce1->band_type_run_end[idx];
  794. idx += bt_run_end - i;
  795. i = bt_run_end;
  796. }
  797. }
  798. coef0 += ics->group_len[g]*128;
  799. coef1 += ics->group_len[g]*128;
  800. }
  801. }
  802. /**
  803. * Decode a channel_pair_element; reference: table 4.4.
  804. *
  805. * @param elem_id Identifies the instance of a syntax element.
  806. *
  807. * @return Returns error status. 0 - OK, !0 - error
  808. */
  809. static int decode_cpe(AACContext * ac, GetBitContext * gb, int elem_id) {
  810. int i, ret, common_window, ms_present = 0;
  811. ChannelElement * cpe;
  812. cpe = ac->che[TYPE_CPE][elem_id];
  813. common_window = get_bits1(gb);
  814. if (common_window) {
  815. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  816. return -1;
  817. i = cpe->ch[1].ics.use_kb_window[0];
  818. cpe->ch[1].ics = cpe->ch[0].ics;
  819. cpe->ch[1].ics.use_kb_window[1] = i;
  820. ms_present = get_bits(gb, 2);
  821. if(ms_present == 3) {
  822. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  823. return -1;
  824. } else if(ms_present)
  825. decode_mid_side_stereo(cpe, gb, ms_present);
  826. }
  827. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  828. return ret;
  829. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  830. return ret;
  831. if (common_window && ms_present)
  832. apply_mid_side_stereo(cpe);
  833. apply_intensity_stereo(cpe, ms_present);
  834. return 0;
  835. }
  836. /**
  837. * Decode coupling_channel_element; reference: table 4.8.
  838. *
  839. * @param elem_id Identifies the instance of a syntax element.
  840. *
  841. * @return Returns error status. 0 - OK, !0 - error
  842. */
  843. static int decode_cce(AACContext * ac, GetBitContext * gb, ChannelElement * che) {
  844. int num_gain = 0;
  845. int c, g, sfb, ret, idx = 0;
  846. int sign;
  847. float scale;
  848. SingleChannelElement * sce = &che->ch[0];
  849. ChannelCoupling * coup = &che->coup;
  850. coup->coupling_point = 2*get_bits1(gb);
  851. coup->num_coupled = get_bits(gb, 3);
  852. for (c = 0; c <= coup->num_coupled; c++) {
  853. num_gain++;
  854. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  855. coup->id_select[c] = get_bits(gb, 4);
  856. if (coup->type[c] == TYPE_CPE) {
  857. coup->ch_select[c] = get_bits(gb, 2);
  858. if (coup->ch_select[c] == 3)
  859. num_gain++;
  860. } else
  861. coup->ch_select[c] = 1;
  862. }
  863. coup->coupling_point += get_bits1(gb);
  864. if (coup->coupling_point == 2) {
  865. av_log(ac->avccontext, AV_LOG_ERROR,
  866. "Independently switched CCE with 'invalid' domain signalled.\n");
  867. memset(coup, 0, sizeof(ChannelCoupling));
  868. return -1;
  869. }
  870. sign = get_bits(gb, 1);
  871. scale = pow(2., pow(2., get_bits(gb, 2) - 3));
  872. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  873. return ret;
  874. for (c = 0; c < num_gain; c++) {
  875. int cge = 1;
  876. int gain = 0;
  877. float gain_cache = 1.;
  878. if (c) {
  879. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  880. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  881. gain_cache = pow(scale, gain);
  882. }
  883. for (g = 0; g < sce->ics.num_window_groups; g++)
  884. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++)
  885. if (sce->band_type[idx] != ZERO_BT) {
  886. if (!cge) {
  887. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  888. if (t) {
  889. int s = 1;
  890. if (sign) {
  891. s -= 2 * (t & 0x1);
  892. t >>= 1;
  893. }
  894. gain += t;
  895. gain_cache = pow(scale, gain) * s;
  896. }
  897. }
  898. coup->gain[c][idx] = gain_cache;
  899. }
  900. }
  901. return 0;
  902. }
  903. /**
  904. * Decode Spectral Band Replication extension data; reference: table 4.55.
  905. *
  906. * @param crc flag indicating the presence of CRC checksum
  907. * @param cnt length of TYPE_FIL syntactic element in bytes
  908. *
  909. * @return Returns number of bytes consumed from the TYPE_FIL element.
  910. */
  911. static int decode_sbr_extension(AACContext * ac, GetBitContext * gb, int crc, int cnt) {
  912. // TODO : sbr_extension implementation
  913. av_log_missing_feature(ac->avccontext, "SBR", 0);
  914. skip_bits_long(gb, 8*cnt - 4); // -4 due to reading extension type
  915. return cnt;
  916. }
  917. /**
  918. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  919. *
  920. * @return Returns number of bytes consumed.
  921. */
  922. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc, GetBitContext * gb) {
  923. int i;
  924. int num_excl_chan = 0;
  925. do {
  926. for (i = 0; i < 7; i++)
  927. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  928. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  929. return num_excl_chan / 7;
  930. }
  931. /**
  932. * Decode dynamic range information; reference: table 4.52.
  933. *
  934. * @param cnt length of TYPE_FIL syntactic element in bytes
  935. *
  936. * @return Returns number of bytes consumed.
  937. */
  938. static int decode_dynamic_range(DynamicRangeControl *che_drc, GetBitContext * gb, int cnt) {
  939. int n = 1;
  940. int drc_num_bands = 1;
  941. int i;
  942. /* pce_tag_present? */
  943. if(get_bits1(gb)) {
  944. che_drc->pce_instance_tag = get_bits(gb, 4);
  945. skip_bits(gb, 4); // tag_reserved_bits
  946. n++;
  947. }
  948. /* excluded_chns_present? */
  949. if(get_bits1(gb)) {
  950. n += decode_drc_channel_exclusions(che_drc, gb);
  951. }
  952. /* drc_bands_present? */
  953. if (get_bits1(gb)) {
  954. che_drc->band_incr = get_bits(gb, 4);
  955. che_drc->interpolation_scheme = get_bits(gb, 4);
  956. n++;
  957. drc_num_bands += che_drc->band_incr;
  958. for (i = 0; i < drc_num_bands; i++) {
  959. che_drc->band_top[i] = get_bits(gb, 8);
  960. n++;
  961. }
  962. }
  963. /* prog_ref_level_present? */
  964. if (get_bits1(gb)) {
  965. che_drc->prog_ref_level = get_bits(gb, 7);
  966. skip_bits1(gb); // prog_ref_level_reserved_bits
  967. n++;
  968. }
  969. for (i = 0; i < drc_num_bands; i++) {
  970. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  971. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  972. n++;
  973. }
  974. return n;
  975. }
  976. /**
  977. * Decode extension data (incomplete); reference: table 4.51.
  978. *
  979. * @param cnt length of TYPE_FIL syntactic element in bytes
  980. *
  981. * @return Returns number of bytes consumed
  982. */
  983. static int decode_extension_payload(AACContext * ac, GetBitContext * gb, int cnt) {
  984. int crc_flag = 0;
  985. int res = cnt;
  986. switch (get_bits(gb, 4)) { // extension type
  987. case EXT_SBR_DATA_CRC:
  988. crc_flag++;
  989. case EXT_SBR_DATA:
  990. res = decode_sbr_extension(ac, gb, crc_flag, cnt);
  991. break;
  992. case EXT_DYNAMIC_RANGE:
  993. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  994. break;
  995. case EXT_FILL:
  996. case EXT_FILL_DATA:
  997. case EXT_DATA_ELEMENT:
  998. default:
  999. skip_bits_long(gb, 8*cnt - 4);
  1000. break;
  1001. };
  1002. return res;
  1003. }
  1004. /**
  1005. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  1006. *
  1007. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  1008. * @param coef spectral coefficients
  1009. */
  1010. static void apply_tns(float coef[1024], TemporalNoiseShaping * tns, IndividualChannelStream * ics, int decode) {
  1011. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  1012. int w, filt, m, i;
  1013. int bottom, top, order, start, end, size, inc;
  1014. float lpc[TNS_MAX_ORDER];
  1015. for (w = 0; w < ics->num_windows; w++) {
  1016. bottom = ics->num_swb;
  1017. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1018. top = bottom;
  1019. bottom = FFMAX(0, top - tns->length[w][filt]);
  1020. order = tns->order[w][filt];
  1021. if (order == 0)
  1022. continue;
  1023. /* tns_decode_coef
  1024. * FIXME: This duplicates the functionality of some double code in lpc.c.
  1025. */
  1026. for (m = 0; m < order; m++) {
  1027. float tmp;
  1028. lpc[m] = tns->coef[w][filt][m];
  1029. for (i = 0; i < m/2; i++) {
  1030. tmp = lpc[i];
  1031. lpc[i] += lpc[m] * lpc[m-1-i];
  1032. lpc[m-1-i] += lpc[m] * tmp;
  1033. }
  1034. if(m & 1)
  1035. lpc[i] += lpc[m] * lpc[i];
  1036. }
  1037. start = ics->swb_offset[FFMIN(bottom, mmm)];
  1038. end = ics->swb_offset[FFMIN( top, mmm)];
  1039. if ((size = end - start) <= 0)
  1040. continue;
  1041. if (tns->direction[w][filt]) {
  1042. inc = -1; start = end - 1;
  1043. } else {
  1044. inc = 1;
  1045. }
  1046. start += w * 128;
  1047. // ar filter
  1048. for (m = 0; m < size; m++, start += inc)
  1049. for (i = 1; i <= FFMIN(m, order); i++)
  1050. coef[start] -= coef[start - i*inc] * lpc[i-1];
  1051. }
  1052. }
  1053. }
  1054. /**
  1055. * Conduct IMDCT and windowing.
  1056. */
  1057. static void imdct_and_windowing(AACContext * ac, SingleChannelElement * sce) {
  1058. IndividualChannelStream * ics = &sce->ics;
  1059. float * in = sce->coeffs;
  1060. float * out = sce->ret;
  1061. float * saved = sce->saved;
  1062. const float * swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  1063. const float * lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  1064. const float * swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  1065. float * buf = ac->buf_mdct;
  1066. DECLARE_ALIGNED(16, float, temp[128]);
  1067. int i;
  1068. // imdct
  1069. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1070. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  1071. av_log(ac->avccontext, AV_LOG_WARNING,
  1072. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  1073. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  1074. for (i = 0; i < 1024; i += 128)
  1075. ff_imdct_half(&ac->mdct_small, buf + i, in + i);
  1076. } else
  1077. ff_imdct_half(&ac->mdct, buf, in);
  1078. /* window overlapping
  1079. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  1080. * and long to short transitions are considered to be short to short
  1081. * transitions. This leaves just two cases (long to long and short to short)
  1082. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  1083. */
  1084. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  1085. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  1086. ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, ac->add_bias, 512);
  1087. } else {
  1088. for (i = 0; i < 448; i++)
  1089. out[i] = saved[i] + ac->add_bias;
  1090. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1091. ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, ac->add_bias, 64);
  1092. ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, ac->add_bias, 64);
  1093. ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, ac->add_bias, 64);
  1094. ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, ac->add_bias, 64);
  1095. ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, ac->add_bias, 64);
  1096. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  1097. } else {
  1098. ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, ac->add_bias, 64);
  1099. for (i = 576; i < 1024; i++)
  1100. out[i] = buf[i-512] + ac->add_bias;
  1101. }
  1102. }
  1103. // buffer update
  1104. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1105. for (i = 0; i < 64; i++)
  1106. saved[i] = temp[64 + i] - ac->add_bias;
  1107. ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
  1108. ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
  1109. ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
  1110. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1111. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1112. memcpy( saved, buf + 512, 448 * sizeof(float));
  1113. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1114. } else { // LONG_STOP or ONLY_LONG
  1115. memcpy( saved, buf + 512, 512 * sizeof(float));
  1116. }
  1117. }
  1118. /**
  1119. * Apply dependent channel coupling (applied before IMDCT).
  1120. *
  1121. * @param index index into coupling gain array
  1122. */
  1123. static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
  1124. IndividualChannelStream * ics = &cc->ch[0].ics;
  1125. const uint16_t * offsets = ics->swb_offset;
  1126. float * dest = sce->coeffs;
  1127. const float * src = cc->ch[0].coeffs;
  1128. int g, i, group, k, idx = 0;
  1129. if(ac->m4ac.object_type == AOT_AAC_LTP) {
  1130. av_log(ac->avccontext, AV_LOG_ERROR,
  1131. "Dependent coupling is not supported together with LTP\n");
  1132. return;
  1133. }
  1134. for (g = 0; g < ics->num_window_groups; g++) {
  1135. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1136. if (cc->ch[0].band_type[idx] != ZERO_BT) {
  1137. for (group = 0; group < ics->group_len[g]; group++) {
  1138. for (k = offsets[i]; k < offsets[i+1]; k++) {
  1139. // XXX dsputil-ize
  1140. dest[group*128+k] += cc->coup.gain[index][idx] * src[group*128+k];
  1141. }
  1142. }
  1143. }
  1144. }
  1145. dest += ics->group_len[g]*128;
  1146. src += ics->group_len[g]*128;
  1147. }
  1148. }
  1149. /**
  1150. * Apply independent channel coupling (applied after IMDCT).
  1151. *
  1152. * @param index index into coupling gain array
  1153. */
  1154. static void apply_independent_coupling(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index) {
  1155. int i;
  1156. for (i = 0; i < 1024; i++)
  1157. sce->ret[i] += cc->coup.gain[index][0] * (cc->ch[0].ret[i] - ac->add_bias);
  1158. }
  1159. /**
  1160. * channel coupling transformation interface
  1161. *
  1162. * @param index index into coupling gain array
  1163. * @param apply_coupling_method pointer to (in)dependent coupling function
  1164. */
  1165. static void apply_channel_coupling(AACContext * ac, ChannelElement * cc,
  1166. void (*apply_coupling_method)(AACContext * ac, SingleChannelElement * sce, ChannelElement * cc, int index))
  1167. {
  1168. int c;
  1169. int index = 0;
  1170. ChannelCoupling * coup = &cc->coup;
  1171. for (c = 0; c <= coup->num_coupled; c++) {
  1172. if (ac->che[coup->type[c]][coup->id_select[c]]) {
  1173. if (coup->ch_select[c] != 2) {
  1174. apply_coupling_method(ac, &ac->che[coup->type[c]][coup->id_select[c]]->ch[0], cc, index);
  1175. if (coup->ch_select[c] != 0)
  1176. index++;
  1177. }
  1178. if (coup->ch_select[c] != 1)
  1179. apply_coupling_method(ac, &ac->che[coup->type[c]][coup->id_select[c]]->ch[1], cc, index++);
  1180. } else {
  1181. av_log(ac->avccontext, AV_LOG_ERROR,
  1182. "coupling target %sE[%d] not available\n",
  1183. coup->type[c] == TYPE_CPE ? "CP" : "SC", coup->id_select[c]);
  1184. break;
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1190. */
  1191. static void spectral_to_sample(AACContext * ac) {
  1192. int i, type;
  1193. for (i = 0; i < MAX_ELEM_ID; i++) {
  1194. for(type = 0; type < 4; type++) {
  1195. ChannelElement *che = ac->che[type][i];
  1196. if(che) {
  1197. if(che->coup.coupling_point == BEFORE_TNS)
  1198. apply_channel_coupling(ac, che, apply_dependent_coupling);
  1199. if(che->ch[0].tns.present)
  1200. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1201. if(che->ch[1].tns.present)
  1202. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1203. if(che->coup.coupling_point == BETWEEN_TNS_AND_IMDCT)
  1204. apply_channel_coupling(ac, che, apply_dependent_coupling);
  1205. imdct_and_windowing(ac, &che->ch[0]);
  1206. if(type == TYPE_CPE)
  1207. imdct_and_windowing(ac, &che->ch[1]);
  1208. if(che->coup.coupling_point == AFTER_IMDCT)
  1209. apply_channel_coupling(ac, che, apply_independent_coupling);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. static int aac_decode_frame(AVCodecContext * avccontext, void * data, int * data_size, const uint8_t * buf, int buf_size) {
  1215. AACContext * ac = avccontext->priv_data;
  1216. GetBitContext gb;
  1217. enum RawDataBlockType elem_type;
  1218. int err, elem_id, data_size_tmp;
  1219. init_get_bits(&gb, buf, buf_size*8);
  1220. // parse
  1221. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1222. elem_id = get_bits(&gb, 4);
  1223. err = -1;
  1224. if(elem_type == TYPE_SCE && elem_id == 1 &&
  1225. !ac->che[TYPE_SCE][elem_id] && ac->che[TYPE_LFE][0]) {
  1226. /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
  1227. instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
  1228. encountered such a stream, transfer the LFE[0] element to SCE[1] */
  1229. ac->che[TYPE_SCE][elem_id] = ac->che[TYPE_LFE][0];
  1230. ac->che[TYPE_LFE][0] = NULL;
  1231. }
  1232. if(elem_type && elem_type < TYPE_DSE) {
  1233. if(!ac->che[elem_type][elem_id])
  1234. return -1;
  1235. if(elem_type != TYPE_CCE)
  1236. ac->che[elem_type][elem_id]->coup.coupling_point = 4;
  1237. }
  1238. switch (elem_type) {
  1239. case TYPE_SCE:
  1240. err = decode_ics(ac, &ac->che[TYPE_SCE][elem_id]->ch[0], &gb, 0, 0);
  1241. break;
  1242. case TYPE_CPE:
  1243. err = decode_cpe(ac, &gb, elem_id);
  1244. break;
  1245. case TYPE_CCE:
  1246. err = decode_cce(ac, &gb, ac->che[TYPE_SCE][elem_id]);
  1247. break;
  1248. case TYPE_LFE:
  1249. err = decode_ics(ac, &ac->che[TYPE_LFE][elem_id]->ch[0], &gb, 0, 0);
  1250. break;
  1251. case TYPE_DSE:
  1252. skip_data_stream_element(&gb);
  1253. err = 0;
  1254. break;
  1255. case TYPE_PCE:
  1256. {
  1257. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1258. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1259. if((err = decode_pce(ac, new_che_pos, &gb)))
  1260. break;
  1261. err = output_configure(ac, ac->che_pos, new_che_pos);
  1262. break;
  1263. }
  1264. case TYPE_FIL:
  1265. if (elem_id == 15)
  1266. elem_id += get_bits(&gb, 8) - 1;
  1267. while (elem_id > 0)
  1268. elem_id -= decode_extension_payload(ac, &gb, elem_id);
  1269. err = 0; /* FIXME */
  1270. break;
  1271. default:
  1272. err = -1; /* should not happen, but keeps compiler happy */
  1273. break;
  1274. }
  1275. if(err)
  1276. return err;
  1277. }
  1278. spectral_to_sample(ac);
  1279. if (!ac->is_saved) {
  1280. ac->is_saved = 1;
  1281. *data_size = 0;
  1282. return buf_size;
  1283. }
  1284. data_size_tmp = 1024 * avccontext->channels * sizeof(int16_t);
  1285. if(*data_size < data_size_tmp) {
  1286. av_log(avccontext, AV_LOG_ERROR,
  1287. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1288. *data_size, data_size_tmp);
  1289. return -1;
  1290. }
  1291. *data_size = data_size_tmp;
  1292. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, 1024, avccontext->channels);
  1293. return buf_size;
  1294. }
  1295. static av_cold int aac_decode_close(AVCodecContext * avccontext) {
  1296. AACContext * ac = avccontext->priv_data;
  1297. int i, type;
  1298. for (i = 0; i < MAX_ELEM_ID; i++) {
  1299. for(type = 0; type < 4; type++)
  1300. av_freep(&ac->che[type][i]);
  1301. }
  1302. ff_mdct_end(&ac->mdct);
  1303. ff_mdct_end(&ac->mdct_small);
  1304. return 0 ;
  1305. }
  1306. AVCodec aac_decoder = {
  1307. "aac",
  1308. CODEC_TYPE_AUDIO,
  1309. CODEC_ID_AAC,
  1310. sizeof(AACContext),
  1311. aac_decode_init,
  1312. NULL,
  1313. aac_decode_close,
  1314. aac_decode_frame,
  1315. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1316. .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
  1317. };