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.

3067 lines
105KB

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