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.

2866 lines
100KB

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