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.

3269 lines
116KB

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