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.

3303 lines
117KB

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