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.

3045 lines
105KB

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