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.

3239 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. if (aot != AOT_ER_AAC_ELD) {
  1136. if (get_bits1(gb)) {
  1137. av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n");
  1138. if (ac->avctx->err_recognition & AV_EF_BITSTREAM)
  1139. return AVERROR_INVALIDDATA;
  1140. }
  1141. ics->window_sequence[1] = ics->window_sequence[0];
  1142. ics->window_sequence[0] = get_bits(gb, 2);
  1143. if (aot == AOT_ER_AAC_LD &&
  1144. ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {
  1145. av_log(ac->avctx, AV_LOG_ERROR,
  1146. "AAC LD is only defined for ONLY_LONG_SEQUENCE but "
  1147. "window sequence %d found.\n", ics->window_sequence[0]);
  1148. ics->window_sequence[0] = ONLY_LONG_SEQUENCE;
  1149. return AVERROR_INVALIDDATA;
  1150. }
  1151. ics->use_kb_window[1] = ics->use_kb_window[0];
  1152. ics->use_kb_window[0] = get_bits1(gb);
  1153. }
  1154. ics->num_window_groups = 1;
  1155. ics->group_len[0] = 1;
  1156. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1157. int i;
  1158. ics->max_sfb = get_bits(gb, 4);
  1159. for (i = 0; i < 7; i++) {
  1160. if (get_bits1(gb)) {
  1161. ics->group_len[ics->num_window_groups - 1]++;
  1162. } else {
  1163. ics->num_window_groups++;
  1164. ics->group_len[ics->num_window_groups - 1] = 1;
  1165. }
  1166. }
  1167. ics->num_windows = 8;
  1168. ics->swb_offset = ff_swb_offset_128[sampling_index];
  1169. ics->num_swb = ff_aac_num_swb_128[sampling_index];
  1170. ics->tns_max_bands = ff_tns_max_bands_128[sampling_index];
  1171. ics->predictor_present = 0;
  1172. } else {
  1173. ics->max_sfb = get_bits(gb, 6);
  1174. ics->num_windows = 1;
  1175. if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {
  1176. if (m4ac->frame_length_short) {
  1177. ics->swb_offset = ff_swb_offset_480[sampling_index];
  1178. ics->num_swb = ff_aac_num_swb_480[sampling_index];
  1179. ics->tns_max_bands = ff_tns_max_bands_480[sampling_index];
  1180. } else {
  1181. ics->swb_offset = ff_swb_offset_512[sampling_index];
  1182. ics->num_swb = ff_aac_num_swb_512[sampling_index];
  1183. ics->tns_max_bands = ff_tns_max_bands_512[sampling_index];
  1184. }
  1185. if (!ics->num_swb || !ics->swb_offset)
  1186. return AVERROR_BUG;
  1187. } else {
  1188. ics->swb_offset = ff_swb_offset_1024[sampling_index];
  1189. ics->num_swb = ff_aac_num_swb_1024[sampling_index];
  1190. ics->tns_max_bands = ff_tns_max_bands_1024[sampling_index];
  1191. }
  1192. if (aot != AOT_ER_AAC_ELD) {
  1193. ics->predictor_present = get_bits1(gb);
  1194. ics->predictor_reset_group = 0;
  1195. }
  1196. if (ics->predictor_present) {
  1197. if (aot == AOT_AAC_MAIN) {
  1198. if (decode_prediction(ac, ics, gb)) {
  1199. goto fail;
  1200. }
  1201. } else if (aot == AOT_AAC_LC ||
  1202. aot == AOT_ER_AAC_LC) {
  1203. av_log(ac->avctx, AV_LOG_ERROR,
  1204. "Prediction is not allowed in AAC-LC.\n");
  1205. goto fail;
  1206. } else {
  1207. if (aot == AOT_ER_AAC_LD) {
  1208. av_log(ac->avctx, AV_LOG_ERROR,
  1209. "LTP in ER AAC LD not yet implemented.\n");
  1210. return AVERROR_PATCHWELCOME;
  1211. }
  1212. if ((ics->ltp.present = get_bits(gb, 1)))
  1213. decode_ltp(&ics->ltp, gb, ics->max_sfb);
  1214. }
  1215. }
  1216. }
  1217. if (ics->max_sfb > ics->num_swb) {
  1218. av_log(ac->avctx, AV_LOG_ERROR,
  1219. "Number of scalefactor bands in group (%d) "
  1220. "exceeds limit (%d).\n",
  1221. ics->max_sfb, ics->num_swb);
  1222. goto fail;
  1223. }
  1224. return 0;
  1225. fail:
  1226. ics->max_sfb = 0;
  1227. return AVERROR_INVALIDDATA;
  1228. }
  1229. /**
  1230. * Decode band types (section_data payload); reference: table 4.46.
  1231. *
  1232. * @param band_type array of the used band type
  1233. * @param band_type_run_end array of the last scalefactor band of a band type run
  1234. *
  1235. * @return Returns error status. 0 - OK, !0 - error
  1236. */
  1237. static int decode_band_types(AACContext *ac, enum BandType band_type[120],
  1238. int band_type_run_end[120], GetBitContext *gb,
  1239. IndividualChannelStream *ics)
  1240. {
  1241. int g, idx = 0;
  1242. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  1243. for (g = 0; g < ics->num_window_groups; g++) {
  1244. int k = 0;
  1245. while (k < ics->max_sfb) {
  1246. uint8_t sect_end = k;
  1247. int sect_len_incr;
  1248. int sect_band_type = get_bits(gb, 4);
  1249. if (sect_band_type == 12) {
  1250. av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");
  1251. return AVERROR_INVALIDDATA;
  1252. }
  1253. do {
  1254. sect_len_incr = get_bits(gb, bits);
  1255. sect_end += sect_len_incr;
  1256. if (get_bits_left(gb) < 0) {
  1257. av_log(ac->avctx, AV_LOG_ERROR, "decode_band_types: "overread_err);
  1258. return AVERROR_INVALIDDATA;
  1259. }
  1260. if (sect_end > ics->max_sfb) {
  1261. av_log(ac->avctx, AV_LOG_ERROR,
  1262. "Number of bands (%d) exceeds limit (%d).\n",
  1263. sect_end, ics->max_sfb);
  1264. return AVERROR_INVALIDDATA;
  1265. }
  1266. } while (sect_len_incr == (1 << bits) - 1);
  1267. for (; k < sect_end; k++) {
  1268. band_type [idx] = sect_band_type;
  1269. band_type_run_end[idx++] = sect_end;
  1270. }
  1271. }
  1272. }
  1273. return 0;
  1274. }
  1275. /**
  1276. * Decode scalefactors; reference: table 4.47.
  1277. *
  1278. * @param global_gain first scalefactor value as scalefactors are differentially coded
  1279. * @param band_type array of the used band type
  1280. * @param band_type_run_end array of the last scalefactor band of a band type run
  1281. * @param sf array of scalefactors or intensity stereo positions
  1282. *
  1283. * @return Returns error status. 0 - OK, !0 - error
  1284. */
  1285. static int decode_scalefactors(AACContext *ac, INTFLOAT sf[120], GetBitContext *gb,
  1286. unsigned int global_gain,
  1287. IndividualChannelStream *ics,
  1288. enum BandType band_type[120],
  1289. int band_type_run_end[120])
  1290. {
  1291. int g, i, idx = 0;
  1292. int offset[3] = { global_gain, global_gain - NOISE_OFFSET, 0 };
  1293. int clipped_offset;
  1294. int noise_flag = 1;
  1295. for (g = 0; g < ics->num_window_groups; g++) {
  1296. for (i = 0; i < ics->max_sfb;) {
  1297. int run_end = band_type_run_end[idx];
  1298. if (band_type[idx] == ZERO_BT) {
  1299. for (; i < run_end; i++, idx++)
  1300. sf[idx] = FIXR(0.);
  1301. } else if ((band_type[idx] == INTENSITY_BT) ||
  1302. (band_type[idx] == INTENSITY_BT2)) {
  1303. for (; i < run_end; i++, idx++) {
  1304. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
  1305. clipped_offset = av_clip(offset[2], -155, 100);
  1306. if (offset[2] != clipped_offset) {
  1307. avpriv_request_sample(ac->avctx,
  1308. "If you heard an audible artifact, there may be a bug in the decoder. "
  1309. "Clipped intensity stereo position (%d -> %d)",
  1310. offset[2], clipped_offset);
  1311. }
  1312. #if USE_FIXED
  1313. sf[idx] = 100 - clipped_offset;
  1314. #else
  1315. sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];
  1316. #endif /* USE_FIXED */
  1317. }
  1318. } else if (band_type[idx] == NOISE_BT) {
  1319. for (; i < run_end; i++, idx++) {
  1320. if (noise_flag-- > 0)
  1321. offset[1] += get_bits(gb, NOISE_PRE_BITS) - NOISE_PRE;
  1322. else
  1323. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
  1324. clipped_offset = av_clip(offset[1], -100, 155);
  1325. if (offset[1] != clipped_offset) {
  1326. avpriv_request_sample(ac->avctx,
  1327. "If you heard an audible artifact, there may be a bug in the decoder. "
  1328. "Clipped noise gain (%d -> %d)",
  1329. offset[1], clipped_offset);
  1330. }
  1331. #if USE_FIXED
  1332. sf[idx] = -(100 + clipped_offset);
  1333. #else
  1334. sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];
  1335. #endif /* USE_FIXED */
  1336. }
  1337. } else {
  1338. for (; i < run_end; i++, idx++) {
  1339. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - SCALE_DIFF_ZERO;
  1340. if (offset[0] > 255U) {
  1341. av_log(ac->avctx, AV_LOG_ERROR,
  1342. "Scalefactor (%d) out of range.\n", offset[0]);
  1343. return AVERROR_INVALIDDATA;
  1344. }
  1345. #if USE_FIXED
  1346. sf[idx] = -offset[0];
  1347. #else
  1348. sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];
  1349. #endif /* USE_FIXED */
  1350. }
  1351. }
  1352. }
  1353. }
  1354. return 0;
  1355. }
  1356. /**
  1357. * Decode pulse data; reference: table 4.7.
  1358. */
  1359. static int decode_pulses(Pulse *pulse, GetBitContext *gb,
  1360. const uint16_t *swb_offset, int num_swb)
  1361. {
  1362. int i, pulse_swb;
  1363. pulse->num_pulse = get_bits(gb, 2) + 1;
  1364. pulse_swb = get_bits(gb, 6);
  1365. if (pulse_swb >= num_swb)
  1366. return -1;
  1367. pulse->pos[0] = swb_offset[pulse_swb];
  1368. pulse->pos[0] += get_bits(gb, 5);
  1369. if (pulse->pos[0] >= swb_offset[num_swb])
  1370. return -1;
  1371. pulse->amp[0] = get_bits(gb, 4);
  1372. for (i = 1; i < pulse->num_pulse; i++) {
  1373. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
  1374. if (pulse->pos[i] >= swb_offset[num_swb])
  1375. return -1;
  1376. pulse->amp[i] = get_bits(gb, 4);
  1377. }
  1378. return 0;
  1379. }
  1380. /**
  1381. * Decode Temporal Noise Shaping data; reference: table 4.48.
  1382. *
  1383. * @return Returns error status. 0 - OK, !0 - error
  1384. */
  1385. static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
  1386. GetBitContext *gb, const IndividualChannelStream *ics)
  1387. {
  1388. int w, filt, i, coef_len, coef_res, coef_compress;
  1389. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  1390. const int tns_max_order = is8 ? 7 : ac->oc[1].m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  1391. for (w = 0; w < ics->num_windows; w++) {
  1392. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  1393. coef_res = get_bits1(gb);
  1394. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1395. int tmp2_idx;
  1396. tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
  1397. if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
  1398. av_log(ac->avctx, AV_LOG_ERROR,
  1399. "TNS filter order %d is greater than maximum %d.\n",
  1400. tns->order[w][filt], tns_max_order);
  1401. tns->order[w][filt] = 0;
  1402. return AVERROR_INVALIDDATA;
  1403. }
  1404. if (tns->order[w][filt]) {
  1405. tns->direction[w][filt] = get_bits1(gb);
  1406. coef_compress = get_bits1(gb);
  1407. coef_len = coef_res + 3 - coef_compress;
  1408. tmp2_idx = 2 * coef_compress + coef_res;
  1409. for (i = 0; i < tns->order[w][filt]; i++)
  1410. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  1411. }
  1412. }
  1413. }
  1414. }
  1415. return 0;
  1416. }
  1417. /**
  1418. * Decode Mid/Side data; reference: table 4.54.
  1419. *
  1420. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1421. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1422. * [3] reserved for scalable AAC
  1423. */
  1424. static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
  1425. int ms_present)
  1426. {
  1427. int idx;
  1428. int max_idx = cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb;
  1429. if (ms_present == 1) {
  1430. for (idx = 0; idx < max_idx; idx++)
  1431. cpe->ms_mask[idx] = get_bits1(gb);
  1432. } else if (ms_present == 2) {
  1433. memset(cpe->ms_mask, 1, max_idx * sizeof(cpe->ms_mask[0]));
  1434. }
  1435. }
  1436. /**
  1437. * Decode spectral data; reference: table 4.50.
  1438. * Dequantize and scale spectral data; reference: 4.6.3.3.
  1439. *
  1440. * @param coef array of dequantized, scaled spectral data
  1441. * @param sf array of scalefactors or intensity stereo positions
  1442. * @param pulse_present set if pulses are present
  1443. * @param pulse pointer to pulse data struct
  1444. * @param band_type array of the used band type
  1445. *
  1446. * @return Returns error status. 0 - OK, !0 - error
  1447. */
  1448. static int decode_spectrum_and_dequant(AACContext *ac, INTFLOAT coef[1024],
  1449. GetBitContext *gb, const INTFLOAT sf[120],
  1450. int pulse_present, const Pulse *pulse,
  1451. const IndividualChannelStream *ics,
  1452. enum BandType band_type[120])
  1453. {
  1454. int i, k, g, idx = 0;
  1455. const int c = 1024 / ics->num_windows;
  1456. const uint16_t *offsets = ics->swb_offset;
  1457. INTFLOAT *coef_base = coef;
  1458. for (g = 0; g < ics->num_windows; g++)
  1459. memset(coef + g * 128 + offsets[ics->max_sfb], 0,
  1460. sizeof(INTFLOAT) * (c - offsets[ics->max_sfb]));
  1461. for (g = 0; g < ics->num_window_groups; g++) {
  1462. unsigned g_len = ics->group_len[g];
  1463. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1464. const unsigned cbt_m1 = band_type[idx] - 1;
  1465. INTFLOAT *cfo = coef + offsets[i];
  1466. int off_len = offsets[i + 1] - offsets[i];
  1467. int group;
  1468. if (cbt_m1 >= INTENSITY_BT2 - 1) {
  1469. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1470. memset(cfo, 0, off_len * sizeof(*cfo));
  1471. }
  1472. } else if (cbt_m1 == NOISE_BT - 1) {
  1473. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1474. #if !USE_FIXED
  1475. float scale;
  1476. #endif /* !USE_FIXED */
  1477. INTFLOAT band_energy;
  1478. for (k = 0; k < off_len; k++) {
  1479. ac->random_state = lcg_random(ac->random_state);
  1480. #if USE_FIXED
  1481. cfo[k] = ac->random_state >> 3;
  1482. #else
  1483. cfo[k] = ac->random_state;
  1484. #endif /* USE_FIXED */
  1485. }
  1486. #if USE_FIXED
  1487. band_energy = ac->fdsp->scalarproduct_fixed(cfo, cfo, off_len);
  1488. band_energy = fixed_sqrt(band_energy, 31);
  1489. noise_scale(cfo, sf[idx], band_energy, off_len);
  1490. #else
  1491. band_energy = ac->fdsp->scalarproduct_float(cfo, cfo, off_len);
  1492. scale = sf[idx] / sqrtf(band_energy);
  1493. ac->fdsp->vector_fmul_scalar(cfo, cfo, scale, off_len);
  1494. #endif /* USE_FIXED */
  1495. }
  1496. } else {
  1497. #if !USE_FIXED
  1498. const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
  1499. #endif /* !USE_FIXED */
  1500. const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
  1501. VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
  1502. OPEN_READER(re, gb);
  1503. switch (cbt_m1 >> 1) {
  1504. case 0:
  1505. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1506. INTFLOAT *cf = cfo;
  1507. int len = off_len;
  1508. do {
  1509. int code;
  1510. unsigned cb_idx;
  1511. UPDATE_CACHE(re, gb);
  1512. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1513. cb_idx = cb_vector_idx[code];
  1514. #if USE_FIXED
  1515. cf = DEC_SQUAD(cf, cb_idx);
  1516. #else
  1517. cf = VMUL4(cf, vq, cb_idx, sf + idx);
  1518. #endif /* USE_FIXED */
  1519. } while (len -= 4);
  1520. }
  1521. break;
  1522. case 1:
  1523. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1524. INTFLOAT *cf = cfo;
  1525. int len = off_len;
  1526. do {
  1527. int code;
  1528. unsigned nnz;
  1529. unsigned cb_idx;
  1530. uint32_t bits;
  1531. UPDATE_CACHE(re, gb);
  1532. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1533. cb_idx = cb_vector_idx[code];
  1534. nnz = cb_idx >> 8 & 15;
  1535. bits = nnz ? GET_CACHE(re, gb) : 0;
  1536. LAST_SKIP_BITS(re, gb, nnz);
  1537. #if USE_FIXED
  1538. cf = DEC_UQUAD(cf, cb_idx, bits);
  1539. #else
  1540. cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
  1541. #endif /* USE_FIXED */
  1542. } while (len -= 4);
  1543. }
  1544. break;
  1545. case 2:
  1546. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1547. INTFLOAT *cf = cfo;
  1548. int len = off_len;
  1549. do {
  1550. int code;
  1551. unsigned cb_idx;
  1552. UPDATE_CACHE(re, gb);
  1553. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1554. cb_idx = cb_vector_idx[code];
  1555. #if USE_FIXED
  1556. cf = DEC_SPAIR(cf, cb_idx);
  1557. #else
  1558. cf = VMUL2(cf, vq, cb_idx, sf + idx);
  1559. #endif /* USE_FIXED */
  1560. } while (len -= 2);
  1561. }
  1562. break;
  1563. case 3:
  1564. case 4:
  1565. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1566. INTFLOAT *cf = cfo;
  1567. int len = off_len;
  1568. do {
  1569. int code;
  1570. unsigned nnz;
  1571. unsigned cb_idx;
  1572. unsigned sign;
  1573. UPDATE_CACHE(re, gb);
  1574. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1575. cb_idx = cb_vector_idx[code];
  1576. nnz = cb_idx >> 8 & 15;
  1577. sign = nnz ? SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12) : 0;
  1578. LAST_SKIP_BITS(re, gb, nnz);
  1579. #if USE_FIXED
  1580. cf = DEC_UPAIR(cf, cb_idx, sign);
  1581. #else
  1582. cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
  1583. #endif /* USE_FIXED */
  1584. } while (len -= 2);
  1585. }
  1586. break;
  1587. default:
  1588. for (group = 0; group < (AAC_SIGNE)g_len; group++, cfo+=128) {
  1589. #if USE_FIXED
  1590. int *icf = cfo;
  1591. int v;
  1592. #else
  1593. float *cf = cfo;
  1594. uint32_t *icf = (uint32_t *) cf;
  1595. #endif /* USE_FIXED */
  1596. int len = off_len;
  1597. do {
  1598. int code;
  1599. unsigned nzt, nnz;
  1600. unsigned cb_idx;
  1601. uint32_t bits;
  1602. int j;
  1603. UPDATE_CACHE(re, gb);
  1604. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1605. if (!code) {
  1606. *icf++ = 0;
  1607. *icf++ = 0;
  1608. continue;
  1609. }
  1610. cb_idx = cb_vector_idx[code];
  1611. nnz = cb_idx >> 12;
  1612. nzt = cb_idx >> 8;
  1613. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  1614. LAST_SKIP_BITS(re, gb, nnz);
  1615. for (j = 0; j < 2; j++) {
  1616. if (nzt & 1<<j) {
  1617. uint32_t b;
  1618. int n;
  1619. /* The total length of escape_sequence must be < 22 bits according
  1620. to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
  1621. UPDATE_CACHE(re, gb);
  1622. b = GET_CACHE(re, gb);
  1623. b = 31 - av_log2(~b);
  1624. if (b > 8) {
  1625. av_log(ac->avctx, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  1626. return AVERROR_INVALIDDATA;
  1627. }
  1628. SKIP_BITS(re, gb, b + 1);
  1629. b += 4;
  1630. n = (1 << b) + SHOW_UBITS(re, gb, b);
  1631. LAST_SKIP_BITS(re, gb, b);
  1632. #if USE_FIXED
  1633. v = n;
  1634. if (bits & 1U<<31)
  1635. v = -v;
  1636. *icf++ = v;
  1637. #else
  1638. *icf++ = cbrt_tab[n] | (bits & 1U<<31);
  1639. #endif /* USE_FIXED */
  1640. bits <<= 1;
  1641. } else {
  1642. #if USE_FIXED
  1643. v = cb_idx & 15;
  1644. if (bits & 1U<<31)
  1645. v = -v;
  1646. *icf++ = v;
  1647. #else
  1648. unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
  1649. *icf++ = (bits & 1U<<31) | v;
  1650. #endif /* USE_FIXED */
  1651. bits <<= !!v;
  1652. }
  1653. cb_idx >>= 4;
  1654. }
  1655. } while (len -= 2);
  1656. #if !USE_FIXED
  1657. ac->fdsp->vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
  1658. #endif /* !USE_FIXED */
  1659. }
  1660. }
  1661. CLOSE_READER(re, gb);
  1662. }
  1663. }
  1664. coef += g_len << 7;
  1665. }
  1666. if (pulse_present) {
  1667. idx = 0;
  1668. for (i = 0; i < pulse->num_pulse; i++) {
  1669. INTFLOAT co = coef_base[ pulse->pos[i] ];
  1670. while (offsets[idx + 1] <= pulse->pos[i])
  1671. idx++;
  1672. if (band_type[idx] != NOISE_BT && sf[idx]) {
  1673. INTFLOAT ico = -pulse->amp[i];
  1674. #if USE_FIXED
  1675. if (co) {
  1676. ico = co + (co > 0 ? -ico : ico);
  1677. }
  1678. coef_base[ pulse->pos[i] ] = ico;
  1679. #else
  1680. if (co) {
  1681. co /= sf[idx];
  1682. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  1683. }
  1684. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  1685. #endif /* USE_FIXED */
  1686. }
  1687. }
  1688. }
  1689. #if USE_FIXED
  1690. coef = coef_base;
  1691. idx = 0;
  1692. for (g = 0; g < ics->num_window_groups; g++) {
  1693. unsigned g_len = ics->group_len[g];
  1694. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1695. const unsigned cbt_m1 = band_type[idx] - 1;
  1696. int *cfo = coef + offsets[i];
  1697. int off_len = offsets[i + 1] - offsets[i];
  1698. int group;
  1699. if (cbt_m1 < NOISE_BT - 1) {
  1700. for (group = 0; group < (int)g_len; group++, cfo+=128) {
  1701. ac->vector_pow43(cfo, off_len);
  1702. ac->subband_scale(cfo, cfo, sf[idx], 34, off_len);
  1703. }
  1704. }
  1705. }
  1706. coef += g_len << 7;
  1707. }
  1708. #endif /* USE_FIXED */
  1709. return 0;
  1710. }
  1711. /**
  1712. * Apply AAC-Main style frequency domain prediction.
  1713. */
  1714. static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
  1715. {
  1716. int sfb, k;
  1717. if (!sce->ics.predictor_initialized) {
  1718. reset_all_predictors(sce->predictor_state);
  1719. sce->ics.predictor_initialized = 1;
  1720. }
  1721. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  1722. for (sfb = 0;
  1723. sfb < ff_aac_pred_sfb_max[ac->oc[1].m4ac.sampling_index];
  1724. sfb++) {
  1725. for (k = sce->ics.swb_offset[sfb];
  1726. k < sce->ics.swb_offset[sfb + 1];
  1727. k++) {
  1728. predict(&sce->predictor_state[k], &sce->coeffs[k],
  1729. sce->ics.predictor_present &&
  1730. sce->ics.prediction_used[sfb]);
  1731. }
  1732. }
  1733. if (sce->ics.predictor_reset_group)
  1734. reset_predictor_group(sce->predictor_state,
  1735. sce->ics.predictor_reset_group);
  1736. } else
  1737. reset_all_predictors(sce->predictor_state);
  1738. }
  1739. /**
  1740. * Decode an individual_channel_stream payload; reference: table 4.44.
  1741. *
  1742. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  1743. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  1744. *
  1745. * @return Returns error status. 0 - OK, !0 - error
  1746. */
  1747. static int decode_ics(AACContext *ac, SingleChannelElement *sce,
  1748. GetBitContext *gb, int common_window, int scale_flag)
  1749. {
  1750. Pulse pulse;
  1751. TemporalNoiseShaping *tns = &sce->tns;
  1752. IndividualChannelStream *ics = &sce->ics;
  1753. INTFLOAT *out = sce->coeffs;
  1754. int global_gain, eld_syntax, er_syntax, pulse_present = 0;
  1755. int ret;
  1756. eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1757. er_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||
  1758. ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||
  1759. ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||
  1760. ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1761. /* This assignment is to silence a GCC warning about the variable being used
  1762. * uninitialized when in fact it always is.
  1763. */
  1764. pulse.num_pulse = 0;
  1765. global_gain = get_bits(gb, 8);
  1766. if (!common_window && !scale_flag) {
  1767. if (decode_ics_info(ac, ics, gb) < 0)
  1768. return AVERROR_INVALIDDATA;
  1769. }
  1770. if ((ret = decode_band_types(ac, sce->band_type,
  1771. sce->band_type_run_end, gb, ics)) < 0)
  1772. return ret;
  1773. if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,
  1774. sce->band_type, sce->band_type_run_end)) < 0)
  1775. return ret;
  1776. pulse_present = 0;
  1777. if (!scale_flag) {
  1778. if (!eld_syntax && (pulse_present = get_bits1(gb))) {
  1779. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1780. av_log(ac->avctx, AV_LOG_ERROR,
  1781. "Pulse tool not allowed in eight short sequence.\n");
  1782. return AVERROR_INVALIDDATA;
  1783. }
  1784. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  1785. av_log(ac->avctx, AV_LOG_ERROR,
  1786. "Pulse data corrupt or invalid.\n");
  1787. return AVERROR_INVALIDDATA;
  1788. }
  1789. }
  1790. tns->present = get_bits1(gb);
  1791. if (tns->present && !er_syntax)
  1792. if (decode_tns(ac, tns, gb, ics) < 0)
  1793. return AVERROR_INVALIDDATA;
  1794. if (!eld_syntax && get_bits1(gb)) {
  1795. avpriv_request_sample(ac->avctx, "SSR");
  1796. return AVERROR_PATCHWELCOME;
  1797. }
  1798. // I see no textual basis in the spec for this occurring after SSR gain
  1799. // control, but this is what both reference and real implmentations do
  1800. if (tns->present && er_syntax)
  1801. if (decode_tns(ac, tns, gb, ics) < 0)
  1802. return AVERROR_INVALIDDATA;
  1803. }
  1804. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,
  1805. &pulse, ics, sce->band_type) < 0)
  1806. return AVERROR_INVALIDDATA;
  1807. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)
  1808. apply_prediction(ac, sce);
  1809. return 0;
  1810. }
  1811. /**
  1812. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  1813. */
  1814. static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
  1815. {
  1816. const IndividualChannelStream *ics = &cpe->ch[0].ics;
  1817. INTFLOAT *ch0 = cpe->ch[0].coeffs;
  1818. INTFLOAT *ch1 = cpe->ch[1].coeffs;
  1819. int g, i, group, idx = 0;
  1820. const uint16_t *offsets = ics->swb_offset;
  1821. for (g = 0; g < ics->num_window_groups; g++) {
  1822. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1823. if (cpe->ms_mask[idx] &&
  1824. cpe->ch[0].band_type[idx] < NOISE_BT &&
  1825. cpe->ch[1].band_type[idx] < NOISE_BT) {
  1826. #if USE_FIXED
  1827. for (group = 0; group < ics->group_len[g]; group++) {
  1828. ac->fdsp->butterflies_fixed(ch0 + group * 128 + offsets[i],
  1829. ch1 + group * 128 + offsets[i],
  1830. offsets[i+1] - offsets[i]);
  1831. #else
  1832. for (group = 0; group < ics->group_len[g]; group++) {
  1833. ac->fdsp->butterflies_float(ch0 + group * 128 + offsets[i],
  1834. ch1 + group * 128 + offsets[i],
  1835. offsets[i+1] - offsets[i]);
  1836. #endif /* USE_FIXED */
  1837. }
  1838. }
  1839. }
  1840. ch0 += ics->group_len[g] * 128;
  1841. ch1 += ics->group_len[g] * 128;
  1842. }
  1843. }
  1844. /**
  1845. * intensity stereo decoding; reference: 4.6.8.2.3
  1846. *
  1847. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1848. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1849. * [3] reserved for scalable AAC
  1850. */
  1851. static void apply_intensity_stereo(AACContext *ac,
  1852. ChannelElement *cpe, int ms_present)
  1853. {
  1854. const IndividualChannelStream *ics = &cpe->ch[1].ics;
  1855. SingleChannelElement *sce1 = &cpe->ch[1];
  1856. INTFLOAT *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  1857. const uint16_t *offsets = ics->swb_offset;
  1858. int g, group, i, idx = 0;
  1859. int c;
  1860. INTFLOAT scale;
  1861. for (g = 0; g < ics->num_window_groups; g++) {
  1862. for (i = 0; i < ics->max_sfb;) {
  1863. if (sce1->band_type[idx] == INTENSITY_BT ||
  1864. sce1->band_type[idx] == INTENSITY_BT2) {
  1865. const int bt_run_end = sce1->band_type_run_end[idx];
  1866. for (; i < bt_run_end; i++, idx++) {
  1867. c = -1 + 2 * (sce1->band_type[idx] - 14);
  1868. if (ms_present)
  1869. c *= 1 - 2 * cpe->ms_mask[idx];
  1870. scale = c * sce1->sf[idx];
  1871. for (group = 0; group < ics->group_len[g]; group++)
  1872. #if USE_FIXED
  1873. ac->subband_scale(coef1 + group * 128 + offsets[i],
  1874. coef0 + group * 128 + offsets[i],
  1875. scale,
  1876. 23,
  1877. offsets[i + 1] - offsets[i]);
  1878. #else
  1879. ac->fdsp->vector_fmul_scalar(coef1 + group * 128 + offsets[i],
  1880. coef0 + group * 128 + offsets[i],
  1881. scale,
  1882. offsets[i + 1] - offsets[i]);
  1883. #endif /* USE_FIXED */
  1884. }
  1885. } else {
  1886. int bt_run_end = sce1->band_type_run_end[idx];
  1887. idx += bt_run_end - i;
  1888. i = bt_run_end;
  1889. }
  1890. }
  1891. coef0 += ics->group_len[g] * 128;
  1892. coef1 += ics->group_len[g] * 128;
  1893. }
  1894. }
  1895. /**
  1896. * Decode a channel_pair_element; reference: table 4.4.
  1897. *
  1898. * @return Returns error status. 0 - OK, !0 - error
  1899. */
  1900. static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
  1901. {
  1902. int i, ret, common_window, ms_present = 0;
  1903. int eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;
  1904. common_window = eld_syntax || get_bits1(gb);
  1905. if (common_window) {
  1906. if (decode_ics_info(ac, &cpe->ch[0].ics, gb))
  1907. return AVERROR_INVALIDDATA;
  1908. i = cpe->ch[1].ics.use_kb_window[0];
  1909. cpe->ch[1].ics = cpe->ch[0].ics;
  1910. cpe->ch[1].ics.use_kb_window[1] = i;
  1911. if (cpe->ch[1].ics.predictor_present &&
  1912. (ac->oc[1].m4ac.object_type != AOT_AAC_MAIN))
  1913. if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1)))
  1914. decode_ltp(&cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb);
  1915. ms_present = get_bits(gb, 2);
  1916. if (ms_present == 3) {
  1917. av_log(ac->avctx, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  1918. return AVERROR_INVALIDDATA;
  1919. } else if (ms_present)
  1920. decode_mid_side_stereo(cpe, gb, ms_present);
  1921. }
  1922. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  1923. return ret;
  1924. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  1925. return ret;
  1926. if (common_window) {
  1927. if (ms_present)
  1928. apply_mid_side_stereo(ac, cpe);
  1929. if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN) {
  1930. apply_prediction(ac, &cpe->ch[0]);
  1931. apply_prediction(ac, &cpe->ch[1]);
  1932. }
  1933. }
  1934. apply_intensity_stereo(ac, cpe, ms_present);
  1935. return 0;
  1936. }
  1937. static const float cce_scale[] = {
  1938. 1.09050773266525765921, //2^(1/8)
  1939. 1.18920711500272106672, //2^(1/4)
  1940. M_SQRT2,
  1941. 2,
  1942. };
  1943. /**
  1944. * Decode coupling_channel_element; reference: table 4.8.
  1945. *
  1946. * @return Returns error status. 0 - OK, !0 - error
  1947. */
  1948. static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
  1949. {
  1950. int num_gain = 0;
  1951. int c, g, sfb, ret;
  1952. int sign;
  1953. INTFLOAT scale;
  1954. SingleChannelElement *sce = &che->ch[0];
  1955. ChannelCoupling *coup = &che->coup;
  1956. coup->coupling_point = 2 * get_bits1(gb);
  1957. coup->num_coupled = get_bits(gb, 3);
  1958. for (c = 0; c <= coup->num_coupled; c++) {
  1959. num_gain++;
  1960. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1961. coup->id_select[c] = get_bits(gb, 4);
  1962. if (coup->type[c] == TYPE_CPE) {
  1963. coup->ch_select[c] = get_bits(gb, 2);
  1964. if (coup->ch_select[c] == 3)
  1965. num_gain++;
  1966. } else
  1967. coup->ch_select[c] = 2;
  1968. }
  1969. coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
  1970. sign = get_bits(gb, 1);
  1971. scale = AAC_RENAME(cce_scale)[get_bits(gb, 2)];
  1972. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1973. return ret;
  1974. for (c = 0; c < num_gain; c++) {
  1975. int idx = 0;
  1976. int cge = 1;
  1977. int gain = 0;
  1978. INTFLOAT gain_cache = FIXR10(1.);
  1979. if (c) {
  1980. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1981. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1982. gain_cache = GET_GAIN(scale, gain);
  1983. }
  1984. if (coup->coupling_point == AFTER_IMDCT) {
  1985. coup->gain[c][0] = gain_cache;
  1986. } else {
  1987. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1988. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1989. if (sce->band_type[idx] != ZERO_BT) {
  1990. if (!cge) {
  1991. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1992. if (t) {
  1993. int s = 1;
  1994. t = gain += t;
  1995. if (sign) {
  1996. s -= 2 * (t & 0x1);
  1997. t >>= 1;
  1998. }
  1999. gain_cache = GET_GAIN(scale, t) * s;
  2000. }
  2001. }
  2002. coup->gain[c][idx] = gain_cache;
  2003. }
  2004. }
  2005. }
  2006. }
  2007. }
  2008. return 0;
  2009. }
  2010. /**
  2011. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  2012. *
  2013. * @return Returns number of bytes consumed.
  2014. */
  2015. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
  2016. GetBitContext *gb)
  2017. {
  2018. int i;
  2019. int num_excl_chan = 0;
  2020. do {
  2021. for (i = 0; i < 7; i++)
  2022. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  2023. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  2024. return num_excl_chan / 7;
  2025. }
  2026. /**
  2027. * Decode dynamic range information; reference: table 4.52.
  2028. *
  2029. * @return Returns number of bytes consumed.
  2030. */
  2031. static int decode_dynamic_range(DynamicRangeControl *che_drc,
  2032. GetBitContext *gb)
  2033. {
  2034. int n = 1;
  2035. int drc_num_bands = 1;
  2036. int i;
  2037. /* pce_tag_present? */
  2038. if (get_bits1(gb)) {
  2039. che_drc->pce_instance_tag = get_bits(gb, 4);
  2040. skip_bits(gb, 4); // tag_reserved_bits
  2041. n++;
  2042. }
  2043. /* excluded_chns_present? */
  2044. if (get_bits1(gb)) {
  2045. n += decode_drc_channel_exclusions(che_drc, gb);
  2046. }
  2047. /* drc_bands_present? */
  2048. if (get_bits1(gb)) {
  2049. che_drc->band_incr = get_bits(gb, 4);
  2050. che_drc->interpolation_scheme = get_bits(gb, 4);
  2051. n++;
  2052. drc_num_bands += che_drc->band_incr;
  2053. for (i = 0; i < drc_num_bands; i++) {
  2054. che_drc->band_top[i] = get_bits(gb, 8);
  2055. n++;
  2056. }
  2057. }
  2058. /* prog_ref_level_present? */
  2059. if (get_bits1(gb)) {
  2060. che_drc->prog_ref_level = get_bits(gb, 7);
  2061. skip_bits1(gb); // prog_ref_level_reserved_bits
  2062. n++;
  2063. }
  2064. for (i = 0; i < drc_num_bands; i++) {
  2065. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  2066. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  2067. n++;
  2068. }
  2069. return n;
  2070. }
  2071. static int decode_fill(AACContext *ac, GetBitContext *gb, int len) {
  2072. uint8_t buf[256];
  2073. int i, major, minor;
  2074. if (len < 13+7*8)
  2075. goto unknown;
  2076. get_bits(gb, 13); len -= 13;
  2077. for(i=0; i+1<sizeof(buf) && len>=8; i++, len-=8)
  2078. buf[i] = get_bits(gb, 8);
  2079. buf[i] = 0;
  2080. if (ac->avctx->debug & FF_DEBUG_PICT_INFO)
  2081. av_log(ac->avctx, AV_LOG_DEBUG, "FILL:%s\n", buf);
  2082. if (sscanf(buf, "libfaac %d.%d", &major, &minor) == 2){
  2083. ac->avctx->internal->skip_samples = 1024;
  2084. }
  2085. unknown:
  2086. skip_bits_long(gb, len);
  2087. return 0;
  2088. }
  2089. /**
  2090. * Decode extension data (incomplete); reference: table 4.51.
  2091. *
  2092. * @param cnt length of TYPE_FIL syntactic element in bytes
  2093. *
  2094. * @return Returns number of bytes consumed
  2095. */
  2096. static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt,
  2097. ChannelElement *che, enum RawDataBlockType elem_type)
  2098. {
  2099. int crc_flag = 0;
  2100. int res = cnt;
  2101. int type = get_bits(gb, 4);
  2102. if (ac->avctx->debug & FF_DEBUG_STARTCODE)
  2103. av_log(ac->avctx, AV_LOG_DEBUG, "extension type: %d len:%d\n", type, cnt);
  2104. switch (type) { // extension type
  2105. case EXT_SBR_DATA_CRC:
  2106. crc_flag++;
  2107. case EXT_SBR_DATA:
  2108. if (!che) {
  2109. av_log(ac->avctx, AV_LOG_ERROR, "SBR was found before the first channel element.\n");
  2110. return res;
  2111. } else if (!ac->oc[1].m4ac.sbr) {
  2112. av_log(ac->avctx, AV_LOG_ERROR, "SBR signaled to be not-present but was found in the bitstream.\n");
  2113. skip_bits_long(gb, 8 * cnt - 4);
  2114. return res;
  2115. } else if (ac->oc[1].m4ac.sbr == -1 && ac->oc[1].status == OC_LOCKED) {
  2116. av_log(ac->avctx, AV_LOG_ERROR, "Implicit SBR was found with a first occurrence after the first frame.\n");
  2117. skip_bits_long(gb, 8 * cnt - 4);
  2118. return res;
  2119. } else if (ac->oc[1].m4ac.ps == -1 && ac->oc[1].status < OC_LOCKED && ac->avctx->channels == 1) {
  2120. ac->oc[1].m4ac.sbr = 1;
  2121. ac->oc[1].m4ac.ps = 1;
  2122. ac->avctx->profile = FF_PROFILE_AAC_HE_V2;
  2123. output_configure(ac, ac->oc[1].layout_map, ac->oc[1].layout_map_tags,
  2124. ac->oc[1].status, 1);
  2125. } else {
  2126. ac->oc[1].m4ac.sbr = 1;
  2127. ac->avctx->profile = FF_PROFILE_AAC_HE;
  2128. }
  2129. res = AAC_RENAME(ff_decode_sbr_extension)(ac, &che->sbr, gb, crc_flag, cnt, elem_type);
  2130. break;
  2131. case EXT_DYNAMIC_RANGE:
  2132. res = decode_dynamic_range(&ac->che_drc, gb);
  2133. break;
  2134. case EXT_FILL:
  2135. decode_fill(ac, gb, 8 * cnt - 4);
  2136. break;
  2137. case EXT_FILL_DATA:
  2138. case EXT_DATA_ELEMENT:
  2139. default:
  2140. skip_bits_long(gb, 8 * cnt - 4);
  2141. break;
  2142. };
  2143. return res;
  2144. }
  2145. /**
  2146. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  2147. *
  2148. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  2149. * @param coef spectral coefficients
  2150. */
  2151. static void apply_tns(INTFLOAT coef[1024], TemporalNoiseShaping *tns,
  2152. IndividualChannelStream *ics, int decode)
  2153. {
  2154. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  2155. int w, filt, m, i;
  2156. int bottom, top, order, start, end, size, inc;
  2157. INTFLOAT lpc[TNS_MAX_ORDER];
  2158. INTFLOAT tmp[TNS_MAX_ORDER+1];
  2159. for (w = 0; w < ics->num_windows; w++) {
  2160. bottom = ics->num_swb;
  2161. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  2162. top = bottom;
  2163. bottom = FFMAX(0, top - tns->length[w][filt]);
  2164. order = tns->order[w][filt];
  2165. if (order == 0)
  2166. continue;
  2167. // tns_decode_coef
  2168. AAC_RENAME(compute_lpc_coefs)(tns->coef[w][filt], order, lpc, 0, 0, 0);
  2169. start = ics->swb_offset[FFMIN(bottom, mmm)];
  2170. end = ics->swb_offset[FFMIN( top, mmm)];
  2171. if ((size = end - start) <= 0)
  2172. continue;
  2173. if (tns->direction[w][filt]) {
  2174. inc = -1;
  2175. start = end - 1;
  2176. } else {
  2177. inc = 1;
  2178. }
  2179. start += w * 128;
  2180. if (decode) {
  2181. // ar filter
  2182. for (m = 0; m < size; m++, start += inc)
  2183. for (i = 1; i <= FFMIN(m, order); i++)
  2184. coef[start] -= AAC_MUL26(coef[start - i * inc], lpc[i - 1]);
  2185. } else {
  2186. // ma filter
  2187. for (m = 0; m < size; m++, start += inc) {
  2188. tmp[0] = coef[start];
  2189. for (i = 1; i <= FFMIN(m, order); i++)
  2190. coef[start] += AAC_MUL26(tmp[i], lpc[i - 1]);
  2191. for (i = order; i > 0; i--)
  2192. tmp[i] = tmp[i - 1];
  2193. }
  2194. }
  2195. }
  2196. }
  2197. }
  2198. /**
  2199. * Apply windowing and MDCT to obtain the spectral
  2200. * coefficient from the predicted sample by LTP.
  2201. */
  2202. static void windowing_and_mdct_ltp(AACContext *ac, INTFLOAT *out,
  2203. INTFLOAT *in, IndividualChannelStream *ics)
  2204. {
  2205. const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2206. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2207. const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2208. const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2209. if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {
  2210. ac->fdsp->vector_fmul(in, in, lwindow_prev, 1024);
  2211. } else {
  2212. memset(in, 0, 448 * sizeof(*in));
  2213. ac->fdsp->vector_fmul(in + 448, in + 448, swindow_prev, 128);
  2214. }
  2215. if (ics->window_sequence[0] != LONG_START_SEQUENCE) {
  2216. ac->fdsp->vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);
  2217. } else {
  2218. ac->fdsp->vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);
  2219. memset(in + 1024 + 576, 0, 448 * sizeof(*in));
  2220. }
  2221. ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);
  2222. }
  2223. /**
  2224. * Apply the long term prediction
  2225. */
  2226. static void apply_ltp(AACContext *ac, SingleChannelElement *sce)
  2227. {
  2228. const LongTermPrediction *ltp = &sce->ics.ltp;
  2229. const uint16_t *offsets = sce->ics.swb_offset;
  2230. int i, sfb;
  2231. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  2232. INTFLOAT *predTime = sce->ret;
  2233. INTFLOAT *predFreq = ac->buf_mdct;
  2234. int16_t num_samples = 2048;
  2235. if (ltp->lag < 1024)
  2236. num_samples = ltp->lag + 1024;
  2237. for (i = 0; i < num_samples; i++)
  2238. predTime[i] = AAC_MUL30(sce->ltp_state[i + 2048 - ltp->lag], ltp->coef);
  2239. memset(&predTime[i], 0, (2048 - i) * sizeof(*predTime));
  2240. ac->windowing_and_mdct_ltp(ac, predFreq, predTime, &sce->ics);
  2241. if (sce->tns.present)
  2242. ac->apply_tns(predFreq, &sce->tns, &sce->ics, 0);
  2243. for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++)
  2244. if (ltp->used[sfb])
  2245. for (i = offsets[sfb]; i < offsets[sfb + 1]; i++)
  2246. sce->coeffs[i] += predFreq[i];
  2247. }
  2248. }
  2249. /**
  2250. * Update the LTP buffer for next frame
  2251. */
  2252. static void update_ltp(AACContext *ac, SingleChannelElement *sce)
  2253. {
  2254. IndividualChannelStream *ics = &sce->ics;
  2255. INTFLOAT *saved = sce->saved;
  2256. INTFLOAT *saved_ltp = sce->coeffs;
  2257. const INTFLOAT *lwindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2258. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2259. int i;
  2260. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2261. memcpy(saved_ltp, saved, 512 * sizeof(*saved_ltp));
  2262. memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
  2263. ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2264. for (i = 0; i < 64; i++)
  2265. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
  2266. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2267. memcpy(saved_ltp, ac->buf_mdct + 512, 448 * sizeof(*saved_ltp));
  2268. memset(saved_ltp + 576, 0, 448 * sizeof(*saved_ltp));
  2269. ac->fdsp->vector_fmul_reverse(saved_ltp + 448, ac->buf_mdct + 960, &swindow[64], 64);
  2270. for (i = 0; i < 64; i++)
  2271. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], swindow[63 - i]);
  2272. } else { // LONG_STOP or ONLY_LONG
  2273. ac->fdsp->vector_fmul_reverse(saved_ltp, ac->buf_mdct + 512, &lwindow[512], 512);
  2274. for (i = 0; i < 512; i++)
  2275. saved_ltp[i + 512] = AAC_MUL31(ac->buf_mdct[1023 - i], lwindow[511 - i]);
  2276. }
  2277. memcpy(sce->ltp_state, sce->ltp_state+1024, 1024 * sizeof(*sce->ltp_state));
  2278. memcpy(sce->ltp_state+1024, sce->ret, 1024 * sizeof(*sce->ltp_state));
  2279. memcpy(sce->ltp_state+2048, saved_ltp, 1024 * sizeof(*sce->ltp_state));
  2280. }
  2281. /**
  2282. * Conduct IMDCT and windowing.
  2283. */
  2284. static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
  2285. {
  2286. IndividualChannelStream *ics = &sce->ics;
  2287. INTFLOAT *in = sce->coeffs;
  2288. INTFLOAT *out = sce->ret;
  2289. INTFLOAT *saved = sce->saved;
  2290. const INTFLOAT *swindow = ics->use_kb_window[0] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2291. const INTFLOAT *lwindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_long_1024) : AAC_RENAME(ff_sine_1024);
  2292. const INTFLOAT *swindow_prev = ics->use_kb_window[1] ? AAC_RENAME(ff_aac_kbd_short_128) : AAC_RENAME(ff_sine_128);
  2293. INTFLOAT *buf = ac->buf_mdct;
  2294. INTFLOAT *temp = ac->temp;
  2295. int i;
  2296. // imdct
  2297. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2298. for (i = 0; i < 1024; i += 128)
  2299. ac->mdct_small.imdct_half(&ac->mdct_small, buf + i, in + i);
  2300. } else {
  2301. ac->mdct.imdct_half(&ac->mdct, buf, in);
  2302. #if USE_FIXED
  2303. for (i=0; i<1024; i++)
  2304. buf[i] = (buf[i] + 4) >> 3;
  2305. #endif /* USE_FIXED */
  2306. }
  2307. /* window overlapping
  2308. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  2309. * and long to short transitions are considered to be short to short
  2310. * transitions. This leaves just two cases (long to long and short to short)
  2311. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  2312. */
  2313. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  2314. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  2315. ac->fdsp->vector_fmul_window( out, saved, buf, lwindow_prev, 512);
  2316. } else {
  2317. memcpy( out, saved, 448 * sizeof(*out));
  2318. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2319. ac->fdsp->vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, 64);
  2320. ac->fdsp->vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, 64);
  2321. ac->fdsp->vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, 64);
  2322. ac->fdsp->vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, 64);
  2323. ac->fdsp->vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, 64);
  2324. memcpy( out + 448 + 4*128, temp, 64 * sizeof(*out));
  2325. } else {
  2326. ac->fdsp->vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, 64);
  2327. memcpy( out + 576, buf + 64, 448 * sizeof(*out));
  2328. }
  2329. }
  2330. // buffer update
  2331. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  2332. memcpy( saved, temp + 64, 64 * sizeof(*saved));
  2333. ac->fdsp->vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 64);
  2334. ac->fdsp->vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 64);
  2335. ac->fdsp->vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 64);
  2336. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
  2337. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  2338. memcpy( saved, buf + 512, 448 * sizeof(*saved));
  2339. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(*saved));
  2340. } else { // LONG_STOP or ONLY_LONG
  2341. memcpy( saved, buf + 512, 512 * sizeof(*saved));
  2342. }
  2343. }
  2344. static void imdct_and_windowing_ld(AACContext *ac, SingleChannelElement *sce)
  2345. {
  2346. IndividualChannelStream *ics = &sce->ics;
  2347. INTFLOAT *in = sce->coeffs;
  2348. INTFLOAT *out = sce->ret;
  2349. INTFLOAT *saved = sce->saved;
  2350. INTFLOAT *buf = ac->buf_mdct;
  2351. #if USE_FIXED
  2352. int i;
  2353. #endif /* USE_FIXED */
  2354. // imdct
  2355. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2356. #if USE_FIXED
  2357. for (i = 0; i < 1024; i++)
  2358. buf[i] = (buf[i] + 2) >> 2;
  2359. #endif /* USE_FIXED */
  2360. // window overlapping
  2361. if (ics->use_kb_window[1]) {
  2362. // AAC LD uses a low overlap sine window instead of a KBD window
  2363. memcpy(out, saved, 192 * sizeof(*out));
  2364. ac->fdsp->vector_fmul_window(out + 192, saved + 192, buf, AAC_RENAME(ff_sine_128), 64);
  2365. memcpy( out + 320, buf + 64, 192 * sizeof(*out));
  2366. } else {
  2367. ac->fdsp->vector_fmul_window(out, saved, buf, AAC_RENAME(ff_sine_512), 256);
  2368. }
  2369. // buffer update
  2370. memcpy(saved, buf + 256, 256 * sizeof(*saved));
  2371. }
  2372. static void imdct_and_windowing_eld(AACContext *ac, SingleChannelElement *sce)
  2373. {
  2374. INTFLOAT *in = sce->coeffs;
  2375. INTFLOAT *out = sce->ret;
  2376. INTFLOAT *saved = sce->saved;
  2377. INTFLOAT *buf = ac->buf_mdct;
  2378. int i;
  2379. const int n = ac->oc[1].m4ac.frame_length_short ? 480 : 512;
  2380. const int n2 = n >> 1;
  2381. const int n4 = n >> 2;
  2382. const INTFLOAT *const window = n == 480 ? AAC_RENAME(ff_aac_eld_window_480) :
  2383. AAC_RENAME(ff_aac_eld_window_512);
  2384. // Inverse transform, mapped to the conventional IMDCT by
  2385. // Chivukula, R.K.; Reznik, Y.A.; Devarajan, V.,
  2386. // "Efficient algorithms for MPEG-4 AAC-ELD, AAC-LD and AAC-LC filterbanks,"
  2387. // International Conference on Audio, Language and Image Processing, ICALIP 2008.
  2388. // URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4590245&isnumber=4589950
  2389. for (i = 0; i < n2; i+=2) {
  2390. INTFLOAT temp;
  2391. temp = in[i ]; in[i ] = -in[n - 1 - i]; in[n - 1 - i] = temp;
  2392. temp = -in[i + 1]; in[i + 1] = in[n - 2 - i]; in[n - 2 - i] = temp;
  2393. }
  2394. #if !USE_FIXED
  2395. if (n == 480)
  2396. ac->mdct480->imdct_half(ac->mdct480, buf, in, 1, -1.f/(16*1024*960));
  2397. else
  2398. #endif
  2399. ac->mdct.imdct_half(&ac->mdct_ld, buf, in);
  2400. #if USE_FIXED
  2401. for (i = 0; i < 1024; i++)
  2402. buf[i] = (buf[i] + 1) >> 1;
  2403. #endif /* USE_FIXED */
  2404. for (i = 0; i < n; i+=2) {
  2405. buf[i] = -buf[i];
  2406. }
  2407. // Like with the regular IMDCT at this point we still have the middle half
  2408. // of a transform but with even symmetry on the left and odd symmetry on
  2409. // the right
  2410. // window overlapping
  2411. // The spec says to use samples [0..511] but the reference decoder uses
  2412. // samples [128..639].
  2413. for (i = n4; i < n2; i ++) {
  2414. out[i - n4] = AAC_MUL31( buf[ n2 - 1 - i] , window[i - n4]) +
  2415. AAC_MUL31( saved[ i + n2] , window[i + n - n4]) +
  2416. AAC_MUL31(-saved[n + n2 - 1 - i] , window[i + 2*n - n4]) +
  2417. AAC_MUL31(-saved[ 2*n + n2 + i] , window[i + 3*n - n4]);
  2418. }
  2419. for (i = 0; i < n2; i ++) {
  2420. out[n4 + i] = AAC_MUL31( buf[ i] , window[i + n2 - n4]) +
  2421. AAC_MUL31(-saved[ n - 1 - i] , window[i + n2 + n - n4]) +
  2422. AAC_MUL31(-saved[ n + i] , window[i + n2 + 2*n - n4]) +
  2423. AAC_MUL31( saved[2*n + n - 1 - i] , window[i + n2 + 3*n - n4]);
  2424. }
  2425. for (i = 0; i < n4; i ++) {
  2426. out[n2 + n4 + i] = AAC_MUL31( buf[ i + n2] , window[i + n - n4]) +
  2427. AAC_MUL31(-saved[n2 - 1 - i] , window[i + 2*n - n4]) +
  2428. AAC_MUL31(-saved[n + n2 + i] , window[i + 3*n - n4]);
  2429. }
  2430. // buffer update
  2431. memmove(saved + n, saved, 2 * n * sizeof(*saved));
  2432. memcpy( saved, buf, n * sizeof(*saved));
  2433. }
  2434. /**
  2435. * channel coupling transformation interface
  2436. *
  2437. * @param apply_coupling_method pointer to (in)dependent coupling function
  2438. */
  2439. static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
  2440. enum RawDataBlockType type, int elem_id,
  2441. enum CouplingPoint coupling_point,
  2442. void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
  2443. {
  2444. int i, c;
  2445. for (i = 0; i < MAX_ELEM_ID; i++) {
  2446. ChannelElement *cce = ac->che[TYPE_CCE][i];
  2447. int index = 0;
  2448. if (cce && cce->coup.coupling_point == coupling_point) {
  2449. ChannelCoupling *coup = &cce->coup;
  2450. for (c = 0; c <= coup->num_coupled; c++) {
  2451. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  2452. if (coup->ch_select[c] != 1) {
  2453. apply_coupling_method(ac, &cc->ch[0], cce, index);
  2454. if (coup->ch_select[c] != 0)
  2455. index++;
  2456. }
  2457. if (coup->ch_select[c] != 2)
  2458. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  2459. } else
  2460. index += 1 + (coup->ch_select[c] == 3);
  2461. }
  2462. }
  2463. }
  2464. }
  2465. /**
  2466. * Convert spectral data to samples, applying all supported tools as appropriate.
  2467. */
  2468. static void spectral_to_sample(AACContext *ac, int samples)
  2469. {
  2470. int i, type;
  2471. void (*imdct_and_window)(AACContext *ac, SingleChannelElement *sce);
  2472. switch (ac->oc[1].m4ac.object_type) {
  2473. case AOT_ER_AAC_LD:
  2474. imdct_and_window = imdct_and_windowing_ld;
  2475. break;
  2476. case AOT_ER_AAC_ELD:
  2477. imdct_and_window = imdct_and_windowing_eld;
  2478. break;
  2479. default:
  2480. imdct_and_window = ac->imdct_and_windowing;
  2481. }
  2482. for (type = 3; type >= 0; type--) {
  2483. for (i = 0; i < MAX_ELEM_ID; i++) {
  2484. ChannelElement *che = ac->che[type][i];
  2485. if (che && che->present) {
  2486. if (type <= TYPE_CPE)
  2487. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, AAC_RENAME(apply_dependent_coupling));
  2488. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP) {
  2489. if (che->ch[0].ics.predictor_present) {
  2490. if (che->ch[0].ics.ltp.present)
  2491. ac->apply_ltp(ac, &che->ch[0]);
  2492. if (che->ch[1].ics.ltp.present && type == TYPE_CPE)
  2493. ac->apply_ltp(ac, &che->ch[1]);
  2494. }
  2495. }
  2496. if (che->ch[0].tns.present)
  2497. ac->apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  2498. if (che->ch[1].tns.present)
  2499. ac->apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  2500. if (type <= TYPE_CPE)
  2501. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, AAC_RENAME(apply_dependent_coupling));
  2502. if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT) {
  2503. imdct_and_window(ac, &che->ch[0]);
  2504. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2505. ac->update_ltp(ac, &che->ch[0]);
  2506. if (type == TYPE_CPE) {
  2507. imdct_and_window(ac, &che->ch[1]);
  2508. if (ac->oc[1].m4ac.object_type == AOT_AAC_LTP)
  2509. ac->update_ltp(ac, &che->ch[1]);
  2510. }
  2511. if (ac->oc[1].m4ac.sbr > 0) {
  2512. AAC_RENAME(ff_sbr_apply)(ac, &che->sbr, type, che->ch[0].ret, che->ch[1].ret);
  2513. }
  2514. }
  2515. if (type <= TYPE_CCE)
  2516. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, AAC_RENAME(apply_independent_coupling));
  2517. #if USE_FIXED
  2518. {
  2519. int j;
  2520. /* preparation for resampler */
  2521. for(j = 0; j<samples; j++){
  2522. che->ch[0].ret[j] = (int32_t)av_clipl_int32((int64_t)che->ch[0].ret[j]<<7)+0x8000;
  2523. if(type == TYPE_CPE)
  2524. che->ch[1].ret[j] = (int32_t)av_clipl_int32((int64_t)che->ch[1].ret[j]<<7)+0x8000;
  2525. }
  2526. }
  2527. #endif /* USE_FIXED */
  2528. che->present = 0;
  2529. } else if (che) {
  2530. av_log(ac->avctx, AV_LOG_VERBOSE, "ChannelElement %d.%d missing \n", type, i);
  2531. }
  2532. }
  2533. }
  2534. }
  2535. static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
  2536. {
  2537. int size;
  2538. AACADTSHeaderInfo hdr_info;
  2539. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2540. int layout_map_tags, ret;
  2541. size = avpriv_aac_parse_header(gb, &hdr_info);
  2542. if (size > 0) {
  2543. if (!ac->warned_num_aac_frames && hdr_info.num_aac_frames != 1) {
  2544. // This is 2 for "VLB " audio in NSV files.
  2545. // See samples/nsv/vlb_audio.
  2546. avpriv_report_missing_feature(ac->avctx,
  2547. "More than one AAC RDB per ADTS frame");
  2548. ac->warned_num_aac_frames = 1;
  2549. }
  2550. push_output_configuration(ac);
  2551. if (hdr_info.chan_config) {
  2552. ac->oc[1].m4ac.chan_config = hdr_info.chan_config;
  2553. if ((ret = set_default_channel_config(ac->avctx,
  2554. layout_map,
  2555. &layout_map_tags,
  2556. hdr_info.chan_config)) < 0)
  2557. return ret;
  2558. if ((ret = output_configure(ac, layout_map, layout_map_tags,
  2559. FFMAX(ac->oc[1].status,
  2560. OC_TRIAL_FRAME), 0)) < 0)
  2561. return ret;
  2562. } else {
  2563. ac->oc[1].m4ac.chan_config = 0;
  2564. /**
  2565. * dual mono frames in Japanese DTV can have chan_config 0
  2566. * WITHOUT specifying PCE.
  2567. * thus, set dual mono as default.
  2568. */
  2569. if (ac->dmono_mode && ac->oc[0].status == OC_NONE) {
  2570. layout_map_tags = 2;
  2571. layout_map[0][0] = layout_map[1][0] = TYPE_SCE;
  2572. layout_map[0][2] = layout_map[1][2] = AAC_CHANNEL_FRONT;
  2573. layout_map[0][1] = 0;
  2574. layout_map[1][1] = 1;
  2575. if (output_configure(ac, layout_map, layout_map_tags,
  2576. OC_TRIAL_FRAME, 0))
  2577. return -7;
  2578. }
  2579. }
  2580. ac->oc[1].m4ac.sample_rate = hdr_info.sample_rate;
  2581. ac->oc[1].m4ac.sampling_index = hdr_info.sampling_index;
  2582. ac->oc[1].m4ac.object_type = hdr_info.object_type;
  2583. ac->oc[1].m4ac.frame_length_short = 0;
  2584. if (ac->oc[0].status != OC_LOCKED ||
  2585. ac->oc[0].m4ac.chan_config != hdr_info.chan_config ||
  2586. ac->oc[0].m4ac.sample_rate != hdr_info.sample_rate) {
  2587. ac->oc[1].m4ac.sbr = -1;
  2588. ac->oc[1].m4ac.ps = -1;
  2589. }
  2590. if (!hdr_info.crc_absent)
  2591. skip_bits(gb, 16);
  2592. }
  2593. return size;
  2594. }
  2595. static int aac_decode_er_frame(AVCodecContext *avctx, void *data,
  2596. int *got_frame_ptr, GetBitContext *gb)
  2597. {
  2598. AACContext *ac = avctx->priv_data;
  2599. const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac;
  2600. ChannelElement *che;
  2601. int err, i;
  2602. int samples = m4ac->frame_length_short ? 960 : 1024;
  2603. int chan_config = m4ac->chan_config;
  2604. int aot = m4ac->object_type;
  2605. if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD)
  2606. samples >>= 1;
  2607. ac->frame = data;
  2608. if ((err = frame_configure_elements(avctx)) < 0)
  2609. return err;
  2610. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2611. // This may lead to an undefined profile being signaled
  2612. ac->avctx->profile = aot - 1;
  2613. ac->tags_mapped = 0;
  2614. if (chan_config < 0 || (chan_config >= 8 && chan_config < 11) || chan_config >= 13) {
  2615. avpriv_request_sample(avctx, "Unknown ER channel configuration %d",
  2616. chan_config);
  2617. return AVERROR_INVALIDDATA;
  2618. }
  2619. for (i = 0; i < tags_per_config[chan_config]; i++) {
  2620. const int elem_type = aac_channel_layout_map[chan_config-1][i][0];
  2621. const int elem_id = aac_channel_layout_map[chan_config-1][i][1];
  2622. if (!(che=get_che(ac, elem_type, elem_id))) {
  2623. av_log(ac->avctx, AV_LOG_ERROR,
  2624. "channel element %d.%d is not allocated\n",
  2625. elem_type, elem_id);
  2626. return AVERROR_INVALIDDATA;
  2627. }
  2628. che->present = 1;
  2629. if (aot != AOT_ER_AAC_ELD)
  2630. skip_bits(gb, 4);
  2631. switch (elem_type) {
  2632. case TYPE_SCE:
  2633. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2634. break;
  2635. case TYPE_CPE:
  2636. err = decode_cpe(ac, gb, che);
  2637. break;
  2638. case TYPE_LFE:
  2639. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2640. break;
  2641. }
  2642. if (err < 0)
  2643. return err;
  2644. }
  2645. spectral_to_sample(ac, samples);
  2646. if (!ac->frame->data[0] && samples) {
  2647. av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
  2648. return AVERROR_INVALIDDATA;
  2649. }
  2650. ac->frame->nb_samples = samples;
  2651. ac->frame->sample_rate = avctx->sample_rate;
  2652. *got_frame_ptr = 1;
  2653. skip_bits_long(gb, get_bits_left(gb));
  2654. return 0;
  2655. }
  2656. static int aac_decode_frame_int(AVCodecContext *avctx, void *data,
  2657. int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)
  2658. {
  2659. AACContext *ac = avctx->priv_data;
  2660. ChannelElement *che = NULL, *che_prev = NULL;
  2661. enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
  2662. int err, elem_id;
  2663. int samples = 0, multiplier, audio_found = 0, pce_found = 0;
  2664. int is_dmono, sce_count = 0;
  2665. ac->frame = data;
  2666. if (show_bits(gb, 12) == 0xfff) {
  2667. if ((err = parse_adts_frame_header(ac, gb)) < 0) {
  2668. av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
  2669. goto fail;
  2670. }
  2671. if (ac->oc[1].m4ac.sampling_index > 12) {
  2672. av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);
  2673. err = AVERROR_INVALIDDATA;
  2674. goto fail;
  2675. }
  2676. }
  2677. if ((err = frame_configure_elements(avctx)) < 0)
  2678. goto fail;
  2679. // The FF_PROFILE_AAC_* defines are all object_type - 1
  2680. // This may lead to an undefined profile being signaled
  2681. ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;
  2682. ac->tags_mapped = 0;
  2683. // parse
  2684. while ((elem_type = get_bits(gb, 3)) != TYPE_END) {
  2685. elem_id = get_bits(gb, 4);
  2686. if (avctx->debug & FF_DEBUG_STARTCODE)
  2687. av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);
  2688. if (!avctx->channels && elem_type != TYPE_PCE) {
  2689. err = AVERROR_INVALIDDATA;
  2690. goto fail;
  2691. }
  2692. if (elem_type < TYPE_DSE) {
  2693. if (!(che=get_che(ac, elem_type, elem_id))) {
  2694. av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",
  2695. elem_type, elem_id);
  2696. err = AVERROR_INVALIDDATA;
  2697. goto fail;
  2698. }
  2699. samples = 1024;
  2700. che->present = 1;
  2701. }
  2702. switch (elem_type) {
  2703. case TYPE_SCE:
  2704. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2705. audio_found = 1;
  2706. sce_count++;
  2707. break;
  2708. case TYPE_CPE:
  2709. err = decode_cpe(ac, gb, che);
  2710. audio_found = 1;
  2711. break;
  2712. case TYPE_CCE:
  2713. err = decode_cce(ac, gb, che);
  2714. break;
  2715. case TYPE_LFE:
  2716. err = decode_ics(ac, &che->ch[0], gb, 0, 0);
  2717. audio_found = 1;
  2718. break;
  2719. case TYPE_DSE:
  2720. err = skip_data_stream_element(ac, gb);
  2721. break;
  2722. case TYPE_PCE: {
  2723. uint8_t layout_map[MAX_ELEM_ID*4][3];
  2724. int tags;
  2725. push_output_configuration(ac);
  2726. tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);
  2727. if (tags < 0) {
  2728. err = tags;
  2729. break;
  2730. }
  2731. if (pce_found) {
  2732. av_log(avctx, AV_LOG_ERROR,
  2733. "Not evaluating a further program_config_element as this construct is dubious at best.\n");
  2734. } else {
  2735. err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);
  2736. if (!err)
  2737. ac->oc[1].m4ac.chan_config = 0;
  2738. pce_found = 1;
  2739. }
  2740. break;
  2741. }
  2742. case TYPE_FIL:
  2743. if (elem_id == 15)
  2744. elem_id += get_bits(gb, 8) - 1;
  2745. if (get_bits_left(gb) < 8 * elem_id) {
  2746. av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);
  2747. err = AVERROR_INVALIDDATA;
  2748. goto fail;
  2749. }
  2750. while (elem_id > 0)
  2751. elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);
  2752. err = 0; /* FIXME */
  2753. break;
  2754. default:
  2755. err = AVERROR_BUG; /* should not happen, but keeps compiler happy */
  2756. break;
  2757. }
  2758. che_prev = che;
  2759. elem_type_prev = elem_type;
  2760. if (err)
  2761. goto fail;
  2762. if (get_bits_left(gb) < 3) {
  2763. av_log(avctx, AV_LOG_ERROR, overread_err);
  2764. err = AVERROR_INVALIDDATA;
  2765. goto fail;
  2766. }
  2767. }
  2768. if (!avctx->channels) {
  2769. *got_frame_ptr = 0;
  2770. return 0;
  2771. }
  2772. multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;
  2773. samples <<= multiplier;
  2774. spectral_to_sample(ac, samples);
  2775. if (ac->oc[1].status && audio_found) {
  2776. avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;
  2777. avctx->frame_size = samples;
  2778. ac->oc[1].status = OC_LOCKED;
  2779. }
  2780. if (multiplier) {
  2781. int side_size;
  2782. const uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
  2783. if (side && side_size>=4)
  2784. AV_WL32(side, 2*AV_RL32(side));
  2785. }
  2786. if (!ac->frame->data[0] && samples) {
  2787. av_log(avctx, AV_LOG_ERROR, "no frame data found\n");
  2788. err = AVERROR_INVALIDDATA;
  2789. goto fail;
  2790. }
  2791. if (samples) {
  2792. ac->frame->nb_samples = samples;
  2793. ac->frame->sample_rate = avctx->sample_rate;
  2794. } else
  2795. av_frame_unref(ac->frame);
  2796. *got_frame_ptr = !!samples;
  2797. /* for dual-mono audio (SCE + SCE) */
  2798. is_dmono = ac->dmono_mode && sce_count == 2 &&
  2799. ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);
  2800. if (is_dmono) {
  2801. if (ac->dmono_mode == 1)
  2802. ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];
  2803. else if (ac->dmono_mode == 2)
  2804. ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];
  2805. }
  2806. return 0;
  2807. fail:
  2808. pop_output_configuration(ac);
  2809. return err;
  2810. }
  2811. static int aac_decode_frame(AVCodecContext *avctx, void *data,
  2812. int *got_frame_ptr, AVPacket *avpkt)
  2813. {
  2814. AACContext *ac = avctx->priv_data;
  2815. const uint8_t *buf = avpkt->data;
  2816. int buf_size = avpkt->size;
  2817. GetBitContext gb;
  2818. int buf_consumed;
  2819. int buf_offset;
  2820. int err;
  2821. int new_extradata_size;
  2822. const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
  2823. AV_PKT_DATA_NEW_EXTRADATA,
  2824. &new_extradata_size);
  2825. int jp_dualmono_size;
  2826. const uint8_t *jp_dualmono = av_packet_get_side_data(avpkt,
  2827. AV_PKT_DATA_JP_DUALMONO,
  2828. &jp_dualmono_size);
  2829. if (new_extradata && 0) {
  2830. av_free(avctx->extradata);
  2831. avctx->extradata = av_mallocz(new_extradata_size +
  2832. AV_INPUT_BUFFER_PADDING_SIZE);
  2833. if (!avctx->extradata)
  2834. return AVERROR(ENOMEM);
  2835. avctx->extradata_size = new_extradata_size;
  2836. memcpy(avctx->extradata, new_extradata, new_extradata_size);
  2837. push_output_configuration(ac);
  2838. if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
  2839. avctx->extradata,
  2840. avctx->extradata_size*8LL, 1) < 0) {
  2841. pop_output_configuration(ac);
  2842. return AVERROR_INVALIDDATA;
  2843. }
  2844. }
  2845. ac->dmono_mode = 0;
  2846. if (jp_dualmono && jp_dualmono_size > 0)
  2847. ac->dmono_mode = 1 + *jp_dualmono;
  2848. if (ac->force_dmono_mode >= 0)
  2849. ac->dmono_mode = ac->force_dmono_mode;
  2850. if (INT_MAX / 8 <= buf_size)
  2851. return AVERROR_INVALIDDATA;
  2852. if ((err = init_get_bits8(&gb, buf, buf_size)) < 0)
  2853. return err;
  2854. switch (ac->oc[1].m4ac.object_type) {
  2855. case AOT_ER_AAC_LC:
  2856. case AOT_ER_AAC_LTP:
  2857. case AOT_ER_AAC_LD:
  2858. case AOT_ER_AAC_ELD:
  2859. err = aac_decode_er_frame(avctx, data, got_frame_ptr, &gb);
  2860. break;
  2861. default:
  2862. err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt);
  2863. }
  2864. if (err < 0)
  2865. return err;
  2866. buf_consumed = (get_bits_count(&gb) + 7) >> 3;
  2867. for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
  2868. if (buf[buf_offset])
  2869. break;
  2870. return buf_size > buf_offset ? buf_consumed : buf_size;
  2871. }
  2872. static av_cold int aac_decode_close(AVCodecContext *avctx)
  2873. {
  2874. AACContext *ac = avctx->priv_data;
  2875. int i, type;
  2876. for (i = 0; i < MAX_ELEM_ID; i++) {
  2877. for (type = 0; type < 4; type++) {
  2878. if (ac->che[type][i])
  2879. AAC_RENAME(ff_aac_sbr_ctx_close)(&ac->che[type][i]->sbr);
  2880. av_freep(&ac->che[type][i]);
  2881. }
  2882. }
  2883. ff_mdct_end(&ac->mdct);
  2884. ff_mdct_end(&ac->mdct_small);
  2885. ff_mdct_end(&ac->mdct_ld);
  2886. ff_mdct_end(&ac->mdct_ltp);
  2887. #if !USE_FIXED
  2888. ff_imdct15_uninit(&ac->mdct480);
  2889. #endif
  2890. av_freep(&ac->fdsp);
  2891. return 0;
  2892. }
  2893. static void aacdec_init(AACContext *c)
  2894. {
  2895. c->imdct_and_windowing = imdct_and_windowing;
  2896. c->apply_ltp = apply_ltp;
  2897. c->apply_tns = apply_tns;
  2898. c->windowing_and_mdct_ltp = windowing_and_mdct_ltp;
  2899. c->update_ltp = update_ltp;
  2900. #if USE_FIXED
  2901. c->vector_pow43 = vector_pow43;
  2902. c->subband_scale = subband_scale;
  2903. #endif
  2904. #if !USE_FIXED
  2905. if(ARCH_MIPS)
  2906. ff_aacdec_init_mips(c);
  2907. #endif /* !USE_FIXED */
  2908. }
  2909. /**
  2910. * AVOptions for Japanese DTV specific extensions (ADTS only)
  2911. */
  2912. #define AACDEC_FLAGS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  2913. static const AVOption options[] = {
  2914. {"dual_mono_mode", "Select the channel to decode for dual mono",
  2915. offsetof(AACContext, force_dmono_mode), AV_OPT_TYPE_INT, {.i64=-1}, -1, 2,
  2916. AACDEC_FLAGS, "dual_mono_mode"},
  2917. {"auto", "autoselection", 0, AV_OPT_TYPE_CONST, {.i64=-1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2918. {"main", "Select Main/Left channel", 0, AV_OPT_TYPE_CONST, {.i64= 1}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2919. {"sub" , "Select Sub/Right channel", 0, AV_OPT_TYPE_CONST, {.i64= 2}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2920. {"both", "Select both channels", 0, AV_OPT_TYPE_CONST, {.i64= 0}, INT_MIN, INT_MAX, AACDEC_FLAGS, "dual_mono_mode"},
  2921. {NULL},
  2922. };
  2923. static const AVClass aac_decoder_class = {
  2924. .class_name = "AAC decoder",
  2925. .item_name = av_default_item_name,
  2926. .option = options,
  2927. .version = LIBAVUTIL_VERSION_INT,
  2928. };
  2929. static const AVProfile profiles[] = {
  2930. { FF_PROFILE_AAC_MAIN, "Main" },
  2931. { FF_PROFILE_AAC_LOW, "LC" },
  2932. { FF_PROFILE_AAC_SSR, "SSR" },
  2933. { FF_PROFILE_AAC_LTP, "LTP" },
  2934. { FF_PROFILE_AAC_HE, "HE-AAC" },
  2935. { FF_PROFILE_AAC_HE_V2, "HE-AACv2" },
  2936. { FF_PROFILE_AAC_LD, "LD" },
  2937. { FF_PROFILE_AAC_ELD, "ELD" },
  2938. { FF_PROFILE_UNKNOWN },
  2939. };