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.

3547 lines
123KB

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