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.

2798 lines
97KB

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