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.

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