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.

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