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.

3287 lines
113KB

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