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.

3572 lines
124KB

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