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.

3063 lines
106KB

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