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.

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