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.

3126 lines
107KB

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