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.

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