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.

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