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.

2654 lines
94KB

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