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.

3360 lines
116KB

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