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.

2842 lines
99KB

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