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.

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