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.

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