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.

3268 lines
116KB

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