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.

1100 lines
39KB

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