You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2627 lines
93KB

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