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.

2811 lines
98KB

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