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.

2607 lines
92KB

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