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.

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