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.

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