aacdec_template.c 125 KB

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