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.

3361 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. av_log(ac->avctx, AV_LOG_ERROR,
  1139. "LTP in ER AAC LD not yet implemented.\n");
  1140. return AVERROR_PATCHWELCOME;
  1141. }
  1142. if ((ics->ltp.present = get_bits(gb, 1)))
  1143. decode_ltp(&ics->ltp, gb, ics->max_sfb);
  1144. }
  1145. }
  1146. }
  1147. if (ics->max_sfb > ics->num_swb) {
  1148. av_log(ac->avctx, AV_LOG_ERROR,
  1149. "Number of scalefactor bands in group (%d) "
  1150. "exceeds limit (%d).\n",
  1151. ics->max_sfb, ics->num_swb);
  1152. return AVERROR_INVALIDDATA;
  1153. }
  1154. return 0;
  1155. }
  1156. /**
  1157. * Decode band types (section_data payload); reference: table 4.46.
  1158. *
  1159. * @param band_type array of the used band type
  1160. * @param band_type_run_end array of the last scalefactor band of a band type run
  1161. *
  1162. * @return Returns error status. 0 - OK, !0 - error
  1163. */
  1164. static int decode_band_types(AACContext *ac, enum BandType band_type[120],
  1165. int band_type_run_end[120], GetBitContext *gb,
  1166. IndividualChannelStream *ics)
  1167. {
  1168. int g, idx = 0;
  1169. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  1170. for (g = 0; g < ics->num_window_groups; g++) {
  1171. int k = 0;
  1172. while (k < ics->max_sfb) {
  1173. uint8_t sect_end = k;
  1174. int sect_len_incr;
  1175. int sect_band_type = get_bits(gb, 4);
  1176. if (sect_band_type == 12) {
  1177. av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
  1178. return AVERROR_INVALIDDATA;
  1179. }
  1180. do {
  1181. sect_len_incr = get_bits(gb, bits);
  1182. sect_end += sect_len_incr;
  1183. if (get_bits_left(gb) < 0) {
  1184. av_log(ac->avctx, AV_LOG_ERROR, overread_err);
  1185. return AVERROR_INVALIDDATA;
  1186. }
  1187. if (sect_end > ics->max_sfb) {
  1188. av_log(ac->avctx, AV_LOG_ERROR,
  1189. "Number of bands (%d) exceeds limit (%d).\n",
  1190. sect_end, ics->max_sfb);
  1191. return AVERROR_INVALIDDATA;
  1192. }
  1193. } while (sect_len_incr == (1 << bits) - 1);
  1194. for (; k < sect_end; k++) {
  1195. band_type [idx] = sect_band_type;
  1196. band_type_run_end[idx++] = sect_end;
  1197. }
  1198. }
  1199. }
  1200. return 0;
  1201. }
  1202. /**
  1203. * Decode scalefactors; reference: table 4.47.
  1204. *
  1205. * @param global_gain first scalefactor value as scalefactors are differentially coded
  1206. * @param band_type array of the used band type
  1207. * @param band_type_run_end array of the last scalefactor band of a band type run
  1208. * @param sf array of scalefactors or intensity stereo positions
  1209. *
  1210. * @return Returns error status. 0 - OK, !0 - error
  1211. */
  1212. static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
  1213. unsigned int global_gain,
  1214. IndividualChannelStream *ics,
  1215. enum BandType band_type[120],
  1216. int band_type_run_end[120])
  1217. {
  1218. int g, i, idx = 0;
  1219. int offset[3] = { global_gain, global_gain - 90, 0 };
  1220. int clipped_offset;
  1221. int noise_flag = 1;
  1222. for (g = 0; g < ics->num_window_groups; g++) {
  1223. for (i = 0; i < ics->max_sfb;) {
  1224. int run_end = band_type_run_end[idx];
  1225. if (band_type[idx] == ZERO_BT) {
  1226. for (; i < run_end; i++, idx++)
  1227. sf[idx] = 0.0;
  1228. } else if ((band_type[idx] == INTENSITY_BT) ||
  1229. (band_type[idx] == INTENSITY_BT2)) {
  1230. for (; i < run_end; i++, idx++) {
  1231. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1232. clipped_offset = av_clip(offset[2], -155, 100);
  1233. if (offset[2] != clipped_offset) {
  1234. avpriv_request_sample(ac->avctx,
  1235. "If you heard an audible artifact, there may be a bug in the decoder. "
  1236. "Clipped intensity stereo position (%d -> %d)",
  1237. offset[2], clipped_offset);
  1238. }
  1239. sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
  1240. }
  1241. } else if (band_type[idx] == NOISE_BT) {
  1242. for (; i < run_end; i++, idx++) {
  1243. if (noise_flag-- > 0)
  1244. offset[1] += get_bits(gb, 9) - 256;
  1245. else
  1246. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1247. clipped_offset = av_clip(offset[1], -100, 155);
  1248. if (offset[1] != clipped_offset) {
  1249. avpriv_request_sample(ac->avctx,
  1250. "If you heard an audible artifact, there may be a bug in the decoder. "
  1251. "Clipped noise gain (%d -> %d)",
  1252. offset[1], clipped_offset);
  1253. }
  1254. sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
  1255. }
  1256. } else {
  1257. for (; i < run_end; i++, idx++) {
  1258. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1259. if (offset[0] > 255U) {
  1260. av_log(ac->avctx, AV_LOG_ERROR,
  1261. "Scalefactor (%d) out of range.\n", offset[0]);
  1262. return AVERROR_INVALIDDATA;
  1263. }
  1264. sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
  1265. }
  1266. }
  1267. }
  1268. }
  1269. return 0;
  1270. }
  1271. /**
  1272. * Decode pulse data; reference: table 4.7.
  1273. */
  1274. static int decode_pulses(Pulse *pulse, GetBitContext *gb,
  1275. const uint16_t *swb_offset, int num_swb)
  1276. {
  1277. int i, pulse_swb;
  1278. pulse->num_pulse = get_bits(gb, 2) + 1;
  1279. pulse_swb = get_bits(gb, 6);
  1280. if (pulse_swb >= num_swb)
  1281. return -1;
  1282. pulse->pos[0] = swb_offset[pulse_swb];
  1283. pulse->pos[0] += get_bits(gb, 5);
  1284. if (pulse->pos[0] > 1023)
  1285. return -1;
  1286. pulse->amp[0] = get_bits(gb, 4);
  1287. for (i = 1; i < pulse->num_pulse; i++) {
  1288. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
  1289. if (pulse->pos[i] > 1023)
  1290. return -1;
  1291. pulse->amp[i] = get_bits(gb, 4);
  1292. }
  1293. return 0;
  1294. }
  1295. /**
  1296. * Decode Temporal Noise Shaping data; reference: table 4.48.
  1297. *
  1298. * @return Returns error status. 0 - OK, !0 - error
  1299. */
  1300. static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
  1301. GetBitContext *gb, const IndividualChannelStream *ics)
  1302. {
  1303. int w, filt, i, coef_len, coef_res, coef_compress;
  1304. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  1305. const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  1306. for (w = 0; w < ics->num_windows; w++) {
  1307. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  1308. coef_res = get_bits1(gb);
  1309. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1310. int tmp2_idx;
  1311. tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
  1312. if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
  1313. av_log(ac->avctx, AV_LOG_ERROR,
  1314. "TNS filter order %d is greater than maximum %d.\n",
  1315. tns->order[w][filt], tns_max_order);
  1316. tns->order[w][filt] = 0;
  1317. return AVERROR_INVALIDDATA;
  1318. }
  1319. if (tns->order[w][filt]) {
  1320. tns->direction[w][filt] = get_bits1(gb);
  1321. coef_compress = get_bits1(gb);
  1322. coef_len = coef_res + 3 - coef_compress;
  1323. tmp2_idx = 2 * coef_compress + coef_res;
  1324. for (i = 0; i < tns->order[w][filt]; i++)
  1325. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  1326. }
  1327. }
  1328. }
  1329. }
  1330. return 0;
  1331. }
  1332. /**
  1333. * Decode Mid/Side data; reference: table 4.54.
  1334. *
  1335. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1336. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1337. * [3] reserved for scalable AAC
  1338. */
  1339. static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
  1340. int ms_present)
  1341. {
  1342. int idx;
  1343. int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
  1344. if (ms_present == 1) {
  1345. for (idx = 0; idx < max_idx; idx++)
  1346. cpe->ms_mask[idx] = get_bits1(gb);
  1347. } else if (ms_present == 2) {
  1348. memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
  1349. }
  1350. }
  1351. #ifndef VMUL2
  1352. static inline float *VMUL2(float *dst, const float *v, unsigned idx,
  1353. const float *scale)
  1354. {
  1355. float s = *scale;
  1356. *dst++ = v[idx & 15] * s;
  1357. *dst++ = v[idx>>4 & 15] * s;
  1358. return dst;
  1359. }
  1360. #endif
  1361. #ifndef VMUL4
  1362. static inline float *VMUL4(float *dst, const float *v, unsigned idx,
  1363. const float *scale)
  1364. {
  1365. float s = *scale;
  1366. *dst++ = v[idx & 3] * s;
  1367. *dst++ = v[idx>>2 & 3] * s;
  1368. *dst++ = v[idx>>4 & 3] * s;
  1369. *dst++ = v[idx>>6 & 3] * s;
  1370. return dst;
  1371. }
  1372. #endif
  1373. #ifndef VMUL2S
  1374. static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
  1375. unsigned sign, const float *scale)
  1376. {
  1377. union av_intfloat32 s0, s1;
  1378. s0.f = s1.f = *scale;
  1379. s0.i ^= sign >> 1 << 31;
  1380. s1.i ^= sign << 31;
  1381. *dst++ = v[idx & 15] * s0.f;
  1382. *dst++ = v[idx>>4 & 15] * s1.f;
  1383. return dst;
  1384. }
  1385. #endif
  1386. #ifndef VMUL4S
  1387. static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
  1388. unsigned sign, const float *scale)
  1389. {
  1390. unsigned nz = idx >> 12;
  1391. union av_intfloat32 s = { .f = *scale };
  1392. union av_intfloat32 t;
  1393. t.i = s.i ^ (sign & 1U<<31);
  1394. *dst++ = v[idx & 3] * t.f;
  1395. sign <<= nz & 1; nz >>= 1;
  1396. t.i = s.i ^ (sign & 1U<<31);
  1397. *dst++ = v[idx>>2 & 3] * t.f;
  1398. sign <<= nz & 1; nz >>= 1;
  1399. t.i = s.i ^ (sign & 1U<<31);
  1400. *dst++ = v[idx>>4 & 3] * t.f;
  1401. sign <<= nz & 1;
  1402. t.i = s.i ^ (sign & 1U<<31);
  1403. *dst++ = v[idx>>6 & 3] * t.f;
  1404. return dst;
  1405. }
  1406. #endif
  1407. /**
  1408. * Decode spectral data; reference: table 4.50.
  1409. * Dequantize and scale spectral data; reference: 4.6.3.3.
  1410. *
  1411. * @param coef array of dequantized, scaled spectral data
  1412. * @param sf array of scalefactors or intensity stereo positions
  1413. * @param pulse_present set if pulses are present
  1414. * @param pulse pointer to pulse data struct
  1415. * @param band_type array of the used band type
  1416. *
  1417. * @return Returns error status. 0 - OK, !0 - error
  1418. */
  1419. static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
  1420. GetBitContext *gb, const float sf[120],
  1421. int pulse_present, const Pulse *pulse,
  1422. const IndividualChannelStream *ics,
  1423. enum BandType band_type[120])
  1424. {
  1425. int i, k, g, idx = 0;
  1426. const int c = 1024 / ics->num_windows;
  1427. const uint16_t *offsets = ics->swb_offset;
  1428. float *coef_base = coef;
  1429. for (g = 0; g < ics->num_windows; g++)
  1430. memset(coef + g * 128 + offsets[ics->max_sfb], 0,
  1431. sizeof(float) * (c - offsets[ics->max_sfb]));
  1432. for (g = 0; g < ics->num_window_groups; g++) {
  1433. unsigned g_len = ics->group_len[g];
  1434. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1435. const unsigned cbt_m1 = band_type[idx] - 1;
  1436. float *cfo = coef + offsets[i];
  1437. int off_len = offsets[i + 1] - offsets[i];
  1438. int group;
  1439. if (cbt_m1 >= INTENSITY_BT2 - 1) {
  1440. for (group = 0; group < g_len; group++, cfo+=128) {
  1441. memset(cfo, 0, off_len * sizeof(float));
  1442. }
  1443. } else if (cbt_m1 == NOISE_BT - 1) {
  1444. for (group = 0; group < g_len; group++, cfo+=128) {
  1445. float scale;
  1446. float band_energy;
  1447. for (k = 0; k < off_len; k++) {
  1448. ac->random_state = lcg_random(ac->random_state);
  1449. cfo[k] = ac->random_state;
  1450. }
  1451. band_energy = ac->fdsp.scalarproduct_float(cfo, cfo, off_len);
  1452. scale = sf[idx] / sqrtf(band_energy);
  1453. ac->fdsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
  1454. }
  1455. } else {
  1456. const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
  1457. const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
  1458. VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
  1459. OPEN_READER(re, gb);
  1460. switch (cbt_m1 >> 1) {
  1461. case 0:
  1462. for (group = 0; group < g_len; group++, cfo+=128) {
  1463. float *cf = cfo;
  1464. int len = off_len;
  1465. do {
  1466. int code;
  1467. unsigned cb_idx;
  1468. UPDATE_CACHE(re, gb);
  1469. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1470. cb_idx = cb_vector_idx[code];
  1471. cf = VMUL4(cf, vq, cb_idx, sf + idx);
  1472. } while (len -= 4);
  1473. }
  1474. break;
  1475. case 1:
  1476. for (group = 0; group < g_len; group++, cfo+=128) {
  1477. float *cf = cfo;
  1478. int len = off_len;
  1479. do {
  1480. int code;
  1481. unsigned nnz;
  1482. unsigned cb_idx;
  1483. uint32_t bits;
  1484. UPDATE_CACHE(re, gb);
  1485. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1486. cb_idx = cb_vector_idx[code];
  1487. nnz = cb_idx >> 8 & 15;
  1488. bits = nnz ? GET_CACHE(re, gb) : 0;
  1489. LAST_SKIP_BITS(re, gb, nnz);
  1490. cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
  1491. } while (len -= 4);
  1492. }
  1493. break;
  1494. case 2:
  1495. for (group = 0; group < g_len; group++, cfo+=128) {
  1496. float *cf = cfo;
  1497. int len = off_len;
  1498. do {
  1499. int code;
  1500. unsigned cb_idx;
  1501. UPDATE_CACHE(re, gb);
  1502. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1503. cb_idx = cb_vector_idx[code];
  1504. cf = VMUL2(cf, vq, cb_idx, sf + idx);
  1505. } while (len -= 2);
  1506. }
  1507. break;
  1508. case 3:
  1509. case 4:
  1510. for (group = 0; group < g_len; group++, cfo+=128) {
  1511. float *cf = cfo;
  1512. int len = off_len;
  1513. do {
  1514. int code;
  1515. unsigned nnz;
  1516. unsigned cb_idx;
  1517. unsigned sign;
  1518. UPDATE_CACHE(re, gb);
  1519. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1520. cb_idx = cb_vector_idx[code];
  1521. nnz = cb_idx >> 8 & 15;
  1522. sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
  1523. LAST_SKIP_BITS(re, gb, nnz);
  1524. cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
  1525. } while (len -= 2);
  1526. }
  1527. break;
  1528. default:
  1529. for (group = 0; group < g_len; group++, cfo+=128) {
  1530. float *cf = cfo;
  1531. uint32_t *icf = (uint32_t *) cf;
  1532. int len = off_len;
  1533. do {
  1534. int code;
  1535. unsigned nzt, nnz;
  1536. unsigned cb_idx;
  1537. uint32_t bits;
  1538. int j;
  1539. UPDATE_CACHE(re, gb);
  1540. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1541. if (!code) {
  1542. *icf++ = 0;
  1543. *icf++ = 0;
  1544. continue;
  1545. }
  1546. cb_idx = cb_vector_idx[code];
  1547. nnz = cb_idx >> 12;
  1548. nzt = cb_idx >> 8;
  1549. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  1550. LAST_SKIP_BITS(re, gb, nnz);
  1551. for (j = 0; j < 2; j++) {
  1552. if (nzt & 1<<j) {
  1553. uint32_t b;
  1554. int n;
  1555. /* The total length of escape_sequence must be < 22 bits according
  1556. to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
  1557. UPDATE_CACHE(re, gb);
  1558. b = GET_CACHE(re, gb);
  1559. b = 31 - av_log2(~b);
  1560. if (b > 8) {
  1561. av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  1562. return AVERROR_INVALIDDATA;
  1563. }
  1564. SKIP_BITS(re, gb, b + 1);
  1565. b += 4;
  1566. n = (1 << b) + SHOW_UBITS(re, gb, b);
  1567. LAST_SKIP_BITS(re, gb, b);
  1568. *icf++ = cbrt_tab[n] | (bits & 1U<<31);
  1569. bits <<= 1;
  1570. } else {
  1571. unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
  1572. *icf++ = (bits & 1U<<31) | v;
  1573. bits <<= !!v;
  1574. }
  1575. cb_idx >>= 4;
  1576. }
  1577. } while (len -= 2);
  1578. ac->fdsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
  1579. }
  1580. }
  1581. CLOSE_READER(re, gb);
  1582. }
  1583. }
  1584. coef += g_len << 7;
  1585. }
  1586. if (pulse_present) {
  1587. idx = 0;
  1588. for (i = 0; i < pulse->num_pulse; i++) {
  1589. float co = coef_base[ pulse->pos[i] ];
  1590. while (offsets[idx + 1] <= pulse->pos[i])
  1591. idx++;
  1592. if (band_type[idx] != NOISE_BT && sf[idx]) {
  1593. float ico = -pulse->amp[i];
  1594. if (co) {
  1595. co /= sf[idx];
  1596. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  1597. }
  1598. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  1599. }
  1600. }
  1601. }
  1602. return 0;
  1603. }
  1604. static av_always_inline float flt16_round(float pf)
  1605. {
  1606. union av_intfloat32 tmp;
  1607. tmp.f = pf;
  1608. tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
  1609. return tmp.f;
  1610. }
  1611. static av_always_inline float flt16_even(float pf)
  1612. {
  1613. union av_intfloat32 tmp;
  1614. tmp.f = pf;
  1615. tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
  1616. return tmp.f;
  1617. }
  1618. static av_always_inline float flt16_trunc(float pf)
  1619. {
  1620. union av_intfloat32 pun;
  1621. pun.f = pf;
  1622. pun.i &= 0xFFFF0000U;
  1623. return pun.f;
  1624. }
  1625. static av_always_inline void predict(PredictorState *ps, float *coef,
  1626. int output_enable)
  1627. {
  1628. const float a = 0.953125; // 61.0 / 64
  1629. const float alpha = 0.90625; // 29.0 / 32
  1630. float e0, e1;
  1631. float pv;
  1632. float k1, k2;
  1633. float r0 = ps->r0, r1 = ps->r1;
  1634. float cor0 = ps->cor0, cor1 = ps->cor1;
  1635. float var0 = ps->var0, var1 = ps->var1;
  1636. k1 = var0 > 1 ? cor0 * flt16_even(a / var0) : 0;
  1637. k2 = var1 > 1 ? cor1 * flt16_even(a / var1) : 0;
  1638. pv = flt16_round(k1 * r0 + k2 * r1);
  1639. if (output_enable)
  1640. *coef += pv;
  1641. e0 = *coef;
  1642. e1 = e0 - k1 * r0;
  1643. ps->cor1 = flt16_trunc(alpha * cor1 + r1 * e1);
  1644. ps->var1 = flt16_trunc(alpha * var1 + 0.5f * (r1 * r1 + e1 * e1));
  1645. ps->cor0 = flt16_trunc(alpha * cor0 + r0 * e0);
  1646. ps->var0 = flt16_trunc(alpha * var0 + 0.5f * (r0 * r0 + e0 * e0));
  1647. ps->r1 = flt16_trunc(a * (r0 - k1 * e0));
  1648. ps->r0 = flt16_trunc(a * e0);
  1649. }
  1650. /**
  1651. * Apply AAC-Main style frequency domain prediction.
  1652. */
  1653. static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
  1654. {
  1655. int sfb, k;
  1656. if (!sce->ics.predictor_initialized) {
  1657. reset_all_predictors(sce->predictor_state);
  1658. sce->ics.predictor_initialized = 1;
  1659. }
  1660. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  1661. for (sfb = 0;
  1662. sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
  1663. sfb++) {
  1664. for (k = sce->ics.swb_offset[sfb];
  1665. k < sce->ics.swb_offset[sfb + 1];
  1666. k++) {
  1667. predict(&sce->predictor_state[k], &sce->coeffs[k],
  1668. sce->ics.predictor_present &&
  1669. sce->ics.prediction_used[sfb]);
  1670. }
  1671. }
  1672. if (sce->ics.predictor_reset_group)
  1673. reset_predictor_group(sce->predictor_state,
  1674. sce->ics.predictor_reset_group);
  1675. } else
  1676. reset_all_predictors(sce->predictor_state);
  1677. }
  1678. /**
  1679. * Decode an individual_channel_stream payload; reference: table 4.44.
  1680. *
  1681. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  1682. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  1683. *
  1684. * @return Returns error status. 0 - OK, !0 - error
  1685. */
  1686. static int decode_ics(AACContext *ac, SingleChannelElement *sce,
  1687. GetBitContext *gb, int common_window, int scale_flag)
  1688. {
  1689. Pulse pulse;
  1690. TemporalNoiseShaping *tns = &sce->tns;
  1691. IndividualChannelStream *ics = &sce->ics;
  1692. float *out = sce->coeffs;
  1693. int global_gain, eld_syntax, er_syntax, pulse_present = 0;
  1694. int ret;
  1695. eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1696. er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
  1697. ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
  1698. ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
  1699. ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1700. /* This assignment is to silence a GCC warning about the variable being used
  1701. * uninitialized when in fact it always is.
  1702. */
  1703. pulse.num_pulse = 0;
  1704. global_gain = get_bits(gb, 8);
  1705. if (!common_window && !scale_flag) {
  1706. if (decode_ics_info(ac, ics, gb) < 0)
  1707. return AVERROR_INVALIDDATA;
  1708. }
  1709. if ((ret = decode_band_types(ac, sce->band_type,
  1710. sce->band_type_run_end, gb, ics)) < 0)
  1711. return ret;
  1712. if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
  1713. sce->band_type, sce->band_type_run_end)) < 0)
  1714. return ret;
  1715. pulse_present = 0;
  1716. if (!scale_flag) {
  1717. if (!eld_syntax && (pulse_present = get_bits1(gb))) {
  1718. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1719. av_log(ac->avctx, AV_LOG_ERROR,
  1720. "Pulse tool not allowed in eight short sequence.\n");
  1721. return AVERROR_INVALIDDATA;
  1722. }
  1723. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  1724. av_log(ac->avctx, AV_LOG_ERROR,
  1725. "Pulse data corrupt or invalid.\n");
  1726. return AVERROR_INVALIDDATA;
  1727. }
  1728. }
  1729. tns->present = get_bits1(gb);
  1730. if (tns->present && !er_syntax)
  1731. if (decode_tns(ac, tns, gb, ics) < 0)
  1732. return AVERROR_INVALIDDATA;
  1733. if (!eld_syntax && get_bits1(gb)) {
  1734. avpriv_request_sample(ac->avctx, "SSR");
  1735. return AVERROR_PATCHWELCOME;
  1736. }
  1737. // I see no textual basis in the spec for this occurring after SSR gain
  1738. // control, but this is what both reference and real implementations do
  1739. if (tns->present && er_syntax)
  1740. if (decode_tns(ac, tns, gb, ics) < 0)
  1741. return AVERROR_INVALIDDATA;
  1742. }
  1743. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
  1744. &pulse, ics, sce->band_type) < 0)
  1745. return AVERROR_INVALIDDATA;
  1746. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
  1747. apply_prediction(ac, sce);
  1748. return 0;
  1749. }
  1750. /**
  1751. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  1752. */
  1753. static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
  1754. {
  1755. const IndividualChannelStream *ics = &cpe->ch[0].ics;
  1756. float *ch0 = cpe->ch[0].coeffs;
  1757. float *ch1 = cpe->ch[1].coeffs;
  1758. int g, i, group, idx = 0;
  1759. const uint16_t *offsets = ics->swb_offset;
  1760. for (g = 0; g < ics->num_window_groups; g++) {
  1761. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1762. if (cpe->ms_mask[idx] &&
  1763. cpe->ch[0].band_type[idx] < NOISE_BT &&
  1764. cpe->ch[1].band_type[idx] < NOISE_BT) {
  1765. for (group = 0; group < ics->group_len[g]; group++) {
  1766. ac->fdsp.butterflies_float(ch0 + group * 128 + offsets[i],
  1767. ch1 + group * 128 + offsets[i],
  1768. offsets[i+1] - offsets[i]);
  1769. }
  1770. }
  1771. }
  1772. ch0 += ics->group_len[g] * 128;
  1773. ch1 += ics->group_len[g] * 128;
  1774. }
  1775. }
  1776. /**
  1777. * intensity stereo decoding; reference: 4.6.8.2.3
  1778. *
  1779. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1780. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1781. * [3] reserved for scalable AAC
  1782. */
  1783. static void apply_intensity_stereo(AACContext *ac,
  1784. ChannelElement *cpe, int ms_present)
  1785. {
  1786. const IndividualChannelStream *ics = &cpe->ch[1].ics;
  1787. SingleChannelElement *sce1 = &cpe->ch[1];
  1788. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  1789. const uint16_t *offsets = ics->swb_offset;
  1790. int g, group, i, idx = 0;
  1791. int c;
  1792. float scale;
  1793. for (g = 0; g < ics->num_window_groups; g++) {
  1794. for (i = 0; i < ics->max_sfb;) {
  1795. if (sce1->band_type[idx] == INTENSITY_BT ||
  1796. sce1->band_type[idx] == INTENSITY_BT2) {
  1797. const int bt_run_end = sce1->band_type_run_end[idx];
  1798. for (; i < bt_run_end; i++, idx++) {
  1799. c = -1 + 2 * (sce1->band_type[idx] - 14);
  1800. if (ms_present)
  1801. c *= 1 - 2 * cpe->ms_mask[idx];
  1802. scale = c * sce1->sf[idx];
  1803. for (group = 0; group < ics->group_len[g]; group++)
  1804. ac->fdsp.vector_fmul_scalar(coef1 + group * 128 + offsets[i],
  1805. coef0 + group * 128 + offsets[i],
  1806. scale,
  1807. offsets[i + 1] - offsets[i]);
  1808. }
  1809. } else {
  1810. int bt_run_end = sce1->band_type_run_end[idx];
  1811. idx += bt_run_end - i;
  1812. i = bt_run_end;
  1813. }
  1814. }
  1815. coef0 += ics->group_len[g] * 128;
  1816. coef1 += ics->group_len[g] * 128;
  1817. }
  1818. }
  1819. /**
  1820. * Decode a channel_pair_element; reference: table 4.4.
  1821. *
  1822. * @return Returns error status. 0 - OK, !0 - error
  1823. */
  1824. static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
  1825. {
  1826. int i, ret, common_window, ms_present = 0;
  1827. int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1828. common_window = eld_syntax || get_bits1(gb);
  1829. if (common_window) {
  1830. if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
  1831. return AVERROR_INVALIDDATA;
  1832. i = cpe->ch[1].ics.use_kb_window[0];
  1833. cpe->ch[1].ics = cpe->ch[0].ics;
  1834. cpe->ch[1].ics.use_kb_window[1] = i;
  1835. if (cpe->ch[1].ics.predictor_present &&
  1836. (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
  1837. if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
  1838. decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
  1839. ms_present = get_bits(gb, 2);
  1840. if (ms_present == 3) {
  1841. av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  1842. return AVERROR_INVALIDDATA;
  1843. } else if (ms_present)
  1844. decode_mid_side_stereo(cpe, gb, ms_present);
  1845. }
  1846. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  1847. return ret;
  1848. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  1849. return ret;
  1850. if (common_window) {
  1851. if (ms_present)
  1852. apply_mid_side_stereo(ac, cpe);
  1853. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
  1854. apply_prediction(ac, &cpe->ch[0]);
  1855. apply_prediction(ac, &cpe->ch[1]);
  1856. }
  1857. }
  1858. apply_intensity_stereo(ac, cpe, ms_present);
  1859. return 0;
  1860. }
  1861. static const float cce_scale[] = {
  1862. 1.09050773266525765921, //2^(1/8)
  1863. 1.18920711500272106672, //2^(1/4)
  1864. M_SQRT2,
  1865. 2,
  1866. };
  1867. /**
  1868. * Decode coupling_channel_element; reference: table 4.8.
  1869. *
  1870. * @return Returns error status. 0 - OK, !0 - error
  1871. */
  1872. static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
  1873. {
  1874. int num_gain = 0;
  1875. int c, g, sfb, ret;
  1876. int sign;
  1877. float scale;
  1878. SingleChannelElement *sce = &che->ch[0];
  1879. ChannelCoupling *coup = &che->coup;
  1880. coup->coupling_point = 2 * get_bits1(gb);
  1881. coup->num_coupled = get_bits(gb, 3);
  1882. for (c = 0; c <= coup->num_coupled; c++) {
  1883. num_gain++;
  1884. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1885. coup->id_select[c] = get_bits(gb, 4);
  1886. if (coup->type[c] == TYPE_CPE) {
  1887. coup->ch_select[c] = get_bits(gb, 2);
  1888. if (coup->ch_select[c] == 3)
  1889. num_gain++;
  1890. } else
  1891. coup->ch_select[c] = 2;
  1892. }
  1893. coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
  1894. sign = get_bits(gb, 1);
  1895. scale = cce_scale[get_bits(gb, 2)];
  1896. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1897. return ret;
  1898. for (c = 0; c < num_gain; c++) {
  1899. int idx = 0;
  1900. int cge = 1;
  1901. int gain = 0;
  1902. float gain_cache = 1.0;
  1903. if (c) {
  1904. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1905. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1906. gain_cache = powf(scale, -gain);
  1907. }
  1908. if (coup->coupling_point == AFTER_IMDCT) {
  1909. coup->gain[c][0] = gain_cache;
  1910. } else {
  1911. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1912. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1913. if (sce->band_type[idx] != ZERO_BT) {
  1914. if (!cge) {
  1915. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1916. if (t) {
  1917. int s = 1;
  1918. t = gain += t;
  1919. if (sign) {
  1920. s -= 2 * (t & 0x1);
  1921. t >>= 1;
  1922. }
  1923. gain_cache = powf(scale, -t) * s;
  1924. }
  1925. }
  1926. coup->gain[c][idx] = gain_cache;
  1927. }
  1928. }
  1929. }
  1930. }
  1931. }
  1932. return 0;
  1933. }
  1934. /**
  1935. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  1936. *
  1937. * @return Returns number of bytes consumed.
  1938. */
  1939. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
  1940. GetBitContext *gb)
  1941. {
  1942. int i;
  1943. int num_excl_chan = 0;
  1944. do {
  1945. for (i = 0; i < 7; i++)
  1946. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  1947. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  1948. return num_excl_chan / 7;
  1949. }
  1950. /**
  1951. * Decode dynamic range information; reference: table 4.52.
  1952. *
  1953. * @return Returns number of bytes consumed.
  1954. */
  1955. static int decode_dynamic_range(DynamicRangeControl *che_drc,
  1956. GetBitContext *gb)
  1957. {
  1958. int n = 1;
  1959. int drc_num_bands = 1;
  1960. int i;
  1961. /* pce_tag_present? */
  1962. if (get_bits1(gb)) {
  1963. che_drc->pce_instance_tag = get_bits(gb, 4);
  1964. skip_bits(gb, 4); // tag_reserved_bits
  1965. n++;
  1966. }
  1967. /* excluded_chns_present? */
  1968. if (get_bits1(gb)) {
  1969. n += decode_drc_channel_exclusions(che_drc, gb);
  1970. }
  1971. /* drc_bands_present? */
  1972. if (get_bits1(gb)) {
  1973. che_drc->band_incr = get_bits(gb, 4);
  1974. che_drc->interpolation_scheme = get_bits(gb, 4);
  1975. n++;
  1976. drc_num_bands += che_drc->band_incr;
  1977. for (i = 0; i < drc_num_bands; i++) {
  1978. che_drc->band_top[i] = get_bits(gb, 8);
  1979. n++;
  1980. }
  1981. }
  1982. /* prog_ref_level_present? */
  1983. if (get_bits1(gb)) {
  1984. che_drc->prog_ref_level = get_bits(gb, 7);
  1985. skip_bits1(gb); // prog_ref_level_reserved_bits
  1986. n++;
  1987. }
  1988. for (i = 0; i < drc_num_bands; i++) {
  1989. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  1990. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  1991. n++;
  1992. }
  1993. return n;
  1994. }
  1995. /**
  1996. * Decode extension data (incomplete); reference: table 4.51.
  1997. *
  1998. * @param cnt length of TYPE_FIL syntactic element in bytes
  1999. *
  2000. * @return Returns number of bytes consumed
  2001. */
  2002. static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
  2003. ChannelElement *che, enum RawDataBlockType elem_type)
  2004. {
  2005. int crc_flag = 0;
  2006. int res = cnt;
  2007. switch (get_bits(gb, 4)) { // extension type
  2008. case EXT_SBR_DATA_CRC:
  2009. crc_flag++;
  2010. case EXT_SBR_DATA:
  2011. if (!che) {
  2012. av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
  2013. return res;
  2014. } else if (!ac->oc[1].m4ac.sbr) {
  2015. av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
  2016. skip_bits_long(gb, 8 * cnt - 4);
  2017. return res;
  2018. } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
  2019. av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
  2020. skip_bits_long(gb, 8 * cnt - 4);
  2021. return res;
  2022. } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
  2023. ac->oc[1].m4ac.sbr = 1;
  2024. ac->oc[1].m4ac.ps = 1;
  2025. ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
  2026. output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
  2027. ac->oc[1].status, 1);
  2028. } else {
  2029. ac->oc[1].m4ac.sbr = 1;
  2030. ac->avctx->profile = FF_PROFILE_AAC_HE;
  2031. }
  2032. res = ff_decode_sbr_extension(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
  2033. break;
  2034. case EXT_DYNAMIC_RANGE:
  2035. res = decode_dynamic_range(&ac->che_drc, gb);
  2036. break;
  2037. case EXT_FILL:
  2038. case EXT_FILL_DATA:
  2039. case EXT_DATA_ELEMENT:
  2040. default:
  2041. skip_bits_long(gb, 8 * cnt - 4);
  2042. break;
  2043. };
  2044. return res;
  2045. }
  2046. /**
  2047. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  2048. *
  2049. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  2050. * @param coef spectral coefficients
  2051. */
  2052. static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
  2053. IndividualChannelStream *ics, int decode)
  2054. {
  2055. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  2056. int w, filt, m, i;
  2057. int bottom, top, order, start, end, size, inc;
  2058. float lpc[TNS_MAX_ORDER];
  2059. float tmp[TNS_MAX_ORDER + 1];
  2060. for (w = 0; w < ics->num_windows; w++) {
  2061. bottom = ics->num_swb;
  2062. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  2063. top = bottom;
  2064. bottom = FFMAX(0, top - tns->length[w][filt]);
  2065. order = tns->order[w][filt];
  2066. if (order == 0)
  2067. continue;
  2068. // tns_decode_coef
  2069. compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
  2070. start = ics->swb_offset[FFMIN(bottom, mmm)];
  2071. end = ics->swb_offset[FFMIN( top, mmm)];
  2072. if ((size = end - start) <= 0)
  2073. continue;
  2074. if (tns->direction[w][filt]) {
  2075. inc = -1;
  2076. start = end - 1;
  2077. } else {
  2078. inc = 1;
  2079. }
  2080. start += w * 128;
  2081. if (decode) {
  2082. // ar filter
  2083. for (m = 0; m < size; m++, start += inc)
  2084. for (i = 1; i <= FFMIN(m, order); i++)
  2085. coef[start] -= coef[start - i * inc] * lpc[i - 1];
  2086. } else {
  2087. // ma filter
  2088. for (m = 0; m < size; m++, start += inc) {
  2089. tmp[0] = coef[start];
  2090. for (i = 1; i <= FFMIN(m, order); i++)
  2091. coef[start] += tmp[i] * lpc[i - 1];
  2092. for (i = order; i > 0; i--)
  2093. tmp[i] = tmp[i - 1];
  2094. }
  2095. }
  2096. }
  2097. }
  2098. }
  2099. /**
  2100. * Apply windowing and MDCT to obtain the spectral
  2101. * coefficient from the predicted sample by LTP.
  2102. */
  2103. static void windowing_and_mdct_ltp(AACContext *ac, float *out,
  2104. float *in, IndividualChannelStream *ics)
  2105. {
  2106. const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  2107. const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  2108. const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  2109. const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  2110. if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
  2111. ac->fdsp.vector_fmul(in, in, lwindow_prev, 1024);
  2112. } else {
  2113. memset(in, 0, 448 * sizeof(float));
  2114. ac->fdsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);
  2115. }
  2116. if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
  2117. ac->fdsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
  2118. } else {
  2119. ac->fdsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
  2120. memset(in + 1024 + 576, 0, 448 * sizeof(float));
  2121. }
  2122. ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
  2123. }
  2124. /**
  2125. * Apply the long term prediction
  2126. */
  2127. static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
  2128. {
  2129. const LongTermPrediction *ltp = &sce->ics.ltp;
  2130. const uint16_t *offsets = sce->ics.swb_offset;
  2131. int i, sfb;
  2132. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  2133. float *predTime = sce->ret;
  2134. float *predFreq = ac->buf_mdct;
  2135. int16_t num_samples = 2048;
  2136. if (ltp->lag < 1024)
  2137. num_samples = ltp->lag + 1024;
  2138. for (i = 0; i < num_samples; i++)
  2139. predTime[i] = sce->ltp_state[i + 2048 - ltp->lag] * ltp->coef;
  2140. memset(&predTime[i], 0, (2048 - i) * sizeof(float));
  2141. windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
  2142. if (sce->tns.present)
  2143. apply_tns(predFreq, &sce->tns, &sce->ics, 0);
  2144. for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
  2145. if (ltp->used[sfb])
  2146. for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
  2147. sce->coeffs[i] += predFreq[i];
  2148. }
  2149. }
  2150. /**
  2151. * Update the LTP buffer for next frame
  2152. */
  2153. static void update_ltp(AACContext *ac, SingleChannelElement *sce)
  2154. {
  2155. IndividualChannelStream *ics = &sce->ics;
  2156. float *saved = sce->saved;
  2157. float *saved_ltp = sce->coeffs;
  2158. const float *lwindow = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  2159. const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  2160. int i;
  2161. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2162. memcpy(saved_ltp, saved, 512 * sizeof(float));
  2163. memset(saved_ltp + 576, 0, 448 * sizeof(float));
  2164. ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2165. for (i = 0; i < 64; i++)
  2166. saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
  2167. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2168. memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(float));
  2169. memset(saved_ltp + 576, 0, 448 * sizeof(float));
  2170. ac->fdsp.vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2171. for (i = 0; i < 64; i++)
  2172. saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * swindow[63 - i];
  2173. } else { // LONG_STOP or ONLY_LONG
  2174. ac->fdsp.vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
  2175. for (i = 0; i < 512; i++)
  2176. saved_ltp[i + 512] = ac->buf_mdct[1023 - i] * lwindow[511 - i];
  2177. }
  2178. memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
  2179. memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
  2180. memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
  2181. }
  2182. /**
  2183. * Conduct IMDCT and windowing.
  2184. */
  2185. static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
  2186. {
  2187. IndividualChannelStream *ics = &sce->ics;
  2188. float *in = sce->coeffs;
  2189. float *out = sce->ret;
  2190. float *saved = sce->saved;
  2191. const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  2192. const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  2193. const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  2194. float *buf = ac->buf_mdct;
  2195. float *temp = ac->temp;
  2196. int i;
  2197. // imdct
  2198. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2199. for (i = 0; i < 1024; i += 128)
  2200. ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
  2201. } else
  2202. ac->mdct.imdct_half(&ac->mdct, buf, in);
  2203. /* window overlapping
  2204. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  2205. * and long to short transitions are considered to be short to short
  2206. * transitions. This leaves just two cases (long to long and short to short)
  2207. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  2208. */
  2209. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  2210. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  2211. ac->fdsp.vector_fmul_window( out, saved, buf, lwindow_prev, 512);
  2212. } else {
  2213. memcpy( out, saved, 448 * sizeof(float));
  2214. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2215. ac->fdsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
  2216. ac->fdsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
  2217. ac->fdsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
  2218. ac->fdsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
  2219. ac->fdsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
  2220. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  2221. } else {
  2222. ac->fdsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
  2223. memcpy( out + 576, buf + 64, 448 * sizeof(float));
  2224. }
  2225. }
  2226. // buffer update
  2227. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2228. memcpy( saved, temp + 64, 64 * sizeof(float));
  2229. ac->fdsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
  2230. ac->fdsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
  2231. ac->fdsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
  2232. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  2233. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2234. memcpy( saved, buf + 512, 448 * sizeof(float));
  2235. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  2236. } else { // LONG_STOP or ONLY_LONG
  2237. memcpy( saved, buf + 512, 512 * sizeof(float));
  2238. }
  2239. }
  2240. static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
  2241. {
  2242. IndividualChannelStream *ics = &sce->ics;
  2243. float *in = sce->coeffs;
  2244. float *out = sce->ret;
  2245. float *saved = sce->saved;
  2246. float *buf = ac->buf_mdct;
  2247. // imdct
  2248. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2249. // window overlapping
  2250. if (ics->use_kb_window[1]) {
  2251. // AAC LD uses a low overlap sine window instead of a KBD window
  2252. memcpy(out, saved, 192 * sizeof(float));
  2253. ac->fdsp.vector_fmul_window(out + 192, saved + 192, buf, ff_sine_128, 64);
  2254. memcpy( out + 320, buf + 64, 192 * sizeof(float));
  2255. } else {
  2256. ac->fdsp.vector_fmul_window(out, saved, buf, ff_sine_512, 256);
  2257. }
  2258. // buffer update
  2259. memcpy(saved, buf + 256, 256 * sizeof(float));
  2260. }
  2261. static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
  2262. {
  2263. float *in = sce->coeffs;
  2264. float *out = sce->ret;
  2265. float *saved = sce->saved;
  2266. float *buf = ac->buf_mdct;
  2267. int i;
  2268. const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
  2269. const int n2 = n >> 1;
  2270. const int n4 = n >> 2;
  2271. const float *const window = n == 480 ? ff_aac_eld_window_480 :
  2272. ff_aac_eld_window_512;
  2273. // Inverse transform, mapped to the conventional IMDCT by
  2274. // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
  2275. // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
  2276. // Audio, Language and Image Processing, 2008. ICALIP 2008. International Conference on
  2277. // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
  2278. for (i = 0; i < n2; i+=2) {
  2279. float temp;
  2280. temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
  2281. temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
  2282. }
  2283. if (n == 480)
  2284. ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
  2285. else
  2286. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2287. for (i = 0; i < n; i+=2) {
  2288. buf[i] = -buf[i];
  2289. }
  2290. // Like with the regular IMDCT at this point we still have the middle half
  2291. // of a transform but with even symmetry on the left and odd symmetry on
  2292. // the right
  2293. // window overlapping
  2294. // The spec says to use samples [0..511] but the reference decoder uses
  2295. // samples [128..639].
  2296. for (i = n4; i < n2; i ++) {
  2297. out[i - n4] = buf[n2 - 1 - i] * window[i - n4] +
  2298. saved[ i + n2] * window[i + n - n4] +
  2299. -saved[ n + n2 - 1 - i] * window[i + 2*n - n4] +
  2300. -saved[2*n + n2 + i] * window[i + 3*n - n4];
  2301. }
  2302. for (i = 0; i < n2; i ++) {
  2303. out[n4 + i] = buf[i] * window[i + n2 - n4] +
  2304. -saved[ n - 1 - i] * window[i + n2 + n - n4] +
  2305. -saved[ n + i] * window[i + n2 + 2*n - n4] +
  2306. saved[2*n + n - 1 - i] * window[i + n2 + 3*n - n4];
  2307. }
  2308. for (i = 0; i < n4; i ++) {
  2309. out[n2 + n4 + i] = buf[ i + n2] * window[i + n - n4] +
  2310. -saved[ n2 - 1 - i] * window[i + 2*n - n4] +
  2311. -saved[ n + n2 + i] * window[i + 3*n - n4];
  2312. }
  2313. // buffer update
  2314. memmove(saved + n, saved, 2 * n * sizeof(float));
  2315. memcpy( saved, buf, n * sizeof(float));
  2316. }
  2317. /**
  2318. * Apply dependent channel coupling (applied before IMDCT).
  2319. *
  2320. * @param index index into coupling gain array
  2321. */
  2322. static void apply_dependent_coupling(AACContext *ac,
  2323. SingleChannelElement *target,
  2324. ChannelElement *cce, int index)
  2325. {
  2326. IndividualChannelStream *ics = &cce->ch[0].ics;
  2327. const uint16_t *offsets = ics->swb_offset;
  2328. float *dest = target->coeffs;
  2329. const float *src = cce->ch[0].coeffs;
  2330. int g, i, group, k, idx = 0;
  2331. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
  2332. av_log(ac->avctx, AV_LOG_ERROR,
  2333. "Dependent coupling is not supported together with LTP\n");
  2334. return;
  2335. }
  2336. for (g = 0; g < ics->num_window_groups; g++) {
  2337. for (i = 0; i < ics->max_sfb; i++, idx++) {
  2338. if (cce->ch[0].band_type[idx] != ZERO_BT) {
  2339. const float gain = cce->coup.gain[index][idx];
  2340. for (group = 0; group < ics->group_len[g]; group++) {
  2341. for (k = offsets[i]; k < offsets[i + 1]; k++) {
  2342. // FIXME: SIMDify
  2343. dest[group * 128 + k] += gain * src[group * 128 + k];
  2344. }
  2345. }
  2346. }
  2347. }
  2348. dest += ics->group_len[g] * 128;
  2349. src += ics->group_len[g] * 128;
  2350. }
  2351. }
  2352. /**
  2353. * Apply independent channel coupling (applied after IMDCT).
  2354. *
  2355. * @param index index into coupling gain array
  2356. */
  2357. static void apply_independent_coupling(AACContext *ac,
  2358. SingleChannelElement *target,
  2359. ChannelElement *cce, int index)
  2360. {
  2361. int i;
  2362. const float gain = cce->coup.gain[index][0];
  2363. const float *src = cce->ch[0].ret;
  2364. float *dest = target->ret;
  2365. const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);
  2366. for (i = 0; i < len; i++)
  2367. dest[i] += gain * src[i];
  2368. }
  2369. /**
  2370. * channel coupling transformation interface
  2371. *
  2372. * @param apply_coupling_method pointer to (in)dependent coupling function
  2373. */
  2374. static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
  2375. enum RawDataBlockType type, int elem_id,
  2376. enum CouplingPoint coupling_point,
  2377. void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
  2378. {
  2379. int i, c;
  2380. for (i = 0; i < MAX_ELEM_ID; i++) {
  2381. ChannelElement *cce = ac->che[TYPE_CCE][i];
  2382. int index = 0;
  2383. if (cce && cce->coup.coupling_point == coupling_point) {
  2384. ChannelCoupling *coup = &cce->coup;
  2385. for (c = 0; c <= coup->num_coupled; c++) {
  2386. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  2387. if (coup->ch_select[c] != 1) {
  2388. apply_coupling_method(ac, &cc->ch[0], cce, index);
  2389. if (coup->ch_select[c] != 0)
  2390. index++;
  2391. }
  2392. if (coup->ch_select[c] != 2)
  2393. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  2394. } else
  2395. index += 1 + (coup->ch_select[c] == 3);
  2396. }
  2397. }
  2398. }
  2399. }
  2400. /**
  2401. * Convert spectral data to float samples, applying all supported tools as appropriate.
  2402. */
  2403. static void spectral_to_sample(AACContext *ac)
  2404. {
  2405. int i, type;
  2406. void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
  2407. switch (ac->oc[1].m4ac.object_type) {
  2408. case AOT_ER_AAC_LD:
  2409. imdct_and_window = imdct_and_windowing_ld;
  2410. break;
  2411. case AOT_ER_AAC_ELD:
  2412. imdct_and_window = imdct_and_windowing_eld;
  2413. break;
  2414. default:
  2415. imdct_and_window = imdct_and_windowing;
  2416. }
  2417. for (type = 3; type >= 0; type--) {
  2418. for (i = 0; i < MAX_ELEM_ID; i++) {
  2419. ChannelElement *che = ac->che[type][i];
  2420. if (che) {
  2421. if (type <= TYPE_CPE)
  2422. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
  2423. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
  2424. if (che->ch[0].ics.predictor_present) {
  2425. if (che->ch[0].ics.ltp.present)
  2426. apply_ltp(ac, &che->ch[0]);
  2427. if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
  2428. apply_ltp(ac, &che->ch[1]);
  2429. }
  2430. }
  2431. if (che->ch[0].tns.present)
  2432. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  2433. if (che->ch[1].tns.present)
  2434. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  2435. if (type <= TYPE_CPE)
  2436. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
  2437. if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
  2438. imdct_and_window(ac, &che->ch[0]);
  2439. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2440. update_ltp(ac, &che->ch[0]);
  2441. if (type == TYPE_CPE) {
  2442. imdct_and_window(ac, &che->ch[1]);
  2443. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2444. update_ltp(ac, &che->ch[1]);
  2445. }
  2446. if (ac->oc[1].m4ac.sbr > 0) {
  2447. ff_sbr_apply(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
  2448. }
  2449. }
  2450. if (type <= TYPE_CCE)
  2451. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
  2452. }
  2453. }
  2454. }
  2455. }
  2456. static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
  2457. {
  2458. int size;
  2459. AACADTSHeaderInfo hdr_info;
  2460. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2461. int layout_map_tags, ret;
  2462. size = avpriv_aac_parse_header(gb, &hdr_info);
  2463. if (size > 0) {
  2464. if (hdr_info.num_aac_frames != 1) {
  2465. avpriv_report_missing_feature(ac->avctx,
  2466. "More than one AAC RDB per ADTS frame");
  2467. return AVERROR_PATCHWELCOME;
  2468. }
  2469. push_output_configuration(ac);
  2470. if (hdr_info.chan_config) {
  2471. ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
  2472. if ((ret = set_default_channel_config(ac->avctx,
  2473. layout_map,
  2474. &layout_map_tags,
  2475. hdr_info.chan_config)) < 0)
  2476. return ret;
  2477. if ((ret = output_configure(ac, layout_map, layout_map_tags,
  2478. FFMAX(ac->oc[1].status,
  2479. OC_TRIAL_FRAME), 0)) < 0)
  2480. return ret;
  2481. } else {
  2482. ac->oc[1].m4ac.chan_config = 0;
  2483. }
  2484. ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
  2485. ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
  2486. ac->oc[1].m4ac.object_type = hdr_info.object_type;
  2487. ac->oc[1].m4ac.frame_length_short = 0;
  2488. if (ac->oc[0].status != OC_LOCKED ||
  2489. ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
  2490. ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
  2491. ac->oc[1].m4ac.sbr = -1;
  2492. ac->oc[1].m4ac.ps = -1;
  2493. }
  2494. if (!hdr_info.crc_absent)
  2495. skip_bits(gb, 16);
  2496. }
  2497. return size;
  2498. }
  2499. static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
  2500. int *got_frame_ptr, GetBitContext *gb)
  2501. {
  2502. AACContext *ac = avctx->priv_data;
  2503. const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
  2504. ChannelElement *che;
  2505. int err, i;
  2506. int samples = m4ac->frame_length_short ? 960 : 1024;
  2507. int chan_config = m4ac->chan_config;
  2508. int aot = m4ac->object_type;
  2509. if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
  2510. samples >>= 1;
  2511. ac->frame = data;
  2512. if ((err = frame_configure_elements(avctx)) < 0)
  2513. return err;
  2514. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2515. // This may lead to an undefined profile being signaled
  2516. ac->avctx->profile = aot - 1;
  2517. ac->tags_mapped = 0;
  2518. if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
  2519. avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
  2520. chan_config);
  2521. return AVERROR_INVALIDDATA;
  2522. }
  2523. for (i = 0; i < tags_per_config[chan_config]; i++) {
  2524. const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
  2525. const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
  2526. if (!(che=get_che(ac, elem_type, elem_id))) {
  2527. av_log(ac->avctx, AV_LOG_ERROR,
  2528. "channel element %d.%d is not allocated\n",
  2529. elem_type, elem_id);
  2530. return AVERROR_INVALIDDATA;
  2531. }
  2532. if (aot != AOT_ER_AAC_ELD)
  2533. skip_bits(gb, 4);
  2534. switch (elem_type) {
  2535. case TYPE_SCE:
  2536. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2537. break;
  2538. case TYPE_CPE:
  2539. err = decode_cpe(ac, gb, che);
  2540. break;
  2541. case TYPE_LFE:
  2542. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2543. break;
  2544. }
  2545. if (err < 0)
  2546. return err;
  2547. }
  2548. spectral_to_sample(ac);
  2549. ac->frame->nb_samples = samples;
  2550. ac->frame->sample_rate = avctx->sample_rate;
  2551. *got_frame_ptr = 1;
  2552. skip_bits_long(gb, get_bits_left(gb));
  2553. return 0;
  2554. }
  2555. static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
  2556. int *got_frame_ptr, GetBitContext *gb)
  2557. {
  2558. AACContext *ac = avctx->priv_data;
  2559. ChannelElement *che = NULL, *che_prev = NULL;
  2560. enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
  2561. int err, elem_id;
  2562. int samples = 0, multiplier, audio_found = 0, pce_found = 0;
  2563. ac->frame = data;
  2564. if (show_bits(gb, 12) == 0xfff) {
  2565. if ((err = parse_adts_frame_header(ac, gb)) < 0) {
  2566. av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
  2567. goto fail;
  2568. }
  2569. if (ac->oc[1].m4ac.sampling_index > 12) {
  2570. av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
  2571. err = AVERROR_INVALIDDATA;
  2572. goto fail;
  2573. }
  2574. }
  2575. if (avctx->channels)
  2576. if ((err = frame_configure_elements(avctx)) < 0)
  2577. goto fail;
  2578. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2579. // This may lead to an undefined profile being signaled
  2580. ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
  2581. ac->tags_mapped = 0;
  2582. // parse
  2583. while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
  2584. elem_id = get_bits(gb, 4);
  2585. if (!avctx->channels && elem_type != TYPE_PCE) {
  2586. err = AVERROR_INVALIDDATA;
  2587. goto fail;
  2588. }
  2589. if (elem_type < TYPE_DSE) {
  2590. if (!(che=get_che(ac, elem_type, elem_id))) {
  2591. av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
  2592. elem_type, elem_id);
  2593. err = AVERROR_INVALIDDATA;
  2594. goto fail;
  2595. }
  2596. samples = 1024;
  2597. }
  2598. switch (elem_type) {
  2599. case TYPE_SCE:
  2600. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2601. audio_found = 1;
  2602. break;
  2603. case TYPE_CPE:
  2604. err = decode_cpe(ac, gb, che);
  2605. audio_found = 1;
  2606. break;
  2607. case TYPE_CCE:
  2608. err = decode_cce(ac, gb, che);
  2609. break;
  2610. case TYPE_LFE:
  2611. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2612. audio_found = 1;
  2613. break;
  2614. case TYPE_DSE:
  2615. err = skip_data_stream_element(ac, gb);
  2616. break;
  2617. case TYPE_PCE: {
  2618. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2619. int tags;
  2620. push_output_configuration(ac);
  2621. tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
  2622. if (tags < 0) {
  2623. err = tags;
  2624. break;
  2625. }
  2626. if (pce_found) {
  2627. av_log(avctx, AV_LOG_ERROR,
  2628. "Not evaluating a further program_config_element as this construct is dubious at best.\n");
  2629. pop_output_configuration(ac);
  2630. } else {
  2631. err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
  2632. pce_found = 1;
  2633. }
  2634. break;
  2635. }
  2636. case TYPE_FIL:
  2637. if (elem_id == 15)
  2638. elem_id += get_bits(gb, 8) - 1;
  2639. if (get_bits_left(gb) < 8 * elem_id) {
  2640. av_log(avctx, AV_LOG_ERROR, overread_err);
  2641. err = AVERROR_INVALIDDATA;
  2642. goto fail;
  2643. }
  2644. while (elem_id > 0)
  2645. elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
  2646. err = 0; /* FIXME */
  2647. break;
  2648. default:
  2649. err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
  2650. break;
  2651. }
  2652. che_prev = che;
  2653. elem_type_prev = elem_type;
  2654. if (err)
  2655. goto fail;
  2656. if (get_bits_left(gb) < 3) {
  2657. av_log(avctx, AV_LOG_ERROR, overread_err);
  2658. err = AVERROR_INVALIDDATA;
  2659. goto fail;
  2660. }
  2661. }
  2662. if (!avctx->channels) {
  2663. *got_frame_ptr = 0;
  2664. return 0;
  2665. }
  2666. spectral_to_sample(ac);
  2667. multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
  2668. samples <<= multiplier;
  2669. if (ac->oc[1].status && audio_found) {
  2670. avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
  2671. avctx->frame_size = samples;
  2672. ac->oc[1].status = OC_LOCKED;
  2673. }
  2674. if (samples) {
  2675. ac->frame->nb_samples = samples;
  2676. ac->frame->sample_rate = avctx->sample_rate;
  2677. }
  2678. *got_frame_ptr = !!samples;
  2679. return 0;
  2680. fail:
  2681. pop_output_configuration(ac);
  2682. return err;
  2683. }
  2684. static int aac_decode_frame(AVCodecContext *avctx, void *data,
  2685. int *got_frame_ptr, AVPacket *avpkt)
  2686. {
  2687. AACContext *ac = avctx->priv_data;
  2688. const uint8_t *buf = avpkt->data;
  2689. int buf_size = avpkt->size;
  2690. GetBitContext gb;
  2691. int buf_consumed;
  2692. int buf_offset;
  2693. int err;
  2694. int new_extradata_size;
  2695. const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
  2696. AV_PKT_DATA_NEW_EXTRADATA,
  2697. &new_extradata_size);
  2698. if (new_extradata) {
  2699. av_free(avctx->extradata);
  2700. avctx->extradata = av_mallocz(new_extradata_size +
  2701. AV_INPUT_BUFFER_PADDING_SIZE);
  2702. if (!avctx->extradata)
  2703. return AVERROR(ENOMEM);
  2704. avctx->extradata_size = new_extradata_size;
  2705. memcpy(avctx->extradata, new_extradata, new_extradata_size);
  2706. push_output_configuration(ac);
  2707. if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
  2708. avctx->extradata,
  2709. avctx->extradata_size*8, 1) < 0) {
  2710. pop_output_configuration(ac);
  2711. return AVERROR_INVALIDDATA;
  2712. }
  2713. }
  2714. if ((err = init_get_bits(&gb, buf, buf_size * 8)) < 0)
  2715. return err;
  2716. switch (ac->oc[1].m4ac.object_type) {
  2717. case AOT_ER_AAC_LC:
  2718. case AOT_ER_AAC_LTP:
  2719. case AOT_ER_AAC_LD:
  2720. case AOT_ER_AAC_ELD:
  2721. err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
  2722. break;
  2723. default:
  2724. err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb);
  2725. }
  2726. if (err < 0)
  2727. return err;
  2728. buf_consumed = (get_bits_count(&gb) + 7) >> 3;
  2729. for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
  2730. if (buf[buf_offset])
  2731. break;
  2732. return buf_size > buf_offset ? buf_consumed : buf_size;
  2733. }
  2734. static av_cold int aac_decode_close(AVCodecContext *avctx)
  2735. {
  2736. AACContext *ac = avctx->priv_data;
  2737. int i, type;
  2738. for (i = 0; i < MAX_ELEM_ID; i++) {
  2739. for (type = 0; type < 4; type++) {
  2740. if (ac->che[type][i])
  2741. ff_aac_sbr_ctx_close(&ac->che[type][i]->sbr);
  2742. av_freep(&ac->che[type][i]);
  2743. }
  2744. }
  2745. ff_mdct_end(&ac->mdct);
  2746. ff_mdct_end(&ac->mdct_small);
  2747. ff_mdct_end(&ac->mdct_ld);
  2748. ff_mdct_end(&ac->mdct_ltp);
  2749. ff_imdct15_uninit(&ac->mdct480);
  2750. return 0;
  2751. }
  2752. #define LOAS_SYNC_WORD 0x2b7 ///< 11 bits LOAS sync word
  2753. struct LATMContext {
  2754. AACContext aac_ctx; ///< containing AACContext
  2755. int initialized; ///< initialized after a valid extradata was seen
  2756. // parser data
  2757. int audio_mux_version_A; ///< LATM syntax version
  2758. int frame_length_type; ///< 0/1 variable/fixed frame length
  2759. int frame_length; ///< frame length for fixed frame length
  2760. };
  2761. static inline uint32_t latm_get_value(GetBitContext *b)
  2762. {
  2763. int length = get_bits(b, 2);
  2764. return get_bits_long(b, (length+1)*8);
  2765. }
  2766. static int latm_decode_audio_specific_config(struct LATMContext *latmctx,
  2767. GetBitContext *gb, int asclen)
  2768. {
  2769. AACContext *ac = &latmctx->aac_ctx;
  2770. AVCodecContext *avctx = ac->avctx;
  2771. MPEG4AudioConfig m4ac = { 0 };
  2772. int config_start_bit = get_bits_count(gb);
  2773. int sync_extension = 0;
  2774. int bits_consumed, esize;
  2775. if (asclen) {
  2776. sync_extension = 1;
  2777. asclen = FFMIN(asclen, get_bits_left(gb));
  2778. } else
  2779. asclen = get_bits_left(gb);
  2780. if (config_start_bit % 8) {
  2781. avpriv_request_sample(latmctx->aac_ctx.avctx,
  2782. "Non-byte-aligned audio-specific config");
  2783. return AVERROR_PATCHWELCOME;
  2784. }
  2785. if (asclen <= 0)
  2786. return AVERROR_INVALIDDATA;
  2787. bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,
  2788. gb->buffer + (config_start_bit / 8),
  2789. asclen, sync_extension);
  2790. if (bits_consumed < 0)
  2791. return AVERROR_INVALIDDATA;
  2792. if (!latmctx->initialized ||
  2793. ac->oc[1].m4ac.sample_rate != m4ac.sample_rate ||
  2794. ac->oc[1].m4ac.chan_config != m4ac.chan_config) {
  2795. av_log(avctx, AV_LOG_INFO, "audio config changed\n");
  2796. latmctx->initialized = 0;
  2797. esize = (bits_consumed+7) / 8;
  2798. if (avctx->extradata_size < esize) {
  2799. av_free(avctx->extradata);
  2800. avctx->extradata = av_malloc(esize + AV_INPUT_BUFFER_PADDING_SIZE);
  2801. if (!avctx->extradata)
  2802. return AVERROR(ENOMEM);
  2803. }
  2804. avctx->extradata_size = esize;
  2805. memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);
  2806. memset(avctx->extradata+esize, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  2807. }
  2808. skip_bits_long(gb, bits_consumed);
  2809. return bits_consumed;
  2810. }
  2811. static int read_stream_mux_config(struct LATMContext *latmctx,
  2812. GetBitContext *gb)
  2813. {
  2814. int ret, audio_mux_version = get_bits(gb, 1);
  2815. latmctx->audio_mux_version_A = 0;
  2816. if (audio_mux_version)
  2817. latmctx->audio_mux_version_A = get_bits(gb, 1);
  2818. if (!latmctx->audio_mux_version_A) {
  2819. if (audio_mux_version)
  2820. latm_get_value(gb); // taraFullness
  2821. skip_bits(gb, 1); // allStreamSameTimeFraming
  2822. skip_bits(gb, 6); // numSubFrames
  2823. // numPrograms
  2824. if (get_bits(gb, 4)) { // numPrograms
  2825. avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple programs");
  2826. return AVERROR_PATCHWELCOME;
  2827. }
  2828. // for each program (which there is only on in DVB)
  2829. // for each layer (which there is only on in DVB)
  2830. if (get_bits(gb, 3)) { // numLayer
  2831. avpriv_request_sample(latmctx->aac_ctx.avctx, "Multiple layers");
  2832. return AVERROR_PATCHWELCOME;
  2833. }
  2834. // for all but first stream: use_same_config = get_bits(gb, 1);
  2835. if (!audio_mux_version) {
  2836. if ((ret = latm_decode_audio_specific_config(latmctx, gb, 0)) < 0)
  2837. return ret;
  2838. } else {
  2839. int ascLen = latm_get_value(gb);
  2840. if ((ret = latm_decode_audio_specific_config(latmctx, gb, ascLen)) < 0)
  2841. return ret;
  2842. ascLen -= ret;
  2843. skip_bits_long(gb, ascLen);
  2844. }
  2845. latmctx->frame_length_type = get_bits(gb, 3);
  2846. switch (latmctx->frame_length_type) {
  2847. case 0:
  2848. skip_bits(gb, 8); // latmBufferFullness
  2849. break;
  2850. case 1:
  2851. latmctx->frame_length = get_bits(gb, 9);
  2852. break;
  2853. case 3:
  2854. case 4:
  2855. case 5:
  2856. skip_bits(gb, 6); // CELP frame length table index
  2857. break;
  2858. case 6:
  2859. case 7:
  2860. skip_bits(gb, 1); // HVXC frame length table index
  2861. break;
  2862. }
  2863. if (get_bits(gb, 1)) { // other data
  2864. if (audio_mux_version) {
  2865. latm_get_value(gb); // other_data_bits
  2866. } else {
  2867. int esc;
  2868. do {
  2869. esc = get_bits(gb, 1);
  2870. skip_bits(gb, 8);
  2871. } while (esc);
  2872. }
  2873. }
  2874. if (get_bits(gb, 1)) // crc present
  2875. skip_bits(gb, 8); // config_crc
  2876. }
  2877. return 0;
  2878. }
  2879. static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb)
  2880. {
  2881. uint8_t tmp;
  2882. if (ctx->frame_length_type == 0) {
  2883. int mux_slot_length = 0;
  2884. do {
  2885. tmp = get_bits(gb, 8);
  2886. mux_slot_length += tmp;
  2887. } while (tmp == 255);
  2888. return mux_slot_length;
  2889. } else if (ctx->frame_length_type == 1) {
  2890. return ctx->frame_length;
  2891. } else if (ctx->frame_length_type == 3 ||
  2892. ctx->frame_length_type == 5 ||
  2893. ctx->frame_length_type == 7) {
  2894. skip_bits(gb, 2); // mux_slot_length_coded
  2895. }
  2896. return 0;
  2897. }
  2898. static int read_audio_mux_element(struct LATMContext *latmctx,
  2899. GetBitContext *gb)
  2900. {
  2901. int err;
  2902. uint8_t use_same_mux = get_bits(gb, 1);
  2903. if (!use_same_mux) {
  2904. if ((err = read_stream_mux_config(latmctx, gb)) < 0)
  2905. return err;
  2906. } else if (!latmctx->aac_ctx.avctx->extradata) {
  2907. av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,
  2908. "no decoder config found\n");
  2909. return AVERROR(EAGAIN);
  2910. }
  2911. if (latmctx->audio_mux_version_A == 0) {
  2912. int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);
  2913. if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {
  2914. av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");
  2915. return AVERROR_INVALIDDATA;
  2916. } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {
  2917. av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
  2918. "frame length mismatch %d << %d\n",
  2919. mux_slot_length_bytes * 8, get_bits_left(gb));
  2920. return AVERROR_INVALIDDATA;
  2921. }
  2922. }
  2923. return 0;
  2924. }
  2925. static int latm_decode_frame(AVCodecContext *avctx, void *out,
  2926. int *got_frame_ptr, AVPacket *avpkt)
  2927. {
  2928. struct LATMContext *latmctx = avctx->priv_data;
  2929. int muxlength, err;
  2930. GetBitContext gb;
  2931. if ((err = init_get_bits(&gb, avpkt->data, avpkt->size * 8)) < 0)
  2932. return err;
  2933. // check for LOAS sync word
  2934. if (get_bits(&gb, 11) != LOAS_SYNC_WORD)
  2935. return AVERROR_INVALIDDATA;
  2936. muxlength = get_bits(&gb, 13) + 3;
  2937. // not enough data, the parser should have sorted this
  2938. if (muxlength > avpkt->size)
  2939. return AVERROR_INVALIDDATA;
  2940. if ((err = read_audio_mux_element(latmctx, &gb)) < 0)
  2941. return err;
  2942. if (!latmctx->initialized) {
  2943. if (!avctx->extradata) {
  2944. *got_frame_ptr = 0;
  2945. return avpkt->size;
  2946. } else {
  2947. push_output_configuration(&latmctx->aac_ctx);
  2948. if ((err = decode_audio_specific_config(
  2949. &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,
  2950. avctx->extradata, avctx->extradata_size*8, 1)) < 0) {
  2951. pop_output_configuration(&latmctx->aac_ctx);
  2952. return err;
  2953. }
  2954. latmctx->initialized = 1;
  2955. }
  2956. }
  2957. if (show_bits(&gb, 12) == 0xfff) {
  2958. av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,
  2959. "ADTS header detected, probably as result of configuration "
  2960. "misparsing\n");
  2961. return AVERROR_INVALIDDATA;
  2962. }
  2963. switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {
  2964. case AOT_ER_AAC_LC:
  2965. case AOT_ER_AAC_LTP:
  2966. case AOT_ER_AAC_LD:
  2967. case AOT_ER_AAC_ELD:
  2968. err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);
  2969. break;
  2970. default:
  2971. err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb);
  2972. }
  2973. if (err < 0)
  2974. return err;
  2975. return muxlength;
  2976. }
  2977. static av_cold int latm_decode_init(AVCodecContext *avctx)
  2978. {
  2979. struct LATMContext *latmctx = avctx->priv_data;
  2980. int ret = aac_decode_init(avctx);
  2981. if (avctx->extradata_size > 0)
  2982. latmctx->initialized = !ret;
  2983. return ret;
  2984. }
  2985. AVCodec ff_aac_decoder = {
  2986. .name = "aac",
  2987. .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
  2988. .type = AVMEDIA_TYPE_AUDIO,
  2989. .id = AV_CODEC_ID_AAC,
  2990. .priv_data_size = sizeof(AACContext),
  2991. .init = aac_decode_init,
  2992. .close = aac_decode_close,
  2993. .decode = aac_decode_frame,
  2994. .sample_fmts = (const enum AVSampleFormat[]) {
  2995. AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
  2996. },
  2997. .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
  2998. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  2999. .channel_layouts = aac_channel_layout,
  3000. };
  3001. /*
  3002. Note: This decoder filter is intended to decode LATM streams transferred
  3003. in MPEG transport streams which only contain one program.
  3004. To do a more complex LATM demuxing a separate LATM demuxer should be used.
  3005. */
  3006. AVCodec ff_aac_latm_decoder = {
  3007. .name = "aac_latm",
  3008. .long_name = NULL_IF_CONFIG_SMALL("AAC LATM (Advanced Audio Coding LATM syntax)"),
  3009. .type = AVMEDIA_TYPE_AUDIO,
  3010. .id = AV_CODEC_ID_AAC_LATM,
  3011. .priv_data_size = sizeof(struct LATMContext),
  3012. .init = latm_decode_init,
  3013. .close = aac_decode_close,
  3014. .decode = latm_decode_frame,
  3015. .sample_fmts = (const enum AVSampleFormat[]) {
  3016. AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE
  3017. },
  3018. .capabilities = AV_CODEC_CAP_CHANNEL_CONF | AV_CODEC_CAP_DR1,
  3019. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  3020. .channel_layouts = aac_channel_layout,
  3021. };