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.

3063 lines
106KB

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