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.

3224 lines
115KB

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