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.

3314 lines
114KB

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