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.

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