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.

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