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.

3005 lines
104KB

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