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.

3147 lines
108KB

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