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.

3559 lines
129KB

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