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.

3242 lines
116KB

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