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.

3316 lines
114KB

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