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.

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