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.

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