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.

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