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.

3345 lines
115KB

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