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.

2627 lines
93KB

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