aac.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  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. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file libavcodec/aac.c
  24. * AAC decoder
  25. * @author Oded Shimon ( ods15 ods15 dyndns org )
  26. * @author Maxim Gavrilov ( maxim.gavrilov gmail com )
  27. */
  28. /*
  29. * supported tools
  30. *
  31. * Support? Name
  32. * N (code in SoC repo) gain control
  33. * Y block switching
  34. * Y window shapes - standard
  35. * N window shapes - Low Delay
  36. * Y filterbank - standard
  37. * N (code in SoC repo) filterbank - Scalable Sample Rate
  38. * Y Temporal Noise Shaping
  39. * N (code in SoC repo) Long Term Prediction
  40. * Y intensity stereo
  41. * Y channel coupling
  42. * Y frequency domain prediction
  43. * Y Perceptual Noise Substitution
  44. * Y Mid/Side stereo
  45. * N Scalable Inverse AAC Quantization
  46. * N Frequency Selective Switch
  47. * N upsampling filter
  48. * Y quantization & coding - AAC
  49. * N quantization & coding - TwinVQ
  50. * N quantization & coding - BSAC
  51. * N AAC Error Resilience tools
  52. * N Error Resilience payload syntax
  53. * N Error Protection tool
  54. * N CELP
  55. * N Silence Compression
  56. * N HVXC
  57. * N HVXC 4kbits/s VR
  58. * N Structured Audio tools
  59. * N Structured Audio Sample Bank Format
  60. * N MIDI
  61. * N Harmonic and Individual Lines plus Noise
  62. * N Text-To-Speech Interface
  63. * N (in progress) Spectral Band Replication
  64. * Y (not in this code) Layer-1
  65. * Y (not in this code) Layer-2
  66. * Y (not in this code) Layer-3
  67. * N SinuSoidal Coding (Transient, Sinusoid, Noise)
  68. * N (planned) Parametric Stereo
  69. * N Direct Stream Transfer
  70. *
  71. * Note: - HE AAC v1 comprises LC AAC with Spectral Band Replication.
  72. * - HE AAC v2 comprises LC AAC with Spectral Band Replication and
  73. Parametric Stereo.
  74. */
  75. #include "avcodec.h"
  76. #include "internal.h"
  77. #include "get_bits.h"
  78. #include "dsputil.h"
  79. #include "fft.h"
  80. #include "lpc.h"
  81. #include "aac.h"
  82. #include "aactab.h"
  83. #include "aacdectab.h"
  84. #include "mpeg4audio.h"
  85. #include "aac_parser.h"
  86. #include <assert.h>
  87. #include <errno.h>
  88. #include <math.h>
  89. #include <string.h>
  90. #if ARCH_ARM
  91. # include "arm/aac.h"
  92. #endif
  93. union float754 {
  94. float f;
  95. uint32_t i;
  96. };
  97. static VLC vlc_scalefactors;
  98. static VLC vlc_spectral[11];
  99. static uint32_t cbrt_tab[1<<13];
  100. static const char overread_err[] = "Input buffer exhausted before END element found\n";
  101. static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
  102. {
  103. if (ac->tag_che_map[type][elem_id]) {
  104. return ac->tag_che_map[type][elem_id];
  105. }
  106. if (ac->tags_mapped >= tags_per_config[ac->m4ac.chan_config]) {
  107. return NULL;
  108. }
  109. switch (ac->m4ac.chan_config) {
  110. case 7:
  111. if (ac->tags_mapped == 3 && type == TYPE_CPE) {
  112. ac->tags_mapped++;
  113. return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][2];
  114. }
  115. case 6:
  116. /* Some streams incorrectly code 5.1 audio as SCE[0] CPE[0] CPE[1] SCE[1]
  117. instead of SCE[0] CPE[0] CPE[0] LFE[0]. If we seem to have
  118. encountered such a stream, transfer the LFE[0] element to SCE[1] */
  119. if (ac->tags_mapped == tags_per_config[ac->m4ac.chan_config] - 1 && (type == TYPE_LFE || type == TYPE_SCE)) {
  120. ac->tags_mapped++;
  121. return ac->tag_che_map[type][elem_id] = ac->che[TYPE_LFE][0];
  122. }
  123. case 5:
  124. if (ac->tags_mapped == 2 && type == TYPE_CPE) {
  125. ac->tags_mapped++;
  126. return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][1];
  127. }
  128. case 4:
  129. if (ac->tags_mapped == 2 && ac->m4ac.chan_config == 4 && type == TYPE_SCE) {
  130. ac->tags_mapped++;
  131. return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][1];
  132. }
  133. case 3:
  134. case 2:
  135. if (ac->tags_mapped == (ac->m4ac.chan_config != 2) && type == TYPE_CPE) {
  136. ac->tags_mapped++;
  137. return ac->tag_che_map[TYPE_CPE][elem_id] = ac->che[TYPE_CPE][0];
  138. } else if (ac->m4ac.chan_config == 2) {
  139. return NULL;
  140. }
  141. case 1:
  142. if (!ac->tags_mapped && type == TYPE_SCE) {
  143. ac->tags_mapped++;
  144. return ac->tag_che_map[TYPE_SCE][elem_id] = ac->che[TYPE_SCE][0];
  145. }
  146. default:
  147. return NULL;
  148. }
  149. }
  150. /**
  151. * Check for the channel element in the current channel position configuration.
  152. * If it exists, make sure the appropriate element is allocated and map the
  153. * channel order to match the internal FFmpeg channel layout.
  154. *
  155. * @param che_pos current channel position configuration
  156. * @param type channel element type
  157. * @param id channel element id
  158. * @param channels count of the number of channels in the configuration
  159. *
  160. * @return Returns error status. 0 - OK, !0 - error
  161. */
  162. static av_cold int che_configure(AACContext *ac,
  163. enum ChannelPosition che_pos[4][MAX_ELEM_ID],
  164. int type, int id,
  165. int *channels)
  166. {
  167. if (che_pos[type][id]) {
  168. if (!ac->che[type][id] && !(ac->che[type][id] = av_mallocz(sizeof(ChannelElement))))
  169. return AVERROR(ENOMEM);
  170. if (type != TYPE_CCE) {
  171. ac->output_data[(*channels)++] = ac->che[type][id]->ch[0].ret;
  172. if (type == TYPE_CPE) {
  173. ac->output_data[(*channels)++] = ac->che[type][id]->ch[1].ret;
  174. }
  175. }
  176. } else
  177. av_freep(&ac->che[type][id]);
  178. return 0;
  179. }
  180. /**
  181. * Configure output channel order based on the current program configuration element.
  182. *
  183. * @param che_pos current channel position configuration
  184. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  185. *
  186. * @return Returns error status. 0 - OK, !0 - error
  187. */
  188. static av_cold int output_configure(AACContext *ac,
  189. enum ChannelPosition che_pos[4][MAX_ELEM_ID],
  190. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  191. int channel_config, enum OCStatus oc_type)
  192. {
  193. AVCodecContext *avctx = ac->avccontext;
  194. int i, type, channels = 0, ret;
  195. memcpy(che_pos, new_che_pos, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  196. if (channel_config) {
  197. for (i = 0; i < tags_per_config[channel_config]; i++) {
  198. if ((ret = che_configure(ac, che_pos,
  199. aac_channel_layout_map[channel_config - 1][i][0],
  200. aac_channel_layout_map[channel_config - 1][i][1],
  201. &channels)))
  202. return ret;
  203. }
  204. memset(ac->tag_che_map, 0, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
  205. ac->tags_mapped = 0;
  206. avctx->channel_layout = aac_channel_layout[channel_config - 1];
  207. } else {
  208. /* Allocate or free elements depending on if they are in the
  209. * current program configuration.
  210. *
  211. * Set up default 1:1 output mapping.
  212. *
  213. * For a 5.1 stream the output order will be:
  214. * [ Center ] [ Front Left ] [ Front Right ] [ LFE ] [ Surround Left ] [ Surround Right ]
  215. */
  216. for (i = 0; i < MAX_ELEM_ID; i++) {
  217. for (type = 0; type < 4; type++) {
  218. if ((ret = che_configure(ac, che_pos, type, i, &channels)))
  219. return ret;
  220. }
  221. }
  222. memcpy(ac->tag_che_map, ac->che, 4 * MAX_ELEM_ID * sizeof(ac->che[0][0]));
  223. ac->tags_mapped = 4 * MAX_ELEM_ID;
  224. avctx->channel_layout = 0;
  225. }
  226. avctx->channels = channels;
  227. ac->output_configured = oc_type;
  228. return 0;
  229. }
  230. /**
  231. * Decode an array of 4 bit element IDs, optionally interleaved with a stereo/mono switching bit.
  232. *
  233. * @param cpe_map Stereo (Channel Pair Element) map, NULL if stereo bit is not present.
  234. * @param sce_map mono (Single Channel Element) map
  235. * @param type speaker type/position for these channels
  236. */
  237. static void decode_channel_map(enum ChannelPosition *cpe_map,
  238. enum ChannelPosition *sce_map,
  239. enum ChannelPosition type,
  240. GetBitContext *gb, int n)
  241. {
  242. while (n--) {
  243. enum ChannelPosition *map = cpe_map && get_bits1(gb) ? cpe_map : sce_map; // stereo or mono map
  244. map[get_bits(gb, 4)] = type;
  245. }
  246. }
  247. /**
  248. * Decode program configuration element; reference: table 4.2.
  249. *
  250. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  251. *
  252. * @return Returns error status. 0 - OK, !0 - error
  253. */
  254. static int decode_pce(AACContext *ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  255. GetBitContext *gb)
  256. {
  257. int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc, sampling_index;
  258. int comment_len;
  259. skip_bits(gb, 2); // object_type
  260. sampling_index = get_bits(gb, 4);
  261. if (ac->m4ac.sampling_index != sampling_index)
  262. av_log(ac->avccontext, AV_LOG_WARNING, "Sample rate index in program config element does not match the sample rate index configured by the container.\n");
  263. num_front = get_bits(gb, 4);
  264. num_side = get_bits(gb, 4);
  265. num_back = get_bits(gb, 4);
  266. num_lfe = get_bits(gb, 2);
  267. num_assoc_data = get_bits(gb, 3);
  268. num_cc = get_bits(gb, 4);
  269. if (get_bits1(gb))
  270. skip_bits(gb, 4); // mono_mixdown_tag
  271. if (get_bits1(gb))
  272. skip_bits(gb, 4); // stereo_mixdown_tag
  273. if (get_bits1(gb))
  274. skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround
  275. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);
  276. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE, gb, num_side );
  277. decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK, gb, num_back );
  278. decode_channel_map(NULL, new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE, gb, num_lfe );
  279. skip_bits_long(gb, 4 * num_assoc_data);
  280. decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC, gb, num_cc );
  281. align_get_bits(gb);
  282. /* comment field, first byte is length */
  283. comment_len = get_bits(gb, 8) * 8;
  284. if (get_bits_left(gb) < comment_len) {
  285. av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
  286. return -1;
  287. }
  288. skip_bits_long(gb, comment_len);
  289. return 0;
  290. }
  291. /**
  292. * Set up channel positions based on a default channel configuration
  293. * as specified in table 1.17.
  294. *
  295. * @param new_che_pos New channel position configuration - we only do something if it differs from the current one.
  296. *
  297. * @return Returns error status. 0 - OK, !0 - error
  298. */
  299. static av_cold int set_default_channel_config(AACContext *ac,
  300. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],
  301. int channel_config)
  302. {
  303. if (channel_config < 1 || channel_config > 7) {
  304. av_log(ac->avccontext, AV_LOG_ERROR, "invalid default channel configuration (%d)\n",
  305. channel_config);
  306. return -1;
  307. }
  308. /* default channel configurations:
  309. *
  310. * 1ch : front center (mono)
  311. * 2ch : L + R (stereo)
  312. * 3ch : front center + L + R
  313. * 4ch : front center + L + R + back center
  314. * 5ch : front center + L + R + back stereo
  315. * 6ch : front center + L + R + back stereo + LFE
  316. * 7ch : front center + L + R + outer front left + outer front right + back stereo + LFE
  317. */
  318. if (channel_config != 2)
  319. new_che_pos[TYPE_SCE][0] = AAC_CHANNEL_FRONT; // front center (or mono)
  320. if (channel_config > 1)
  321. new_che_pos[TYPE_CPE][0] = AAC_CHANNEL_FRONT; // L + R (or stereo)
  322. if (channel_config == 4)
  323. new_che_pos[TYPE_SCE][1] = AAC_CHANNEL_BACK; // back center
  324. if (channel_config > 4)
  325. new_che_pos[TYPE_CPE][(channel_config == 7) + 1]
  326. = AAC_CHANNEL_BACK; // back stereo
  327. if (channel_config > 5)
  328. new_che_pos[TYPE_LFE][0] = AAC_CHANNEL_LFE; // LFE
  329. if (channel_config == 7)
  330. new_che_pos[TYPE_CPE][1] = AAC_CHANNEL_FRONT; // outer front left + outer front right
  331. return 0;
  332. }
  333. /**
  334. * Decode GA "General Audio" specific configuration; reference: table 4.1.
  335. *
  336. * @return Returns error status. 0 - OK, !0 - error
  337. */
  338. static int decode_ga_specific_config(AACContext *ac, GetBitContext *gb,
  339. int channel_config)
  340. {
  341. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  342. int extension_flag, ret;
  343. if (get_bits1(gb)) { // frameLengthFlag
  344. av_log_missing_feature(ac->avccontext, "960/120 MDCT window is", 1);
  345. return -1;
  346. }
  347. if (get_bits1(gb)) // dependsOnCoreCoder
  348. skip_bits(gb, 14); // coreCoderDelay
  349. extension_flag = get_bits1(gb);
  350. if (ac->m4ac.object_type == AOT_AAC_SCALABLE ||
  351. ac->m4ac.object_type == AOT_ER_AAC_SCALABLE)
  352. skip_bits(gb, 3); // layerNr
  353. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  354. if (channel_config == 0) {
  355. skip_bits(gb, 4); // element_instance_tag
  356. if ((ret = decode_pce(ac, new_che_pos, gb)))
  357. return ret;
  358. } else {
  359. if ((ret = set_default_channel_config(ac, new_che_pos, channel_config)))
  360. return ret;
  361. }
  362. if ((ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
  363. return ret;
  364. if (extension_flag) {
  365. switch (ac->m4ac.object_type) {
  366. case AOT_ER_BSAC:
  367. skip_bits(gb, 5); // numOfSubFrame
  368. skip_bits(gb, 11); // layer_length
  369. break;
  370. case AOT_ER_AAC_LC:
  371. case AOT_ER_AAC_LTP:
  372. case AOT_ER_AAC_SCALABLE:
  373. case AOT_ER_AAC_LD:
  374. skip_bits(gb, 3); /* aacSectionDataResilienceFlag
  375. * aacScalefactorDataResilienceFlag
  376. * aacSpectralDataResilienceFlag
  377. */
  378. break;
  379. }
  380. skip_bits1(gb); // extensionFlag3 (TBD in version 3)
  381. }
  382. return 0;
  383. }
  384. /**
  385. * Decode audio specific configuration; reference: table 1.13.
  386. *
  387. * @param data pointer to AVCodecContext extradata
  388. * @param data_size size of AVCCodecContext extradata
  389. *
  390. * @return Returns error status. 0 - OK, !0 - error
  391. */
  392. static int decode_audio_specific_config(AACContext *ac, void *data,
  393. int data_size)
  394. {
  395. GetBitContext gb;
  396. int i;
  397. init_get_bits(&gb, data, data_size * 8);
  398. if ((i = ff_mpeg4audio_get_config(&ac->m4ac, data, data_size)) < 0)
  399. return -1;
  400. if (ac->m4ac.sampling_index > 12) {
  401. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  402. return -1;
  403. }
  404. skip_bits_long(&gb, i);
  405. switch (ac->m4ac.object_type) {
  406. case AOT_AAC_MAIN:
  407. case AOT_AAC_LC:
  408. if (decode_ga_specific_config(ac, &gb, ac->m4ac.chan_config))
  409. return -1;
  410. break;
  411. default:
  412. av_log(ac->avccontext, AV_LOG_ERROR, "Audio object type %s%d is not supported.\n",
  413. ac->m4ac.sbr == 1? "SBR+" : "", ac->m4ac.object_type);
  414. return -1;
  415. }
  416. return 0;
  417. }
  418. /**
  419. * linear congruential pseudorandom number generator
  420. *
  421. * @param previous_val pointer to the current state of the generator
  422. *
  423. * @return Returns a 32-bit pseudorandom integer
  424. */
  425. static av_always_inline int lcg_random(int previous_val)
  426. {
  427. return previous_val * 1664525 + 1013904223;
  428. }
  429. static av_always_inline void reset_predict_state(PredictorState *ps)
  430. {
  431. ps->r0 = 0.0f;
  432. ps->r1 = 0.0f;
  433. ps->cor0 = 0.0f;
  434. ps->cor1 = 0.0f;
  435. ps->var0 = 1.0f;
  436. ps->var1 = 1.0f;
  437. }
  438. static void reset_all_predictors(PredictorState *ps)
  439. {
  440. int i;
  441. for (i = 0; i < MAX_PREDICTORS; i++)
  442. reset_predict_state(&ps[i]);
  443. }
  444. static void reset_predictor_group(PredictorState *ps, int group_num)
  445. {
  446. int i;
  447. for (i = group_num - 1; i < MAX_PREDICTORS; i += 30)
  448. reset_predict_state(&ps[i]);
  449. }
  450. static av_cold int aac_decode_init(AVCodecContext *avccontext)
  451. {
  452. AACContext *ac = avccontext->priv_data;
  453. int i;
  454. ac->avccontext = avccontext;
  455. if (avccontext->extradata_size > 0) {
  456. if (decode_audio_specific_config(ac, avccontext->extradata, avccontext->extradata_size))
  457. return -1;
  458. avccontext->sample_rate = ac->m4ac.sample_rate;
  459. } else if (avccontext->channels > 0) {
  460. ac->m4ac.sample_rate = avccontext->sample_rate;
  461. }
  462. avccontext->sample_fmt = SAMPLE_FMT_S16;
  463. avccontext->frame_size = 1024;
  464. AAC_INIT_VLC_STATIC( 0, 304);
  465. AAC_INIT_VLC_STATIC( 1, 270);
  466. AAC_INIT_VLC_STATIC( 2, 550);
  467. AAC_INIT_VLC_STATIC( 3, 300);
  468. AAC_INIT_VLC_STATIC( 4, 328);
  469. AAC_INIT_VLC_STATIC( 5, 294);
  470. AAC_INIT_VLC_STATIC( 6, 306);
  471. AAC_INIT_VLC_STATIC( 7, 268);
  472. AAC_INIT_VLC_STATIC( 8, 510);
  473. AAC_INIT_VLC_STATIC( 9, 366);
  474. AAC_INIT_VLC_STATIC(10, 462);
  475. dsputil_init(&ac->dsp, avccontext);
  476. ac->random_state = 0x1f2e3d4c;
  477. // -1024 - Compensate wrong IMDCT method.
  478. // 32768 - Required to scale values to the correct range for the bias method
  479. // for float to int16 conversion.
  480. if (ac->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
  481. ac->add_bias = 385.0f;
  482. ac->sf_scale = 1. / (-1024. * 32768.);
  483. ac->sf_offset = 0;
  484. } else {
  485. ac->add_bias = 0.0f;
  486. ac->sf_scale = 1. / -1024.;
  487. ac->sf_offset = 60;
  488. }
  489. #if !CONFIG_HARDCODED_TABLES
  490. for (i = 0; i < 428; i++)
  491. ff_aac_pow2sf_tab[i] = pow(2, (i - 200) / 4.);
  492. #endif /* CONFIG_HARDCODED_TABLES */
  493. INIT_VLC_STATIC(&vlc_scalefactors,7,FF_ARRAY_ELEMS(ff_aac_scalefactor_code),
  494. ff_aac_scalefactor_bits, sizeof(ff_aac_scalefactor_bits[0]), sizeof(ff_aac_scalefactor_bits[0]),
  495. ff_aac_scalefactor_code, sizeof(ff_aac_scalefactor_code[0]), sizeof(ff_aac_scalefactor_code[0]),
  496. 352);
  497. ff_mdct_init(&ac->mdct, 11, 1, 1.0);
  498. ff_mdct_init(&ac->mdct_small, 8, 1, 1.0);
  499. // window initialization
  500. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  501. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  502. ff_init_ff_sine_windows(10);
  503. ff_init_ff_sine_windows( 7);
  504. if (!cbrt_tab[(1<<13) - 1]) {
  505. for (i = 0; i < 1<<13; i++) {
  506. union float754 f;
  507. f.f = cbrtf(i) * i;
  508. cbrt_tab[i] = f.i;
  509. }
  510. }
  511. return 0;
  512. }
  513. /**
  514. * Skip data_stream_element; reference: table 4.10.
  515. */
  516. static int skip_data_stream_element(AACContext *ac, GetBitContext *gb)
  517. {
  518. int byte_align = get_bits1(gb);
  519. int count = get_bits(gb, 8);
  520. if (count == 255)
  521. count += get_bits(gb, 8);
  522. if (byte_align)
  523. align_get_bits(gb);
  524. if (get_bits_left(gb) < 8 * count) {
  525. av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
  526. return -1;
  527. }
  528. skip_bits_long(gb, 8 * count);
  529. return 0;
  530. }
  531. static int decode_prediction(AACContext *ac, IndividualChannelStream *ics,
  532. GetBitContext *gb)
  533. {
  534. int sfb;
  535. if (get_bits1(gb)) {
  536. ics->predictor_reset_group = get_bits(gb, 5);
  537. if (ics->predictor_reset_group == 0 || ics->predictor_reset_group > 30) {
  538. av_log(ac->avccontext, AV_LOG_ERROR, "Invalid Predictor Reset Group.\n");
  539. return -1;
  540. }
  541. }
  542. for (sfb = 0; sfb < FFMIN(ics->max_sfb, ff_aac_pred_sfb_max[ac->m4ac.sampling_index]); sfb++) {
  543. ics->prediction_used[sfb] = get_bits1(gb);
  544. }
  545. return 0;
  546. }
  547. /**
  548. * Decode Individual Channel Stream info; reference: table 4.6.
  549. *
  550. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  551. */
  552. static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,
  553. GetBitContext *gb, int common_window)
  554. {
  555. if (get_bits1(gb)) {
  556. av_log(ac->avccontext, AV_LOG_ERROR, "Reserved bit set.\n");
  557. memset(ics, 0, sizeof(IndividualChannelStream));
  558. return -1;
  559. }
  560. ics->window_sequence[1] = ics->window_sequence[0];
  561. ics->window_sequence[0] = get_bits(gb, 2);
  562. ics->use_kb_window[1] = ics->use_kb_window[0];
  563. ics->use_kb_window[0] = get_bits1(gb);
  564. ics->num_window_groups = 1;
  565. ics->group_len[0] = 1;
  566. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  567. int i;
  568. ics->max_sfb = get_bits(gb, 4);
  569. for (i = 0; i < 7; i++) {
  570. if (get_bits1(gb)) {
  571. ics->group_len[ics->num_window_groups - 1]++;
  572. } else {
  573. ics->num_window_groups++;
  574. ics->group_len[ics->num_window_groups - 1] = 1;
  575. }
  576. }
  577. ics->num_windows = 8;
  578. ics->swb_offset = ff_swb_offset_128[ac->m4ac.sampling_index];
  579. ics->num_swb = ff_aac_num_swb_128[ac->m4ac.sampling_index];
  580. ics->tns_max_bands = ff_tns_max_bands_128[ac->m4ac.sampling_index];
  581. ics->predictor_present = 0;
  582. } else {
  583. ics->max_sfb = get_bits(gb, 6);
  584. ics->num_windows = 1;
  585. ics->swb_offset = ff_swb_offset_1024[ac->m4ac.sampling_index];
  586. ics->num_swb = ff_aac_num_swb_1024[ac->m4ac.sampling_index];
  587. ics->tns_max_bands = ff_tns_max_bands_1024[ac->m4ac.sampling_index];
  588. ics->predictor_present = get_bits1(gb);
  589. ics->predictor_reset_group = 0;
  590. if (ics->predictor_present) {
  591. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  592. if (decode_prediction(ac, ics, gb)) {
  593. memset(ics, 0, sizeof(IndividualChannelStream));
  594. return -1;
  595. }
  596. } else if (ac->m4ac.object_type == AOT_AAC_LC) {
  597. av_log(ac->avccontext, AV_LOG_ERROR, "Prediction is not allowed in AAC-LC.\n");
  598. memset(ics, 0, sizeof(IndividualChannelStream));
  599. return -1;
  600. } else {
  601. av_log_missing_feature(ac->avccontext, "Predictor bit set but LTP is", 1);
  602. memset(ics, 0, sizeof(IndividualChannelStream));
  603. return -1;
  604. }
  605. }
  606. }
  607. if (ics->max_sfb > ics->num_swb) {
  608. av_log(ac->avccontext, AV_LOG_ERROR,
  609. "Number of scalefactor bands in group (%d) exceeds limit (%d).\n",
  610. ics->max_sfb, ics->num_swb);
  611. memset(ics, 0, sizeof(IndividualChannelStream));
  612. return -1;
  613. }
  614. return 0;
  615. }
  616. /**
  617. * Decode band types (section_data payload); reference: table 4.46.
  618. *
  619. * @param band_type array of the used band type
  620. * @param band_type_run_end array of the last scalefactor band of a band type run
  621. *
  622. * @return Returns error status. 0 - OK, !0 - error
  623. */
  624. static int decode_band_types(AACContext *ac, enum BandType band_type[120],
  625. int band_type_run_end[120], GetBitContext *gb,
  626. IndividualChannelStream *ics)
  627. {
  628. int g, idx = 0;
  629. const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;
  630. for (g = 0; g < ics->num_window_groups; g++) {
  631. int k = 0;
  632. while (k < ics->max_sfb) {
  633. uint8_t sect_end = k;
  634. int sect_len_incr;
  635. int sect_band_type = get_bits(gb, 4);
  636. if (sect_band_type == 12) {
  637. av_log(ac->avccontext, AV_LOG_ERROR, "invalid band type\n");
  638. return -1;
  639. }
  640. while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)
  641. sect_end += sect_len_incr;
  642. sect_end += sect_len_incr;
  643. if (get_bits_left(gb) < 0) {
  644. av_log(ac->avccontext, AV_LOG_ERROR, overread_err);
  645. return -1;
  646. }
  647. if (sect_end > ics->max_sfb) {
  648. av_log(ac->avccontext, AV_LOG_ERROR,
  649. "Number of bands (%d) exceeds limit (%d).\n",
  650. sect_end, ics->max_sfb);
  651. return -1;
  652. }
  653. for (; k < sect_end; k++) {
  654. band_type [idx] = sect_band_type;
  655. band_type_run_end[idx++] = sect_end;
  656. }
  657. }
  658. }
  659. return 0;
  660. }
  661. /**
  662. * Decode scalefactors; reference: table 4.47.
  663. *
  664. * @param global_gain first scalefactor value as scalefactors are differentially coded
  665. * @param band_type array of the used band type
  666. * @param band_type_run_end array of the last scalefactor band of a band type run
  667. * @param sf array of scalefactors or intensity stereo positions
  668. *
  669. * @return Returns error status. 0 - OK, !0 - error
  670. */
  671. static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,
  672. unsigned int global_gain,
  673. IndividualChannelStream *ics,
  674. enum BandType band_type[120],
  675. int band_type_run_end[120])
  676. {
  677. const int sf_offset = ac->sf_offset + (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE ? 12 : 0);
  678. int g, i, idx = 0;
  679. int offset[3] = { global_gain, global_gain - 90, 100 };
  680. int noise_flag = 1;
  681. static const char *sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };
  682. for (g = 0; g < ics->num_window_groups; g++) {
  683. for (i = 0; i < ics->max_sfb;) {
  684. int run_end = band_type_run_end[idx];
  685. if (band_type[idx] == ZERO_BT) {
  686. for (; i < run_end; i++, idx++)
  687. sf[idx] = 0.;
  688. } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {
  689. for (; i < run_end; i++, idx++) {
  690. offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  691. if (offset[2] > 255U) {
  692. av_log(ac->avccontext, AV_LOG_ERROR,
  693. "%s (%d) out of range.\n", sf_str[2], offset[2]);
  694. return -1;
  695. }
  696. sf[idx] = ff_aac_pow2sf_tab[-offset[2] + 300];
  697. }
  698. } else if (band_type[idx] == NOISE_BT) {
  699. for (; i < run_end; i++, idx++) {
  700. if (noise_flag-- > 0)
  701. offset[1] += get_bits(gb, 9) - 256;
  702. else
  703. offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  704. if (offset[1] > 255U) {
  705. av_log(ac->avccontext, AV_LOG_ERROR,
  706. "%s (%d) out of range.\n", sf_str[1], offset[1]);
  707. return -1;
  708. }
  709. sf[idx] = -ff_aac_pow2sf_tab[offset[1] + sf_offset + 100];
  710. }
  711. } else {
  712. for (; i < run_end; i++, idx++) {
  713. offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  714. if (offset[0] > 255U) {
  715. av_log(ac->avccontext, AV_LOG_ERROR,
  716. "%s (%d) out of range.\n", sf_str[0], offset[0]);
  717. return -1;
  718. }
  719. sf[idx] = -ff_aac_pow2sf_tab[ offset[0] + sf_offset];
  720. }
  721. }
  722. }
  723. }
  724. return 0;
  725. }
  726. /**
  727. * Decode pulse data; reference: table 4.7.
  728. */
  729. static int decode_pulses(Pulse *pulse, GetBitContext *gb,
  730. const uint16_t *swb_offset, int num_swb)
  731. {
  732. int i, pulse_swb;
  733. pulse->num_pulse = get_bits(gb, 2) + 1;
  734. pulse_swb = get_bits(gb, 6);
  735. if (pulse_swb >= num_swb)
  736. return -1;
  737. pulse->pos[0] = swb_offset[pulse_swb];
  738. pulse->pos[0] += get_bits(gb, 5);
  739. if (pulse->pos[0] > 1023)
  740. return -1;
  741. pulse->amp[0] = get_bits(gb, 4);
  742. for (i = 1; i < pulse->num_pulse; i++) {
  743. pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i - 1];
  744. if (pulse->pos[i] > 1023)
  745. return -1;
  746. pulse->amp[i] = get_bits(gb, 4);
  747. }
  748. return 0;
  749. }
  750. /**
  751. * Decode Temporal Noise Shaping data; reference: table 4.48.
  752. *
  753. * @return Returns error status. 0 - OK, !0 - error
  754. */
  755. static int decode_tns(AACContext *ac, TemporalNoiseShaping *tns,
  756. GetBitContext *gb, const IndividualChannelStream *ics)
  757. {
  758. int w, filt, i, coef_len, coef_res, coef_compress;
  759. const int is8 = ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE;
  760. const int tns_max_order = is8 ? 7 : ac->m4ac.object_type == AOT_AAC_MAIN ? 20 : 12;
  761. for (w = 0; w < ics->num_windows; w++) {
  762. if ((tns->n_filt[w] = get_bits(gb, 2 - is8))) {
  763. coef_res = get_bits1(gb);
  764. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  765. int tmp2_idx;
  766. tns->length[w][filt] = get_bits(gb, 6 - 2 * is8);
  767. if ((tns->order[w][filt] = get_bits(gb, 5 - 2 * is8)) > tns_max_order) {
  768. av_log(ac->avccontext, AV_LOG_ERROR, "TNS filter order %d is greater than maximum %d.",
  769. tns->order[w][filt], tns_max_order);
  770. tns->order[w][filt] = 0;
  771. return -1;
  772. }
  773. if (tns->order[w][filt]) {
  774. tns->direction[w][filt] = get_bits1(gb);
  775. coef_compress = get_bits1(gb);
  776. coef_len = coef_res + 3 - coef_compress;
  777. tmp2_idx = 2 * coef_compress + coef_res;
  778. for (i = 0; i < tns->order[w][filt]; i++)
  779. tns->coef[w][filt][i] = tns_tmp2_map[tmp2_idx][get_bits(gb, coef_len)];
  780. }
  781. }
  782. }
  783. }
  784. return 0;
  785. }
  786. /**
  787. * Decode Mid/Side data; reference: table 4.54.
  788. *
  789. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  790. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  791. * [3] reserved for scalable AAC
  792. */
  793. static void decode_mid_side_stereo(ChannelElement *cpe, GetBitContext *gb,
  794. int ms_present)
  795. {
  796. int idx;
  797. if (ms_present == 1) {
  798. for (idx = 0; idx < cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb; idx++)
  799. cpe->ms_mask[idx] = get_bits1(gb);
  800. } else if (ms_present == 2) {
  801. memset(cpe->ms_mask, 1, cpe->ch[0].ics.num_window_groups * cpe->ch[0].ics.max_sfb * sizeof(cpe->ms_mask[0]));
  802. }
  803. }
  804. #ifndef VMUL2
  805. static inline float *VMUL2(float *dst, const float *v, unsigned idx,
  806. const float *scale)
  807. {
  808. float s = *scale;
  809. *dst++ = v[idx & 15] * s;
  810. *dst++ = v[idx>>4 & 15] * s;
  811. return dst;
  812. }
  813. #endif
  814. #ifndef VMUL4
  815. static inline float *VMUL4(float *dst, const float *v, unsigned idx,
  816. const float *scale)
  817. {
  818. float s = *scale;
  819. *dst++ = v[idx & 3] * s;
  820. *dst++ = v[idx>>2 & 3] * s;
  821. *dst++ = v[idx>>4 & 3] * s;
  822. *dst++ = v[idx>>6 & 3] * s;
  823. return dst;
  824. }
  825. #endif
  826. #ifndef VMUL2S
  827. static inline float *VMUL2S(float *dst, const float *v, unsigned idx,
  828. unsigned sign, const float *scale)
  829. {
  830. union float754 s0, s1;
  831. s0.f = s1.f = *scale;
  832. s0.i ^= sign >> 1 << 31;
  833. s1.i ^= sign << 31;
  834. *dst++ = v[idx & 15] * s0.f;
  835. *dst++ = v[idx>>4 & 15] * s1.f;
  836. return dst;
  837. }
  838. #endif
  839. #ifndef VMUL4S
  840. static inline float *VMUL4S(float *dst, const float *v, unsigned idx,
  841. unsigned sign, const float *scale)
  842. {
  843. unsigned nz = idx >> 12;
  844. union float754 s = { .f = *scale };
  845. union float754 t;
  846. t.i = s.i ^ (sign & 1<<31);
  847. *dst++ = v[idx & 3] * t.f;
  848. sign <<= nz & 1; nz >>= 1;
  849. t.i = s.i ^ (sign & 1<<31);
  850. *dst++ = v[idx>>2 & 3] * t.f;
  851. sign <<= nz & 1; nz >>= 1;
  852. t.i = s.i ^ (sign & 1<<31);
  853. *dst++ = v[idx>>4 & 3] * t.f;
  854. sign <<= nz & 1; nz >>= 1;
  855. t.i = s.i ^ (sign & 1<<31);
  856. *dst++ = v[idx>>6 & 3] * t.f;
  857. return dst;
  858. }
  859. #endif
  860. /**
  861. * Decode spectral data; reference: table 4.50.
  862. * Dequantize and scale spectral data; reference: 4.6.3.3.
  863. *
  864. * @param coef array of dequantized, scaled spectral data
  865. * @param sf array of scalefactors or intensity stereo positions
  866. * @param pulse_present set if pulses are present
  867. * @param pulse pointer to pulse data struct
  868. * @param band_type array of the used band type
  869. *
  870. * @return Returns error status. 0 - OK, !0 - error
  871. */
  872. static int decode_spectrum_and_dequant(AACContext *ac, float coef[1024],
  873. GetBitContext *gb, const float sf[120],
  874. int pulse_present, const Pulse *pulse,
  875. const IndividualChannelStream *ics,
  876. enum BandType band_type[120])
  877. {
  878. int i, k, g, idx = 0;
  879. const int c = 1024 / ics->num_windows;
  880. const uint16_t *offsets = ics->swb_offset;
  881. float *coef_base = coef;
  882. int err_idx;
  883. for (g = 0; g < ics->num_windows; g++)
  884. memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float) * (c - offsets[ics->max_sfb]));
  885. for (g = 0; g < ics->num_window_groups; g++) {
  886. unsigned g_len = ics->group_len[g];
  887. for (i = 0; i < ics->max_sfb; i++, idx++) {
  888. const unsigned cbt_m1 = band_type[idx] - 1;
  889. float *cfo = coef + offsets[i];
  890. int off_len = offsets[i + 1] - offsets[i];
  891. int group;
  892. if (cbt_m1 >= INTENSITY_BT2 - 1) {
  893. for (group = 0; group < g_len; group++, cfo+=128) {
  894. memset(cfo, 0, off_len * sizeof(float));
  895. }
  896. } else if (cbt_m1 == NOISE_BT - 1) {
  897. for (group = 0; group < g_len; group++, cfo+=128) {
  898. float scale;
  899. float band_energy;
  900. for (k = 0; k < off_len; k++) {
  901. ac->random_state = lcg_random(ac->random_state);
  902. cfo[k] = ac->random_state;
  903. }
  904. band_energy = ac->dsp.scalarproduct_float(cfo, cfo, off_len);
  905. scale = sf[idx] / sqrtf(band_energy);
  906. ac->dsp.vector_fmul_scalar(cfo, cfo, scale, off_len);
  907. }
  908. } else {
  909. const float *vq = ff_aac_codebook_vector_vals[cbt_m1];
  910. const uint16_t *cb_vector_idx = ff_aac_codebook_vector_idx[cbt_m1];
  911. VLC_TYPE (*vlc_tab)[2] = vlc_spectral[cbt_m1].table;
  912. const int cb_size = ff_aac_spectral_sizes[cbt_m1];
  913. OPEN_READER(re, gb);
  914. switch (cbt_m1 >> 1) {
  915. case 0:
  916. for (group = 0; group < g_len; group++, cfo+=128) {
  917. float *cf = cfo;
  918. int len = off_len;
  919. do {
  920. int code;
  921. unsigned cb_idx;
  922. UPDATE_CACHE(re, gb);
  923. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  924. if (code >= cb_size) {
  925. err_idx = code;
  926. goto err_cb_overflow;
  927. }
  928. cb_idx = cb_vector_idx[code];
  929. cf = VMUL4(cf, vq, cb_idx, sf + idx);
  930. } while (len -= 4);
  931. }
  932. break;
  933. case 1:
  934. for (group = 0; group < g_len; group++, cfo+=128) {
  935. float *cf = cfo;
  936. int len = off_len;
  937. do {
  938. int code;
  939. unsigned nnz;
  940. unsigned cb_idx;
  941. uint32_t bits;
  942. UPDATE_CACHE(re, gb);
  943. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  944. if (code >= cb_size) {
  945. err_idx = code;
  946. goto err_cb_overflow;
  947. }
  948. #if MIN_CACHE_BITS < 20
  949. UPDATE_CACHE(re, gb);
  950. #endif
  951. cb_idx = cb_vector_idx[code];
  952. nnz = cb_idx >> 8 & 15;
  953. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  954. LAST_SKIP_BITS(re, gb, nnz);
  955. cf = VMUL4S(cf, vq, cb_idx, bits, sf + idx);
  956. } while (len -= 4);
  957. }
  958. break;
  959. case 2:
  960. for (group = 0; group < g_len; group++, cfo+=128) {
  961. float *cf = cfo;
  962. int len = off_len;
  963. do {
  964. int code;
  965. unsigned cb_idx;
  966. UPDATE_CACHE(re, gb);
  967. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  968. if (code >= cb_size) {
  969. err_idx = code;
  970. goto err_cb_overflow;
  971. }
  972. cb_idx = cb_vector_idx[code];
  973. cf = VMUL2(cf, vq, cb_idx, sf + idx);
  974. } while (len -= 2);
  975. }
  976. break;
  977. case 3:
  978. case 4:
  979. for (group = 0; group < g_len; group++, cfo+=128) {
  980. float *cf = cfo;
  981. int len = off_len;
  982. do {
  983. int code;
  984. unsigned nnz;
  985. unsigned cb_idx;
  986. unsigned sign;
  987. UPDATE_CACHE(re, gb);
  988. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  989. if (code >= cb_size) {
  990. err_idx = code;
  991. goto err_cb_overflow;
  992. }
  993. cb_idx = cb_vector_idx[code];
  994. nnz = cb_idx >> 8 & 15;
  995. sign = SHOW_UBITS(re, gb, nnz) << (cb_idx >> 12);
  996. LAST_SKIP_BITS(re, gb, nnz);
  997. cf = VMUL2S(cf, vq, cb_idx, sign, sf + idx);
  998. } while (len -= 2);
  999. }
  1000. break;
  1001. default:
  1002. for (group = 0; group < g_len; group++, cfo+=128) {
  1003. float *cf = cfo;
  1004. uint32_t *icf = (uint32_t *) cf;
  1005. int len = off_len;
  1006. do {
  1007. int code;
  1008. unsigned nzt, nnz;
  1009. unsigned cb_idx;
  1010. uint32_t bits;
  1011. int j;
  1012. UPDATE_CACHE(re, gb);
  1013. GET_VLC(code, re, gb, vlc_tab, 8, 2);
  1014. if (!code) {
  1015. *icf++ = 0;
  1016. *icf++ = 0;
  1017. continue;
  1018. }
  1019. if (code >= cb_size) {
  1020. err_idx = code;
  1021. goto err_cb_overflow;
  1022. }
  1023. cb_idx = cb_vector_idx[code];
  1024. nnz = cb_idx >> 12;
  1025. nzt = cb_idx >> 8;
  1026. bits = SHOW_UBITS(re, gb, nnz) << (32-nnz);
  1027. LAST_SKIP_BITS(re, gb, nnz);
  1028. for (j = 0; j < 2; j++) {
  1029. if (nzt & 1<<j) {
  1030. uint32_t b;
  1031. int n;
  1032. /* The total length of escape_sequence must be < 22 bits according
  1033. to the specification (i.e. max is 111111110xxxxxxxxxxxx). */
  1034. UPDATE_CACHE(re, gb);
  1035. b = GET_CACHE(re, gb);
  1036. b = 31 - av_log2(~b);
  1037. if (b > 8) {
  1038. av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");
  1039. return -1;
  1040. }
  1041. #if MIN_CACHE_BITS < 21
  1042. LAST_SKIP_BITS(re, gb, b + 1);
  1043. UPDATE_CACHE(re, gb);
  1044. #else
  1045. SKIP_BITS(re, gb, b + 1);
  1046. #endif
  1047. b += 4;
  1048. n = (1 << b) + SHOW_UBITS(re, gb, b);
  1049. LAST_SKIP_BITS(re, gb, b);
  1050. *icf++ = cbrt_tab[n] | (bits & 1<<31);
  1051. bits <<= 1;
  1052. } else {
  1053. unsigned v = ((const uint32_t*)vq)[cb_idx & 15];
  1054. *icf++ = (bits & 1<<31) | v;
  1055. bits <<= !!v;
  1056. }
  1057. cb_idx >>= 4;
  1058. }
  1059. } while (len -= 2);
  1060. ac->dsp.vector_fmul_scalar(cfo, cfo, sf[idx], off_len);
  1061. }
  1062. }
  1063. CLOSE_READER(re, gb);
  1064. }
  1065. }
  1066. coef += g_len << 7;
  1067. }
  1068. if (pulse_present) {
  1069. idx = 0;
  1070. for (i = 0; i < pulse->num_pulse; i++) {
  1071. float co = coef_base[ pulse->pos[i] ];
  1072. while (offsets[idx + 1] <= pulse->pos[i])
  1073. idx++;
  1074. if (band_type[idx] != NOISE_BT && sf[idx]) {
  1075. float ico = -pulse->amp[i];
  1076. if (co) {
  1077. co /= sf[idx];
  1078. ico = co / sqrtf(sqrtf(fabsf(co))) + (co > 0 ? -ico : ico);
  1079. }
  1080. coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico * sf[idx];
  1081. }
  1082. }
  1083. }
  1084. return 0;
  1085. err_cb_overflow:
  1086. av_log(ac->avccontext, AV_LOG_ERROR,
  1087. "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",
  1088. band_type[idx], err_idx, ff_aac_spectral_sizes[band_type[idx]]);
  1089. return -1;
  1090. }
  1091. static av_always_inline float flt16_round(float pf)
  1092. {
  1093. union float754 tmp;
  1094. tmp.f = pf;
  1095. tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
  1096. return tmp.f;
  1097. }
  1098. static av_always_inline float flt16_even(float pf)
  1099. {
  1100. union float754 tmp;
  1101. tmp.f = pf;
  1102. tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U >> 16)) & 0xFFFF0000U;
  1103. return tmp.f;
  1104. }
  1105. static av_always_inline float flt16_trunc(float pf)
  1106. {
  1107. union float754 pun;
  1108. pun.f = pf;
  1109. pun.i &= 0xFFFF0000U;
  1110. return pun.f;
  1111. }
  1112. static av_always_inline void predict(AACContext *ac, PredictorState *ps, float *coef,
  1113. int output_enable)
  1114. {
  1115. const float a = 0.953125; // 61.0 / 64
  1116. const float alpha = 0.90625; // 29.0 / 32
  1117. float e0, e1;
  1118. float pv;
  1119. float k1, k2;
  1120. k1 = ps->var0 > 1 ? ps->cor0 * flt16_even(a / ps->var0) : 0;
  1121. k2 = ps->var1 > 1 ? ps->cor1 * flt16_even(a / ps->var1) : 0;
  1122. pv = flt16_round(k1 * ps->r0 + k2 * ps->r1);
  1123. if (output_enable)
  1124. *coef += pv * ac->sf_scale;
  1125. e0 = *coef / ac->sf_scale;
  1126. e1 = e0 - k1 * ps->r0;
  1127. ps->cor1 = flt16_trunc(alpha * ps->cor1 + ps->r1 * e1);
  1128. ps->var1 = flt16_trunc(alpha * ps->var1 + 0.5 * (ps->r1 * ps->r1 + e1 * e1));
  1129. ps->cor0 = flt16_trunc(alpha * ps->cor0 + ps->r0 * e0);
  1130. ps->var0 = flt16_trunc(alpha * ps->var0 + 0.5 * (ps->r0 * ps->r0 + e0 * e0));
  1131. ps->r1 = flt16_trunc(a * (ps->r0 - k1 * e0));
  1132. ps->r0 = flt16_trunc(a * e0);
  1133. }
  1134. /**
  1135. * Apply AAC-Main style frequency domain prediction.
  1136. */
  1137. static void apply_prediction(AACContext *ac, SingleChannelElement *sce)
  1138. {
  1139. int sfb, k;
  1140. if (!sce->ics.predictor_initialized) {
  1141. reset_all_predictors(sce->predictor_state);
  1142. sce->ics.predictor_initialized = 1;
  1143. }
  1144. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  1145. for (sfb = 0; sfb < ff_aac_pred_sfb_max[ac->m4ac.sampling_index]; sfb++) {
  1146. for (k = sce->ics.swb_offset[sfb]; k < sce->ics.swb_offset[sfb + 1]; k++) {
  1147. predict(ac, &sce->predictor_state[k], &sce->coeffs[k],
  1148. sce->ics.predictor_present && sce->ics.prediction_used[sfb]);
  1149. }
  1150. }
  1151. if (sce->ics.predictor_reset_group)
  1152. reset_predictor_group(sce->predictor_state, sce->ics.predictor_reset_group);
  1153. } else
  1154. reset_all_predictors(sce->predictor_state);
  1155. }
  1156. /**
  1157. * Decode an individual_channel_stream payload; reference: table 4.44.
  1158. *
  1159. * @param common_window Channels have independent [0], or shared [1], Individual Channel Stream information.
  1160. * @param scale_flag scalable [1] or non-scalable [0] AAC (Unused until scalable AAC is implemented.)
  1161. *
  1162. * @return Returns error status. 0 - OK, !0 - error
  1163. */
  1164. static int decode_ics(AACContext *ac, SingleChannelElement *sce,
  1165. GetBitContext *gb, int common_window, int scale_flag)
  1166. {
  1167. Pulse pulse;
  1168. TemporalNoiseShaping *tns = &sce->tns;
  1169. IndividualChannelStream *ics = &sce->ics;
  1170. float *out = sce->coeffs;
  1171. int global_gain, pulse_present = 0;
  1172. /* This assignment is to silence a GCC warning about the variable being used
  1173. * uninitialized when in fact it always is.
  1174. */
  1175. pulse.num_pulse = 0;
  1176. global_gain = get_bits(gb, 8);
  1177. if (!common_window && !scale_flag) {
  1178. if (decode_ics_info(ac, ics, gb, 0) < 0)
  1179. return -1;
  1180. }
  1181. if (decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics) < 0)
  1182. return -1;
  1183. if (decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end) < 0)
  1184. return -1;
  1185. pulse_present = 0;
  1186. if (!scale_flag) {
  1187. if ((pulse_present = get_bits1(gb))) {
  1188. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1189. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n");
  1190. return -1;
  1191. }
  1192. if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {
  1193. av_log(ac->avccontext, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n");
  1194. return -1;
  1195. }
  1196. }
  1197. if ((tns->present = get_bits1(gb)) && decode_tns(ac, tns, gb, ics))
  1198. return -1;
  1199. if (get_bits1(gb)) {
  1200. av_log_missing_feature(ac->avccontext, "SSR", 1);
  1201. return -1;
  1202. }
  1203. }
  1204. if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, &pulse, ics, sce->band_type) < 0)
  1205. return -1;
  1206. if (ac->m4ac.object_type == AOT_AAC_MAIN && !common_window)
  1207. apply_prediction(ac, sce);
  1208. return 0;
  1209. }
  1210. /**
  1211. * Mid/Side stereo decoding; reference: 4.6.8.1.3.
  1212. */
  1213. static void apply_mid_side_stereo(AACContext *ac, ChannelElement *cpe)
  1214. {
  1215. const IndividualChannelStream *ics = &cpe->ch[0].ics;
  1216. float *ch0 = cpe->ch[0].coeffs;
  1217. float *ch1 = cpe->ch[1].coeffs;
  1218. int g, i, group, idx = 0;
  1219. const uint16_t *offsets = ics->swb_offset;
  1220. for (g = 0; g < ics->num_window_groups; g++) {
  1221. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1222. if (cpe->ms_mask[idx] &&
  1223. cpe->ch[0].band_type[idx] < NOISE_BT && cpe->ch[1].band_type[idx] < NOISE_BT) {
  1224. for (group = 0; group < ics->group_len[g]; group++) {
  1225. ac->dsp.butterflies_float(ch0 + group * 128 + offsets[i],
  1226. ch1 + group * 128 + offsets[i],
  1227. offsets[i+1] - offsets[i]);
  1228. }
  1229. }
  1230. }
  1231. ch0 += ics->group_len[g] * 128;
  1232. ch1 += ics->group_len[g] * 128;
  1233. }
  1234. }
  1235. /**
  1236. * intensity stereo decoding; reference: 4.6.8.2.3
  1237. *
  1238. * @param ms_present Indicates mid/side stereo presence. [0] mask is all 0s;
  1239. * [1] mask is decoded from bitstream; [2] mask is all 1s;
  1240. * [3] reserved for scalable AAC
  1241. */
  1242. static void apply_intensity_stereo(ChannelElement *cpe, int ms_present)
  1243. {
  1244. const IndividualChannelStream *ics = &cpe->ch[1].ics;
  1245. SingleChannelElement *sce1 = &cpe->ch[1];
  1246. float *coef0 = cpe->ch[0].coeffs, *coef1 = cpe->ch[1].coeffs;
  1247. const uint16_t *offsets = ics->swb_offset;
  1248. int g, group, i, k, idx = 0;
  1249. int c;
  1250. float scale;
  1251. for (g = 0; g < ics->num_window_groups; g++) {
  1252. for (i = 0; i < ics->max_sfb;) {
  1253. if (sce1->band_type[idx] == INTENSITY_BT || sce1->band_type[idx] == INTENSITY_BT2) {
  1254. const int bt_run_end = sce1->band_type_run_end[idx];
  1255. for (; i < bt_run_end; i++, idx++) {
  1256. c = -1 + 2 * (sce1->band_type[idx] - 14);
  1257. if (ms_present)
  1258. c *= 1 - 2 * cpe->ms_mask[idx];
  1259. scale = c * sce1->sf[idx];
  1260. for (group = 0; group < ics->group_len[g]; group++)
  1261. for (k = offsets[i]; k < offsets[i + 1]; k++)
  1262. coef1[group * 128 + k] = scale * coef0[group * 128 + k];
  1263. }
  1264. } else {
  1265. int bt_run_end = sce1->band_type_run_end[idx];
  1266. idx += bt_run_end - i;
  1267. i = bt_run_end;
  1268. }
  1269. }
  1270. coef0 += ics->group_len[g] * 128;
  1271. coef1 += ics->group_len[g] * 128;
  1272. }
  1273. }
  1274. /**
  1275. * Decode a channel_pair_element; reference: table 4.4.
  1276. *
  1277. * @param elem_id Identifies the instance of a syntax element.
  1278. *
  1279. * @return Returns error status. 0 - OK, !0 - error
  1280. */
  1281. static int decode_cpe(AACContext *ac, GetBitContext *gb, ChannelElement *cpe)
  1282. {
  1283. int i, ret, common_window, ms_present = 0;
  1284. common_window = get_bits1(gb);
  1285. if (common_window) {
  1286. if (decode_ics_info(ac, &cpe->ch[0].ics, gb, 1))
  1287. return -1;
  1288. i = cpe->ch[1].ics.use_kb_window[0];
  1289. cpe->ch[1].ics = cpe->ch[0].ics;
  1290. cpe->ch[1].ics.use_kb_window[1] = i;
  1291. ms_present = get_bits(gb, 2);
  1292. if (ms_present == 3) {
  1293. av_log(ac->avccontext, AV_LOG_ERROR, "ms_present = 3 is reserved.\n");
  1294. return -1;
  1295. } else if (ms_present)
  1296. decode_mid_side_stereo(cpe, gb, ms_present);
  1297. }
  1298. if ((ret = decode_ics(ac, &cpe->ch[0], gb, common_window, 0)))
  1299. return ret;
  1300. if ((ret = decode_ics(ac, &cpe->ch[1], gb, common_window, 0)))
  1301. return ret;
  1302. if (common_window) {
  1303. if (ms_present)
  1304. apply_mid_side_stereo(ac, cpe);
  1305. if (ac->m4ac.object_type == AOT_AAC_MAIN) {
  1306. apply_prediction(ac, &cpe->ch[0]);
  1307. apply_prediction(ac, &cpe->ch[1]);
  1308. }
  1309. }
  1310. apply_intensity_stereo(cpe, ms_present);
  1311. return 0;
  1312. }
  1313. /**
  1314. * Decode coupling_channel_element; reference: table 4.8.
  1315. *
  1316. * @param elem_id Identifies the instance of a syntax element.
  1317. *
  1318. * @return Returns error status. 0 - OK, !0 - error
  1319. */
  1320. static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che)
  1321. {
  1322. int num_gain = 0;
  1323. int c, g, sfb, ret;
  1324. int sign;
  1325. float scale;
  1326. SingleChannelElement *sce = &che->ch[0];
  1327. ChannelCoupling *coup = &che->coup;
  1328. coup->coupling_point = 2 * get_bits1(gb);
  1329. coup->num_coupled = get_bits(gb, 3);
  1330. for (c = 0; c <= coup->num_coupled; c++) {
  1331. num_gain++;
  1332. coup->type[c] = get_bits1(gb) ? TYPE_CPE : TYPE_SCE;
  1333. coup->id_select[c] = get_bits(gb, 4);
  1334. if (coup->type[c] == TYPE_CPE) {
  1335. coup->ch_select[c] = get_bits(gb, 2);
  1336. if (coup->ch_select[c] == 3)
  1337. num_gain++;
  1338. } else
  1339. coup->ch_select[c] = 2;
  1340. }
  1341. coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1);
  1342. sign = get_bits(gb, 1);
  1343. scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
  1344. if ((ret = decode_ics(ac, sce, gb, 0, 0)))
  1345. return ret;
  1346. for (c = 0; c < num_gain; c++) {
  1347. int idx = 0;
  1348. int cge = 1;
  1349. int gain = 0;
  1350. float gain_cache = 1.;
  1351. if (c) {
  1352. cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb);
  1353. gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0;
  1354. gain_cache = pow(scale, -gain);
  1355. }
  1356. if (coup->coupling_point == AFTER_IMDCT) {
  1357. coup->gain[c][0] = gain_cache;
  1358. } else {
  1359. for (g = 0; g < sce->ics.num_window_groups; g++) {
  1360. for (sfb = 0; sfb < sce->ics.max_sfb; sfb++, idx++) {
  1361. if (sce->band_type[idx] != ZERO_BT) {
  1362. if (!cge) {
  1363. int t = get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;
  1364. if (t) {
  1365. int s = 1;
  1366. t = gain += t;
  1367. if (sign) {
  1368. s -= 2 * (t & 0x1);
  1369. t >>= 1;
  1370. }
  1371. gain_cache = pow(scale, -t) * s;
  1372. }
  1373. }
  1374. coup->gain[c][idx] = gain_cache;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. return 0;
  1381. }
  1382. /**
  1383. * Decode Spectral Band Replication extension data; reference: table 4.55.
  1384. *
  1385. * @param crc flag indicating the presence of CRC checksum
  1386. * @param cnt length of TYPE_FIL syntactic element in bytes
  1387. *
  1388. * @return Returns number of bytes consumed from the TYPE_FIL element.
  1389. */
  1390. static int decode_sbr_extension(AACContext *ac, GetBitContext *gb,
  1391. int crc, int cnt)
  1392. {
  1393. // TODO : sbr_extension implementation
  1394. av_log_missing_feature(ac->avccontext, "SBR", 0);
  1395. skip_bits_long(gb, 8 * cnt - 4); // -4 due to reading extension type
  1396. return cnt;
  1397. }
  1398. /**
  1399. * Parse whether channels are to be excluded from Dynamic Range Compression; reference: table 4.53.
  1400. *
  1401. * @return Returns number of bytes consumed.
  1402. */
  1403. static int decode_drc_channel_exclusions(DynamicRangeControl *che_drc,
  1404. GetBitContext *gb)
  1405. {
  1406. int i;
  1407. int num_excl_chan = 0;
  1408. do {
  1409. for (i = 0; i < 7; i++)
  1410. che_drc->exclude_mask[num_excl_chan++] = get_bits1(gb);
  1411. } while (num_excl_chan < MAX_CHANNELS - 7 && get_bits1(gb));
  1412. return num_excl_chan / 7;
  1413. }
  1414. /**
  1415. * Decode dynamic range information; reference: table 4.52.
  1416. *
  1417. * @param cnt length of TYPE_FIL syntactic element in bytes
  1418. *
  1419. * @return Returns number of bytes consumed.
  1420. */
  1421. static int decode_dynamic_range(DynamicRangeControl *che_drc,
  1422. GetBitContext *gb, int cnt)
  1423. {
  1424. int n = 1;
  1425. int drc_num_bands = 1;
  1426. int i;
  1427. /* pce_tag_present? */
  1428. if (get_bits1(gb)) {
  1429. che_drc->pce_instance_tag = get_bits(gb, 4);
  1430. skip_bits(gb, 4); // tag_reserved_bits
  1431. n++;
  1432. }
  1433. /* excluded_chns_present? */
  1434. if (get_bits1(gb)) {
  1435. n += decode_drc_channel_exclusions(che_drc, gb);
  1436. }
  1437. /* drc_bands_present? */
  1438. if (get_bits1(gb)) {
  1439. che_drc->band_incr = get_bits(gb, 4);
  1440. che_drc->interpolation_scheme = get_bits(gb, 4);
  1441. n++;
  1442. drc_num_bands += che_drc->band_incr;
  1443. for (i = 0; i < drc_num_bands; i++) {
  1444. che_drc->band_top[i] = get_bits(gb, 8);
  1445. n++;
  1446. }
  1447. }
  1448. /* prog_ref_level_present? */
  1449. if (get_bits1(gb)) {
  1450. che_drc->prog_ref_level = get_bits(gb, 7);
  1451. skip_bits1(gb); // prog_ref_level_reserved_bits
  1452. n++;
  1453. }
  1454. for (i = 0; i < drc_num_bands; i++) {
  1455. che_drc->dyn_rng_sgn[i] = get_bits1(gb);
  1456. che_drc->dyn_rng_ctl[i] = get_bits(gb, 7);
  1457. n++;
  1458. }
  1459. return n;
  1460. }
  1461. /**
  1462. * Decode extension data (incomplete); reference: table 4.51.
  1463. *
  1464. * @param cnt length of TYPE_FIL syntactic element in bytes
  1465. *
  1466. * @return Returns number of bytes consumed
  1467. */
  1468. static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt)
  1469. {
  1470. int crc_flag = 0;
  1471. int res = cnt;
  1472. switch (get_bits(gb, 4)) { // extension type
  1473. case EXT_SBR_DATA_CRC:
  1474. crc_flag++;
  1475. case EXT_SBR_DATA:
  1476. res = decode_sbr_extension(ac, gb, crc_flag, cnt);
  1477. break;
  1478. case EXT_DYNAMIC_RANGE:
  1479. res = decode_dynamic_range(&ac->che_drc, gb, cnt);
  1480. break;
  1481. case EXT_FILL:
  1482. case EXT_FILL_DATA:
  1483. case EXT_DATA_ELEMENT:
  1484. default:
  1485. skip_bits_long(gb, 8 * cnt - 4);
  1486. break;
  1487. };
  1488. return res;
  1489. }
  1490. /**
  1491. * Decode Temporal Noise Shaping filter coefficients and apply all-pole filters; reference: 4.6.9.3.
  1492. *
  1493. * @param decode 1 if tool is used normally, 0 if tool is used in LTP.
  1494. * @param coef spectral coefficients
  1495. */
  1496. static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,
  1497. IndividualChannelStream *ics, int decode)
  1498. {
  1499. const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);
  1500. int w, filt, m, i;
  1501. int bottom, top, order, start, end, size, inc;
  1502. float lpc[TNS_MAX_ORDER];
  1503. for (w = 0; w < ics->num_windows; w++) {
  1504. bottom = ics->num_swb;
  1505. for (filt = 0; filt < tns->n_filt[w]; filt++) {
  1506. top = bottom;
  1507. bottom = FFMAX(0, top - tns->length[w][filt]);
  1508. order = tns->order[w][filt];
  1509. if (order == 0)
  1510. continue;
  1511. // tns_decode_coef
  1512. compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);
  1513. start = ics->swb_offset[FFMIN(bottom, mmm)];
  1514. end = ics->swb_offset[FFMIN( top, mmm)];
  1515. if ((size = end - start) <= 0)
  1516. continue;
  1517. if (tns->direction[w][filt]) {
  1518. inc = -1;
  1519. start = end - 1;
  1520. } else {
  1521. inc = 1;
  1522. }
  1523. start += w * 128;
  1524. // ar filter
  1525. for (m = 0; m < size; m++, start += inc)
  1526. for (i = 1; i <= FFMIN(m, order); i++)
  1527. coef[start] -= coef[start - i * inc] * lpc[i - 1];
  1528. }
  1529. }
  1530. }
  1531. /**
  1532. * Conduct IMDCT and windowing.
  1533. */
  1534. static void imdct_and_windowing(AACContext *ac, SingleChannelElement *sce)
  1535. {
  1536. IndividualChannelStream *ics = &sce->ics;
  1537. float *in = sce->coeffs;
  1538. float *out = sce->ret;
  1539. float *saved = sce->saved;
  1540. const float *swindow = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  1541. const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  1542. const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  1543. float *buf = ac->buf_mdct;
  1544. float *temp = ac->temp;
  1545. int i;
  1546. // imdct
  1547. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1548. if (ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE)
  1549. av_log(ac->avccontext, AV_LOG_WARNING,
  1550. "Transition from an ONLY_LONG or LONG_STOP to an EIGHT_SHORT sequence detected. "
  1551. "If you heard an audible artifact, please submit the sample to the FFmpeg developers.\n");
  1552. for (i = 0; i < 1024; i += 128)
  1553. ff_imdct_half(&ac->mdct_small, buf + i, in + i);
  1554. } else
  1555. ff_imdct_half(&ac->mdct, buf, in);
  1556. /* window overlapping
  1557. * NOTE: To simplify the overlapping code, all 'meaningless' short to long
  1558. * and long to short transitions are considered to be short to short
  1559. * transitions. This leaves just two cases (long to long and short to short)
  1560. * with a little special sauce for EIGHT_SHORT_SEQUENCE.
  1561. */
  1562. if ((ics->window_sequence[1] == ONLY_LONG_SEQUENCE || ics->window_sequence[1] == LONG_STOP_SEQUENCE) &&
  1563. (ics->window_sequence[0] == ONLY_LONG_SEQUENCE || ics->window_sequence[0] == LONG_START_SEQUENCE)) {
  1564. ac->dsp.vector_fmul_window( out, saved, buf, lwindow_prev, ac->add_bias, 512);
  1565. } else {
  1566. for (i = 0; i < 448; i++)
  1567. out[i] = saved[i] + ac->add_bias;
  1568. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1569. ac->dsp.vector_fmul_window(out + 448 + 0*128, saved + 448, buf + 0*128, swindow_prev, ac->add_bias, 64);
  1570. ac->dsp.vector_fmul_window(out + 448 + 1*128, buf + 0*128 + 64, buf + 1*128, swindow, ac->add_bias, 64);
  1571. ac->dsp.vector_fmul_window(out + 448 + 2*128, buf + 1*128 + 64, buf + 2*128, swindow, ac->add_bias, 64);
  1572. ac->dsp.vector_fmul_window(out + 448 + 3*128, buf + 2*128 + 64, buf + 3*128, swindow, ac->add_bias, 64);
  1573. ac->dsp.vector_fmul_window(temp, buf + 3*128 + 64, buf + 4*128, swindow, ac->add_bias, 64);
  1574. memcpy( out + 448 + 4*128, temp, 64 * sizeof(float));
  1575. } else {
  1576. ac->dsp.vector_fmul_window(out + 448, saved + 448, buf, swindow_prev, ac->add_bias, 64);
  1577. for (i = 576; i < 1024; i++)
  1578. out[i] = buf[i-512] + ac->add_bias;
  1579. }
  1580. }
  1581. // buffer update
  1582. if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {
  1583. for (i = 0; i < 64; i++)
  1584. saved[i] = temp[64 + i] - ac->add_bias;
  1585. ac->dsp.vector_fmul_window(saved + 64, buf + 4*128 + 64, buf + 5*128, swindow, 0, 64);
  1586. ac->dsp.vector_fmul_window(saved + 192, buf + 5*128 + 64, buf + 6*128, swindow, 0, 64);
  1587. ac->dsp.vector_fmul_window(saved + 320, buf + 6*128 + 64, buf + 7*128, swindow, 0, 64);
  1588. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1589. } else if (ics->window_sequence[0] == LONG_START_SEQUENCE) {
  1590. memcpy( saved, buf + 512, 448 * sizeof(float));
  1591. memcpy( saved + 448, buf + 7*128 + 64, 64 * sizeof(float));
  1592. } else { // LONG_STOP or ONLY_LONG
  1593. memcpy( saved, buf + 512, 512 * sizeof(float));
  1594. }
  1595. }
  1596. /**
  1597. * Apply dependent channel coupling (applied before IMDCT).
  1598. *
  1599. * @param index index into coupling gain array
  1600. */
  1601. static void apply_dependent_coupling(AACContext *ac,
  1602. SingleChannelElement *target,
  1603. ChannelElement *cce, int index)
  1604. {
  1605. IndividualChannelStream *ics = &cce->ch[0].ics;
  1606. const uint16_t *offsets = ics->swb_offset;
  1607. float *dest = target->coeffs;
  1608. const float *src = cce->ch[0].coeffs;
  1609. int g, i, group, k, idx = 0;
  1610. if (ac->m4ac.object_type == AOT_AAC_LTP) {
  1611. av_log(ac->avccontext, AV_LOG_ERROR,
  1612. "Dependent coupling is not supported together with LTP\n");
  1613. return;
  1614. }
  1615. for (g = 0; g < ics->num_window_groups; g++) {
  1616. for (i = 0; i < ics->max_sfb; i++, idx++) {
  1617. if (cce->ch[0].band_type[idx] != ZERO_BT) {
  1618. const float gain = cce->coup.gain[index][idx];
  1619. for (group = 0; group < ics->group_len[g]; group++) {
  1620. for (k = offsets[i]; k < offsets[i + 1]; k++) {
  1621. // XXX dsputil-ize
  1622. dest[group * 128 + k] += gain * src[group * 128 + k];
  1623. }
  1624. }
  1625. }
  1626. }
  1627. dest += ics->group_len[g] * 128;
  1628. src += ics->group_len[g] * 128;
  1629. }
  1630. }
  1631. /**
  1632. * Apply independent channel coupling (applied after IMDCT).
  1633. *
  1634. * @param index index into coupling gain array
  1635. */
  1636. static void apply_independent_coupling(AACContext *ac,
  1637. SingleChannelElement *target,
  1638. ChannelElement *cce, int index)
  1639. {
  1640. int i;
  1641. const float gain = cce->coup.gain[index][0];
  1642. const float bias = ac->add_bias;
  1643. const float *src = cce->ch[0].ret;
  1644. float *dest = target->ret;
  1645. for (i = 0; i < 1024; i++)
  1646. dest[i] += gain * (src[i] - bias);
  1647. }
  1648. /**
  1649. * channel coupling transformation interface
  1650. *
  1651. * @param index index into coupling gain array
  1652. * @param apply_coupling_method pointer to (in)dependent coupling function
  1653. */
  1654. static void apply_channel_coupling(AACContext *ac, ChannelElement *cc,
  1655. enum RawDataBlockType type, int elem_id,
  1656. enum CouplingPoint coupling_point,
  1657. void (*apply_coupling_method)(AACContext *ac, SingleChannelElement *target, ChannelElement *cce, int index))
  1658. {
  1659. int i, c;
  1660. for (i = 0; i < MAX_ELEM_ID; i++) {
  1661. ChannelElement *cce = ac->che[TYPE_CCE][i];
  1662. int index = 0;
  1663. if (cce && cce->coup.coupling_point == coupling_point) {
  1664. ChannelCoupling *coup = &cce->coup;
  1665. for (c = 0; c <= coup->num_coupled; c++) {
  1666. if (coup->type[c] == type && coup->id_select[c] == elem_id) {
  1667. if (coup->ch_select[c] != 1) {
  1668. apply_coupling_method(ac, &cc->ch[0], cce, index);
  1669. if (coup->ch_select[c] != 0)
  1670. index++;
  1671. }
  1672. if (coup->ch_select[c] != 2)
  1673. apply_coupling_method(ac, &cc->ch[1], cce, index++);
  1674. } else
  1675. index += 1 + (coup->ch_select[c] == 3);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. /**
  1681. * Convert spectral data to float samples, applying all supported tools as appropriate.
  1682. */
  1683. static void spectral_to_sample(AACContext *ac)
  1684. {
  1685. int i, type;
  1686. for (type = 3; type >= 0; type--) {
  1687. for (i = 0; i < MAX_ELEM_ID; i++) {
  1688. ChannelElement *che = ac->che[type][i];
  1689. if (che) {
  1690. if (type <= TYPE_CPE)
  1691. apply_channel_coupling(ac, che, type, i, BEFORE_TNS, apply_dependent_coupling);
  1692. if (che->ch[0].tns.present)
  1693. apply_tns(che->ch[0].coeffs, &che->ch[0].tns, &che->ch[0].ics, 1);
  1694. if (che->ch[1].tns.present)
  1695. apply_tns(che->ch[1].coeffs, &che->ch[1].tns, &che->ch[1].ics, 1);
  1696. if (type <= TYPE_CPE)
  1697. apply_channel_coupling(ac, che, type, i, BETWEEN_TNS_AND_IMDCT, apply_dependent_coupling);
  1698. if (type != TYPE_CCE || che->coup.coupling_point == AFTER_IMDCT)
  1699. imdct_and_windowing(ac, &che->ch[0]);
  1700. if (type == TYPE_CPE)
  1701. imdct_and_windowing(ac, &che->ch[1]);
  1702. if (type <= TYPE_CCE)
  1703. apply_channel_coupling(ac, che, type, i, AFTER_IMDCT, apply_independent_coupling);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. static int parse_adts_frame_header(AACContext *ac, GetBitContext *gb)
  1709. {
  1710. int size;
  1711. AACADTSHeaderInfo hdr_info;
  1712. size = ff_aac_parse_header(gb, &hdr_info);
  1713. if (size > 0) {
  1714. if (ac->output_configured != OC_LOCKED && hdr_info.chan_config) {
  1715. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1716. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1717. ac->m4ac.chan_config = hdr_info.chan_config;
  1718. if (set_default_channel_config(ac, new_che_pos, hdr_info.chan_config))
  1719. return -7;
  1720. if (output_configure(ac, ac->che_pos, new_che_pos, hdr_info.chan_config, OC_TRIAL_FRAME))
  1721. return -7;
  1722. } else if (ac->output_configured != OC_LOCKED) {
  1723. ac->output_configured = OC_NONE;
  1724. }
  1725. if (ac->output_configured != OC_LOCKED)
  1726. ac->m4ac.sbr = -1;
  1727. ac->m4ac.sample_rate = hdr_info.sample_rate;
  1728. ac->m4ac.sampling_index = hdr_info.sampling_index;
  1729. ac->m4ac.object_type = hdr_info.object_type;
  1730. if (!ac->avccontext->sample_rate)
  1731. ac->avccontext->sample_rate = hdr_info.sample_rate;
  1732. if (hdr_info.num_aac_frames == 1) {
  1733. if (!hdr_info.crc_absent)
  1734. skip_bits(gb, 16);
  1735. } else {
  1736. av_log_missing_feature(ac->avccontext, "More than one AAC RDB per ADTS frame is", 0);
  1737. return -1;
  1738. }
  1739. }
  1740. return size;
  1741. }
  1742. static int aac_decode_frame(AVCodecContext *avccontext, void *data,
  1743. int *data_size, AVPacket *avpkt)
  1744. {
  1745. const uint8_t *buf = avpkt->data;
  1746. int buf_size = avpkt->size;
  1747. AACContext *ac = avccontext->priv_data;
  1748. ChannelElement *che = NULL;
  1749. GetBitContext gb;
  1750. enum RawDataBlockType elem_type;
  1751. int err, elem_id, data_size_tmp;
  1752. int buf_consumed;
  1753. init_get_bits(&gb, buf, buf_size * 8);
  1754. if (show_bits(&gb, 12) == 0xfff) {
  1755. if (parse_adts_frame_header(ac, &gb) < 0) {
  1756. av_log(avccontext, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
  1757. return -1;
  1758. }
  1759. if (ac->m4ac.sampling_index > 12) {
  1760. av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
  1761. return -1;
  1762. }
  1763. }
  1764. // parse
  1765. while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
  1766. elem_id = get_bits(&gb, 4);
  1767. if (elem_type < TYPE_DSE && !(che=get_che(ac, elem_type, elem_id))) {
  1768. av_log(ac->avccontext, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id);
  1769. return -1;
  1770. }
  1771. switch (elem_type) {
  1772. case TYPE_SCE:
  1773. err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
  1774. break;
  1775. case TYPE_CPE:
  1776. err = decode_cpe(ac, &gb, che);
  1777. break;
  1778. case TYPE_CCE:
  1779. err = decode_cce(ac, &gb, che);
  1780. break;
  1781. case TYPE_LFE:
  1782. err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
  1783. break;
  1784. case TYPE_DSE:
  1785. err = skip_data_stream_element(ac, &gb);
  1786. break;
  1787. case TYPE_PCE: {
  1788. enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
  1789. memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
  1790. if ((err = decode_pce(ac, new_che_pos, &gb)))
  1791. break;
  1792. if (ac->output_configured > OC_TRIAL_PCE)
  1793. av_log(avccontext, AV_LOG_ERROR,
  1794. "Not evaluating a further program_config_element as this construct is dubious at best.\n");
  1795. else
  1796. err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
  1797. break;
  1798. }
  1799. case TYPE_FIL:
  1800. if (elem_id == 15)
  1801. elem_id += get_bits(&gb, 8) - 1;
  1802. if (get_bits_left(&gb) < 8 * elem_id) {
  1803. av_log(avccontext, AV_LOG_ERROR, overread_err);
  1804. return -1;
  1805. }
  1806. while (elem_id > 0)
  1807. elem_id -= decode_extension_payload(ac, &gb, elem_id);
  1808. err = 0; /* FIXME */
  1809. break;
  1810. default:
  1811. err = -1; /* should not happen, but keeps compiler happy */
  1812. break;
  1813. }
  1814. if (err)
  1815. return err;
  1816. if (get_bits_left(&gb) < 3) {
  1817. av_log(avccontext, AV_LOG_ERROR, overread_err);
  1818. return -1;
  1819. }
  1820. }
  1821. spectral_to_sample(ac);
  1822. data_size_tmp = 1024 * avccontext->channels * sizeof(int16_t);
  1823. if (*data_size < data_size_tmp) {
  1824. av_log(avccontext, AV_LOG_ERROR,
  1825. "Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
  1826. *data_size, data_size_tmp);
  1827. return -1;
  1828. }
  1829. *data_size = data_size_tmp;
  1830. ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, 1024, avccontext->channels);
  1831. if (ac->output_configured)
  1832. ac->output_configured = OC_LOCKED;
  1833. buf_consumed = (get_bits_count(&gb) + 7) >> 3;
  1834. return buf_size > buf_consumed ? buf_consumed : buf_size;
  1835. }
  1836. static av_cold int aac_decode_close(AVCodecContext *avccontext)
  1837. {
  1838. AACContext *ac = avccontext->priv_data;
  1839. int i, type;
  1840. for (i = 0; i < MAX_ELEM_ID; i++) {
  1841. for (type = 0; type < 4; type++)
  1842. av_freep(&ac->che[type][i]);
  1843. }
  1844. ff_mdct_end(&ac->mdct);
  1845. ff_mdct_end(&ac->mdct_small);
  1846. return 0;
  1847. }
  1848. AVCodec aac_decoder = {
  1849. "aac",
  1850. CODEC_TYPE_AUDIO,
  1851. CODEC_ID_AAC,
  1852. sizeof(AACContext),
  1853. aac_decode_init,
  1854. NULL,
  1855. aac_decode_close,
  1856. aac_decode_frame,
  1857. .long_name = NULL_IF_CONFIG_SMALL("Advanced Audio Coding"),
  1858. .sample_fmts = (const enum SampleFormat[]) {
  1859. SAMPLE_FMT_S16,SAMPLE_FMT_NONE
  1860. },
  1861. .channel_layouts = aac_channel_layout,
  1862. };