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.

3298 lines
113KB

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