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.

3291 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. if (decode_ics_info(ac, ics, gb) < 0)
  1801. return AVERROR_INVALIDDATA;
  1802. }
  1803. if ((ret = decode_band_types(ac, sce->band_type,
  1804. sce->band_type_run_end, gb, ics)) < 0)
  1805. return ret;
  1806. if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
  1807. sce->band_type, sce->band_type_run_end)) < 0)
  1808. return ret;
  1809. pulse_present = 0;
  1810. if (!scale_flag) {
  1811. if (!eld_syntax && (pulse_present = get_bits1(gb))) {
  1812. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1813. av_log(ac->avctx, AV_LOG_ERROR,
  1814. "Pulse tool not allowed in eight short sequence.\n");
  1815. return AVERROR_INVALIDDATA;
  1816. }
  1817. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  1818. av_log(ac->avctx, AV_LOG_ERROR,
  1819. "Pulse data corrupt or invalid.\n");
  1820. return AVERROR_INVALIDDATA;
  1821. }
  1822. }
  1823. tns->present = get_bits1(gb);
  1824. if (tns->present && !er_syntax)
  1825. if (decode_tns(ac, tns, gb, ics) < 0)
  1826. return AVERROR_INVALIDDATA;
  1827. if (!eld_syntax && get_bits1(gb)) {
  1828. avpriv_request_sample(ac->avctx, "SSR");
  1829. return AVERROR_PATCHWELCOME;
  1830. }
  1831. // I see no textual basis in the spec for this occurring after SSR gain
  1832. // control, but this is what both reference and real implmentations do
  1833. if (tns->present && er_syntax)
  1834. if (decode_tns(ac, tns, gb, ics) < 0)
  1835. return AVERROR_INVALIDDATA;
  1836. }
  1837. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
  1838. &pulse, ics, sce->band_type) < 0)
  1839. return AVERROR_INVALIDDATA;
  1840. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
  1841. apply_prediction(ac, sce);
  1842. return 0;
  1843. }
  1844. /**
  1845. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  1846. */
  1847. static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
  1848. {
  1849. const IndividualChannelStream *ics = &cpe->ch[0].ics;
  1850. INTFLOAT *ch0 = cpe->ch[0].coeffs;
  1851. INTFLOAT *ch1 = cpe->ch[1].coeffs;
  1852. int g, i, group, idx = 0;
  1853. const uint16_t *offsets = ics->swb_offset;
  1854. for (g = 0; g < ics->num_window_groups; g++) {
  1855. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1856. if (cpe->ms_mask[idx] &&
  1857. cpe->ch[0].band_type[idx] < NOISE_BT &&
  1858. cpe->ch[1].band_type[idx] < NOISE_BT) {
  1859. #if USE_FIXED
  1860. for (group = 0; group < ics->group_len[g]; group++) {
  1861. ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
  1862. ch1 + group * 128 + offsets[i],
  1863. offsets[i+1] - offsets[i]);
  1864. #else
  1865. for (group = 0; group < ics->group_len[g]; group++) {
  1866. ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
  1867. ch1 + group * 128 + offsets[i],
  1868. offsets[i+1] - offsets[i]);
  1869. #endif /* USE_FIXED */
  1870. }
  1871. }
  1872. }
  1873. ch0 += ics->group_len[g] * 128;
  1874. ch1 += ics->group_len[g] * 128;
  1875. }
  1876. }
  1877. /**
  1878. * intensity stereo decoding; reference: 4.6.8.2.3
  1879. *
  1880. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1881. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1882. * [3] reserved for scalable AAC
  1883. */
  1884. static void apply_intensity_stereo(AACContext *ac,
  1885. ChannelElement *cpe, int ms_present)
  1886. {
  1887. const IndividualChannelStream *ics = &cpe->ch[1].ics;
  1888. SingleChannelElement *sce1 = &cpe->ch[1];
  1889. INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  1890. const uint16_t *offsets = ics->swb_offset;
  1891. int g, group, i, idx = 0;
  1892. int c;
  1893. INTFLOAT scale;
  1894. for (g = 0; g < ics->num_window_groups; g++) {
  1895. for (i = 0; i < ics->max_sfb;) {
  1896. if (sce1->band_type[idx] == INTENSITY_BT ||
  1897. sce1->band_type[idx] == INTENSITY_BT2) {
  1898. const int bt_run_end = sce1->band_type_run_end[idx];
  1899. for (; i < bt_run_end; i++, idx++) {
  1900. c = -1 + 2 * (sce1->band_type[idx] - 14);
  1901. if (ms_present)
  1902. c *= 1 - 2 * cpe->ms_mask[idx];
  1903. scale = c * sce1->sf[idx];
  1904. for (group = 0; group < ics->group_len[g]; group++)
  1905. #if USE_FIXED
  1906. ac->subband_scale(coef1 + group * 128 + offsets[i],
  1907. coef0 + group * 128 + offsets[i],
  1908. scale,
  1909. 23,
  1910. offsets[i + 1] - offsets[i]);
  1911. #else
  1912. ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
  1913. coef0 + group * 128 + offsets[i],
  1914. scale,
  1915. offsets[i + 1] - offsets[i]);
  1916. #endif /* USE_FIXED */
  1917. }
  1918. } else {
  1919. int bt_run_end = sce1->band_type_run_end[idx];
  1920. idx += bt_run_end - i;
  1921. i = bt_run_end;
  1922. }
  1923. }
  1924. coef0 += ics->group_len[g] * 128;
  1925. coef1 += ics->group_len[g] * 128;
  1926. }
  1927. }
  1928. /**
  1929. * Decode a channel_pair_element; reference: table 4.4.
  1930. *
  1931. * @return Returns error status. 0 - OK, !0 - error
  1932. */
  1933. static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
  1934. {
  1935. int i, ret, common_window, ms_present = 0;
  1936. int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1937. common_window = eld_syntax || get_bits1(gb);
  1938. if (common_window) {
  1939. if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
  1940. return AVERROR_INVALIDDATA;
  1941. i = cpe->ch[1].ics.use_kb_window[0];
  1942. cpe->ch[1].ics = cpe->ch[0].ics;
  1943. cpe->ch[1].ics.use_kb_window[1] = i;
  1944. if (cpe->ch[1].ics.predictor_present &&
  1945. (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
  1946. if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
  1947. decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
  1948. ms_present = get_bits(gb, 2);
  1949. if (ms_present == 3) {
  1950. av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  1951. return AVERROR_INVALIDDATA;
  1952. } else if (ms_present)
  1953. decode_mid_side_stereo(cpe, gb, ms_present);
  1954. }
  1955. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  1956. return ret;
  1957. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  1958. return ret;
  1959. if (common_window) {
  1960. if (ms_present)
  1961. apply_mid_side_stereo(ac, cpe);
  1962. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
  1963. apply_prediction(ac, &cpe->ch[0]);
  1964. apply_prediction(ac, &cpe->ch[1]);
  1965. }
  1966. }
  1967. apply_intensity_stereo(ac, cpe, ms_present);
  1968. return 0;
  1969. }
  1970. static const float cce_scale[] = {
  1971. 1.09050773266525765921, //2^(1/8)
  1972. 1.18920711500272106672, //2^(1/4)
  1973. M_SQRT2,
  1974. 2,
  1975. };
  1976. /**
  1977. * Decode coupling_channel_element; reference: table 4.8.
  1978. *
  1979. * @return Returns error status. 0 - OK, !0 - error
  1980. */
  1981. static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
  1982. {
  1983. int num_gain = 0;
  1984. int c, g, sfb, ret;
  1985. int sign;
  1986. INTFLOAT scale;
  1987. SingleChannelElement *sce = &che->ch[0];
  1988. ChannelCoupling *coup = &che->coup;
  1989. coup->coupling_point = 2 * get_bits1(gb);
  1990. coup->num_coupled = get_bits(gb, 3);
  1991. for (c = 0; c <= coup->num_coupled; c++) {
  1992. num_gain++;
  1993. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1994. coup->id_select[c] = get_bits(gb, 4);
  1995. if (coup->type[c] == TYPE_CPE) {
  1996. coup->ch_select[c] = get_bits(gb, 2);
  1997. if (coup->ch_select[c] == 3)
  1998. num_gain++;
  1999. } else
  2000. coup->ch_select[c] = 2;
  2001. }
  2002. coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
  2003. sign = get_bits(gb, 1);
  2004. #if USE_FIXED
  2005. scale = get_bits(gb, 2);
  2006. #else
  2007. scale = cce_scale[get_bits(gb, 2)];
  2008. #endif
  2009. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  2010. return ret;
  2011. for (c = 0; c < num_gain; c++) {
  2012. int idx = 0;
  2013. int cge = 1;
  2014. int gain = 0;
  2015. INTFLOAT gain_cache = FIXR10(1.);
  2016. if (c) {
  2017. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  2018. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  2019. gain_cache = GET_GAIN(scale, gain);
  2020. #if USE_FIXED
  2021. if ((abs(gain_cache)-1024) >> 3 > 30)
  2022. return AVERROR(ERANGE);
  2023. #endif
  2024. }
  2025. if (coup->coupling_point == AFTER_IMDCT) {
  2026. coup->gain[c][0] = gain_cache;
  2027. } else {
  2028. for (g = 0; g < sce->ics.num_window_groups; g++) {
  2029. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  2030. if (sce->band_type[idx] != ZERO_BT) {
  2031. if (!cge) {
  2032. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  2033. if (t) {
  2034. int s = 1;
  2035. t = gain += t;
  2036. if (sign) {
  2037. s -= 2 * (t & 0x1);
  2038. t >>= 1;
  2039. }
  2040. gain_cache = GET_GAIN(scale, t) * s;
  2041. #if USE_FIXED
  2042. if ((abs(gain_cache)-1024) >> 3 > 30)
  2043. return AVERROR(ERANGE);
  2044. #endif
  2045. }
  2046. }
  2047. coup->gain[c][idx] = gain_cache;
  2048. }
  2049. }
  2050. }
  2051. }
  2052. }
  2053. return 0;
  2054. }
  2055. /**
  2056. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  2057. *
  2058. * @return Returns number of bytes consumed.
  2059. */
  2060. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
  2061. GetBitContext *gb)
  2062. {
  2063. int i;
  2064. int num_excl_chan = 0;
  2065. do {
  2066. for (i = 0; i < 7; i++)
  2067. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  2068. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  2069. return num_excl_chan / 7;
  2070. }
  2071. /**
  2072. * Decode dynamic range information; reference: table 4.52.
  2073. *
  2074. * @return Returns number of bytes consumed.
  2075. */
  2076. static int decode_dynamic_range(DynamicRangeControl *che_drc,
  2077. GetBitContext *gb)
  2078. {
  2079. int n = 1;
  2080. int drc_num_bands = 1;
  2081. int i;
  2082. /* pce_tag_present? */
  2083. if (get_bits1(gb)) {
  2084. che_drc->pce_instance_tag = get_bits(gb, 4);
  2085. skip_bits(gb, 4); // tag_reserved_bits
  2086. n++;
  2087. }
  2088. /* excluded_chns_present? */
  2089. if (get_bits1(gb)) {
  2090. n += decode_drc_channel_exclusions(che_drc, gb);
  2091. }
  2092. /* drc_bands_present? */
  2093. if (get_bits1(gb)) {
  2094. che_drc->band_incr = get_bits(gb, 4);
  2095. che_drc->interpolation_scheme = get_bits(gb, 4);
  2096. n++;
  2097. drc_num_bands += che_drc->band_incr;
  2098. for (i = 0; i < drc_num_bands; i++) {
  2099. che_drc->band_top[i] = get_bits(gb, 8);
  2100. n++;
  2101. }
  2102. }
  2103. /* prog_ref_level_present? */
  2104. if (get_bits1(gb)) {
  2105. che_drc->prog_ref_level = get_bits(gb, 7);
  2106. skip_bits1(gb); // prog_ref_level_reserved_bits
  2107. n++;
  2108. }
  2109. for (i = 0; i < drc_num_bands; i++) {
  2110. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  2111. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  2112. n++;
  2113. }
  2114. return n;
  2115. }
  2116. static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
  2117. uint8_t buf[256];
  2118. int i, major, minor;
  2119. if (len < 13+7*8)
  2120. goto unknown;
  2121. get_bits(gb, 13); len -= 13;
  2122. for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
  2123. buf[i] = get_bits(gb, 8);
  2124. buf[i] = 0;
  2125. if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
  2126. av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
  2127. if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
  2128. ac->avctx->internal->skip_samples = 1024;
  2129. }
  2130. unknown:
  2131. skip_bits_long(gb, len);
  2132. return 0;
  2133. }
  2134. /**
  2135. * Decode extension data (incomplete); reference: table 4.51.
  2136. *
  2137. * @param cnt length of TYPE_FIL syntactic element in bytes
  2138. *
  2139. * @return Returns number of bytes consumed
  2140. */
  2141. static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
  2142. ChannelElement *che, enum RawDataBlockType elem_type)
  2143. {
  2144. int crc_flag = 0;
  2145. int res = cnt;
  2146. int type = get_bits(gb, 4);
  2147. if (ac->avctx->debug & FF_DEBUG_STARTCODE)
  2148. av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
  2149. switch (type) { // extension type
  2150. case EXT_SBR_DATA_CRC:
  2151. crc_flag++;
  2152. case EXT_SBR_DATA:
  2153. if (!che) {
  2154. av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
  2155. return res;
  2156. } else if (!ac->oc[1].m4ac.sbr) {
  2157. av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
  2158. skip_bits_long(gb, 8 * cnt - 4);
  2159. return res;
  2160. } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
  2161. av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
  2162. skip_bits_long(gb, 8 * cnt - 4);
  2163. return res;
  2164. } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
  2165. ac->oc[1].m4ac.sbr = 1;
  2166. ac->oc[1].m4ac.ps = 1;
  2167. ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
  2168. output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
  2169. ac->oc[1].status, 1);
  2170. } else {
  2171. ac->oc[1].m4ac.sbr = 1;
  2172. ac->avctx->profile = FF_PROFILE_AAC_HE;
  2173. }
  2174. res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
  2175. break;
  2176. case EXT_DYNAMIC_RANGE:
  2177. res = decode_dynamic_range(&ac->che_drc, gb);
  2178. break;
  2179. case EXT_FILL:
  2180. decode_fill(ac, gb, 8 * cnt - 4);
  2181. break;
  2182. case EXT_FILL_DATA:
  2183. case EXT_DATA_ELEMENT:
  2184. default:
  2185. skip_bits_long(gb, 8 * cnt - 4);
  2186. break;
  2187. };
  2188. return res;
  2189. }
  2190. /**
  2191. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  2192. *
  2193. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  2194. * @param coef spectral coefficients
  2195. */
  2196. static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns,
  2197. IndividualChannelStream *ics, int decode)
  2198. {
  2199. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  2200. int w, filt, m, i;
  2201. int bottom, top, order, start, end, size, inc;
  2202. INTFLOAT lpc[TNS_MAX_ORDER];
  2203. INTFLOAT tmp[TNS_MAX_ORDER+1];
  2204. UINTFLOAT *coef = coef_param;
  2205. for (w = 0; w < ics->num_windows; w++) {
  2206. bottom = ics->num_swb;
  2207. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  2208. top = bottom;
  2209. bottom = FFMAX(0, top - tns->length[w][filt]);
  2210. order = tns->order[w][filt];
  2211. if (order == 0)
  2212. continue;
  2213. // tns_decode_coef
  2214. AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
  2215. start = ics->swb_offset[FFMIN(bottom, mmm)];
  2216. end = ics->swb_offset[FFMIN( top, mmm)];
  2217. if ((size = end - start) <= 0)
  2218. continue;
  2219. if (tns->direction[w][filt]) {
  2220. inc = -1;
  2221. start = end - 1;
  2222. } else {
  2223. inc = 1;
  2224. }
  2225. start += w * 128;
  2226. if (decode) {
  2227. // ar filter
  2228. for (m = 0; m < size; m++, start += inc)
  2229. for (i = 1; i <= FFMIN(m, order); i++)
  2230. coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]);
  2231. } else {
  2232. // ma filter
  2233. for (m = 0; m < size; m++, start += inc) {
  2234. tmp[0] = coef[start];
  2235. for (i = 1; i <= FFMIN(m, order); i++)
  2236. coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
  2237. for (i = order; i > 0; i--)
  2238. tmp[i] = tmp[i - 1];
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. /**
  2245. * Apply windowing and MDCT to obtain the spectral
  2246. * coefficient from the predicted sample by LTP.
  2247. */
  2248. static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
  2249. INTFLOAT *in, IndividualChannelStream *ics)
  2250. {
  2251. const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2252. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2253. const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2254. const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2255. if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
  2256. ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
  2257. } else {
  2258. memset(in, 0, 448 * sizeof(*in));
  2259. ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
  2260. }
  2261. if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
  2262. ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
  2263. } else {
  2264. ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
  2265. memset(in + 1024 + 576, 0, 448 * sizeof(*in));
  2266. }
  2267. ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
  2268. }
  2269. /**
  2270. * Apply the long term prediction
  2271. */
  2272. static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
  2273. {
  2274. const LongTermPrediction *ltp = &sce->ics.ltp;
  2275. const uint16_t *offsets = sce->ics.swb_offset;
  2276. int i, sfb;
  2277. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  2278. INTFLOAT *predTime = sce->ret;
  2279. INTFLOAT *predFreq = ac->buf_mdct;
  2280. int16_t num_samples = 2048;
  2281. if (ltp->lag < 1024)
  2282. num_samples = ltp->lag + 1024;
  2283. for (i = 0; i < num_samples; i++)
  2284. predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
  2285. memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
  2286. ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
  2287. if (sce->tns.present)
  2288. ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
  2289. for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
  2290. if (ltp->used[sfb])
  2291. for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
  2292. sce->coeffs[i] += predFreq[i];
  2293. }
  2294. }
  2295. /**
  2296. * Update the LTP buffer for next frame
  2297. */
  2298. static void update_ltp(AACContext *ac, SingleChannelElement *sce)
  2299. {
  2300. IndividualChannelStream *ics = &sce->ics;
  2301. INTFLOAT *saved = sce->saved;
  2302. INTFLOAT *saved_ltp = sce->coeffs;
  2303. const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2304. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2305. int i;
  2306. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2307. memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
  2308. memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
  2309. ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2310. for (i = 0; i < 64; i++)
  2311. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
  2312. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2313. memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
  2314. memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
  2315. ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2316. for (i = 0; i < 64; i++)
  2317. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
  2318. } else { // LONG_STOP or ONLY_LONG
  2319. ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
  2320. for (i = 0; i < 512; i++)
  2321. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
  2322. }
  2323. memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
  2324. memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
  2325. memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
  2326. }
  2327. /**
  2328. * Conduct IMDCT and windowing.
  2329. */
  2330. static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
  2331. {
  2332. IndividualChannelStream *ics = &sce->ics;
  2333. INTFLOAT *in = sce->coeffs;
  2334. INTFLOAT *out = sce->ret;
  2335. INTFLOAT *saved = sce->saved;
  2336. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2337. const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2338. const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2339. INTFLOAT *buf = ac->buf_mdct;
  2340. INTFLOAT *temp = ac->temp;
  2341. int i;
  2342. // imdct
  2343. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2344. for (i = 0; i < 1024; i += 128)
  2345. ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
  2346. } else {
  2347. ac->mdct.imdct_half(&ac->mdct, buf, in);
  2348. #if USE_FIXED
  2349. for (i=0; i<1024; i++)
  2350. buf[i] = (buf[i] + 4) >> 3;
  2351. #endif /* USE_FIXED */
  2352. }
  2353. /* window overlapping
  2354. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  2355. * and long to short transitions are considered to be short to short
  2356. * transitions. This leaves just two cases (long to long and short to short)
  2357. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  2358. */
  2359. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  2360. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  2361. ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
  2362. } else {
  2363. memcpy( out, saved, 448 * sizeof(*out));
  2364. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2365. ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
  2366. ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
  2367. ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
  2368. ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
  2369. ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
  2370. memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
  2371. } else {
  2372. ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
  2373. memcpy( out + 576, buf + 64, 448 * sizeof(*out));
  2374. }
  2375. }
  2376. // buffer update
  2377. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2378. memcpy( saved, temp + 64, 64 * sizeof(*saved));
  2379. ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
  2380. ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
  2381. ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
  2382. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
  2383. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2384. memcpy( saved, buf + 512, 448 * sizeof(*saved));
  2385. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
  2386. } else { // LONG_STOP or ONLY_LONG
  2387. memcpy( saved, buf + 512, 512 * sizeof(*saved));
  2388. }
  2389. }
  2390. static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
  2391. {
  2392. IndividualChannelStream *ics = &sce->ics;
  2393. INTFLOAT *in = sce->coeffs;
  2394. INTFLOAT *out = sce->ret;
  2395. INTFLOAT *saved = sce->saved;
  2396. INTFLOAT *buf = ac->buf_mdct;
  2397. #if USE_FIXED
  2398. int i;
  2399. #endif /* USE_FIXED */
  2400. // imdct
  2401. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2402. #if USE_FIXED
  2403. for (i = 0; i < 1024; i++)
  2404. buf[i] = (buf[i] + 2) >> 2;
  2405. #endif /* USE_FIXED */
  2406. // window overlapping
  2407. if (ics->use_kb_window[1]) {
  2408. // AAC LD uses a low overlap sine window instead of a KBD window
  2409. memcpy(out, saved, 192 * sizeof(*out));
  2410. ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
  2411. memcpy( out + 320, buf + 64, 192 * sizeof(*out));
  2412. } else {
  2413. ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
  2414. }
  2415. // buffer update
  2416. memcpy(saved, buf + 256, 256 * sizeof(*saved));
  2417. }
  2418. static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
  2419. {
  2420. INTFLOAT *in = sce->coeffs;
  2421. INTFLOAT *out = sce->ret;
  2422. INTFLOAT *saved = sce->saved;
  2423. INTFLOAT *buf = ac->buf_mdct;
  2424. int i;
  2425. const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
  2426. const int n2 = n >> 1;
  2427. const int n4 = n >> 2;
  2428. const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
  2429. AAC_RENAME(ff_aac_eld_window_512);
  2430. // Inverse transform, mapped to the conventional IMDCT by
  2431. // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
  2432. // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
  2433. // International Conference on Audio, Language and Image Processing, ICALIP 2008.
  2434. // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
  2435. for (i = 0; i < n2; i+=2) {
  2436. INTFLOAT temp;
  2437. temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
  2438. temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
  2439. }
  2440. #if !USE_FIXED
  2441. if (n == 480)
  2442. ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
  2443. else
  2444. #endif
  2445. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2446. #if USE_FIXED
  2447. for (i = 0; i < 1024; i++)
  2448. buf[i] = (buf[i] + 1) >> 1;
  2449. #endif /* USE_FIXED */
  2450. for (i = 0; i < n; i+=2) {
  2451. buf[i] = -buf[i];
  2452. }
  2453. // Like with the regular IMDCT at this point we still have the middle half
  2454. // of a transform but with even symmetry on the left and odd symmetry on
  2455. // the right
  2456. // window overlapping
  2457. // The spec says to use samples [0..511] but the reference decoder uses
  2458. // samples [128..639].
  2459. for (i = n4; i < n2; i ++) {
  2460. out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
  2461. AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
  2462. AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
  2463. AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
  2464. }
  2465. for (i = 0; i < n2; i ++) {
  2466. out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
  2467. AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
  2468. AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
  2469. AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
  2470. }
  2471. for (i = 0; i < n4; i ++) {
  2472. out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
  2473. AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
  2474. AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
  2475. }
  2476. // buffer update
  2477. memmove(saved + n, saved, 2 * n * sizeof(*saved));
  2478. memcpy( saved, buf, n * sizeof(*saved));
  2479. }
  2480. /**
  2481. * channel coupling transformation interface
  2482. *
  2483. * @param apply_coupling_method pointer to (in)dependent coupling function
  2484. */
  2485. static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
  2486. enum RawDataBlockType type, int elem_id,
  2487. enum CouplingPoint coupling_point,
  2488. void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
  2489. {
  2490. int i, c;
  2491. for (i = 0; i < MAX_ELEM_ID; i++) {
  2492. ChannelElement *cce = ac->che[TYPE_CCE][i];
  2493. int index = 0;
  2494. if (cce && cce->coup.coupling_point == coupling_point) {
  2495. ChannelCoupling *coup = &cce->coup;
  2496. for (c = 0; c <= coup->num_coupled; c++) {
  2497. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  2498. if (coup->ch_select[c] != 1) {
  2499. apply_coupling_method(ac, &cc->ch[0], cce, index);
  2500. if (coup->ch_select[c] != 0)
  2501. index++;
  2502. }
  2503. if (coup->ch_select[c] != 2)
  2504. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  2505. } else
  2506. index += 1 + (coup->ch_select[c] == 3);
  2507. }
  2508. }
  2509. }
  2510. }
  2511. /**
  2512. * Convert spectral data to samples, applying all supported tools as appropriate.
  2513. */
  2514. static void spectral_to_sample(AACContext *ac, int samples)
  2515. {
  2516. int i, type;
  2517. void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
  2518. switch (ac->oc[1].m4ac.object_type) {
  2519. case AOT_ER_AAC_LD:
  2520. imdct_and_window = imdct_and_windowing_ld;
  2521. break;
  2522. case AOT_ER_AAC_ELD:
  2523. imdct_and_window = imdct_and_windowing_eld;
  2524. break;
  2525. default:
  2526. imdct_and_window = ac->imdct_and_windowing;
  2527. }
  2528. for (type = 3; type >= 0; type--) {
  2529. for (i = 0; i < MAX_ELEM_ID; i++) {
  2530. ChannelElement *che = ac->che[type][i];
  2531. if (che && che->present) {
  2532. if (type <= TYPE_CPE)
  2533. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
  2534. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
  2535. if (che->ch[0].ics.predictor_present) {
  2536. if (che->ch[0].ics.ltp.present)
  2537. ac->apply_ltp(ac, &che->ch[0]);
  2538. if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
  2539. ac->apply_ltp(ac, &che->ch[1]);
  2540. }
  2541. }
  2542. if (che->ch[0].tns.present)
  2543. ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  2544. if (che->ch[1].tns.present)
  2545. ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  2546. if (type <= TYPE_CPE)
  2547. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
  2548. if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
  2549. imdct_and_window(ac, &che->ch[0]);
  2550. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2551. ac->update_ltp(ac, &che->ch[0]);
  2552. if (type == TYPE_CPE) {
  2553. imdct_and_window(ac, &che->ch[1]);
  2554. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2555. ac->update_ltp(ac, &che->ch[1]);
  2556. }
  2557. if (ac->oc[1].m4ac.sbr > 0) {
  2558. AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
  2559. }
  2560. }
  2561. if (type <= TYPE_CCE)
  2562. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
  2563. #if USE_FIXED
  2564. {
  2565. int j;
  2566. /* preparation for resampler */
  2567. for(j = 0; j<samples; j++){
  2568. che->ch[0].ret[j] = (int32_t)av_clipl_int32((int64_t)che->ch[0].ret[j]<<7)+0x8000;
  2569. if(type == TYPE_CPE)
  2570. che->ch[1].ret[j] = (int32_t)av_clipl_int32((int64_t)che->ch[1].ret[j]<<7)+0x8000;
  2571. }
  2572. }
  2573. #endif /* USE_FIXED */
  2574. che->present = 0;
  2575. } else if (che) {
  2576. av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
  2577. }
  2578. }
  2579. }
  2580. }
  2581. static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
  2582. {
  2583. int size;
  2584. AACADTSHeaderInfo hdr_info;
  2585. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2586. int layout_map_tags, ret;
  2587. size = avpriv_aac_parse_header(gb, &hdr_info);
  2588. if (size > 0) {
  2589. if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
  2590. // This is 2 for "VLB " audio in NSV files.
  2591. // See samples/nsv/vlb_audio.
  2592. avpriv_report_missing_feature(ac->avctx,
  2593. "More than one AAC RDB per ADTS frame");
  2594. ac->warned_num_aac_frames = 1;
  2595. }
  2596. push_output_configuration(ac);
  2597. if (hdr_info.chan_config) {
  2598. ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
  2599. if ((ret = set_default_channel_config(ac->avctx,
  2600. layout_map,
  2601. &layout_map_tags,
  2602. hdr_info.chan_config)) < 0)
  2603. return ret;
  2604. if ((ret = output_configure(ac, layout_map, layout_map_tags,
  2605. FFMAX(ac->oc[1].status,
  2606. OC_TRIAL_FRAME), 0)) < 0)
  2607. return ret;
  2608. } else {
  2609. ac->oc[1].m4ac.chan_config = 0;
  2610. /**
  2611. * dual mono frames in Japanese DTV can have chan_config 0
  2612. * WITHOUT specifying PCE.
  2613. * thus, set dual mono as default.
  2614. */
  2615. if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
  2616. layout_map_tags = 2;
  2617. layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
  2618. layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
  2619. layout_map[0][1] = 0;
  2620. layout_map[1][1] = 1;
  2621. if (output_configure(ac, layout_map, layout_map_tags,
  2622. OC_TRIAL_FRAME, 0))
  2623. return -7;
  2624. }
  2625. }
  2626. ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
  2627. ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
  2628. ac->oc[1].m4ac.object_type = hdr_info.object_type;
  2629. ac->oc[1].m4ac.frame_length_short = 0;
  2630. if (ac->oc[0].status != OC_LOCKED ||
  2631. ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
  2632. ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
  2633. ac->oc[1].m4ac.sbr = -1;
  2634. ac->oc[1].m4ac.ps = -1;
  2635. }
  2636. if (!hdr_info.crc_absent)
  2637. skip_bits(gb, 16);
  2638. }
  2639. return size;
  2640. }
  2641. static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
  2642. int *got_frame_ptr, GetBitContext *gb)
  2643. {
  2644. AACContext *ac = avctx->priv_data;
  2645. const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
  2646. ChannelElement *che;
  2647. int err, i;
  2648. int samples = m4ac->frame_length_short ? 960 : 1024;
  2649. int chan_config = m4ac->chan_config;
  2650. int aot = m4ac->object_type;
  2651. if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
  2652. samples >>= 1;
  2653. ac->frame = data;
  2654. if ((err = frame_configure_elements(avctx)) < 0)
  2655. return err;
  2656. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2657. // This may lead to an undefined profile being signaled
  2658. ac->avctx->profile = aot - 1;
  2659. ac->tags_mapped = 0;
  2660. if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
  2661. avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
  2662. chan_config);
  2663. return AVERROR_INVALIDDATA;
  2664. }
  2665. for (i = 0; i < tags_per_config[chan_config]; i++) {
  2666. const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
  2667. const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
  2668. if (!(che=get_che(ac, elem_type, elem_id))) {
  2669. av_log(ac->avctx, AV_LOG_ERROR,
  2670. "channel element %d.%d is not allocated\n",
  2671. elem_type, elem_id);
  2672. return AVERROR_INVALIDDATA;
  2673. }
  2674. che->present = 1;
  2675. if (aot != AOT_ER_AAC_ELD)
  2676. skip_bits(gb, 4);
  2677. switch (elem_type) {
  2678. case TYPE_SCE:
  2679. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2680. break;
  2681. case TYPE_CPE:
  2682. err = decode_cpe(ac, gb, che);
  2683. break;
  2684. case TYPE_LFE:
  2685. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2686. break;
  2687. }
  2688. if (err < 0)
  2689. return err;
  2690. }
  2691. spectral_to_sample(ac, samples);
  2692. if (!ac->frame->data[0] && samples) {
  2693. av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
  2694. return AVERROR_INVALIDDATA;
  2695. }
  2696. ac->frame->nb_samples = samples;
  2697. ac->frame->sample_rate = avctx->sample_rate;
  2698. *got_frame_ptr = 1;
  2699. skip_bits_long(gb, get_bits_left(gb));
  2700. return 0;
  2701. }
  2702. static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
  2703. int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
  2704. {
  2705. AACContext *ac = avctx->priv_data;
  2706. ChannelElement *che = NULL, *che_prev = NULL;
  2707. enum RawDataBlockType elem_type, che_prev_type = TYPE_END;
  2708. int err, elem_id;
  2709. int samples = 0, multiplier, audio_found = 0, pce_found = 0;
  2710. int is_dmono, sce_count = 0;
  2711. int payload_alignment;
  2712. ac->frame = data;
  2713. if (show_bits(gb, 12) == 0xfff) {
  2714. if ((err = parse_adts_frame_header(ac, gb)) < 0) {
  2715. av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
  2716. goto fail;
  2717. }
  2718. if (ac->oc[1].m4ac.sampling_index > 12) {
  2719. av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
  2720. err = AVERROR_INVALIDDATA;
  2721. goto fail;
  2722. }
  2723. }
  2724. if ((err = frame_configure_elements(avctx)) < 0)
  2725. goto fail;
  2726. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2727. // This may lead to an undefined profile being signaled
  2728. ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
  2729. payload_alignment = get_bits_count(gb);
  2730. ac->tags_mapped = 0;
  2731. // parse
  2732. while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
  2733. elem_id = get_bits(gb, 4);
  2734. if (avctx->debug & FF_DEBUG_STARTCODE)
  2735. av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
  2736. if (!avctx->channels && elem_type != TYPE_PCE) {
  2737. err = AVERROR_INVALIDDATA;
  2738. goto fail;
  2739. }
  2740. if (elem_type < TYPE_DSE) {
  2741. if (!(che=get_che(ac, elem_type, elem_id))) {
  2742. av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
  2743. elem_type, elem_id);
  2744. err = AVERROR_INVALIDDATA;
  2745. goto fail;
  2746. }
  2747. samples = 1024;
  2748. che->present = 1;
  2749. }
  2750. switch (elem_type) {
  2751. case TYPE_SCE:
  2752. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2753. audio_found = 1;
  2754. sce_count++;
  2755. break;
  2756. case TYPE_CPE:
  2757. err = decode_cpe(ac, gb, che);
  2758. audio_found = 1;
  2759. break;
  2760. case TYPE_CCE:
  2761. err = decode_cce(ac, gb, che);
  2762. break;
  2763. case TYPE_LFE:
  2764. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2765. audio_found = 1;
  2766. break;
  2767. case TYPE_DSE:
  2768. err = skip_data_stream_element(ac, gb);
  2769. break;
  2770. case TYPE_PCE: {
  2771. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2772. int tags;
  2773. int pushed = push_output_configuration(ac);
  2774. if (pce_found && !pushed) {
  2775. err = AVERROR_INVALIDDATA;
  2776. goto fail;
  2777. }
  2778. tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,
  2779. payload_alignment);
  2780. if (tags < 0) {
  2781. err = tags;
  2782. break;
  2783. }
  2784. if (pce_found) {
  2785. av_log(avctx, AV_LOG_ERROR,
  2786. "Not evaluating a further program_config_element as this construct is dubious at best.\n");
  2787. pop_output_configuration(ac);
  2788. } else {
  2789. err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
  2790. if (!err)
  2791. ac->oc[1].m4ac.chan_config = 0;
  2792. pce_found = 1;
  2793. }
  2794. break;
  2795. }
  2796. case TYPE_FIL:
  2797. if (elem_id == 15)
  2798. elem_id += get_bits(gb, 8) - 1;
  2799. if (get_bits_left(gb) < 8 * elem_id) {
  2800. av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
  2801. err = AVERROR_INVALIDDATA;
  2802. goto fail;
  2803. }
  2804. while (elem_id > 0)
  2805. elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);
  2806. err = 0; /* FIXME */
  2807. break;
  2808. default:
  2809. err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
  2810. break;
  2811. }
  2812. if (elem_type < TYPE_DSE) {
  2813. che_prev = che;
  2814. che_prev_type = elem_type;
  2815. }
  2816. if (err)
  2817. goto fail;
  2818. if (get_bits_left(gb) < 3) {
  2819. av_log(avctx, AV_LOG_ERROR, overread_err);
  2820. err = AVERROR_INVALIDDATA;
  2821. goto fail;
  2822. }
  2823. }
  2824. if (!avctx->channels) {
  2825. *got_frame_ptr = 0;
  2826. return 0;
  2827. }
  2828. multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
  2829. samples <<= multiplier;
  2830. spectral_to_sample(ac, samples);
  2831. if (ac->oc[1].status && audio_found) {
  2832. avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
  2833. avctx->frame_size = samples;
  2834. ac->oc[1].status = OC_LOCKED;
  2835. }
  2836. if (multiplier)
  2837. avctx->internal->skip_samples_multiplier = 2;
  2838. if (!ac->frame->data[0] && samples) {
  2839. av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
  2840. err = AVERROR_INVALIDDATA;
  2841. goto fail;
  2842. }
  2843. if (samples) {
  2844. ac->frame->nb_samples = samples;
  2845. ac->frame->sample_rate = avctx->sample_rate;
  2846. } else
  2847. av_frame_unref(ac->frame);
  2848. *got_frame_ptr = !!samples;
  2849. /* for dual-mono audio (SCE + SCE) */
  2850. is_dmono = ac->dmono_mode && sce_count == 2 &&
  2851. ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
  2852. if (is_dmono) {
  2853. if (ac->dmono_mode == 1)
  2854. ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
  2855. else if (ac->dmono_mode == 2)
  2856. ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
  2857. }
  2858. return 0;
  2859. fail:
  2860. pop_output_configuration(ac);
  2861. return err;
  2862. }
  2863. static int aac_decode_frame(AVCodecContext *avctx, void *data,
  2864. int *got_frame_ptr, AVPacket *avpkt)
  2865. {
  2866. AACContext *ac = avctx->priv_data;
  2867. const uint8_t *buf = avpkt->data;
  2868. int buf_size = avpkt->size;
  2869. GetBitContext gb;
  2870. int buf_consumed;
  2871. int buf_offset;
  2872. int err;
  2873. int new_extradata_size;
  2874. const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
  2875. AV_PKT_DATA_NEW_EXTRADATA,
  2876. &new_extradata_size);
  2877. int jp_dualmono_size;
  2878. const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
  2879. AV_PKT_DATA_JP_DUALMONO,
  2880. &jp_dualmono_size);
  2881. if (new_extradata && 0) {
  2882. av_free(avctx->extradata);
  2883. avctx->extradata = av_mallocz(new_extradata_size +
  2884. AV_INPUT_BUFFER_PADDING_SIZE);
  2885. if (!avctx->extradata)
  2886. return AVERROR(ENOMEM);
  2887. avctx->extradata_size = new_extradata_size;
  2888. memcpy(avctx->extradata, new_extradata, new_extradata_size);
  2889. push_output_configuration(ac);
  2890. if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
  2891. avctx->extradata,
  2892. avctx->extradata_size*8LL, 1) < 0) {
  2893. pop_output_configuration(ac);
  2894. return AVERROR_INVALIDDATA;
  2895. }
  2896. }
  2897. ac->dmono_mode = 0;
  2898. if (jp_dualmono && jp_dualmono_size > 0)
  2899. ac->dmono_mode = 1 + *jp_dualmono;
  2900. if (ac->force_dmono_mode >= 0)
  2901. ac->dmono_mode = ac->force_dmono_mode;
  2902. if (INT_MAX / 8 <= buf_size)
  2903. return AVERROR_INVALIDDATA;
  2904. if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
  2905. return err;
  2906. switch (ac->oc[1].m4ac.object_type) {
  2907. case AOT_ER_AAC_LC:
  2908. case AOT_ER_AAC_LTP:
  2909. case AOT_ER_AAC_LD:
  2910. case AOT_ER_AAC_ELD:
  2911. err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
  2912. break;
  2913. default:
  2914. err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
  2915. }
  2916. if (err < 0)
  2917. return err;
  2918. buf_consumed = (get_bits_count(&gb) + 7) >> 3;
  2919. for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
  2920. if (buf[buf_offset])
  2921. break;
  2922. return buf_size > buf_offset ? buf_consumed : buf_size;
  2923. }
  2924. static av_cold int aac_decode_close(AVCodecContext *avctx)
  2925. {
  2926. AACContext *ac = avctx->priv_data;
  2927. int i, type;
  2928. for (i = 0; i < MAX_ELEM_ID; i++) {
  2929. for (type = 0; type < 4; type++) {
  2930. if (ac->che[type][i])
  2931. AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
  2932. av_freep(&ac->che[type][i]);
  2933. }
  2934. }
  2935. ff_mdct_end(&ac->mdct);
  2936. ff_mdct_end(&ac->mdct_small);
  2937. ff_mdct_end(&ac->mdct_ld);
  2938. ff_mdct_end(&ac->mdct_ltp);
  2939. #if !USE_FIXED
  2940. ff_mdct15_uninit(&ac->mdct480);
  2941. #endif
  2942. av_freep(&ac->fdsp);
  2943. return 0;
  2944. }
  2945. static void aacdec_init(AACContext *c)
  2946. {
  2947. c->imdct_and_windowing = imdct_and_windowing;
  2948. c->apply_ltp = apply_ltp;
  2949. c->apply_tns = apply_tns;
  2950. c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
  2951. c->update_ltp = update_ltp;
  2952. #if USE_FIXED
  2953. c->vector_pow43 = vector_pow43;
  2954. c->subband_scale = subband_scale;
  2955. #endif
  2956. #if !USE_FIXED
  2957. if(ARCH_MIPS)
  2958. ff_aacdec_init_mips(c);
  2959. #endif /* !USE_FIXED */
  2960. }
  2961. /**
  2962. * AVOptions for Japanese DTV specific extensions (ADTS only)
  2963. */
  2964. #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  2965. static const AVOption options[] = {
  2966. {"dual_mono_mode", "Select the channel to decode for dual mono",
  2967. offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
  2968. AACDEC_FLAGS, "dual_mono_mode"},
  2969. {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2970. {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2971. {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2972. {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2973. {NULL},
  2974. };
  2975. static const AVClass aac_decoder_class = {
  2976. .class_name = "AAC decoder",
  2977. .item_name = av_default_item_name,
  2978. .option = options,
  2979. .version = LIBAVUTIL_VERSION_INT,
  2980. };