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.

2822 lines
98KB

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