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.

3586 lines
125KB

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