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.

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