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.

2519 lines
88KB

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