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.

2579 lines
91KB

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