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.

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