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.

3438 lines
119KB

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