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.

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