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.

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