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.

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