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.

2611 lines
92KB

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