stb_vorbis.c 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376
  1. // Ogg Vorbis I audio decoder -- version 0.99996
  2. //
  3. // Written in April 2007 by Sean Barrett, sponsored by RAD Game Tools.
  4. //
  5. // Placed in the public domain April 2007 by the author: no copyright is
  6. // claimed, and you may use it for any purpose you like.
  7. //
  8. // No warranty for any purpose is expressed or implied by the author (nor
  9. // by RAD Game Tools). Report bugs and send enhancements to the author.
  10. //
  11. // Get the latest version and other information at:
  12. // http://nothings.org/stb_vorbis/
  13. // Todo:
  14. //
  15. // - seeking (note you can seek yourself using the pushdata API)
  16. //
  17. // Limitations:
  18. //
  19. // - floor 0 not supported (used in old ogg vorbis files)
  20. // - lossless sample-truncation at beginning ignored
  21. // - cannot concatenate multiple vorbis streams
  22. // - sample positions are 32-bit, limiting seekable 192Khz
  23. // files to around 6 hours (Ogg supports 64-bit)
  24. //
  25. // All of these limitations may be removed in future versions.
  26. //////////////////////////////////////////////////////////////////////////////
  27. //
  28. // HEADER BEGINS HERE
  29. //
  30. #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
  31. #define STB_VORBIS_INCLUDE_STB_VORBIS_H
  32. #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
  33. #define STB_VORBIS_NO_STDIO 1
  34. #endif
  35. #ifndef STB_VORBIS_NO_STDIO
  36. #include <stdio.h>
  37. #endif
  38. #ifdef __cplusplus
  39. extern "C" {
  40. #endif
  41. /////////// THREAD SAFETY
  42. // Individual stb_vorbis* handles are not thread-safe; you cannot decode from
  43. // them from multiple threads at the same time. However, you can have multiple
  44. // stb_vorbis* handles and decode from them independently in multiple thrads.
  45. /////////// MEMORY ALLOCATION
  46. // normally stb_vorbis uses malloc() to allocate memory at startup,
  47. // and alloca() to allocate temporary memory during a frame on the
  48. // stack. (Memory consumption will depend on the amount of setup
  49. // data in the file and how you set the compile flags for speed
  50. // vs. size. In my test files the maximal-size usage is ~150KB.)
  51. //
  52. // You can modify the wrapper functions in the source (setup_malloc,
  53. // setup_temp_malloc, temp_malloc) to change this behavior, or you
  54. // can use a simpler allocation model: you pass in a buffer from
  55. // which stb_vorbis will allocate _all_ its memory (including the
  56. // temp memory). "open" may fail with a VORBIS_outofmem if you
  57. // do not pass in enough data; there is no way to determine how
  58. // much you do need except to succeed (at which point you can
  59. // query get_info to find the exact amount required. yes I know
  60. // this is lame).
  61. //
  62. // If you pass in a non-NULL buffer of the type below, allocation
  63. // will occur from it as described above. Otherwise just pass NULL
  64. // to use malloc()/alloca()
  65. typedef struct
  66. {
  67. char *alloc_buffer;
  68. int alloc_buffer_length_in_bytes;
  69. } stb_vorbis_alloc;
  70. /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
  71. typedef struct stb_vorbis stb_vorbis;
  72. typedef struct
  73. {
  74. unsigned int sample_rate;
  75. int channels;
  76. unsigned int setup_memory_required;
  77. unsigned int setup_temp_memory_required;
  78. unsigned int temp_memory_required;
  79. int max_frame_size;
  80. } stb_vorbis_info;
  81. // get general information about the file
  82. extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
  83. // get the last error detected (clears it, too)
  84. extern int stb_vorbis_get_error(stb_vorbis *f);
  85. // close an ogg vorbis file and free all memory in use
  86. extern void stb_vorbis_close(stb_vorbis *f);
  87. // this function returns the offset (in samples) from the beginning of the
  88. // file that will be returned by the next decode, if it is known, or -1
  89. // otherwise. after a flush_pushdata() call, this may take a while before
  90. // it becomes valid again.
  91. // NOT WORKING YET after a seek with PULLDATA API
  92. extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
  93. // returns the current seek point within the file, or offset from the beginning
  94. // of the memory buffer. In pushdata mode it returns 0.
  95. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
  96. /////////// PUSHDATA API
  97. #ifndef STB_VORBIS_NO_PUSHDATA_API
  98. // this API allows you to get blocks of data from any source and hand
  99. // them to stb_vorbis. you have to buffer them; stb_vorbis will tell
  100. // you how much it used, and you have to give it the rest next time;
  101. // and stb_vorbis may not have enough data to work with and you will
  102. // need to give it the same data again PLUS more. Note that the Vorbis
  103. // specification does not bound the size of an individual frame.
  104. extern stb_vorbis *stb_vorbis_open_pushdata(
  105. unsigned char *datablock, int datablock_length_in_bytes,
  106. int *datablock_memory_consumed_in_bytes,
  107. int *error,
  108. stb_vorbis_alloc *alloc_buffer);
  109. // create a vorbis decoder by passing in the initial data block containing
  110. // the ogg&vorbis headers (you don't need to do parse them, just provide
  111. // the first N bytes of the file--you're told if it's not enough, see below)
  112. // on success, returns an stb_vorbis *, does not set error, returns the amount of
  113. // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
  114. // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
  115. // if returns NULL and *error is VORBIS_need_more_data, then the input block was
  116. // incomplete and you need to pass in a larger block from the start of the file
  117. extern int stb_vorbis_decode_frame_pushdata(
  118. stb_vorbis *f, unsigned char *datablock, int datablock_length_in_bytes,
  119. int *channels, // place to write number of float * buffers
  120. float ***output, // place to write float ** array of float * buffers
  121. int *samples // place to write number of output samples
  122. );
  123. // decode a frame of audio sample data if possible from the passed-in data block
  124. //
  125. // return value: number of bytes we used from datablock
  126. // possible cases:
  127. // 0 bytes used, 0 samples output (need more data)
  128. // N bytes used, 0 samples output (resynching the stream, keep going)
  129. // N bytes used, M samples output (one frame of data)
  130. // note that after opening a file, you will ALWAYS get one N-bytes,0-sample
  131. // frame, because Vorbis always "discards" the first frame.
  132. //
  133. // Note that on resynch, stb_vorbis will rarely consume all of the buffer,
  134. // instead only datablock_length_in_bytes-3 or less. This is because it wants
  135. // to avoid missing parts of a page header if they cross a datablock boundary,
  136. // without writing state-machiney code to record a partial detection.
  137. //
  138. // The number of channels returned are stored in *channels (which can be
  139. // NULL--it is always the same as the number of channels reported by
  140. // get_info). *output will contain an array of float* buffers, one per
  141. // channel. In other words, (*output)[0][0] contains the first sample from
  142. // the first channel, and (*output)[1][0] contains the first sample from
  143. // the second channel.
  144. extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
  145. // inform stb_vorbis that your next datablock will not be contiguous with
  146. // previous ones (e.g. you've seeked in the data); future attempts to decode
  147. // frames will cause stb_vorbis to resynchronize (as noted above), and
  148. // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
  149. // will begin decoding the _next_ frame.
  150. //
  151. // if you want to seek using pushdata, you need to seek in your file, then
  152. // call stb_vorbis_flush_pushdata(), then start calling decoding, then once
  153. // decoding is returning you data, call stb_vorbis_get_sample_offset, and
  154. // if you don't like the result, seek your file again and repeat.
  155. #endif
  156. ////////// PULLING INPUT API
  157. #ifndef STB_VORBIS_NO_PULLDATA_API
  158. // This API assumes stb_vorbis is allowed to pull data from a source--
  159. // either a block of memory containing the _entire_ vorbis stream, or a
  160. // FILE * that you or it create, or possibly some other reading mechanism
  161. // if you go modify the source to replace the FILE * case with some kind
  162. // of callback to your code. (But if you don't support seeking, you may
  163. // just want to go ahead and use pushdata.)
  164. #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
  165. extern int stb_vorbis_decode_filename(char *filename, int *channels, short **output);
  166. #endif
  167. extern int stb_vorbis_decode_memory(unsigned char *mem, int len, int *channels, short **output);
  168. // decode an entire file and output the data interleaved into a malloc()ed
  169. // buffer stored in *output. The return value is the number of samples
  170. // decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
  171. // When you're done with it, just free() the pointer returned in *output.
  172. extern stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len,
  173. int *error, stb_vorbis_alloc *alloc_buffer);
  174. // create an ogg vorbis decoder from an ogg vorbis stream in memory (note
  175. // this must be the entire stream!). on failure, returns NULL and sets *error
  176. #ifndef STB_VORBIS_NO_STDIO
  177. extern stb_vorbis * stb_vorbis_open_filename(char *filename,
  178. int *error, stb_vorbis_alloc *alloc_buffer);
  179. // create an ogg vorbis decoder from a filename via fopen(). on failure,
  180. // returns NULL and sets *error (possibly to VORBIS_file_open_failure).
  181. extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
  182. int *error, stb_vorbis_alloc *alloc_buffer);
  183. // create an ogg vorbis decoder from an open FILE *, looking for a stream at
  184. // the _current_ seek point (ftell). on failure, returns NULL and sets *error.
  185. // note that stb_vorbis must "own" this stream; if you seek it in between
  186. // calls to stb_vorbis, it will become confused. Morever, if you attempt to
  187. // perform stb_vorbis_seek_*() operations on this file, it will assume it
  188. // owns the _entire_ rest of the file after the start point. Use the next
  189. // function, stb_vorbis_open_file_section(), to limit it.
  190. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
  191. int *error, stb_vorbis_alloc *alloc_buffer, unsigned int len);
  192. // create an ogg vorbis decoder from an open FILE *, looking for a stream at
  193. // the _current_ seek point (ftell); the stream will be of length 'len' bytes.
  194. // on failure, returns NULL and sets *error. note that stb_vorbis must "own"
  195. // this stream; if you seek it in between calls to stb_vorbis, it will become
  196. // confused.
  197. #endif
  198. extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
  199. extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
  200. // NOT WORKING YET
  201. // these functions seek in the Vorbis file to (approximately) 'sample_number'.
  202. // after calling seek_frame(), the next call to get_frame_*() will include
  203. // the specified sample. after calling stb_vorbis_seek(), the next call to
  204. // stb_vorbis_get_samples_* will start with the specified sample. If you
  205. // do not need to seek to EXACTLY the target sample when using get_samples_*,
  206. // you can also use seek_frame().
  207. extern void stb_vorbis_seek_start(stb_vorbis *f);
  208. // this function is equivalent to stb_vorbis_seek(f,0), but it
  209. // actually works
  210. extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
  211. extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
  212. // these functions return the total length of the vorbis stream
  213. extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
  214. // decode the next frame and return the number of samples. the number of
  215. // channels returned are stored in *channels (which can be NULL--it is always
  216. // the same as the number of channels reported by get_info). *output will
  217. // contain an array of float* buffers, one per channel. These outputs will
  218. // be overwritten on the next call to stb_vorbis_get_frame_*.
  219. //
  220. // You generally should not intermix calls to stb_vorbis_get_frame_*()
  221. // and stb_vorbis_get_samples_*(), since the latter calls the former.
  222. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  223. extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
  224. extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
  225. #endif
  226. // decode the next frame and return the number of samples per channel. the
  227. // data is coerced to the number of channels you request according to the
  228. // channel coercion rules (see below). You must pass in the size of your
  229. // buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
  230. // The maximum buffer size needed can be gotten from get_info(); however,
  231. // the Vorbis I specification implies an absolute maximum of 4096 samples
  232. // per channel. Note that for interleaved data, you pass in the number of
  233. // shorts (the size of your array), but the return value is the number of
  234. // samples per channel, not the total number of samples.
  235. // Channel coercion rules:
  236. // Let M be the number of channels requested, and N the number of channels present,
  237. // and Cn be the nth channel; let stereo L be the sum of all L and center channels,
  238. // and stereo R be the sum of all R and center channels (channel assignment from the
  239. // vorbis spec).
  240. // M N output
  241. // 1 k sum(Ck) for all k
  242. // 2 * stereo L, stereo R
  243. // k l k > l, the first l channels, then 0s
  244. // k l k <= l, the first k channels
  245. // Note that this is not _good_ surround etc. mixing at all! It's just so
  246. // you get something useful.
  247. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
  248. extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
  249. // gets num_samples samples, not necessarily on a frame boundary--this requires
  250. // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
  251. // Returns the number of samples stored per channel; it may be less than requested
  252. // at the end of the file. If there are no more samples in the file, returns 0.
  253. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  254. extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
  255. extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
  256. #endif
  257. // gets num_samples samples, not necessarily on a frame boundary--this requires
  258. // buffering so you have to supply the buffers. Applies the coercion rules above
  259. // to produce 'channels' channels. Returns the number of samples stored per channel;
  260. // it may be less than requested at the end of the file. If there are no more
  261. // samples in the file, returns 0.
  262. #endif
  263. //////// ERROR CODES
  264. enum STBVorbisError
  265. {
  266. VORBIS__no_error,
  267. VORBIS_need_more_data=1, // not a real error
  268. VORBIS_invalid_api_mixing, // can't mix API modes
  269. VORBIS_outofmem, // not enough memory
  270. VORBIS_feature_not_supported, // uses floor 0
  271. VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
  272. VORBIS_file_open_failure, // fopen() failed
  273. VORBIS_seek_without_length, // can't seek in unknown-length file
  274. VORBIS_unexpected_eof=10, // file is truncated?
  275. VORBIS_seek_invalid, // seek past EOF
  276. // decoding errors (corrupt/invalid stream) -- you probably
  277. // don't care about the exact details of these
  278. // vorbis errors:
  279. VORBIS_invalid_setup=20,
  280. VORBIS_invalid_stream,
  281. // ogg errors:
  282. VORBIS_missing_capture_pattern=30,
  283. VORBIS_invalid_stream_structure_version,
  284. VORBIS_continued_packet_flag_invalid,
  285. VORBIS_incorrect_stream_serial_number,
  286. VORBIS_invalid_first_page,
  287. VORBIS_bad_packet_type,
  288. VORBIS_cant_find_last_page,
  289. VORBIS_seek_failed,
  290. };
  291. #ifdef __cplusplus
  292. }
  293. #endif
  294. #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
  295. //
  296. // HEADER ENDS HERE
  297. //
  298. //////////////////////////////////////////////////////////////////////////////
  299. #ifndef STB_VORBIS_HEADER_ONLY
  300. // global configuration settings (e.g. set these in the project/makefile),
  301. // or just set them in this file at the top (although ideally the first few
  302. // should be visible when the header file is compiled too, although it's not
  303. // crucial)
  304. // STB_VORBIS_NO_PUSHDATA_API
  305. // does not compile the code for the various stb_vorbis_*_pushdata()
  306. // functions
  307. // #define STB_VORBIS_NO_PUSHDATA_API
  308. // STB_VORBIS_NO_PULLDATA_API
  309. // does not compile the code for the non-pushdata APIs
  310. // #define STB_VORBIS_NO_PULLDATA_API
  311. // STB_VORBIS_NO_STDIO
  312. // does not compile the code for the APIs that use FILE *s internally
  313. // or externally (implied by STB_VORBIS_NO_PULLDATA_API)
  314. // #define STB_VORBIS_NO_STDIO
  315. // STB_VORBIS_NO_INTEGER_CONVERSION
  316. // does not compile the code for converting audio sample data from
  317. // float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
  318. // #define STB_VORBIS_NO_INTEGER_CONVERSION
  319. // STB_VORBIS_NO_FAST_SCALED_FLOAT
  320. // does not use a fast float-to-int trick to accelerate float-to-int on
  321. // most platforms which requires endianness be defined correctly.
  322. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT
  323. // STB_VORBIS_MAX_CHANNELS [number]
  324. // globally define this to the maximum number of channels you need.
  325. // The spec does not put a restriction on channels except that
  326. // the count is stored in a byte, so 255 is the hard limit.
  327. // Reducing this saves about 16 bytes per value, so using 16 saves
  328. // (255-16)*16 or around 4KB. Plus anything other memory usage
  329. // I forgot to account for. Can probably go as low as 8 (7.1 audio),
  330. // 6 (5.1 audio), or 2 (stereo only).
  331. #ifndef STB_VORBIS_MAX_CHANNELS
  332. #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
  333. #endif
  334. // STB_VORBIS_PUSHDATA_CRC_COUNT [number]
  335. // after a flush_pushdata(), stb_vorbis begins scanning for the
  336. // next valid page, without backtracking. when it finds something
  337. // that looks like a page, it streams through it and verifies its
  338. // CRC32. Should that validation fail, it keeps scanning. But it's
  339. // possible that _while_ streaming through to check the CRC32 of
  340. // one candidate page, it sees another candidate page. This #define
  341. // determines how many "overlapping" candidate pages it can search
  342. // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
  343. // garbage pages could be as big as 64KB, but probably average ~16KB.
  344. // So don't hose ourselves by scanning an apparent 64KB page and
  345. // missing a ton of real ones in the interim; so minimum of 2
  346. #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
  347. #define STB_VORBIS_PUSHDATA_CRC_COUNT 4
  348. #endif
  349. // STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
  350. // sets the log size of the huffman-acceleration table. Maximum
  351. // supported value is 24. with larger numbers, more decodings are O(1),
  352. // but the table size is larger so worse cache missing, so you'll have
  353. // to probe (and try multiple ogg vorbis files) to find the sweet spot.
  354. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
  355. #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
  356. #endif
  357. // STB_VORBIS_FAST_BINARY_LENGTH [number]
  358. // sets the log size of the binary-search acceleration table. this
  359. // is used in similar fashion to the fast-huffman size to set initial
  360. // parameters for the binary search
  361. // STB_VORBIS_FAST_HUFFMAN_INT
  362. // The fast huffman tables are much more efficient if they can be
  363. // stored as 16-bit results instead of 32-bit results. This restricts
  364. // the codebooks to having only 65535 possible outcomes, though.
  365. // (At least, accelerated by the huffman table.)
  366. #ifndef STB_VORBIS_FAST_HUFFMAN_INT
  367. #define STB_VORBIS_FAST_HUFFMAN_SHORT
  368. #endif
  369. // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  370. // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
  371. // back on binary searching for the correct one. This requires storing
  372. // extra tables with the huffman codes in sorted order. Defining this
  373. // symbol trades off space for speed by forcing a linear search in the
  374. // non-fast case, except for "sparse" codebooks.
  375. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  376. // STB_VORBIS_DIVIDES_IN_RESIDUE
  377. // stb_vorbis precomputes the result of the scalar residue decoding
  378. // that would otherwise require a divide per chunk. you can trade off
  379. // space for time by defining this symbol.
  380. // #define STB_VORBIS_DIVIDES_IN_RESIDUE
  381. // STB_VORBIS_DIVIDES_IN_CODEBOOK
  382. // vorbis VQ codebooks can be encoded two ways: with every case explicitly
  383. // stored, or with all elements being chosen from a small range of values,
  384. // and all values possible in all elements. By default, stb_vorbis expands
  385. // this latter kind out to look like the former kind for ease of decoding,
  386. // because otherwise an integer divide-per-vector-element is required to
  387. // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
  388. // trade off storage for speed.
  389. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK
  390. // STB_VORBIS_CODEBOOK_SHORTS
  391. // The vorbis file format encodes VQ codebook floats as ax+b where a and
  392. // b are floating point per-codebook constants, and x is a 16-bit int.
  393. // Normally, stb_vorbis decodes them to floats rather than leaving them
  394. // as 16-bit ints and computing ax+b while decoding. This is a speed/space
  395. // tradeoff; you can save space by defining this flag.
  396. #ifndef STB_VORBIS_CODEBOOK_SHORTS
  397. #define STB_VORBIS_CODEBOOK_FLOATS
  398. #endif
  399. // STB_VORBIS_DIVIDE_TABLE
  400. // this replaces small integer divides in the floor decode loop with
  401. // table lookups. made less than 1% difference, so disabled by default.
  402. // STB_VORBIS_NO_INLINE_DECODE
  403. // disables the inlining of the scalar codebook fast-huffman decode.
  404. // might save a little codespace; useful for debugging
  405. // #define STB_VORBIS_NO_INLINE_DECODE
  406. // STB_VORBIS_NO_DEFER_FLOOR
  407. // Normally we only decode the floor without synthesizing the actual
  408. // full curve. We can instead synthesize the curve immediately. This
  409. // requires more memory and is very likely slower, so I don't think
  410. // you'd ever want to do it except for debugging.
  411. // #define STB_VORBIS_NO_DEFER_FLOOR
  412. //////////////////////////////////////////////////////////////////////////////
  413. #ifdef STB_VORBIS_NO_PULLDATA_API
  414. #define STB_VORBIS_NO_INTEGER_CONVERSION
  415. #define STB_VORBIS_NO_STDIO
  416. #endif
  417. #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
  418. #define STB_VORBIS_NO_STDIO 1
  419. #endif
  420. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  421. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  422. // only need endianness for fast-float-to-int, which we don't
  423. // use for pushdata
  424. #ifndef STB_VORBIS_BIG_ENDIAN
  425. #define STB_VORBIS_ENDIAN 0
  426. #else
  427. #define STB_VORBIS_ENDIAN 1
  428. #endif
  429. #endif
  430. #endif
  431. #ifndef STB_VORBIS_NO_STDIO
  432. #include <stdio.h>
  433. #endif
  434. #ifndef STB_VORBIS_NO_CRT
  435. #include <stdlib.h>
  436. #include <string.h>
  437. #include <assert.h>
  438. #include <math.h>
  439. #if !(defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh) || defined(__SYMBIAN32__))
  440. #include <malloc.h>
  441. #endif
  442. #else
  443. #define NULL 0
  444. #endif
  445. #ifdef __SYMBIAN32__
  446. // define alloca(), missing from symbian sdk
  447. #define alloca(size) __builtin_alloca (size)
  448. #endif
  449. #ifndef _MSC_VER
  450. #if __GNUC__
  451. #define __forceinline inline
  452. #else
  453. #define __forceinline
  454. #endif
  455. #endif
  456. #if STB_VORBIS_MAX_CHANNELS > 256
  457. #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
  458. #endif
  459. #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
  460. #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
  461. #endif
  462. #define MAX_BLOCKSIZE_LOG 13 // from specification
  463. #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
  464. typedef unsigned char uint8;
  465. typedef signed char int8;
  466. typedef unsigned short uint16;
  467. typedef signed short int16;
  468. typedef unsigned int uint32;
  469. typedef signed int int32;
  470. #ifndef TRUE
  471. #define TRUE 1
  472. #define FALSE 0
  473. #endif
  474. #ifdef STB_VORBIS_CODEBOOK_FLOATS
  475. typedef float codetype;
  476. #else
  477. typedef uint16 codetype;
  478. #endif
  479. // @NOTE
  480. //
  481. // Some arrays below are tagged "//varies", which means it's actually
  482. // a variable-sized piece of data, but rather than malloc I assume it's
  483. // small enough it's better to just allocate it all together with the
  484. // main thing
  485. //
  486. // Most of the variables are specified with the smallest size I could pack
  487. // them into. It might give better performance to make them all full-sized
  488. // integers. It should be safe to freely rearrange the structures or change
  489. // the sizes larger--nothing relies on silently truncating etc., nor the
  490. // order of variables.
  491. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
  492. #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
  493. typedef struct
  494. {
  495. int dimensions, entries;
  496. uint8 *codeword_lengths;
  497. float minimum_value;
  498. float delta_value;
  499. uint8 value_bits;
  500. uint8 lookup_type;
  501. uint8 sequence_p;
  502. uint8 sparse;
  503. uint32 lookup_values;
  504. codetype *multiplicands;
  505. uint32 *codewords;
  506. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  507. int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  508. #else
  509. int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  510. #endif
  511. uint32 *sorted_codewords;
  512. int *sorted_values;
  513. int sorted_entries;
  514. } Codebook;
  515. typedef struct
  516. {
  517. uint8 order;
  518. uint16 rate;
  519. uint16 bark_map_size;
  520. uint8 amplitude_bits;
  521. uint8 amplitude_offset;
  522. uint8 number_of_books;
  523. uint8 book_list[16]; // varies
  524. } Floor0;
  525. typedef struct
  526. {
  527. uint8 partitions;
  528. uint8 partition_class_list[32]; // varies
  529. uint8 class_dimensions[16]; // varies
  530. uint8 class_subclasses[16]; // varies
  531. uint8 class_masterbooks[16]; // varies
  532. int16 subclass_books[16][8]; // varies
  533. uint16 Xlist[31*8+2]; // varies
  534. uint8 sorted_order[31*8+2];
  535. uint8 neighbors[31*8+2][2];
  536. uint8 floor1_multiplier;
  537. uint8 rangebits;
  538. int values;
  539. } Floor1;
  540. typedef union
  541. {
  542. Floor0 floor0;
  543. Floor1 floor1;
  544. } Floor;
  545. typedef struct
  546. {
  547. uint32 begin, end;
  548. uint32 part_size;
  549. uint8 classifications;
  550. uint8 classbook;
  551. uint8 **classdata;
  552. int16 (*residue_books)[8];
  553. } Residue;
  554. typedef struct
  555. {
  556. uint8 magnitude;
  557. uint8 angle;
  558. uint8 mux;
  559. } MappingChannel;
  560. typedef struct
  561. {
  562. uint16 coupling_steps;
  563. MappingChannel *chan;
  564. uint8 submaps;
  565. uint8 submap_floor[15]; // varies
  566. uint8 submap_residue[15]; // varies
  567. } Mapping;
  568. typedef struct
  569. {
  570. uint8 blockflag;
  571. uint8 mapping;
  572. uint16 windowtype;
  573. uint16 transformtype;
  574. } Mode;
  575. typedef struct
  576. {
  577. uint32 goal_crc; // expected crc if match
  578. int bytes_left; // bytes left in packet
  579. uint32 crc_so_far; // running crc
  580. int bytes_done; // bytes processed in _current_ chunk
  581. uint32 sample_loc; // granule pos encoded in page
  582. } CRCscan;
  583. typedef struct
  584. {
  585. uint32 page_start, page_end;
  586. uint32 after_previous_page_start;
  587. uint32 first_decoded_sample;
  588. uint32 last_decoded_sample;
  589. } ProbedPage;
  590. struct stb_vorbis
  591. {
  592. // user-accessible info
  593. unsigned int sample_rate;
  594. int channels;
  595. unsigned int setup_memory_required;
  596. unsigned int temp_memory_required;
  597. unsigned int setup_temp_memory_required;
  598. // input config
  599. #ifndef STB_VORBIS_NO_STDIO
  600. FILE *f;
  601. uint32 f_start;
  602. int close_on_free;
  603. #endif
  604. uint8 *stream;
  605. uint8 *stream_start;
  606. uint8 *stream_end;
  607. uint32 stream_len;
  608. uint8 push_mode;
  609. uint32 first_audio_page_offset;
  610. ProbedPage p_first, p_last;
  611. // memory management
  612. stb_vorbis_alloc alloc;
  613. int setup_offset;
  614. int temp_offset;
  615. // run-time results
  616. int eof;
  617. enum STBVorbisError error;
  618. // user-useful data
  619. // header info
  620. int blocksize[2];
  621. int blocksize_0, blocksize_1;
  622. int codebook_count;
  623. Codebook *codebooks;
  624. int floor_count;
  625. uint16 floor_types[64]; // varies
  626. Floor *floor_config;
  627. int residue_count;
  628. uint16 residue_types[64]; // varies
  629. Residue *residue_config;
  630. int mapping_count;
  631. Mapping *mapping;
  632. int mode_count;
  633. Mode mode_config[64]; // varies
  634. uint32 total_samples;
  635. // decode buffer
  636. float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
  637. float *outputs [STB_VORBIS_MAX_CHANNELS];
  638. float *previous_window[STB_VORBIS_MAX_CHANNELS];
  639. int previous_length;
  640. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  641. int16 *finalY[STB_VORBIS_MAX_CHANNELS];
  642. #else
  643. float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
  644. #endif
  645. uint32 current_loc; // sample location of next frame to decode
  646. int current_loc_valid;
  647. // per-blocksize precomputed data
  648. // twiddle factors
  649. float *A[2],*B[2],*C[2];
  650. float *window[2];
  651. uint16 *bit_reverse[2];
  652. // current page/packet/segment streaming info
  653. uint32 serial; // stream serial number for verification
  654. int last_page;
  655. int segment_count;
  656. uint8 segments[255];
  657. uint8 page_flag;
  658. uint8 bytes_in_seg;
  659. uint8 first_decode;
  660. int next_seg;
  661. int last_seg; // flag that we're on the last segment
  662. int last_seg_which; // what was the segment number of the last seg?
  663. uint32 acc;
  664. int valid_bits;
  665. int packet_bytes;
  666. int end_seg_with_known_loc;
  667. uint32 known_loc_for_packet;
  668. int discard_samples_deferred;
  669. uint32 samples_output;
  670. // push mode scanning
  671. int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
  672. #ifndef STB_VORBIS_NO_PUSHDATA_API
  673. CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
  674. #endif
  675. // sample-access
  676. int channel_buffer_start;
  677. int channel_buffer_end;
  678. };
  679. extern int my_prof(int slot);
  680. //#define stb_prof my_prof
  681. #ifndef stb_prof
  682. #define stb_prof(x) 0
  683. #endif
  684. #if defined(STB_VORBIS_NO_PUSHDATA_API)
  685. #define IS_PUSH_MODE(f) FALSE
  686. #elif defined(STB_VORBIS_NO_PULLDATA_API)
  687. #define IS_PUSH_MODE(f) TRUE
  688. #else
  689. #define IS_PUSH_MODE(f) ((f)->push_mode)
  690. #endif
  691. typedef struct stb_vorbis vorb;
  692. static int error(vorb *f, enum STBVorbisError e)
  693. {
  694. f->error = e;
  695. if (!f->eof && e != VORBIS_need_more_data) {
  696. f->error=e; // breakpoint for debugging
  697. }
  698. return 0;
  699. }
  700. // these functions are used for allocating temporary memory
  701. // while decoding. if you can afford the stack space, use
  702. // alloca(); otherwise, provide a temp buffer and it will
  703. // allocate out of those.
  704. #define array_size_required(count,size) (count*(sizeof(void *)+(size)))
  705. #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
  706. #ifdef dealloca
  707. #define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))
  708. #else
  709. #define temp_free(f,p) 0
  710. #endif
  711. #define temp_alloc_save(f) ((f)->temp_offset)
  712. #define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
  713. #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
  714. // given a sufficiently large block of memory, make an array of pointers to subblocks of it
  715. static void *make_block_array(void *mem, int count, int size)
  716. {
  717. int i;
  718. void ** p = (void **) mem;
  719. char *q = (char *) (p + count);
  720. for (i=0; i < count; ++i) {
  721. p[i] = q;
  722. q += size;
  723. }
  724. return p;
  725. }
  726. static void *setup_malloc(vorb *f, int sz)
  727. {
  728. sz = (sz+3) & ~3;
  729. f->setup_memory_required += sz;
  730. if (f->alloc.alloc_buffer) {
  731. void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
  732. if (f->setup_offset + sz > f->temp_offset) return NULL;
  733. f->setup_offset += sz;
  734. return p;
  735. }
  736. return sz ? malloc(sz) : NULL;
  737. }
  738. static void setup_free(vorb *f, void *p)
  739. {
  740. if (f->alloc.alloc_buffer) return; // do nothing; setup mem is not a stack
  741. free(p);
  742. }
  743. static void *setup_temp_malloc(vorb *f, int sz)
  744. {
  745. sz = (sz+3) & ~3;
  746. if (f->alloc.alloc_buffer) {
  747. if (f->temp_offset - sz < f->setup_offset) return NULL;
  748. f->temp_offset -= sz;
  749. return (char *) f->alloc.alloc_buffer + f->temp_offset;
  750. }
  751. return malloc(sz);
  752. }
  753. static void setup_temp_free(vorb *f, void *p, size_t sz)
  754. {
  755. if (f->alloc.alloc_buffer) {
  756. f->temp_offset += (sz+3)&~3;
  757. return;
  758. }
  759. free(p);
  760. }
  761. #define CRC32_POLY 0x04c11db7 // from spec
  762. static uint32 crc_table[256];
  763. static void crc32_init(void)
  764. {
  765. int i,j;
  766. uint32 s;
  767. for(i=0; i < 256; i++) {
  768. for (s=i<<24, j=0; j < 8; ++j)
  769. s = (s << 1) ^ (s >= (1<<31) ? CRC32_POLY : 0);
  770. crc_table[i] = s;
  771. }
  772. }
  773. static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
  774. {
  775. return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
  776. }
  777. // used in setup, and for huffman that doesn't go fast path
  778. static unsigned int bit_reverse(unsigned int n)
  779. {
  780. n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
  781. n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
  782. n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
  783. n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
  784. return (n >> 16) | (n << 16);
  785. }
  786. static float square(float x)
  787. {
  788. return x*x;
  789. }
  790. // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
  791. // as required by the specification. fast(?) implementation from stb.h
  792. // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
  793. static int ilog(int32 n)
  794. {
  795. static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
  796. // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
  797. if (n < (1U << 14))
  798. if (n < (1U << 4)) return 0 + log2_4[n ];
  799. else if (n < (1U << 9)) return 5 + log2_4[n >> 5];
  800. else return 10 + log2_4[n >> 10];
  801. else if (n < (1U << 24))
  802. if (n < (1U << 19)) return 15 + log2_4[n >> 15];
  803. else return 20 + log2_4[n >> 20];
  804. else if (n < (1U << 29)) return 25 + log2_4[n >> 25];
  805. else if (n < (1U << 31)) return 30 + log2_4[n >> 30];
  806. else return 0; // signed n returns 0
  807. }
  808. #ifndef M_PI
  809. #define M_PI 3.14159265358979323846264f // from CRC
  810. #endif
  811. // code length assigned to a value with no huffman encoding
  812. #define NO_CODE 255
  813. /////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
  814. //
  815. // these functions are only called at setup, and only a few times
  816. // per file
  817. static float float32_unpack(uint32 x)
  818. {
  819. // from the specification
  820. uint32 mantissa = x & 0x1fffff;
  821. uint32 sign = x & 0x80000000;
  822. uint32 exp = (x & 0x7fe00000) >> 21;
  823. double res = sign ? -(double)mantissa : (double)mantissa;
  824. return (float) ldexp((float)res, exp-788);
  825. }
  826. // zlib & jpeg huffman tables assume that the output symbols
  827. // can either be arbitrarily arranged, or have monotonically
  828. // increasing frequencies--they rely on the lengths being sorted;
  829. // this makes for a very simple generation algorithm.
  830. // vorbis allows a huffman table with non-sorted lengths. This
  831. // requires a more sophisticated construction, since symbols in
  832. // order do not map to huffman codes "in order".
  833. static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
  834. {
  835. if (!c->sparse) {
  836. c->codewords [symbol] = huff_code;
  837. } else {
  838. c->codewords [count] = huff_code;
  839. c->codeword_lengths[count] = len;
  840. values [count] = symbol;
  841. }
  842. }
  843. static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
  844. {
  845. int i,k,m=0;
  846. uint32 available[32];
  847. memset(available, 0, sizeof(available));
  848. // find the first entry
  849. for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
  850. if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
  851. // add to the list
  852. add_entry(c, 0, k, m++, len[k], values);
  853. // add all available leaves
  854. for (i=1; i <= len[k]; ++i)
  855. available[i] = 1 << (32-i);
  856. // note that the above code treats the first case specially,
  857. // but it's really the same as the following code, so they
  858. // could probably be combined (except the initial code is 0,
  859. // and I use 0 in available[] to mean 'empty')
  860. for (i=k+1; i < n; ++i) {
  861. uint32 res;
  862. int z = len[i], y;
  863. if (z == NO_CODE) continue;
  864. // find lowest available leaf (should always be earliest,
  865. // which is what the specification calls for)
  866. // note that this property, and the fact we can never have
  867. // more than one free leaf at a given level, isn't totally
  868. // trivial to prove, but it seems true and the assert never
  869. // fires, so!
  870. while (z > 0 && !available[z]) --z;
  871. if (z == 0) { assert(0); return FALSE; }
  872. res = available[z];
  873. available[z] = 0;
  874. add_entry(c, bit_reverse(res), i, m++, len[i], values);
  875. // propogate availability up the tree
  876. if (z != len[i]) {
  877. for (y=len[i]; y > z; --y) {
  878. assert(available[y] == 0);
  879. available[y] = res + (1 << (32-y));
  880. }
  881. }
  882. }
  883. return TRUE;
  884. }
  885. // accelerated huffman table allows fast O(1) match of all symbols
  886. // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
  887. static void compute_accelerated_huffman(Codebook *c)
  888. {
  889. int i, len;
  890. for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
  891. c->fast_huffman[i] = -1;
  892. len = c->sparse ? c->sorted_entries : c->entries;
  893. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  894. if (len > 32767) len = 32767; // largest possible value we can encode!
  895. #endif
  896. for (i=0; i < len; ++i) {
  897. if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
  898. uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
  899. // set table entries for all bit combinations in the higher bits
  900. while (z < FAST_HUFFMAN_TABLE_SIZE) {
  901. c->fast_huffman[z] = i;
  902. z += 1 << c->codeword_lengths[i];
  903. }
  904. }
  905. }
  906. }
  907. static int uint32_compare(const void *p, const void *q)
  908. {
  909. uint32 x = * (uint32 *) p;
  910. uint32 y = * (uint32 *) q;
  911. return x < y ? -1 : x > y;
  912. }
  913. static int include_in_sort(Codebook *c, uint8 len)
  914. {
  915. if (c->sparse) { assert(len != NO_CODE); return TRUE; }
  916. if (len == NO_CODE) return FALSE;
  917. if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
  918. return FALSE;
  919. }
  920. // if the fast table above doesn't work, we want to binary
  921. // search them... need to reverse the bits
  922. static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
  923. {
  924. int i, len;
  925. // build a list of all the entries
  926. // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
  927. // this is kind of a frivolous optimization--I don't see any performance improvement,
  928. // but it's like 4 extra lines of code, so.
  929. if (!c->sparse) {
  930. int k = 0;
  931. for (i=0; i < c->entries; ++i)
  932. if (include_in_sort(c, lengths[i]))
  933. c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
  934. assert(k == c->sorted_entries);
  935. } else {
  936. for (i=0; i < c->sorted_entries; ++i)
  937. c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
  938. }
  939. qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
  940. c->sorted_codewords[c->sorted_entries] = 0xffffffff;
  941. len = c->sparse ? c->sorted_entries : c->entries;
  942. // now we need to indicate how they correspond; we could either
  943. // #1: sort a different data structure that says who they correspond to
  944. // #2: for each sorted entry, search the original list to find who corresponds
  945. // #3: for each original entry, find the sorted entry
  946. // #1 requires extra storage, #2 is slow, #3 can use binary search!
  947. for (i=0; i < len; ++i) {
  948. int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
  949. if (include_in_sort(c,huff_len)) {
  950. uint32 code = bit_reverse(c->codewords[i]);
  951. int x=0, n=c->sorted_entries;
  952. while (n > 1) {
  953. // invariant: sc[x] <= code < sc[x+n]
  954. int m = x + (n >> 1);
  955. if (c->sorted_codewords[m] <= code) {
  956. x = m;
  957. n -= (n>>1);
  958. } else {
  959. n >>= 1;
  960. }
  961. }
  962. assert(c->sorted_codewords[x] == code);
  963. if (c->sparse) {
  964. c->sorted_values[x] = values[i];
  965. c->codeword_lengths[x] = huff_len;
  966. } else {
  967. c->sorted_values[x] = i;
  968. }
  969. }
  970. }
  971. }
  972. // only run while parsing the header (3 times)
  973. static int vorbis_validate(uint8 *data)
  974. {
  975. static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
  976. return memcmp(data, vorbis, 6) == 0;
  977. }
  978. // called from setup only, once per code book
  979. // (formula implied by specification)
  980. static int lookup1_values(int entries, int dim)
  981. {
  982. int r = (int) floor(exp((float) log((float) entries) / dim));
  983. if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
  984. ++r; // floor() to avoid _ftol() when non-CRT
  985. assert(pow((float) r+1, dim) > entries);
  986. assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
  987. return r;
  988. }
  989. // called twice per file
  990. static void compute_twiddle_factors(int n, float *A, float *B, float *C)
  991. {
  992. int n4 = n >> 2, n8 = n >> 3;
  993. int k,k2;
  994. for (k=k2=0; k < n4; ++k,k2+=2) {
  995. A[k2 ] = (float) cos(4*k*M_PI/n);
  996. A[k2+1] = (float) -sin(4*k*M_PI/n);
  997. B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
  998. B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
  999. }
  1000. for (k=k2=0; k < n8; ++k,k2+=2) {
  1001. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  1002. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  1003. }
  1004. }
  1005. static void compute_window(int n, float *window)
  1006. {
  1007. int n2 = n >> 1, i;
  1008. for (i=0; i < n2; ++i)
  1009. window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
  1010. }
  1011. static void compute_bitreverse(int n, uint16 *rev)
  1012. {
  1013. int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  1014. int i, n8 = n >> 3;
  1015. for (i=0; i < n8; ++i)
  1016. rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
  1017. }
  1018. static int init_blocksize(vorb *f, int b, int n)
  1019. {
  1020. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
  1021. f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  1022. f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  1023. f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
  1024. if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
  1025. compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
  1026. f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  1027. if (!f->window[b]) return error(f, VORBIS_outofmem);
  1028. compute_window(n, f->window[b]);
  1029. f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
  1030. if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
  1031. compute_bitreverse(n, f->bit_reverse[b]);
  1032. return TRUE;
  1033. }
  1034. static void neighbors(uint16 *x, int n, int *plow, int *phigh)
  1035. {
  1036. int low = -1;
  1037. int high = 65536;
  1038. int i;
  1039. for (i=0; i < n; ++i) {
  1040. if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
  1041. if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
  1042. }
  1043. }
  1044. // this has been repurposed so y is now the original index instead of y
  1045. typedef struct
  1046. {
  1047. uint16 x,y;
  1048. } Point;
  1049. int point_compare(const void *p, const void *q)
  1050. {
  1051. Point *a = (Point *) p;
  1052. Point *b = (Point *) q;
  1053. return a->x < b->x ? -1 : a->x > b->x;
  1054. }
  1055. //
  1056. /////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
  1057. #if defined(STB_VORBIS_NO_STDIO)
  1058. #define USE_MEMORY(z) TRUE
  1059. #else
  1060. #define USE_MEMORY(z) ((z)->stream)
  1061. #endif
  1062. static uint8 get8(vorb *z)
  1063. {
  1064. if (USE_MEMORY(z)) {
  1065. if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
  1066. return *z->stream++;
  1067. }
  1068. #ifndef STB_VORBIS_NO_STDIO
  1069. {
  1070. int c = fgetc(z->f);
  1071. if (c == EOF) { z->eof = TRUE; return 0; }
  1072. return c;
  1073. }
  1074. #endif
  1075. }
  1076. static uint32 get32(vorb *f)
  1077. {
  1078. uint32 x;
  1079. x = get8(f);
  1080. x += get8(f) << 8;
  1081. x += get8(f) << 16;
  1082. x += get8(f) << 24;
  1083. return x;
  1084. }
  1085. static int getn(vorb *z, uint8 *data, int n)
  1086. {
  1087. if (USE_MEMORY(z)) {
  1088. if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
  1089. memcpy(data, z->stream, n);
  1090. z->stream += n;
  1091. return 1;
  1092. }
  1093. #ifndef STB_VORBIS_NO_STDIO
  1094. if (fread(data, n, 1, z->f) == 1)
  1095. return 1;
  1096. else {
  1097. z->eof = 1;
  1098. return 0;
  1099. }
  1100. #endif
  1101. }
  1102. static void skip(vorb *z, int n)
  1103. {
  1104. if (USE_MEMORY(z)) {
  1105. z->stream += n;
  1106. if (z->stream >= z->stream_end) z->eof = 1;
  1107. return;
  1108. }
  1109. #ifndef STB_VORBIS_NO_STDIO
  1110. {
  1111. long x = ftell(z->f);
  1112. fseek(z->f, x+n, SEEK_SET);
  1113. }
  1114. #endif
  1115. }
  1116. static int set_file_offset(stb_vorbis *f, unsigned int loc)
  1117. {
  1118. #ifndef STB_VORBIS_NO_PUSHDATA_API
  1119. if (f->push_mode) return 0;
  1120. #endif
  1121. f->eof = 0;
  1122. if (USE_MEMORY(f)) {
  1123. if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
  1124. f->stream = f->stream_end;
  1125. f->eof = 1;
  1126. return 0;
  1127. } else {
  1128. f->stream = f->stream_start + loc;
  1129. return 1;
  1130. }
  1131. }
  1132. #ifndef STB_VORBIS_NO_STDIO
  1133. if (loc + f->f_start < loc || loc >= 0x80000000) {
  1134. loc = 0x7fffffff;
  1135. f->eof = 1;
  1136. } else {
  1137. loc += f->f_start;
  1138. }
  1139. if (!fseek(f->f, loc, SEEK_SET))
  1140. return 1;
  1141. f->eof = 1;
  1142. fseek(f->f, f->f_start, SEEK_END);
  1143. return 0;
  1144. #endif
  1145. }
  1146. static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
  1147. static int capture_pattern(vorb *f)
  1148. {
  1149. if (0x4f != get8(f)) return FALSE;
  1150. if (0x67 != get8(f)) return FALSE;
  1151. if (0x67 != get8(f)) return FALSE;
  1152. if (0x53 != get8(f)) return FALSE;
  1153. return TRUE;
  1154. }
  1155. #define PAGEFLAG_continued_packet 1
  1156. #define PAGEFLAG_first_page 2
  1157. #define PAGEFLAG_last_page 4
  1158. static int start_page_no_capturepattern(vorb *f)
  1159. {
  1160. uint32 loc0,loc1,n,i;
  1161. // stream structure version
  1162. if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
  1163. // header flag
  1164. f->page_flag = get8(f);
  1165. // absolute granule position
  1166. loc0 = get32(f);
  1167. loc1 = get32(f);
  1168. // @TODO: validate loc0,loc1 as valid positions?
  1169. // stream serial number -- vorbis doesn't interleave, so discard
  1170. get32(f);
  1171. //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
  1172. // page sequence number
  1173. n = get32(f);
  1174. f->last_page = n;
  1175. // CRC32
  1176. get32(f);
  1177. // page_segments
  1178. f->segment_count = get8(f);
  1179. if (!getn(f, f->segments, f->segment_count))
  1180. return error(f, VORBIS_unexpected_eof);
  1181. // assume we _don't_ know any the sample position of any segments
  1182. f->end_seg_with_known_loc = -2;
  1183. if (loc0 != ~0 || loc1 != ~0) {
  1184. // determine which packet is the last one that will complete
  1185. for (i=f->segment_count-1; i >= 0; --i)
  1186. if (f->segments[i] < 255)
  1187. break;
  1188. // 'i' is now the index of the _last_ segment of a packet that ends
  1189. if (i >= 0) {
  1190. f->end_seg_with_known_loc = i;
  1191. f->known_loc_for_packet = loc0;
  1192. }
  1193. }
  1194. if (f->first_decode) {
  1195. int i,len;
  1196. ProbedPage p;
  1197. len = 0;
  1198. for (i=0; i < f->segment_count; ++i)
  1199. len += f->segments[i];
  1200. len += 27 + f->segment_count;
  1201. p.page_start = f->first_audio_page_offset;
  1202. p.page_end = p.page_start + len;
  1203. p.after_previous_page_start = p.page_start;
  1204. p.first_decoded_sample = 0;
  1205. p.last_decoded_sample = loc0;
  1206. f->p_first = p;
  1207. }
  1208. f->next_seg = 0;
  1209. return TRUE;
  1210. }
  1211. static int start_page(vorb *f)
  1212. {
  1213. if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
  1214. return start_page_no_capturepattern(f);
  1215. }
  1216. static int start_packet(vorb *f)
  1217. {
  1218. while (f->next_seg == -1) {
  1219. if (!start_page(f)) return FALSE;
  1220. if (f->page_flag & PAGEFLAG_continued_packet)
  1221. return error(f, VORBIS_continued_packet_flag_invalid);
  1222. }
  1223. f->last_seg = FALSE;
  1224. f->valid_bits = 0;
  1225. f->packet_bytes = 0;
  1226. f->bytes_in_seg = 0;
  1227. // f->next_seg is now valid
  1228. return TRUE;
  1229. }
  1230. static int maybe_start_packet(vorb *f)
  1231. {
  1232. if (f->next_seg == -1) {
  1233. int x = get8(f);
  1234. if (f->eof) return FALSE; // EOF at page boundary is not an error!
  1235. if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
  1236. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1237. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1238. if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1239. if (!start_page_no_capturepattern(f)) return FALSE;
  1240. if (f->page_flag & PAGEFLAG_continued_packet) {
  1241. // set up enough state that we can read this packet if we want,
  1242. // e.g. during recovery
  1243. f->last_seg = FALSE;
  1244. f->bytes_in_seg = 0;
  1245. return error(f, VORBIS_continued_packet_flag_invalid);
  1246. }
  1247. }
  1248. return start_packet(f);
  1249. }
  1250. static int next_segment(vorb *f)
  1251. {
  1252. int len;
  1253. if (f->last_seg) return 0;
  1254. if (f->next_seg == -1) {
  1255. f->last_seg_which = f->segment_count-1; // in case start_page fails
  1256. if (!start_page(f)) { f->last_seg = 1; return 0; }
  1257. if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
  1258. }
  1259. len = f->segments[f->next_seg++];
  1260. if (len < 255) {
  1261. f->last_seg = TRUE;
  1262. f->last_seg_which = f->next_seg-1;
  1263. }
  1264. if (f->next_seg >= f->segment_count)
  1265. f->next_seg = -1;
  1266. assert(f->bytes_in_seg == 0);
  1267. f->bytes_in_seg = len;
  1268. return len;
  1269. }
  1270. #define EOP (-1)
  1271. #define INVALID_BITS (-1)
  1272. static int get8_packet_raw(vorb *f)
  1273. {
  1274. if (!f->bytes_in_seg)
  1275. if (f->last_seg) return EOP;
  1276. else if (!next_segment(f)) return EOP;
  1277. assert(f->bytes_in_seg > 0);
  1278. --f->bytes_in_seg;
  1279. ++f->packet_bytes;
  1280. return get8(f);
  1281. }
  1282. static int get8_packet(vorb *f)
  1283. {
  1284. int x = get8_packet_raw(f);
  1285. f->valid_bits = 0;
  1286. return x;
  1287. }
  1288. static void flush_packet(vorb *f)
  1289. {
  1290. while (get8_packet_raw(f) != EOP);
  1291. }
  1292. // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
  1293. // as the huffman decoder?
  1294. static uint32 get_bits(vorb *f, int n)
  1295. {
  1296. uint32 z;
  1297. if (f->valid_bits < 0) return 0;
  1298. if (f->valid_bits < n) {
  1299. if (n > 24) {
  1300. // the accumulator technique below would not work correctly in this case
  1301. z = get_bits(f, 24);
  1302. z += get_bits(f, n-24) << 24;
  1303. return z;
  1304. }
  1305. if (f->valid_bits == 0) f->acc = 0;
  1306. while (f->valid_bits < n) {
  1307. int z = get8_packet_raw(f);
  1308. if (z == EOP) {
  1309. f->valid_bits = INVALID_BITS;
  1310. return 0;
  1311. }
  1312. f->acc += z << f->valid_bits;
  1313. f->valid_bits += 8;
  1314. }
  1315. }
  1316. if (f->valid_bits < 0) return 0;
  1317. z = f->acc & ((1 << n)-1);
  1318. f->acc >>= n;
  1319. f->valid_bits -= n;
  1320. return z;
  1321. }
  1322. static int32 get_bits_signed(vorb *f, int n)
  1323. {
  1324. uint32 z = get_bits(f, n);
  1325. if (z & (1 << (n-1)))
  1326. z += ~((1 << n) - 1);
  1327. return (int32) z;
  1328. }
  1329. // @OPTIMIZE: primary accumulator for huffman
  1330. // expand the buffer to as many bits as possible without reading off end of packet
  1331. // it might be nice to allow f->valid_bits and f->acc to be stored in registers,
  1332. // e.g. cache them locally and decode locally
  1333. static __forceinline void prep_huffman(vorb *f)
  1334. {
  1335. if (f->valid_bits <= 24) {
  1336. if (f->valid_bits == 0) f->acc = 0;
  1337. do {
  1338. int z;
  1339. if (f->last_seg && !f->bytes_in_seg) return;
  1340. z = get8_packet_raw(f);
  1341. if (z == EOP) return;
  1342. f->acc += z << f->valid_bits;
  1343. f->valid_bits += 8;
  1344. } while (f->valid_bits <= 24);
  1345. }
  1346. }
  1347. enum
  1348. {
  1349. VORBIS_packet_id = 1,
  1350. VORBIS_packet_comment = 3,
  1351. VORBIS_packet_setup = 5,
  1352. };
  1353. static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
  1354. {
  1355. int i;
  1356. prep_huffman(f);
  1357. assert(c->sorted_codewords || c->codewords);
  1358. // cases to use binary search: sorted_codewords && !c->codewords
  1359. // sorted_codewords && c->entries > 8
  1360. if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
  1361. // binary search
  1362. uint32 code = bit_reverse(f->acc);
  1363. int x=0, n=c->sorted_entries, len;
  1364. while (n > 1) {
  1365. // invariant: sc[x] <= code < sc[x+n]
  1366. int m = x + (n >> 1);
  1367. if (c->sorted_codewords[m] <= code) {
  1368. x = m;
  1369. n -= (n>>1);
  1370. } else {
  1371. n >>= 1;
  1372. }
  1373. }
  1374. // x is now the sorted index
  1375. if (!c->sparse) x = c->sorted_values[x];
  1376. // x is now sorted index if sparse, or symbol otherwise
  1377. len = c->codeword_lengths[x];
  1378. if (f->valid_bits >= len) {
  1379. f->acc >>= len;
  1380. f->valid_bits -= len;
  1381. return x;
  1382. }
  1383. f->valid_bits = 0;
  1384. return -1;
  1385. }
  1386. // if small, linear search
  1387. assert(!c->sparse);
  1388. for (i=0; i < c->entries; ++i) {
  1389. if (c->codeword_lengths[i] == NO_CODE) continue;
  1390. if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
  1391. if (f->valid_bits >= c->codeword_lengths[i]) {
  1392. f->acc >>= c->codeword_lengths[i];
  1393. f->valid_bits -= c->codeword_lengths[i];
  1394. return i;
  1395. }
  1396. f->valid_bits = 0;
  1397. return -1;
  1398. }
  1399. }
  1400. error(f, VORBIS_invalid_stream);
  1401. f->valid_bits = 0;
  1402. return -1;
  1403. }
  1404. static int codebook_decode_scalar(vorb *f, Codebook *c)
  1405. {
  1406. int i;
  1407. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
  1408. prep_huffman(f);
  1409. // fast huffman table lookup
  1410. i = f->acc & FAST_HUFFMAN_TABLE_MASK;
  1411. i = c->fast_huffman[i];
  1412. if (i >= 0) {
  1413. f->acc >>= c->codeword_lengths[i];
  1414. f->valid_bits -= c->codeword_lengths[i];
  1415. if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
  1416. return i;
  1417. }
  1418. return codebook_decode_scalar_raw(f,c);
  1419. }
  1420. #ifndef STB_VORBIS_NO_INLINE_DECODE
  1421. #define DECODE_RAW(var, f,c) \
  1422. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
  1423. prep_huffman(f); \
  1424. var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
  1425. var = c->fast_huffman[var]; \
  1426. if (var >= 0) { \
  1427. int n = c->codeword_lengths[var]; \
  1428. f->acc >>= n; \
  1429. f->valid_bits -= n; \
  1430. if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
  1431. } else { \
  1432. var = codebook_decode_scalar_raw(f,c); \
  1433. }
  1434. #else
  1435. #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
  1436. #endif
  1437. #define DECODE(var,f,c) \
  1438. DECODE_RAW(var,f,c) \
  1439. if (c->sparse) var = c->sorted_values[var];
  1440. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1441. #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
  1442. #else
  1443. #define DECODE_VQ(var,f,c) DECODE(var,f,c)
  1444. #endif
  1445. // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
  1446. // where we avoid one addition
  1447. #ifndef STB_VORBIS_CODEBOOK_FLOATS
  1448. #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off] * c->delta_value + c->minimum_value)
  1449. #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off] * c->delta_value)
  1450. #define CODEBOOK_ELEMENT_BASE(c) (c->minimum_value)
  1451. #else
  1452. #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
  1453. #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
  1454. #define CODEBOOK_ELEMENT_BASE(c) (0)
  1455. #endif
  1456. static int codebook_decode_start(vorb *f, Codebook *c, int len)
  1457. {
  1458. int z = -1;
  1459. // type 0 is only legal in a scalar context
  1460. if (c->lookup_type == 0)
  1461. error(f, VORBIS_invalid_stream);
  1462. else {
  1463. DECODE_VQ(z,f,c);
  1464. if (c->sparse) assert(z < c->sorted_entries);
  1465. if (z < 0) { // check for EOP
  1466. if (!f->bytes_in_seg)
  1467. if (f->last_seg)
  1468. return z;
  1469. error(f, VORBIS_invalid_stream);
  1470. }
  1471. }
  1472. return z;
  1473. }
  1474. static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
  1475. {
  1476. int i,z = codebook_decode_start(f,c,len);
  1477. if (z < 0) return FALSE;
  1478. if (len > c->dimensions) len = c->dimensions;
  1479. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1480. if (c->lookup_type == 1) {
  1481. float last = CODEBOOK_ELEMENT_BASE(c);
  1482. int div = 1;
  1483. for (i=0; i < len; ++i) {
  1484. int off = (z / div) % c->lookup_values;
  1485. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1486. output[i] += val;
  1487. if (c->sequence_p) last = val + c->minimum_value;
  1488. div *= c->lookup_values;
  1489. }
  1490. return TRUE;
  1491. }
  1492. #endif
  1493. z *= c->dimensions;
  1494. if (c->sequence_p) {
  1495. float last = CODEBOOK_ELEMENT_BASE(c);
  1496. for (i=0; i < len; ++i) {
  1497. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1498. output[i] += val;
  1499. last = val + c->minimum_value;
  1500. }
  1501. } else {
  1502. float last = CODEBOOK_ELEMENT_BASE(c);
  1503. for (i=0; i < len; ++i) {
  1504. output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1505. }
  1506. }
  1507. return TRUE;
  1508. }
  1509. static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
  1510. {
  1511. int i,z = codebook_decode_start(f,c,len);
  1512. float last = CODEBOOK_ELEMENT_BASE(c);
  1513. if (z < 0) return FALSE;
  1514. if (len > c->dimensions) len = c->dimensions;
  1515. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1516. if (c->lookup_type == 1) {
  1517. int div = 1;
  1518. for (i=0; i < len; ++i) {
  1519. int off = (z / div) % c->lookup_values;
  1520. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1521. output[i*step] += val;
  1522. if (c->sequence_p) last = val;
  1523. div *= c->lookup_values;
  1524. }
  1525. return TRUE;
  1526. }
  1527. #endif
  1528. z *= c->dimensions;
  1529. for (i=0; i < len; ++i) {
  1530. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1531. output[i*step] += val;
  1532. if (c->sequence_p) last = val;
  1533. }
  1534. return TRUE;
  1535. }
  1536. static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
  1537. {
  1538. int c_inter = *c_inter_p;
  1539. int p_inter = *p_inter_p;
  1540. int i,z, effective = c->dimensions;
  1541. // type 0 is only legal in a scalar context
  1542. if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
  1543. while (total_decode > 0) {
  1544. float last = CODEBOOK_ELEMENT_BASE(c);
  1545. DECODE_VQ(z,f,c);
  1546. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1547. assert(!c->sparse || z < c->sorted_entries);
  1548. #endif
  1549. if (z < 0) {
  1550. if (!f->bytes_in_seg)
  1551. if (f->last_seg) return FALSE;
  1552. return error(f, VORBIS_invalid_stream);
  1553. }
  1554. // if this will take us off the end of the buffers, stop short!
  1555. // we check by computing the length of the virtual interleaved
  1556. // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
  1557. // and the length we'll be using (effective)
  1558. if (c_inter + p_inter*ch + effective > len * ch) {
  1559. effective = len*ch - (p_inter*ch - c_inter);
  1560. }
  1561. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1562. if (c->lookup_type == 1) {
  1563. int div = 1;
  1564. for (i=0; i < effective; ++i) {
  1565. int off = (z / div) % c->lookup_values;
  1566. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1567. outputs[c_inter][p_inter] += val;
  1568. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1569. if (c->sequence_p) last = val;
  1570. div *= c->lookup_values;
  1571. }
  1572. } else
  1573. #endif
  1574. {
  1575. z *= c->dimensions;
  1576. if (c->sequence_p) {
  1577. for (i=0; i < effective; ++i) {
  1578. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1579. outputs[c_inter][p_inter] += val;
  1580. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1581. last = val;
  1582. }
  1583. } else {
  1584. for (i=0; i < effective; ++i) {
  1585. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1586. outputs[c_inter][p_inter] += val;
  1587. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1588. }
  1589. }
  1590. }
  1591. total_decode -= effective;
  1592. }
  1593. *c_inter_p = c_inter;
  1594. *p_inter_p = p_inter;
  1595. return TRUE;
  1596. }
  1597. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1598. static int codebook_decode_deinterleave_repeat_2(vorb *f, Codebook *c, float **outputs, int *c_inter_p, int *p_inter_p, int len, int total_decode)
  1599. {
  1600. int c_inter = *c_inter_p;
  1601. int p_inter = *p_inter_p;
  1602. int i,z, effective = c->dimensions;
  1603. // type 0 is only legal in a scalar context
  1604. if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
  1605. while (total_decode > 0) {
  1606. float last = CODEBOOK_ELEMENT_BASE(c);
  1607. DECODE_VQ(z,f,c);
  1608. if (z < 0) {
  1609. if (!f->bytes_in_seg)
  1610. if (f->last_seg) return FALSE;
  1611. return error(f, VORBIS_invalid_stream);
  1612. }
  1613. // if this will take us off the end of the buffers, stop short!
  1614. // we check by computing the length of the virtual interleaved
  1615. // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
  1616. // and the length we'll be using (effective)
  1617. if (c_inter + p_inter*2 + effective > len * 2) {
  1618. effective = len*2 - (p_inter*2 - c_inter);
  1619. }
  1620. {
  1621. z *= c->dimensions;
  1622. stb_prof(11);
  1623. if (c->sequence_p) {
  1624. // haven't optimized this case because I don't have any examples
  1625. for (i=0; i < effective; ++i) {
  1626. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1627. outputs[c_inter][p_inter] += val;
  1628. if (++c_inter == 2) { c_inter = 0; ++p_inter; }
  1629. last = val;
  1630. }
  1631. } else {
  1632. i=0;
  1633. if (c_inter == 1) {
  1634. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1635. outputs[c_inter][p_inter] += val;
  1636. c_inter = 0; ++p_inter;
  1637. ++i;
  1638. }
  1639. {
  1640. float *z0 = outputs[0];
  1641. float *z1 = outputs[1];
  1642. for (; i+1 < effective;) {
  1643. z0[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1644. z1[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i+1) + last;
  1645. ++p_inter;
  1646. i += 2;
  1647. }
  1648. }
  1649. if (i < effective) {
  1650. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1651. outputs[c_inter][p_inter] += val;
  1652. if (++c_inter == 2) { c_inter = 0; ++p_inter; }
  1653. }
  1654. }
  1655. }
  1656. total_decode -= effective;
  1657. }
  1658. *c_inter_p = c_inter;
  1659. *p_inter_p = p_inter;
  1660. return TRUE;
  1661. }
  1662. #endif
  1663. static int predict_point(int x, int x0, int x1, int y0, int y1)
  1664. {
  1665. int dy = y1 - y0;
  1666. int adx = x1 - x0;
  1667. // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
  1668. int err = abs(dy) * (x - x0);
  1669. int off = err / adx;
  1670. return dy < 0 ? y0 - off : y0 + off;
  1671. }
  1672. // the following table is block-copied from the specification
  1673. static float inverse_db_table[256] =
  1674. {
  1675. 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
  1676. 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
  1677. 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
  1678. 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
  1679. 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
  1680. 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
  1681. 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
  1682. 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
  1683. 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
  1684. 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
  1685. 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
  1686. 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
  1687. 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
  1688. 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
  1689. 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
  1690. 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
  1691. 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
  1692. 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
  1693. 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
  1694. 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
  1695. 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
  1696. 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
  1697. 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
  1698. 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
  1699. 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
  1700. 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
  1701. 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
  1702. 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
  1703. 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
  1704. 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
  1705. 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
  1706. 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
  1707. 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
  1708. 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
  1709. 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
  1710. 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
  1711. 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
  1712. 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
  1713. 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
  1714. 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
  1715. 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
  1716. 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
  1717. 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
  1718. 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
  1719. 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
  1720. 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
  1721. 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
  1722. 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
  1723. 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
  1724. 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
  1725. 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
  1726. 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
  1727. 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
  1728. 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
  1729. 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
  1730. 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
  1731. 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
  1732. 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
  1733. 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
  1734. 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
  1735. 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
  1736. 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
  1737. 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
  1738. 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
  1739. };
  1740. // @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
  1741. // note that you must produce bit-identical output to decode correctly;
  1742. // this specific sequence of operations is specified in the spec (it's
  1743. // drawing integer-quantized frequency-space lines that the encoder
  1744. // expects to be exactly the same)
  1745. // ... also, isn't the whole point of Bresenham's algorithm to NOT
  1746. // have to divide in the setup? sigh.
  1747. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  1748. #define LINE_OP(a,b) a *= b
  1749. #else
  1750. #define LINE_OP(a,b) a = b
  1751. #endif
  1752. #ifdef STB_VORBIS_DIVIDE_TABLE
  1753. #define DIVTAB_NUMER 32
  1754. #define DIVTAB_DENOM 64
  1755. int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
  1756. #endif
  1757. static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
  1758. {
  1759. int dy = y1 - y0;
  1760. int adx = x1 - x0;
  1761. int ady = abs(dy);
  1762. int base;
  1763. int x=x0,y=y0;
  1764. int err = 0;
  1765. int sy;
  1766. #ifdef STB_VORBIS_DIVIDE_TABLE
  1767. if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
  1768. if (dy < 0) {
  1769. base = -integer_divide_table[ady][adx];
  1770. sy = base-1;
  1771. } else {
  1772. base = integer_divide_table[ady][adx];
  1773. sy = base+1;
  1774. }
  1775. } else {
  1776. base = dy / adx;
  1777. if (dy < 0)
  1778. sy = base - 1;
  1779. else
  1780. sy = base+1;
  1781. }
  1782. #else
  1783. base = dy / adx;
  1784. if (dy < 0)
  1785. sy = base - 1;
  1786. else
  1787. sy = base+1;
  1788. #endif
  1789. ady -= abs(base) * adx;
  1790. if (x1 > n) x1 = n;
  1791. LINE_OP(output[x], inverse_db_table[y]);
  1792. for (++x; x < x1; ++x) {
  1793. err += ady;
  1794. if (err >= adx) {
  1795. err -= adx;
  1796. y += sy;
  1797. } else
  1798. y += base;
  1799. LINE_OP(output[x], inverse_db_table[y]);
  1800. }
  1801. }
  1802. static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
  1803. {
  1804. int k;
  1805. if (rtype == 0) {
  1806. int step = n / book->dimensions;
  1807. for (k=0; k < step; ++k)
  1808. if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
  1809. return FALSE;
  1810. } else {
  1811. for (k=0; k < n; ) {
  1812. if (!codebook_decode(f, book, target+offset, n-k))
  1813. return FALSE;
  1814. k += book->dimensions;
  1815. offset += book->dimensions;
  1816. }
  1817. }
  1818. return TRUE;
  1819. }
  1820. static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
  1821. {
  1822. int i,j,pass;
  1823. Residue *r = f->residue_config + rn;
  1824. int rtype = f->residue_types[rn];
  1825. int c = r->classbook;
  1826. int classwords = f->codebooks[c].dimensions;
  1827. int n_read = r->end - r->begin;
  1828. int part_read = n_read / r->part_size;
  1829. int temp_alloc_point = temp_alloc_save(f);
  1830. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1831. uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
  1832. #else
  1833. int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
  1834. #endif
  1835. stb_prof(2);
  1836. for (i=0; i < ch; ++i)
  1837. if (!do_not_decode[i])
  1838. memset(residue_buffers[i], 0, sizeof(float) * n);
  1839. if (rtype == 2 && ch != 1) {
  1840. int len = ch * n;
  1841. for (j=0; j < ch; ++j)
  1842. if (!do_not_decode[j])
  1843. break;
  1844. if (j == ch)
  1845. goto done;
  1846. stb_prof(3);
  1847. for (pass=0; pass < 8; ++pass) {
  1848. int pcount = 0, class_set = 0;
  1849. if (ch == 2) {
  1850. stb_prof(13);
  1851. while (pcount < part_read) {
  1852. int z = r->begin + pcount*r->part_size;
  1853. int c_inter = (z & 1), p_inter = z>>1;
  1854. if (pass == 0) {
  1855. Codebook *c = f->codebooks+r->classbook;
  1856. int q;
  1857. DECODE(q,f,c);
  1858. if (q == EOP) goto done;
  1859. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1860. part_classdata[0][class_set] = r->classdata[q];
  1861. #else
  1862. for (i=classwords-1; i >= 0; --i) {
  1863. classifications[0][i+pcount] = q % r->classifications;
  1864. q /= r->classifications;
  1865. }
  1866. #endif
  1867. }
  1868. stb_prof(5);
  1869. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1870. int z = r->begin + pcount*r->part_size;
  1871. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1872. int c = part_classdata[0][class_set][i];
  1873. #else
  1874. int c = classifications[0][pcount];
  1875. #endif
  1876. int b = r->residue_books[c][pass];
  1877. if (b >= 0) {
  1878. Codebook *book = f->codebooks + b;
  1879. stb_prof(20); // accounts for X time
  1880. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1881. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1882. goto done;
  1883. #else
  1884. // saves 1%
  1885. if (!codebook_decode_deinterleave_repeat_2(f, book, residue_buffers, &c_inter, &p_inter, n, r->part_size))
  1886. goto done;
  1887. #endif
  1888. stb_prof(7);
  1889. } else {
  1890. z += r->part_size;
  1891. c_inter = z & 1;
  1892. p_inter = z >> 1;
  1893. }
  1894. }
  1895. stb_prof(8);
  1896. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1897. ++class_set;
  1898. #endif
  1899. }
  1900. } else if (ch == 1) {
  1901. while (pcount < part_read) {
  1902. int z = r->begin + pcount*r->part_size;
  1903. int c_inter = 0, p_inter = z;
  1904. if (pass == 0) {
  1905. Codebook *c = f->codebooks+r->classbook;
  1906. int q;
  1907. DECODE(q,f,c);
  1908. if (q == EOP) goto done;
  1909. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1910. part_classdata[0][class_set] = r->classdata[q];
  1911. #else
  1912. for (i=classwords-1; i >= 0; --i) {
  1913. classifications[0][i+pcount] = q % r->classifications;
  1914. q /= r->classifications;
  1915. }
  1916. #endif
  1917. }
  1918. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1919. int z = r->begin + pcount*r->part_size;
  1920. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1921. int c = part_classdata[0][class_set][i];
  1922. #else
  1923. int c = classifications[0][pcount];
  1924. #endif
  1925. int b = r->residue_books[c][pass];
  1926. if (b >= 0) {
  1927. Codebook *book = f->codebooks + b;
  1928. stb_prof(22);
  1929. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1930. goto done;
  1931. stb_prof(3);
  1932. } else {
  1933. z += r->part_size;
  1934. c_inter = 0;
  1935. p_inter = z;
  1936. }
  1937. }
  1938. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1939. ++class_set;
  1940. #endif
  1941. }
  1942. } else {
  1943. while (pcount < part_read) {
  1944. int z = r->begin + pcount*r->part_size;
  1945. int c_inter = z % ch, p_inter = z/ch;
  1946. if (pass == 0) {
  1947. Codebook *c = f->codebooks+r->classbook;
  1948. int q;
  1949. DECODE(q,f,c);
  1950. if (q == EOP) goto done;
  1951. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1952. part_classdata[0][class_set] = r->classdata[q];
  1953. #else
  1954. for (i=classwords-1; i >= 0; --i) {
  1955. classifications[0][i+pcount] = q % r->classifications;
  1956. q /= r->classifications;
  1957. }
  1958. #endif
  1959. }
  1960. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1961. int z = r->begin + pcount*r->part_size;
  1962. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1963. int c = part_classdata[0][class_set][i];
  1964. #else
  1965. int c = classifications[0][pcount];
  1966. #endif
  1967. int b = r->residue_books[c][pass];
  1968. if (b >= 0) {
  1969. Codebook *book = f->codebooks + b;
  1970. stb_prof(22);
  1971. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1972. goto done;
  1973. stb_prof(3);
  1974. } else {
  1975. z += r->part_size;
  1976. c_inter = z % ch;
  1977. p_inter = z / ch;
  1978. }
  1979. }
  1980. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1981. ++class_set;
  1982. #endif
  1983. }
  1984. }
  1985. }
  1986. goto done;
  1987. }
  1988. stb_prof(9);
  1989. for (pass=0; pass < 8; ++pass) {
  1990. int pcount = 0, class_set=0;
  1991. while (pcount < part_read) {
  1992. if (pass == 0) {
  1993. for (j=0; j < ch; ++j) {
  1994. if (!do_not_decode[j]) {
  1995. Codebook *c = f->codebooks+r->classbook;
  1996. int temp;
  1997. DECODE(temp,f,c);
  1998. if (temp == EOP) goto done;
  1999. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  2000. part_classdata[j][class_set] = r->classdata[temp];
  2001. #else
  2002. for (i=classwords-1; i >= 0; --i) {
  2003. classifications[j][i+pcount] = temp % r->classifications;
  2004. temp /= r->classifications;
  2005. }
  2006. #endif
  2007. }
  2008. }
  2009. }
  2010. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  2011. for (j=0; j < ch; ++j) {
  2012. if (!do_not_decode[j]) {
  2013. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  2014. int c = part_classdata[j][class_set][i];
  2015. #else
  2016. int c = classifications[j][pcount];
  2017. #endif
  2018. int b = r->residue_books[c][pass];
  2019. if (b >= 0) {
  2020. float *target = residue_buffers[j];
  2021. int offset = r->begin + pcount * r->part_size;
  2022. int n = r->part_size;
  2023. Codebook *book = f->codebooks + b;
  2024. if (!residue_decode(f, book, target, offset, n, rtype))
  2025. goto done;
  2026. }
  2027. }
  2028. }
  2029. }
  2030. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  2031. ++class_set;
  2032. #endif
  2033. }
  2034. }
  2035. done:
  2036. stb_prof(0);
  2037. temp_alloc_restore(f,temp_alloc_point);
  2038. }
  2039. #if 0
  2040. // slow way for debugging
  2041. void inverse_mdct_slow(float *buffer, int n)
  2042. {
  2043. int i,j;
  2044. int n2 = n >> 1;
  2045. float *x = (float *) malloc(sizeof(*x) * n2);
  2046. memcpy(x, buffer, sizeof(*x) * n2);
  2047. for (i=0; i < n; ++i) {
  2048. float acc = 0;
  2049. for (j=0; j < n2; ++j)
  2050. // formula from paper:
  2051. //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
  2052. // formula from wikipedia
  2053. //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
  2054. // these are equivalent, except the formula from the paper inverts the multiplier!
  2055. // however, what actually works is NO MULTIPLIER!?!
  2056. //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
  2057. acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
  2058. buffer[i] = acc;
  2059. }
  2060. free(x);
  2061. }
  2062. #elif 0
  2063. // same as above, but just barely able to run in real time on modern machines
  2064. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  2065. {
  2066. float mcos[16384];
  2067. int i,j;
  2068. int n2 = n >> 1, nmask = (n << 2) -1;
  2069. float *x = (float *) malloc(sizeof(*x) * n2);
  2070. memcpy(x, buffer, sizeof(*x) * n2);
  2071. for (i=0; i < 4*n; ++i)
  2072. mcos[i] = (float) cos(M_PI / 2 * i / n);
  2073. for (i=0; i < n; ++i) {
  2074. float acc = 0;
  2075. for (j=0; j < n2; ++j)
  2076. acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
  2077. buffer[i] = acc;
  2078. }
  2079. free(x);
  2080. }
  2081. #else
  2082. // transform to use a slow dct-iv; this is STILL basically trivial,
  2083. // but only requires half as many ops
  2084. void dct_iv_slow(float *buffer, int n)
  2085. {
  2086. float mcos[16384];
  2087. float x[2048];
  2088. int i,j;
  2089. int n2 = n >> 1, nmask = (n << 3) - 1;
  2090. memcpy(x, buffer, sizeof(*x) * n);
  2091. for (i=0; i < 8*n; ++i)
  2092. mcos[i] = (float) cos(M_PI / 4 * i / n);
  2093. for (i=0; i < n; ++i) {
  2094. float acc = 0;
  2095. for (j=0; j < n; ++j)
  2096. acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
  2097. //acc += x[j] * cos(M_PI / n * (i + 0.5) * (j + 0.5));
  2098. buffer[i] = acc;
  2099. }
  2100. free(x);
  2101. }
  2102. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  2103. {
  2104. int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
  2105. float temp[4096];
  2106. memcpy(temp, buffer, n2 * sizeof(float));
  2107. dct_iv_slow(temp, n2); // returns -c'-d, a-b'
  2108. for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
  2109. for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
  2110. for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
  2111. }
  2112. #endif
  2113. #ifndef LIBVORBIS_MDCT
  2114. #define LIBVORBIS_MDCT 0
  2115. #endif
  2116. #if LIBVORBIS_MDCT
  2117. // directly call the vorbis MDCT using an interface documented
  2118. // by Jeff Roberts... useful for performance comparison
  2119. typedef struct
  2120. {
  2121. int n;
  2122. int log2n;
  2123. float *trig;
  2124. int *bitrev;
  2125. float scale;
  2126. } mdct_lookup;
  2127. extern void mdct_init(mdct_lookup *lookup, int n);
  2128. extern void mdct_clear(mdct_lookup *l);
  2129. extern void mdct_backward(mdct_lookup *init, float *in, float *out);
  2130. mdct_lookup M1,M2;
  2131. void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  2132. {
  2133. mdct_lookup *M;
  2134. if (M1.n == n) M = &M1;
  2135. else if (M2.n == n) M = &M2;
  2136. else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
  2137. else {
  2138. if (M2.n) __asm int 3;
  2139. mdct_init(&M2, n);
  2140. M = &M2;
  2141. }
  2142. mdct_backward(M, buffer, buffer);
  2143. }
  2144. #endif
  2145. // the following were split out into separate functions while optimizing;
  2146. // they could be pushed back up but eh. __forceinline showed no change;
  2147. // they're probably already being inlined.
  2148. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
  2149. {
  2150. float *ee0 = e + i_off;
  2151. float *ee2 = ee0 + k_off;
  2152. int i;
  2153. assert((n & 3) == 0);
  2154. for (i=(n>>2); i > 0; --i) {
  2155. float k00_20, k01_21;
  2156. k00_20 = ee0[ 0] - ee2[ 0];
  2157. k01_21 = ee0[-1] - ee2[-1];
  2158. ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
  2159. ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
  2160. ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
  2161. ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
  2162. A += 8;
  2163. k00_20 = ee0[-2] - ee2[-2];
  2164. k01_21 = ee0[-3] - ee2[-3];
  2165. ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
  2166. ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
  2167. ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
  2168. ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
  2169. A += 8;
  2170. k00_20 = ee0[-4] - ee2[-4];
  2171. k01_21 = ee0[-5] - ee2[-5];
  2172. ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
  2173. ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
  2174. ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
  2175. ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
  2176. A += 8;
  2177. k00_20 = ee0[-6] - ee2[-6];
  2178. k01_21 = ee0[-7] - ee2[-7];
  2179. ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
  2180. ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
  2181. ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
  2182. ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
  2183. A += 8;
  2184. ee0 -= 8;
  2185. ee2 -= 8;
  2186. }
  2187. }
  2188. static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
  2189. {
  2190. int i;
  2191. float k00_20, k01_21;
  2192. float *e0 = e + d0;
  2193. float *e2 = e0 + k_off;
  2194. for (i=lim >> 2; i > 0; --i) {
  2195. k00_20 = e0[-0] - e2[-0];
  2196. k01_21 = e0[-1] - e2[-1];
  2197. e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
  2198. e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
  2199. e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
  2200. e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
  2201. A += k1;
  2202. k00_20 = e0[-2] - e2[-2];
  2203. k01_21 = e0[-3] - e2[-3];
  2204. e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
  2205. e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
  2206. e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
  2207. e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
  2208. A += k1;
  2209. k00_20 = e0[-4] - e2[-4];
  2210. k01_21 = e0[-5] - e2[-5];
  2211. e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
  2212. e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
  2213. e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
  2214. e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
  2215. A += k1;
  2216. k00_20 = e0[-6] - e2[-6];
  2217. k01_21 = e0[-7] - e2[-7];
  2218. e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
  2219. e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
  2220. e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
  2221. e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
  2222. e0 -= 8;
  2223. e2 -= 8;
  2224. A += k1;
  2225. }
  2226. }
  2227. static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
  2228. {
  2229. int i;
  2230. float A0 = A[0];
  2231. float A1 = A[0+1];
  2232. float A2 = A[0+a_off];
  2233. float A3 = A[0+a_off+1];
  2234. float A4 = A[0+a_off*2+0];
  2235. float A5 = A[0+a_off*2+1];
  2236. float A6 = A[0+a_off*3+0];
  2237. float A7 = A[0+a_off*3+1];
  2238. float k00,k11;
  2239. float *ee0 = e +i_off;
  2240. float *ee2 = ee0+k_off;
  2241. for (i=n; i > 0; --i) {
  2242. k00 = ee0[ 0] - ee2[ 0];
  2243. k11 = ee0[-1] - ee2[-1];
  2244. ee0[ 0] = ee0[ 0] + ee2[ 0];
  2245. ee0[-1] = ee0[-1] + ee2[-1];
  2246. ee2[ 0] = (k00) * A0 - (k11) * A1;
  2247. ee2[-1] = (k11) * A0 + (k00) * A1;
  2248. k00 = ee0[-2] - ee2[-2];
  2249. k11 = ee0[-3] - ee2[-3];
  2250. ee0[-2] = ee0[-2] + ee2[-2];
  2251. ee0[-3] = ee0[-3] + ee2[-3];
  2252. ee2[-2] = (k00) * A2 - (k11) * A3;
  2253. ee2[-3] = (k11) * A2 + (k00) * A3;
  2254. k00 = ee0[-4] - ee2[-4];
  2255. k11 = ee0[-5] - ee2[-5];
  2256. ee0[-4] = ee0[-4] + ee2[-4];
  2257. ee0[-5] = ee0[-5] + ee2[-5];
  2258. ee2[-4] = (k00) * A4 - (k11) * A5;
  2259. ee2[-5] = (k11) * A4 + (k00) * A5;
  2260. k00 = ee0[-6] - ee2[-6];
  2261. k11 = ee0[-7] - ee2[-7];
  2262. ee0[-6] = ee0[-6] + ee2[-6];
  2263. ee0[-7] = ee0[-7] + ee2[-7];
  2264. ee2[-6] = (k00) * A6 - (k11) * A7;
  2265. ee2[-7] = (k11) * A6 + (k00) * A7;
  2266. ee0 -= k0;
  2267. ee2 -= k0;
  2268. }
  2269. }
  2270. static __forceinline void iter_54(float *z)
  2271. {
  2272. float k00,k11,k22,k33;
  2273. float y0,y1,y2,y3;
  2274. k00 = z[ 0] - z[-4];
  2275. y0 = z[ 0] + z[-4];
  2276. y2 = z[-2] + z[-6];
  2277. k22 = z[-2] - z[-6];
  2278. z[-0] = y0 + y2; // z0 + z4 + z2 + z6
  2279. z[-2] = y0 - y2; // z0 + z4 - z2 - z6
  2280. // done with y0,y2
  2281. k33 = z[-3] - z[-7];
  2282. z[-4] = k00 + k33; // z0 - z4 + z3 - z7
  2283. z[-6] = k00 - k33; // z0 - z4 - z3 + z7
  2284. // done with k33
  2285. k11 = z[-1] - z[-5];
  2286. y1 = z[-1] + z[-5];
  2287. y3 = z[-3] + z[-7];
  2288. z[-1] = y1 + y3; // z1 + z5 + z3 + z7
  2289. z[-3] = y1 - y3; // z1 + z5 - z3 - z7
  2290. z[-5] = k11 - k22; // z1 - z5 + z2 - z6
  2291. z[-7] = k11 + k22; // z1 - z5 - z2 + z6
  2292. }
  2293. static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
  2294. {
  2295. int k_off = -8;
  2296. int a_off = base_n >> 3;
  2297. float A2 = A[0+a_off];
  2298. float *z = e + i_off;
  2299. float *base = z - 16 * n;
  2300. while (z > base) {
  2301. float k00,k11;
  2302. k00 = z[-0] - z[-8];
  2303. k11 = z[-1] - z[-9];
  2304. z[-0] = z[-0] + z[-8];
  2305. z[-1] = z[-1] + z[-9];
  2306. z[-8] = k00;
  2307. z[-9] = k11 ;
  2308. k00 = z[ -2] - z[-10];
  2309. k11 = z[ -3] - z[-11];
  2310. z[ -2] = z[ -2] + z[-10];
  2311. z[ -3] = z[ -3] + z[-11];
  2312. z[-10] = (k00+k11) * A2;
  2313. z[-11] = (k11-k00) * A2;
  2314. k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
  2315. k11 = z[ -5] - z[-13];
  2316. z[ -4] = z[ -4] + z[-12];
  2317. z[ -5] = z[ -5] + z[-13];
  2318. z[-12] = k11;
  2319. z[-13] = k00;
  2320. k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
  2321. k11 = z[ -7] - z[-15];
  2322. z[ -6] = z[ -6] + z[-14];
  2323. z[ -7] = z[ -7] + z[-15];
  2324. z[-14] = (k00+k11) * A2;
  2325. z[-15] = (k00-k11) * A2;
  2326. iter_54(z);
  2327. iter_54(z-8);
  2328. z -= 16;
  2329. }
  2330. }
  2331. static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  2332. {
  2333. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  2334. int n3_4 = n - n4, ld;
  2335. // @OPTIMIZE: reduce register pressure by using fewer variables?
  2336. int save_point = temp_alloc_save(f);
  2337. float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
  2338. float *u=NULL,*v=NULL;
  2339. // twiddle factors
  2340. float *A = f->A[blocktype];
  2341. // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
  2342. // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
  2343. // kernel from paper
  2344. // merged:
  2345. // copy and reflect spectral data
  2346. // step 0
  2347. // note that it turns out that the items added together during
  2348. // this step are, in fact, being added to themselves (as reflected
  2349. // by step 0). inexplicable inefficiency! this became obvious
  2350. // once I combined the passes.
  2351. // so there's a missing 'times 2' here (for adding X to itself).
  2352. // this propogates through linearly to the end, where the numbers
  2353. // are 1/2 too small, and need to be compensated for.
  2354. {
  2355. float *d,*e, *AA, *e_stop;
  2356. d = &buf2[n2-2];
  2357. AA = A;
  2358. e = &buffer[0];
  2359. e_stop = &buffer[n2];
  2360. while (e != e_stop) {
  2361. d[1] = (e[0] * AA[0] - e[2]*AA[1]);
  2362. d[0] = (e[0] * AA[1] + e[2]*AA[0]);
  2363. d -= 2;
  2364. AA += 2;
  2365. e += 4;
  2366. }
  2367. e = &buffer[n2-3];
  2368. while (d >= buf2) {
  2369. d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
  2370. d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
  2371. d -= 2;
  2372. AA += 2;
  2373. e -= 4;
  2374. }
  2375. }
  2376. // now we use symbolic names for these, so that we can
  2377. // possibly swap their meaning as we change which operations
  2378. // are in place
  2379. u = buffer;
  2380. v = buf2;
  2381. // step 2 (paper output is w, now u)
  2382. // this could be in place, but the data ends up in the wrong
  2383. // place... _somebody_'s got to swap it, so this is nominated
  2384. {
  2385. float *AA = &A[n2-8];
  2386. float *d0,*d1, *e0, *e1;
  2387. e0 = &v[n4];
  2388. e1 = &v[0];
  2389. d0 = &u[n4];
  2390. d1 = &u[0];
  2391. while (AA >= A) {
  2392. float v40_20, v41_21;
  2393. v41_21 = e0[1] - e1[1];
  2394. v40_20 = e0[0] - e1[0];
  2395. d0[1] = e0[1] + e1[1];
  2396. d0[0] = e0[0] + e1[0];
  2397. d1[1] = v41_21*AA[4] - v40_20*AA[5];
  2398. d1[0] = v40_20*AA[4] + v41_21*AA[5];
  2399. v41_21 = e0[3] - e1[3];
  2400. v40_20 = e0[2] - e1[2];
  2401. d0[3] = e0[3] + e1[3];
  2402. d0[2] = e0[2] + e1[2];
  2403. d1[3] = v41_21*AA[0] - v40_20*AA[1];
  2404. d1[2] = v40_20*AA[0] + v41_21*AA[1];
  2405. AA -= 8;
  2406. d0 += 4;
  2407. d1 += 4;
  2408. e0 += 4;
  2409. e1 += 4;
  2410. }
  2411. }
  2412. // step 3
  2413. ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  2414. // optimized step 3:
  2415. // the original step3 loop can be nested r inside s or s inside r;
  2416. // it's written originally as s inside r, but this is dumb when r
  2417. // iterates many times, and s few. So I have two copies of it and
  2418. // switch between them halfway.
  2419. // this is iteration 0 of step 3
  2420. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
  2421. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
  2422. // this is iteration 1 of step 3
  2423. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
  2424. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
  2425. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
  2426. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
  2427. l=2;
  2428. for (; l < (ld-3)>>1; ++l) {
  2429. int k0 = n >> (l+2), k0_2 = k0>>1;
  2430. int lim = 1 << (l+1);
  2431. int i;
  2432. for (i=0; i < lim; ++i)
  2433. imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
  2434. }
  2435. for (; l < ld-6; ++l) {
  2436. int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
  2437. int rlim = n >> (l+6), r;
  2438. int lim = 1 << (l+1);
  2439. int i_off;
  2440. float *A0 = A;
  2441. i_off = n2-1;
  2442. for (r=rlim; r > 0; --r) {
  2443. imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
  2444. A0 += k1*4;
  2445. i_off -= 8;
  2446. }
  2447. }
  2448. // iterations with count:
  2449. // ld-6,-5,-4 all interleaved together
  2450. // the big win comes from getting rid of needless flops
  2451. // due to the constants on pass 5 & 4 being all 1 and 0;
  2452. // combining them to be simultaneous to improve cache made little difference
  2453. imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
  2454. // output is u
  2455. // step 4, 5, and 6
  2456. // cannot be in-place because of step 5
  2457. {
  2458. uint16 *bitrev = f->bit_reverse[blocktype];
  2459. // weirdly, I'd have thought reading sequentially and writing
  2460. // erratically would have been better than vice-versa, but in
  2461. // fact that's not what my testing showed. (That is, with
  2462. // j = bitreverse(i), do you read i and write j, or read j and write i.)
  2463. float *d0 = &v[n4-4];
  2464. float *d1 = &v[n2-4];
  2465. while (d0 >= v) {
  2466. int k4;
  2467. k4 = bitrev[0];
  2468. d1[3] = u[k4+0];
  2469. d1[2] = u[k4+1];
  2470. d0[3] = u[k4+2];
  2471. d0[2] = u[k4+3];
  2472. k4 = bitrev[1];
  2473. d1[1] = u[k4+0];
  2474. d1[0] = u[k4+1];
  2475. d0[1] = u[k4+2];
  2476. d0[0] = u[k4+3];
  2477. d0 -= 4;
  2478. d1 -= 4;
  2479. bitrev += 2;
  2480. }
  2481. }
  2482. // (paper output is u, now v)
  2483. // data must be in buf2
  2484. assert(v == buf2);
  2485. // step 7 (paper output is v, now v)
  2486. // this is now in place
  2487. {
  2488. float *C = f->C[blocktype];
  2489. float *d, *e;
  2490. d = v;
  2491. e = v + n2 - 4;
  2492. while (d < e) {
  2493. float a02,a11,b0,b1,b2,b3;
  2494. a02 = d[0] - e[2];
  2495. a11 = d[1] + e[3];
  2496. b0 = C[1]*a02 + C[0]*a11;
  2497. b1 = C[1]*a11 - C[0]*a02;
  2498. b2 = d[0] + e[ 2];
  2499. b3 = d[1] - e[ 3];
  2500. d[0] = b2 + b0;
  2501. d[1] = b3 + b1;
  2502. e[2] = b2 - b0;
  2503. e[3] = b1 - b3;
  2504. a02 = d[2] - e[0];
  2505. a11 = d[3] + e[1];
  2506. b0 = C[3]*a02 + C[2]*a11;
  2507. b1 = C[3]*a11 - C[2]*a02;
  2508. b2 = d[2] + e[ 0];
  2509. b3 = d[3] - e[ 1];
  2510. d[2] = b2 + b0;
  2511. d[3] = b3 + b1;
  2512. e[0] = b2 - b0;
  2513. e[1] = b1 - b3;
  2514. C += 4;
  2515. d += 4;
  2516. e -= 4;
  2517. }
  2518. }
  2519. // data must be in buf2
  2520. // step 8+decode (paper output is X, now buffer)
  2521. // this generates pairs of data a la 8 and pushes them directly through
  2522. // the decode kernel (pushing rather than pulling) to avoid having
  2523. // to make another pass later
  2524. // this cannot POSSIBLY be in place, so we refer to the buffers directly
  2525. {
  2526. float *d0,*d1,*d2,*d3;
  2527. float *B = f->B[blocktype] + n2 - 8;
  2528. float *e = buf2 + n2 - 8;
  2529. d0 = &buffer[0];
  2530. d1 = &buffer[n2-4];
  2531. d2 = &buffer[n2];
  2532. d3 = &buffer[n-4];
  2533. while (e >= v) {
  2534. float p0,p1,p2,p3;
  2535. p3 = e[6]*B[7] - e[7]*B[6];
  2536. p2 = -e[6]*B[6] - e[7]*B[7];
  2537. d0[0] = p3;
  2538. d1[3] = - p3;
  2539. d2[0] = p2;
  2540. d3[3] = p2;
  2541. p1 = e[4]*B[5] - e[5]*B[4];
  2542. p0 = -e[4]*B[4] - e[5]*B[5];
  2543. d0[1] = p1;
  2544. d1[2] = - p1;
  2545. d2[1] = p0;
  2546. d3[2] = p0;
  2547. p3 = e[2]*B[3] - e[3]*B[2];
  2548. p2 = -e[2]*B[2] - e[3]*B[3];
  2549. d0[2] = p3;
  2550. d1[1] = - p3;
  2551. d2[2] = p2;
  2552. d3[1] = p2;
  2553. p1 = e[0]*B[1] - e[1]*B[0];
  2554. p0 = -e[0]*B[0] - e[1]*B[1];
  2555. d0[3] = p1;
  2556. d1[0] = - p1;
  2557. d2[3] = p0;
  2558. d3[0] = p0;
  2559. B -= 8;
  2560. e -= 8;
  2561. d0 += 4;
  2562. d2 += 4;
  2563. d1 -= 4;
  2564. d3 -= 4;
  2565. }
  2566. }
  2567. temp_alloc_restore(f,save_point);
  2568. }
  2569. #if 0
  2570. // this is the original version of the above code, if you want to optimize it from scratch
  2571. void inverse_mdct_naive(float *buffer, int n)
  2572. {
  2573. float s;
  2574. float A[1 << 12], B[1 << 12], C[1 << 11];
  2575. int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  2576. int n3_4 = n - n4, ld;
  2577. // how can they claim this only uses N words?!
  2578. // oh, because they're only used sparsely, whoops
  2579. float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
  2580. // set up twiddle factors
  2581. for (k=k2=0; k < n4; ++k,k2+=2) {
  2582. A[k2 ] = (float) cos(4*k*M_PI/n);
  2583. A[k2+1] = (float) -sin(4*k*M_PI/n);
  2584. B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
  2585. B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
  2586. }
  2587. for (k=k2=0; k < n8; ++k,k2+=2) {
  2588. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  2589. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  2590. }
  2591. // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
  2592. // Note there are bugs in that pseudocode, presumably due to them attempting
  2593. // to rename the arrays nicely rather than representing the way their actual
  2594. // implementation bounces buffers back and forth. As a result, even in the
  2595. // "some formulars corrected" version, a direct implementation fails. These
  2596. // are noted below as "paper bug".
  2597. // copy and reflect spectral data
  2598. for (k=0; k < n2; ++k) u[k] = buffer[k];
  2599. for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
  2600. // kernel from paper
  2601. // step 1
  2602. for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
  2603. v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
  2604. v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
  2605. }
  2606. // step 2
  2607. for (k=k4=0; k < n8; k+=1, k4+=4) {
  2608. w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
  2609. w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
  2610. w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
  2611. w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
  2612. }
  2613. // step 3
  2614. ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  2615. for (l=0; l < ld-3; ++l) {
  2616. int k0 = n >> (l+2), k1 = 1 << (l+3);
  2617. int rlim = n >> (l+4), r4, r;
  2618. int s2lim = 1 << (l+2), s2;
  2619. for (r=r4=0; r < rlim; r4+=4,++r) {
  2620. for (s2=0; s2 < s2lim; s2+=2) {
  2621. u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
  2622. u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
  2623. u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
  2624. - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
  2625. u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
  2626. + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
  2627. }
  2628. }
  2629. if (l+1 < ld-3) {
  2630. // paper bug: ping-ponging of u&w here is omitted
  2631. memcpy(w, u, sizeof(u));
  2632. }
  2633. }
  2634. // step 4
  2635. for (i=0; i < n8; ++i) {
  2636. int j = bit_reverse(i) >> (32-ld+3);
  2637. assert(j < n8);
  2638. if (i == j) {
  2639. // paper bug: original code probably swapped in place; if copying,
  2640. // need to directly copy in this case
  2641. int i8 = i << 3;
  2642. v[i8+1] = u[i8+1];
  2643. v[i8+3] = u[i8+3];
  2644. v[i8+5] = u[i8+5];
  2645. v[i8+7] = u[i8+7];
  2646. } else if (i < j) {
  2647. int i8 = i << 3, j8 = j << 3;
  2648. v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
  2649. v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
  2650. v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
  2651. v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
  2652. }
  2653. }
  2654. // step 5
  2655. for (k=0; k < n2; ++k) {
  2656. w[k] = v[k*2+1];
  2657. }
  2658. // step 6
  2659. for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
  2660. u[n-1-k2] = w[k4];
  2661. u[n-2-k2] = w[k4+1];
  2662. u[n3_4 - 1 - k2] = w[k4+2];
  2663. u[n3_4 - 2 - k2] = w[k4+3];
  2664. }
  2665. // step 7
  2666. for (k=k2=0; k < n8; ++k, k2 += 2) {
  2667. v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
  2668. v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
  2669. v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
  2670. v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
  2671. }
  2672. // step 8
  2673. for (k=k2=0; k < n4; ++k,k2 += 2) {
  2674. X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
  2675. X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
  2676. }
  2677. // decode kernel to output
  2678. // determined the following value experimentally
  2679. // (by first figuring out what made inverse_mdct_slow work); then matching that here
  2680. // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
  2681. s = 0.5; // theoretically would be n4
  2682. // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
  2683. // so it needs to use the "old" B values to behave correctly, or else
  2684. // set s to 1.0 ]]]
  2685. for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
  2686. for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
  2687. for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
  2688. }
  2689. #endif
  2690. static float *get_window(vorb *f, int len)
  2691. {
  2692. len <<= 1;
  2693. if (len == f->blocksize_0) return f->window[0];
  2694. if (len == f->blocksize_1) return f->window[1];
  2695. assert(0);
  2696. return NULL;
  2697. }
  2698. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2699. typedef int16 YTYPE;
  2700. #else
  2701. typedef int YTYPE;
  2702. #endif
  2703. static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
  2704. {
  2705. int n2 = n >> 1;
  2706. int s = map->chan[i].mux, floor;
  2707. floor = map->submap_floor[s];
  2708. if (f->floor_types[floor] == 0) {
  2709. return error(f, VORBIS_invalid_stream);
  2710. } else {
  2711. Floor1 *g = &f->floor_config[floor].floor1;
  2712. int j,q;
  2713. int lx = 0, ly = finalY[0] * g->floor1_multiplier;
  2714. for (q=1; q < g->values; ++q) {
  2715. j = g->sorted_order[q];
  2716. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2717. if (finalY[j] >= 0)
  2718. #else
  2719. if (step2_flag[j])
  2720. #endif
  2721. {
  2722. int hy = finalY[j] * g->floor1_multiplier;
  2723. int hx = g->Xlist[j];
  2724. draw_line(target, lx,ly, hx,hy, n2);
  2725. lx = hx, ly = hy;
  2726. }
  2727. }
  2728. if (lx < n2)
  2729. // optimization of: draw_line(target, lx,ly, n,ly, n2);
  2730. for (j=lx; j < n2; ++j)
  2731. LINE_OP(target[j], inverse_db_table[ly]);
  2732. }
  2733. return TRUE;
  2734. }
  2735. static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
  2736. {
  2737. Mode *m;
  2738. int i, n, prev, next, window_center;
  2739. f->channel_buffer_start = f->channel_buffer_end = 0;
  2740. retry:
  2741. if (f->eof) return FALSE;
  2742. if (!maybe_start_packet(f))
  2743. return FALSE;
  2744. // check packet type
  2745. if (get_bits(f,1) != 0) {
  2746. if (IS_PUSH_MODE(f))
  2747. return error(f,VORBIS_bad_packet_type);
  2748. while (EOP != get8_packet(f));
  2749. goto retry;
  2750. }
  2751. if (f->alloc.alloc_buffer)
  2752. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2753. i = get_bits(f, ilog(f->mode_count-1));
  2754. if (i == EOP) return FALSE;
  2755. if (i >= f->mode_count) return FALSE;
  2756. *mode = i;
  2757. m = f->mode_config + i;
  2758. if (m->blockflag) {
  2759. n = f->blocksize_1;
  2760. prev = get_bits(f,1);
  2761. next = get_bits(f,1);
  2762. } else {
  2763. prev = next = 0;
  2764. n = f->blocksize_0;
  2765. }
  2766. // WINDOWING
  2767. window_center = n >> 1;
  2768. if (m->blockflag && !prev) {
  2769. *p_left_start = (n - f->blocksize_0) >> 2;
  2770. *p_left_end = (n + f->blocksize_0) >> 2;
  2771. } else {
  2772. *p_left_start = 0;
  2773. *p_left_end = window_center;
  2774. }
  2775. if (m->blockflag && !next) {
  2776. *p_right_start = (n*3 - f->blocksize_0) >> 2;
  2777. *p_right_end = (n*3 + f->blocksize_0) >> 2;
  2778. } else {
  2779. *p_right_start = window_center;
  2780. *p_right_end = n;
  2781. }
  2782. return TRUE;
  2783. }
  2784. static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
  2785. {
  2786. Mapping *map;
  2787. int i,j,k,n,n2;
  2788. int zero_channel[256];
  2789. int really_zero_channel[256];
  2790. int window_center;
  2791. // WINDOWING
  2792. n = f->blocksize[m->blockflag];
  2793. window_center = n >> 1;
  2794. map = &f->mapping[m->mapping];
  2795. // FLOORS
  2796. n2 = n >> 1;
  2797. stb_prof(1);
  2798. for (i=0; i < f->channels; ++i) {
  2799. int s = map->chan[i].mux, floor;
  2800. zero_channel[i] = FALSE;
  2801. floor = map->submap_floor[s];
  2802. if (f->floor_types[floor] == 0) {
  2803. return error(f, VORBIS_invalid_stream);
  2804. } else {
  2805. Floor1 *g = &f->floor_config[floor].floor1;
  2806. if (get_bits(f, 1)) {
  2807. short *finalY;
  2808. uint8 step2_flag[256];
  2809. static int range_list[4] = { 256, 128, 86, 64 };
  2810. int range = range_list[g->floor1_multiplier-1];
  2811. int offset = 2;
  2812. finalY = f->finalY[i];
  2813. finalY[0] = get_bits(f, ilog(range)-1);
  2814. finalY[1] = get_bits(f, ilog(range)-1);
  2815. for (j=0; j < g->partitions; ++j) {
  2816. int pclass = g->partition_class_list[j];
  2817. int cdim = g->class_dimensions[pclass];
  2818. int cbits = g->class_subclasses[pclass];
  2819. int csub = (1 << cbits)-1;
  2820. int cval = 0;
  2821. if (cbits) {
  2822. Codebook *c = f->codebooks + g->class_masterbooks[pclass];
  2823. DECODE(cval,f,c);
  2824. }
  2825. for (k=0; k < cdim; ++k) {
  2826. int book = g->subclass_books[pclass][cval & csub];
  2827. cval = cval >> cbits;
  2828. if (book >= 0) {
  2829. int temp;
  2830. Codebook *c = f->codebooks + book;
  2831. DECODE(temp,f,c);
  2832. finalY[offset++] = temp;
  2833. } else
  2834. finalY[offset++] = 0;
  2835. }
  2836. }
  2837. if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
  2838. step2_flag[0] = step2_flag[1] = 1;
  2839. for (j=2; j < g->values; ++j) {
  2840. int low, high, pred, highroom, lowroom, room, val;
  2841. low = g->neighbors[j][0];
  2842. high = g->neighbors[j][1];
  2843. //neighbors(g->Xlist, j, &low, &high);
  2844. pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
  2845. val = finalY[j];
  2846. highroom = range - pred;
  2847. lowroom = pred;
  2848. if (highroom < lowroom)
  2849. room = highroom * 2;
  2850. else
  2851. room = lowroom * 2;
  2852. if (val) {
  2853. step2_flag[low] = step2_flag[high] = 1;
  2854. step2_flag[j] = 1;
  2855. if (val >= room)
  2856. if (highroom > lowroom)
  2857. finalY[j] = val - lowroom + pred;
  2858. else
  2859. finalY[j] = pred - val + highroom - 1;
  2860. else
  2861. if (val & 1)
  2862. finalY[j] = pred - ((val+1)>>1);
  2863. else
  2864. finalY[j] = pred + (val>>1);
  2865. } else {
  2866. step2_flag[j] = 0;
  2867. finalY[j] = pred;
  2868. }
  2869. }
  2870. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  2871. do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
  2872. #else
  2873. // defer final floor computation until _after_ residue
  2874. for (j=0; j < g->values; ++j) {
  2875. if (!step2_flag[j])
  2876. finalY[j] = -1;
  2877. }
  2878. #endif
  2879. } else {
  2880. error:
  2881. zero_channel[i] = TRUE;
  2882. }
  2883. // So we just defer everything else to later
  2884. // at this point we've decoded the floor into buffer
  2885. }
  2886. }
  2887. stb_prof(0);
  2888. // at this point we've decoded all floors
  2889. if (f->alloc.alloc_buffer)
  2890. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2891. // re-enable coupled channels if necessary
  2892. memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
  2893. for (i=0; i < map->coupling_steps; ++i)
  2894. if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
  2895. zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
  2896. }
  2897. // RESIDUE DECODE
  2898. for (i=0; i < map->submaps; ++i) {
  2899. float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
  2900. int r,t;
  2901. uint8 do_not_decode[256];
  2902. int ch = 0;
  2903. for (j=0; j < f->channels; ++j) {
  2904. if (map->chan[j].mux == i) {
  2905. if (zero_channel[j]) {
  2906. do_not_decode[ch] = TRUE;
  2907. residue_buffers[ch] = NULL;
  2908. } else {
  2909. do_not_decode[ch] = FALSE;
  2910. residue_buffers[ch] = f->channel_buffers[j];
  2911. }
  2912. ++ch;
  2913. }
  2914. }
  2915. r = map->submap_residue[i];
  2916. t = f->residue_types[r];
  2917. decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
  2918. }
  2919. if (f->alloc.alloc_buffer)
  2920. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2921. // INVERSE COUPLING
  2922. stb_prof(14);
  2923. for (i = map->coupling_steps-1; i >= 0; --i) {
  2924. int n2 = n >> 1;
  2925. float *m = f->channel_buffers[map->chan[i].magnitude];
  2926. float *a = f->channel_buffers[map->chan[i].angle ];
  2927. for (j=0; j < n2; ++j) {
  2928. float a2,m2;
  2929. if (m[j] > 0)
  2930. if (a[j] > 0)
  2931. m2 = m[j], a2 = m[j] - a[j];
  2932. else
  2933. a2 = m[j], m2 = m[j] + a[j];
  2934. else
  2935. if (a[j] > 0)
  2936. m2 = m[j], a2 = m[j] + a[j];
  2937. else
  2938. a2 = m[j], m2 = m[j] - a[j];
  2939. m[j] = m2;
  2940. a[j] = a2;
  2941. }
  2942. }
  2943. // finish decoding the floors
  2944. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2945. stb_prof(15);
  2946. for (i=0; i < f->channels; ++i) {
  2947. if (really_zero_channel[i]) {
  2948. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  2949. } else {
  2950. do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
  2951. }
  2952. }
  2953. #else
  2954. for (i=0; i < f->channels; ++i) {
  2955. if (really_zero_channel[i]) {
  2956. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  2957. } else {
  2958. for (j=0; j < n2; ++j)
  2959. f->channel_buffers[i][j] *= f->floor_buffers[i][j];
  2960. }
  2961. }
  2962. #endif
  2963. // INVERSE MDCT
  2964. stb_prof(16);
  2965. for (i=0; i < f->channels; ++i)
  2966. inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
  2967. stb_prof(0);
  2968. // this shouldn't be necessary, unless we exited on an error
  2969. // and want to flush to get to the next packet
  2970. flush_packet(f);
  2971. if (f->first_decode) {
  2972. // assume we start so first non-discarded sample is sample 0
  2973. // this isn't to spec, but spec would require us to read ahead
  2974. // and decode the size of all current frames--could be done,
  2975. // but presumably it's not a commonly used feature
  2976. f->current_loc = -n2; // start of first frame is positioned for discard
  2977. // we might have to discard samples "from" the next frame too,
  2978. // if we're lapping a large block then a small at the start?
  2979. f->discard_samples_deferred = n - right_end;
  2980. f->current_loc_valid = TRUE;
  2981. f->first_decode = FALSE;
  2982. } else if (f->discard_samples_deferred) {
  2983. left_start += f->discard_samples_deferred;
  2984. *p_left = left_start;
  2985. f->discard_samples_deferred = 0;
  2986. } else if (f->previous_length == 0 && f->current_loc_valid) {
  2987. // we're recovering from a seek... that means we're going to discard
  2988. // the samples from this packet even though we know our position from
  2989. // the last page header, so we need to update the position based on
  2990. // the discarded samples here
  2991. // but wait, the code below is going to add this in itself even
  2992. // on a discard, so we don't need to do it here...
  2993. }
  2994. // check if we have ogg information about the sample # for this packet
  2995. if (f->last_seg_which == f->end_seg_with_known_loc) {
  2996. // if we have a valid current loc, and this is final:
  2997. if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
  2998. uint32 current_end = f->known_loc_for_packet - (n-right_end);
  2999. // then let's infer the size of the (probably) short final frame
  3000. if (current_end < f->current_loc + right_end) {
  3001. if (current_end < f->current_loc) {
  3002. // negative truncation, that's impossible!
  3003. *len = 0;
  3004. } else {
  3005. *len = current_end - f->current_loc;
  3006. }
  3007. *len += left_start;
  3008. f->current_loc += *len;
  3009. return TRUE;
  3010. }
  3011. }
  3012. // otherwise, just set our sample loc
  3013. // guess that the ogg granule pos refers to the _middle_ of the
  3014. // last frame?
  3015. // set f->current_loc to the position of left_start
  3016. f->current_loc = f->known_loc_for_packet - (n2-left_start);
  3017. f->current_loc_valid = TRUE;
  3018. }
  3019. if (f->current_loc_valid)
  3020. f->current_loc += (right_start - left_start);
  3021. if (f->alloc.alloc_buffer)
  3022. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  3023. *len = right_end; // ignore samples after the window goes to 0
  3024. return TRUE;
  3025. }
  3026. static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
  3027. {
  3028. int mode, left_end, right_end;
  3029. if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
  3030. return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
  3031. }
  3032. static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
  3033. {
  3034. int prev,i,j;
  3035. // we use right&left (the start of the right- and left-window sin()-regions)
  3036. // to determine how much to return, rather than inferring from the rules
  3037. // (same result, clearer code); 'left' indicates where our sin() window
  3038. // starts, therefore where the previous window's right edge starts, and
  3039. // therefore where to start mixing from the previous buffer. 'right'
  3040. // indicates where our sin() ending-window starts, therefore that's where
  3041. // we start saving, and where our returned-data ends.
  3042. // mixin from previous window
  3043. if (f->previous_length) {
  3044. int i,j, n = f->previous_length;
  3045. float *w = get_window(f, n);
  3046. for (i=0; i < f->channels; ++i) {
  3047. for (j=0; j < n; ++j)
  3048. f->channel_buffers[i][left+j] =
  3049. f->channel_buffers[i][left+j]*w[ j] +
  3050. f->previous_window[i][ j]*w[n-1-j];
  3051. }
  3052. }
  3053. prev = f->previous_length;
  3054. // last half of this data becomes previous window
  3055. f->previous_length = len - right;
  3056. // @OPTIMIZE: could avoid this copy by double-buffering the
  3057. // output (flipping previous_window with channel_buffers), but
  3058. // then previous_window would have to be 2x as large, and
  3059. // channel_buffers couldn't be temp mem (although they're NOT
  3060. // currently temp mem, they could be (unless we want to level
  3061. // performance by spreading out the computation))
  3062. for (i=0; i < f->channels; ++i)
  3063. for (j=0; right+j < len; ++j)
  3064. f->previous_window[i][j] = f->channel_buffers[i][right+j];
  3065. if (!prev)
  3066. // there was no previous packet, so this data isn't valid...
  3067. // this isn't entirely true, only the would-have-overlapped data
  3068. // isn't valid, but this seems to be what the spec requires
  3069. return 0;
  3070. // truncate a short frame
  3071. if (len < right) right = len;
  3072. f->samples_output += right-left;
  3073. return right - left;
  3074. }
  3075. static void vorbis_pump_first_frame(stb_vorbis *f)
  3076. {
  3077. int len, right, left;
  3078. if (vorbis_decode_packet(f, &len, &left, &right))
  3079. vorbis_finish_frame(f, len, left, right);
  3080. }
  3081. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3082. static int is_whole_packet_present(stb_vorbis *f, int end_page)
  3083. {
  3084. // make sure that we have the packet available before continuing...
  3085. // this requires a full ogg parse, but we know we can fetch from f->stream
  3086. // instead of coding this out explicitly, we could save the current read state,
  3087. // read the next packet with get8() until end-of-packet, check f->eof, then
  3088. // reset the state? but that would be slower, esp. since we'd have over 256 bytes
  3089. // of state to restore (primarily the page segment table)
  3090. int s = f->next_seg, first = TRUE;
  3091. uint8 *p = f->stream;
  3092. if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
  3093. for (; s < f->segment_count; ++s) {
  3094. p += f->segments[s];
  3095. if (f->segments[s] < 255) // stop at first short segment
  3096. break;
  3097. }
  3098. // either this continues, or it ends it...
  3099. if (end_page)
  3100. if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);
  3101. if (s == f->segment_count)
  3102. s = -1; // set 'crosses page' flag
  3103. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  3104. first = FALSE;
  3105. }
  3106. for (; s == -1;) {
  3107. uint8 *q;
  3108. int n;
  3109. // check that we have the page header ready
  3110. if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
  3111. // validate the page
  3112. if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
  3113. if (p[4] != 0) return error(f, VORBIS_invalid_stream);
  3114. if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
  3115. if (f->previous_length)
  3116. if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
  3117. // if no previous length, we're resynching, so we can come in on a continued-packet,
  3118. // which we'll just drop
  3119. } else {
  3120. if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
  3121. }
  3122. n = p[26]; // segment counts
  3123. q = p+27; // q points to segment table
  3124. p = q + n; // advance past header
  3125. // make sure we've read the segment table
  3126. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  3127. for (s=0; s < n; ++s) {
  3128. p += q[s];
  3129. if (q[s] < 255)
  3130. break;
  3131. }
  3132. if (end_page)
  3133. if (s < n-1) return error(f, VORBIS_invalid_stream);
  3134. if (s == f->segment_count)
  3135. s = -1; // set 'crosses page' flag
  3136. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  3137. first = FALSE;
  3138. }
  3139. return TRUE;
  3140. }
  3141. #endif // !STB_VORBIS_NO_PUSHDATA_API
  3142. static int start_decoder(vorb *f)
  3143. {
  3144. uint8 header[6], x,y;
  3145. int len,i,j,k, max_submaps = 0;
  3146. int longest_floorlist=0;
  3147. // first page, first packet
  3148. if (!start_page(f)) return FALSE;
  3149. // validate page flag
  3150. if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
  3151. if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
  3152. if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
  3153. // check for expected packet length
  3154. if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
  3155. if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
  3156. // read packet
  3157. // check packet header
  3158. if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
  3159. if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
  3160. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
  3161. // vorbis_version
  3162. if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
  3163. f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
  3164. if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
  3165. f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
  3166. get32(f); // bitrate_maximum
  3167. get32(f); // bitrate_nominal
  3168. get32(f); // bitrate_minimum
  3169. x = get8(f);
  3170. { int log0,log1;
  3171. log0 = x & 15;
  3172. log1 = x >> 4;
  3173. f->blocksize_0 = 1 << log0;
  3174. f->blocksize_1 = 1 << log1;
  3175. if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
  3176. if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
  3177. if (log0 > log1) return error(f, VORBIS_invalid_setup);
  3178. }
  3179. // framing_flag
  3180. x = get8(f);
  3181. if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
  3182. // second packet!
  3183. if (!start_page(f)) return FALSE;
  3184. if (!start_packet(f)) return FALSE;
  3185. do {
  3186. len = next_segment(f);
  3187. skip(f, len);
  3188. f->bytes_in_seg = 0;
  3189. } while (len);
  3190. // third packet!
  3191. if (!start_packet(f)) return FALSE;
  3192. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3193. if (IS_PUSH_MODE(f)) {
  3194. if (!is_whole_packet_present(f, TRUE)) {
  3195. // convert error in ogg header to write type
  3196. if (f->error == VORBIS_invalid_stream)
  3197. f->error = VORBIS_invalid_setup;
  3198. return FALSE;
  3199. }
  3200. }
  3201. #endif
  3202. crc32_init(); // always init it, to avoid multithread race conditions
  3203. if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
  3204. for (i=0; i < 6; ++i) header[i] = get8_packet(f);
  3205. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
  3206. // codebooks
  3207. f->codebook_count = get_bits(f,8) + 1;
  3208. f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
  3209. if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
  3210. memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
  3211. for (i=0; i < f->codebook_count; ++i) {
  3212. uint32 *values;
  3213. int ordered, sorted_count;
  3214. int total=0;
  3215. uint8 *lengths;
  3216. Codebook *c = f->codebooks+i;
  3217. x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
  3218. x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
  3219. x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
  3220. x = get_bits(f, 8);
  3221. c->dimensions = (get_bits(f, 8)<<8) + x;
  3222. x = get_bits(f, 8);
  3223. y = get_bits(f, 8);
  3224. c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
  3225. ordered = get_bits(f,1);
  3226. c->sparse = ordered ? 0 : get_bits(f,1);
  3227. if (c->sparse)
  3228. lengths = (uint8 *) setup_temp_malloc(f, c->entries);
  3229. else
  3230. lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  3231. if (!lengths) return error(f, VORBIS_outofmem);
  3232. if (ordered) {
  3233. int current_entry = 0;
  3234. int current_length = get_bits(f,5) + 1;
  3235. while (current_entry < c->entries) {
  3236. int limit = c->entries - current_entry;
  3237. int n = get_bits(f, ilog(limit));
  3238. if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
  3239. memset(lengths + current_entry, current_length, n);
  3240. current_entry += n;
  3241. ++current_length;
  3242. }
  3243. } else {
  3244. for (j=0; j < c->entries; ++j) {
  3245. int present = c->sparse ? get_bits(f,1) : 1;
  3246. if (present) {
  3247. lengths[j] = get_bits(f, 5) + 1;
  3248. ++total;
  3249. } else {
  3250. lengths[j] = NO_CODE;
  3251. }
  3252. }
  3253. }
  3254. if (c->sparse && total >= c->entries >> 2) {
  3255. // convert sparse items to non-sparse!
  3256. if (c->entries > (int) f->setup_temp_memory_required)
  3257. f->setup_temp_memory_required = c->entries;
  3258. c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  3259. memcpy(c->codeword_lengths, lengths, c->entries);
  3260. setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
  3261. lengths = c->codeword_lengths;
  3262. c->sparse = 0;
  3263. }
  3264. // compute the size of the sorted tables
  3265. if (c->sparse) {
  3266. sorted_count = total;
  3267. //assert(total != 0);
  3268. } else {
  3269. sorted_count = 0;
  3270. #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  3271. for (j=0; j < c->entries; ++j)
  3272. if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
  3273. ++sorted_count;
  3274. #endif
  3275. }
  3276. c->sorted_entries = sorted_count;
  3277. values = NULL;
  3278. if (!c->sparse) {
  3279. c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
  3280. if (!c->codewords) return error(f, VORBIS_outofmem);
  3281. } else {
  3282. unsigned int size;
  3283. if (c->sorted_entries) {
  3284. c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
  3285. if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
  3286. c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
  3287. if (!c->codewords) return error(f, VORBIS_outofmem);
  3288. values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
  3289. if (!values) return error(f, VORBIS_outofmem);
  3290. }
  3291. size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
  3292. if (size > f->setup_temp_memory_required)
  3293. f->setup_temp_memory_required = size;
  3294. }
  3295. if (!compute_codewords(c, lengths, c->entries, values)) {
  3296. if (c->sparse) setup_temp_free(f, values, 0);
  3297. return error(f, VORBIS_invalid_setup);
  3298. }
  3299. if (c->sorted_entries) {
  3300. // allocate an extra slot for sentinels
  3301. c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
  3302. // allocate an extra slot at the front so that c->sorted_values[-1] is defined
  3303. // so that we can catch that case without an extra if
  3304. c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
  3305. if (c->sorted_values) { ++c->sorted_values; c->sorted_values[-1] = -1; }
  3306. compute_sorted_huffman(c, lengths, values);
  3307. }
  3308. if (c->sparse) {
  3309. setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
  3310. setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
  3311. setup_temp_free(f, lengths, c->entries);
  3312. c->codewords = NULL;
  3313. }
  3314. compute_accelerated_huffman(c);
  3315. c->lookup_type = get_bits(f, 4);
  3316. if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
  3317. if (c->lookup_type > 0) {
  3318. uint16 *mults;
  3319. c->minimum_value = float32_unpack(get_bits(f, 32));
  3320. c->delta_value = float32_unpack(get_bits(f, 32));
  3321. c->value_bits = get_bits(f, 4)+1;
  3322. c->sequence_p = get_bits(f,1);
  3323. if (c->lookup_type == 1) {
  3324. c->lookup_values = lookup1_values(c->entries, c->dimensions);
  3325. } else {
  3326. c->lookup_values = c->entries * c->dimensions;
  3327. }
  3328. mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
  3329. if (mults == NULL) return error(f, VORBIS_outofmem);
  3330. for (j=0; j < (int) c->lookup_values; ++j) {
  3331. int q = get_bits(f, c->value_bits);
  3332. if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
  3333. mults[j] = q;
  3334. }
  3335. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3336. if (c->lookup_type == 1) {
  3337. int len, sparse = c->sparse;
  3338. // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
  3339. if (sparse) {
  3340. if (c->sorted_entries == 0) goto skip;
  3341. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
  3342. } else
  3343. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
  3344. if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
  3345. len = sparse ? c->sorted_entries : c->entries;
  3346. for (j=0; j < len; ++j) {
  3347. int z = sparse ? c->sorted_values[j] : j, div=1;
  3348. for (k=0; k < c->dimensions; ++k) {
  3349. int off = (z / div) % c->lookup_values;
  3350. c->multiplicands[j*c->dimensions + k] =
  3351. #ifndef STB_VORBIS_CODEBOOK_FLOATS
  3352. mults[off];
  3353. #else
  3354. mults[off]*c->delta_value + c->minimum_value;
  3355. // in this case (and this case only) we could pre-expand c->sequence_p,
  3356. // and throw away the decode logic for it; have to ALSO do
  3357. // it in the case below, but it can only be done if
  3358. // STB_VORBIS_CODEBOOK_FLOATS
  3359. // !STB_VORBIS_DIVIDES_IN_CODEBOOK
  3360. #endif
  3361. div *= c->lookup_values;
  3362. }
  3363. }
  3364. setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
  3365. c->lookup_type = 2;
  3366. }
  3367. else
  3368. #endif
  3369. {
  3370. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
  3371. #ifndef STB_VORBIS_CODEBOOK_FLOATS
  3372. memcpy(c->multiplicands, mults, sizeof(c->multiplicands[0]) * c->lookup_values);
  3373. #else
  3374. for (j=0; j < (int) c->lookup_values; ++j)
  3375. c->multiplicands[j] = mults[j] * c->delta_value + c->minimum_value;
  3376. setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
  3377. #endif
  3378. }
  3379. skip:;
  3380. #ifdef STB_VORBIS_CODEBOOK_FLOATS
  3381. if (c->lookup_type == 2 && c->sequence_p) {
  3382. for (j=1; j < (int) c->lookup_values; ++j)
  3383. c->multiplicands[j] = c->multiplicands[j-1];
  3384. c->sequence_p = 0;
  3385. }
  3386. #endif
  3387. }
  3388. }
  3389. // time domain transfers (notused)
  3390. x = get_bits(f, 6) + 1;
  3391. for (i=0; i < x; ++i) {
  3392. uint32 z = get_bits(f, 16);
  3393. if (z != 0) return error(f, VORBIS_invalid_setup);
  3394. }
  3395. // Floors
  3396. f->floor_count = get_bits(f, 6)+1;
  3397. f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
  3398. for (i=0; i < f->floor_count; ++i) {
  3399. f->floor_types[i] = get_bits(f, 16);
  3400. if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
  3401. if (f->floor_types[i] == 0) {
  3402. Floor0 *g = &f->floor_config[i].floor0;
  3403. g->order = get_bits(f,8);
  3404. g->rate = get_bits(f,16);
  3405. g->bark_map_size = get_bits(f,16);
  3406. g->amplitude_bits = get_bits(f,6);
  3407. g->amplitude_offset = get_bits(f,8);
  3408. g->number_of_books = get_bits(f,4) + 1;
  3409. for (j=0; j < g->number_of_books; ++j)
  3410. g->book_list[j] = get_bits(f,8);
  3411. return error(f, VORBIS_feature_not_supported);
  3412. } else {
  3413. Point p[31*8+2];
  3414. Floor1 *g = &f->floor_config[i].floor1;
  3415. int max_class = -1;
  3416. g->partitions = get_bits(f, 5);
  3417. for (j=0; j < g->partitions; ++j) {
  3418. g->partition_class_list[j] = get_bits(f, 4);
  3419. if (g->partition_class_list[j] > max_class)
  3420. max_class = g->partition_class_list[j];
  3421. }
  3422. for (j=0; j <= max_class; ++j) {
  3423. g->class_dimensions[j] = get_bits(f, 3)+1;
  3424. g->class_subclasses[j] = get_bits(f, 2);
  3425. if (g->class_subclasses[j]) {
  3426. g->class_masterbooks[j] = get_bits(f, 8);
  3427. if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3428. }
  3429. for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
  3430. g->subclass_books[j][k] = get_bits(f,8)-1;
  3431. if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3432. }
  3433. }
  3434. g->floor1_multiplier = get_bits(f,2)+1;
  3435. g->rangebits = get_bits(f,4);
  3436. g->Xlist[0] = 0;
  3437. g->Xlist[1] = 1 << g->rangebits;
  3438. g->values = 2;
  3439. for (j=0; j < g->partitions; ++j) {
  3440. int c = g->partition_class_list[j];
  3441. for (k=0; k < g->class_dimensions[c]; ++k) {
  3442. g->Xlist[g->values] = get_bits(f, g->rangebits);
  3443. ++g->values;
  3444. }
  3445. }
  3446. // precompute the sorting
  3447. for (j=0; j < g->values; ++j) {
  3448. p[j].x = g->Xlist[j];
  3449. p[j].y = j;
  3450. }
  3451. qsort(p, g->values, sizeof(p[0]), point_compare);
  3452. for (j=0; j < g->values; ++j)
  3453. g->sorted_order[j] = (uint8) p[j].y;
  3454. // precompute the neighbors
  3455. for (j=2; j < g->values; ++j) {
  3456. int low,hi;
  3457. neighbors(g->Xlist, j, &low,&hi);
  3458. g->neighbors[j][0] = low;
  3459. g->neighbors[j][1] = hi;
  3460. }
  3461. if (g->values > longest_floorlist)
  3462. longest_floorlist = g->values;
  3463. }
  3464. }
  3465. // Residue
  3466. f->residue_count = get_bits(f, 6)+1;
  3467. f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(*f->residue_config));
  3468. for (i=0; i < f->residue_count; ++i) {
  3469. uint8 residue_cascade[64];
  3470. Residue *r = f->residue_config+i;
  3471. f->residue_types[i] = get_bits(f, 16);
  3472. if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
  3473. r->begin = get_bits(f, 24);
  3474. r->end = get_bits(f, 24);
  3475. r->part_size = get_bits(f,24)+1;
  3476. r->classifications = get_bits(f,6)+1;
  3477. r->classbook = get_bits(f,8);
  3478. for (j=0; j < r->classifications; ++j) {
  3479. uint8 high_bits=0;
  3480. uint8 low_bits=get_bits(f,3);
  3481. if (get_bits(f,1))
  3482. high_bits = get_bits(f,5);
  3483. residue_cascade[j] = high_bits*8 + low_bits;
  3484. }
  3485. r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
  3486. for (j=0; j < r->classifications; ++j) {
  3487. for (k=0; k < 8; ++k) {
  3488. if (residue_cascade[j] & (1 << k)) {
  3489. r->residue_books[j][k] = get_bits(f, 8);
  3490. if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3491. } else {
  3492. r->residue_books[j][k] = -1;
  3493. }
  3494. }
  3495. }
  3496. // precompute the classifications[] array to avoid inner-loop mod/divide
  3497. // call it 'classdata' since we already have r->classifications
  3498. r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  3499. if (!r->classdata) return error(f, VORBIS_outofmem);
  3500. memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  3501. for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
  3502. int classwords = f->codebooks[r->classbook].dimensions;
  3503. int temp = j;
  3504. r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
  3505. for (k=classwords-1; k >= 0; --k) {
  3506. r->classdata[j][k] = temp % r->classifications;
  3507. temp /= r->classifications;
  3508. }
  3509. }
  3510. }
  3511. f->mapping_count = get_bits(f,6)+1;
  3512. f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
  3513. for (i=0; i < f->mapping_count; ++i) {
  3514. Mapping *m = f->mapping + i;
  3515. int mapping_type = get_bits(f,16);
  3516. if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
  3517. m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
  3518. if (get_bits(f,1))
  3519. m->submaps = get_bits(f,4);
  3520. else
  3521. m->submaps = 1;
  3522. if (m->submaps > max_submaps)
  3523. max_submaps = m->submaps;
  3524. if (get_bits(f,1)) {
  3525. m->coupling_steps = get_bits(f,8)+1;
  3526. for (k=0; k < m->coupling_steps; ++k) {
  3527. m->chan[k].magnitude = get_bits(f, ilog(f->channels)-1);
  3528. m->chan[k].angle = get_bits(f, ilog(f->channels)-1);
  3529. if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
  3530. if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
  3531. if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
  3532. }
  3533. } else
  3534. m->coupling_steps = 0;
  3535. // reserved field
  3536. if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
  3537. if (m->submaps > 1) {
  3538. for (j=0; j < f->channels; ++j) {
  3539. m->chan[j].mux = get_bits(f, 4);
  3540. if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
  3541. }
  3542. } else
  3543. // @SPECIFICATION: this case is missing from the spec
  3544. for (j=0; j < f->channels; ++j)
  3545. m->chan[j].mux = 0;
  3546. for (j=0; j < m->submaps; ++j) {
  3547. get_bits(f,8); // discard
  3548. m->submap_floor[j] = get_bits(f,8);
  3549. m->submap_residue[j] = get_bits(f,8);
  3550. if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
  3551. if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
  3552. }
  3553. }
  3554. // Modes
  3555. f->mode_count = get_bits(f, 6)+1;
  3556. for (i=0; i < f->mode_count; ++i) {
  3557. Mode *m = f->mode_config+i;
  3558. m->blockflag = get_bits(f,1);
  3559. m->windowtype = get_bits(f,16);
  3560. m->transformtype = get_bits(f,16);
  3561. m->mapping = get_bits(f,8);
  3562. if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
  3563. if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
  3564. if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
  3565. }
  3566. flush_packet(f);
  3567. f->previous_length = 0;
  3568. for (i=0; i < f->channels; ++i) {
  3569. f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
  3570. f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  3571. f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
  3572. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  3573. f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  3574. #endif
  3575. }
  3576. if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
  3577. if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
  3578. f->blocksize[0] = f->blocksize_0;
  3579. f->blocksize[1] = f->blocksize_1;
  3580. #ifdef STB_VORBIS_DIVIDE_TABLE
  3581. if (integer_divide_table[1][1]==0)
  3582. for (i=0; i < DIVTAB_NUMER; ++i)
  3583. for (j=1; j < DIVTAB_DENOM; ++j)
  3584. integer_divide_table[i][j] = i / j;
  3585. #endif
  3586. // compute how much temporary memory is needed
  3587. // 1.
  3588. {
  3589. uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
  3590. uint32 classify_mem;
  3591. int i,max_part_read=0;
  3592. for (i=0; i < f->residue_count; ++i) {
  3593. Residue *r = f->residue_config + i;
  3594. int n_read = r->end - r->begin;
  3595. int part_read = n_read / r->part_size;
  3596. if (part_read > max_part_read)
  3597. max_part_read = part_read;
  3598. }
  3599. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3600. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
  3601. #else
  3602. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
  3603. #endif
  3604. f->temp_memory_required = classify_mem;
  3605. if (imdct_mem > f->temp_memory_required)
  3606. f->temp_memory_required = imdct_mem;
  3607. }
  3608. f->first_decode = TRUE;
  3609. if (f->alloc.alloc_buffer) {
  3610. assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
  3611. // check if there's enough temp memory so we don't error later
  3612. if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
  3613. return error(f, VORBIS_outofmem);
  3614. }
  3615. f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
  3616. return TRUE;
  3617. }
  3618. static void vorbis_deinit(stb_vorbis *p)
  3619. {
  3620. int i,j;
  3621. for (i=0; i < p->residue_count; ++i) {
  3622. Residue *r = p->residue_config+i;
  3623. if (r->classdata) {
  3624. for (j=0; j < p->codebooks[r->classbook].entries; ++j)
  3625. setup_free(p, r->classdata[j]);
  3626. setup_free(p, r->classdata);
  3627. }
  3628. setup_free(p, r->residue_books);
  3629. }
  3630. if (p->codebooks) {
  3631. for (i=0; i < p->codebook_count; ++i) {
  3632. Codebook *c = p->codebooks + i;
  3633. setup_free(p, c->codeword_lengths);
  3634. setup_free(p, c->multiplicands);
  3635. setup_free(p, c->codewords);
  3636. setup_free(p, c->sorted_codewords);
  3637. // c->sorted_values[-1] is the first entry in the array
  3638. setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
  3639. }
  3640. setup_free(p, p->codebooks);
  3641. }
  3642. setup_free(p, p->floor_config);
  3643. setup_free(p, p->residue_config);
  3644. for (i=0; i < p->mapping_count; ++i)
  3645. setup_free(p, p->mapping[i].chan);
  3646. setup_free(p, p->mapping);
  3647. for (i=0; i < p->channels; ++i) {
  3648. setup_free(p, p->channel_buffers[i]);
  3649. setup_free(p, p->previous_window[i]);
  3650. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  3651. setup_free(p, p->floor_buffers[i]);
  3652. #endif
  3653. setup_free(p, p->finalY[i]);
  3654. }
  3655. for (i=0; i < 2; ++i) {
  3656. setup_free(p, p->A[i]);
  3657. setup_free(p, p->B[i]);
  3658. setup_free(p, p->C[i]);
  3659. setup_free(p, p->window[i]);
  3660. }
  3661. #ifndef STB_VORBIS_NO_STDIO
  3662. if (p->close_on_free) fclose(p->f);
  3663. #endif
  3664. }
  3665. void stb_vorbis_close(stb_vorbis *p)
  3666. {
  3667. if (p == NULL) return;
  3668. vorbis_deinit(p);
  3669. setup_free(p,p);
  3670. }
  3671. static void vorbis_init(stb_vorbis *p, stb_vorbis_alloc *z)
  3672. {
  3673. memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
  3674. if (z) {
  3675. p->alloc = *z;
  3676. p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
  3677. p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
  3678. }
  3679. p->eof = 0;
  3680. p->error = VORBIS__no_error;
  3681. p->stream = NULL;
  3682. p->codebooks = NULL;
  3683. p->page_crc_tests = -1;
  3684. #ifndef STB_VORBIS_NO_STDIO
  3685. p->close_on_free = FALSE;
  3686. p->f = NULL;
  3687. #endif
  3688. }
  3689. int stb_vorbis_get_sample_offset(stb_vorbis *f)
  3690. {
  3691. if (f->current_loc_valid)
  3692. return f->current_loc;
  3693. else
  3694. return -1;
  3695. }
  3696. stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
  3697. {
  3698. stb_vorbis_info d;
  3699. d.channels = f->channels;
  3700. d.sample_rate = f->sample_rate;
  3701. d.setup_memory_required = f->setup_memory_required;
  3702. d.setup_temp_memory_required = f->setup_temp_memory_required;
  3703. d.temp_memory_required = f->temp_memory_required;
  3704. d.max_frame_size = f->blocksize_1 >> 1;
  3705. return d;
  3706. }
  3707. int stb_vorbis_get_error(stb_vorbis *f)
  3708. {
  3709. int e = f->error;
  3710. f->error = VORBIS__no_error;
  3711. return e;
  3712. }
  3713. static stb_vorbis * vorbis_alloc(stb_vorbis *f)
  3714. {
  3715. stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
  3716. return p;
  3717. }
  3718. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3719. void stb_vorbis_flush_pushdata(stb_vorbis *f)
  3720. {
  3721. f->previous_length = 0;
  3722. f->page_crc_tests = 0;
  3723. f->discard_samples_deferred = 0;
  3724. f->current_loc_valid = FALSE;
  3725. f->first_decode = FALSE;
  3726. f->samples_output = 0;
  3727. f->channel_buffer_start = 0;
  3728. f->channel_buffer_end = 0;
  3729. }
  3730. static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
  3731. {
  3732. int i,n;
  3733. for (i=0; i < f->page_crc_tests; ++i)
  3734. f->scan[i].bytes_done = 0;
  3735. // if we have room for more scans, search for them first, because
  3736. // they may cause us to stop early if their header is incomplete
  3737. if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
  3738. if (data_len < 4) return 0;
  3739. data_len -= 3; // need to look for 4-byte sequence, so don't miss
  3740. // one that straddles a boundary
  3741. for (i=0; i < data_len; ++i) {
  3742. if (data[i] == 0x4f) {
  3743. if (0==memcmp(data+i, ogg_page_header, 4)) {
  3744. int j,len;
  3745. uint32 crc;
  3746. // make sure we have the whole page header
  3747. if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
  3748. // only read up to this page start, so hopefully we'll
  3749. // have the whole page header start next time
  3750. data_len = i;
  3751. break;
  3752. }
  3753. // ok, we have it all; compute the length of the page
  3754. len = 27 + data[i+26];
  3755. for (j=0; j < data[i+26]; ++j)
  3756. len += data[i+27+j];
  3757. // scan everything up to the embedded crc (which we must 0)
  3758. crc = 0;
  3759. for (j=0; j < 22; ++j)
  3760. crc = crc32_update(crc, data[i+j]);
  3761. // now process 4 0-bytes
  3762. for ( ; j < 26; ++j)
  3763. crc = crc32_update(crc, 0);
  3764. // len is the total number of bytes we need to scan
  3765. n = f->page_crc_tests++;
  3766. f->scan[n].bytes_left = len-j;
  3767. f->scan[n].crc_so_far = crc;
  3768. f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
  3769. // if the last frame on a page is continued to the next, then
  3770. // we can't recover the sample_loc immediately
  3771. if (data[i+27+data[i+26]-1] == 255)
  3772. f->scan[n].sample_loc = ~0;
  3773. else
  3774. f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
  3775. f->scan[n].bytes_done = i+j;
  3776. if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
  3777. break;
  3778. // keep going if we still have room for more
  3779. }
  3780. }
  3781. }
  3782. }
  3783. for (i=0; i < f->page_crc_tests;) {
  3784. uint32 crc;
  3785. int j;
  3786. int n = f->scan[i].bytes_done;
  3787. int m = f->scan[i].bytes_left;
  3788. if (m > data_len - n) m = data_len - n;
  3789. // m is the bytes to scan in the current chunk
  3790. crc = f->scan[i].crc_so_far;
  3791. for (j=0; j < m; ++j)
  3792. crc = crc32_update(crc, data[n+j]);
  3793. f->scan[i].bytes_left -= m;
  3794. f->scan[i].crc_so_far = crc;
  3795. if (f->scan[i].bytes_left == 0) {
  3796. // does it match?
  3797. if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
  3798. // Houston, we have page
  3799. data_len = n+m; // consumption amount is wherever that scan ended
  3800. f->page_crc_tests = -1; // drop out of page scan mode
  3801. f->previous_length = 0; // decode-but-don't-output one frame
  3802. f->next_seg = -1; // start a new page
  3803. f->current_loc = f->scan[i].sample_loc; // set the current sample location
  3804. // to the amount we'd have decoded had we decoded this page
  3805. f->current_loc_valid = f->current_loc != ~0;
  3806. return data_len;
  3807. }
  3808. // delete entry
  3809. f->scan[i] = f->scan[--f->page_crc_tests];
  3810. } else {
  3811. ++i;
  3812. }
  3813. }
  3814. return data_len;
  3815. }
  3816. // return value: number of bytes we used
  3817. int stb_vorbis_decode_frame_pushdata(
  3818. stb_vorbis *f, // the file we're decoding
  3819. uint8 *data, int data_len, // the memory available for decoding
  3820. int *channels, // place to write number of float * buffers
  3821. float ***output, // place to write float ** array of float * buffers
  3822. int *samples // place to write number of output samples
  3823. )
  3824. {
  3825. int i;
  3826. int len,right,left;
  3827. if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  3828. if (f->page_crc_tests >= 0) {
  3829. *samples = 0;
  3830. return vorbis_search_for_page_pushdata(f, data, data_len);
  3831. }
  3832. f->stream = data;
  3833. f->stream_end = data + data_len;
  3834. f->error = VORBIS__no_error;
  3835. // check that we have the entire packet in memory
  3836. if (!is_whole_packet_present(f, FALSE)) {
  3837. *samples = 0;
  3838. return 0;
  3839. }
  3840. if (!vorbis_decode_packet(f, &len, &left, &right)) {
  3841. // save the actual error we encountered
  3842. enum STBVorbisError error = f->error;
  3843. if (error == VORBIS_bad_packet_type) {
  3844. // flush and resynch
  3845. f->error = VORBIS__no_error;
  3846. while (get8_packet(f) != EOP)
  3847. if (f->eof) break;
  3848. *samples = 0;
  3849. return f->stream - data;
  3850. }
  3851. if (error == VORBIS_continued_packet_flag_invalid) {
  3852. if (f->previous_length == 0) {
  3853. // we may be resynching, in which case it's ok to hit one
  3854. // of these; just discard the packet
  3855. f->error = VORBIS__no_error;
  3856. while (get8_packet(f) != EOP)
  3857. if (f->eof) break;
  3858. *samples = 0;
  3859. return f->stream - data;
  3860. }
  3861. }
  3862. // if we get an error while parsing, what to do?
  3863. // well, it DEFINITELY won't work to continue from where we are!
  3864. stb_vorbis_flush_pushdata(f);
  3865. // restore the error that actually made us bail
  3866. f->error = error;
  3867. *samples = 0;
  3868. return 1;
  3869. }
  3870. // success!
  3871. len = vorbis_finish_frame(f, len, left, right);
  3872. for (i=0; i < f->channels; ++i)
  3873. f->outputs[i] = f->channel_buffers[i] + left;
  3874. if (channels) *channels = f->channels;
  3875. *samples = len;
  3876. *output = f->outputs;
  3877. return f->stream - data;
  3878. }
  3879. stb_vorbis *stb_vorbis_open_pushdata(
  3880. unsigned char *data, int data_len, // the memory available for decoding
  3881. int *data_used, // only defined if result is not NULL
  3882. int *error, stb_vorbis_alloc *alloc)
  3883. {
  3884. stb_vorbis *f, p;
  3885. vorbis_init(&p, alloc);
  3886. p.stream = data;
  3887. p.stream_end = data + data_len;
  3888. p.push_mode = TRUE;
  3889. if (!start_decoder(&p)) {
  3890. if (p.eof)
  3891. *error = VORBIS_need_more_data;
  3892. else
  3893. *error = p.error;
  3894. return NULL;
  3895. }
  3896. f = vorbis_alloc(&p);
  3897. if (f) {
  3898. *f = p;
  3899. *data_used = f->stream - data;
  3900. *error = 0;
  3901. return f;
  3902. } else {
  3903. vorbis_deinit(&p);
  3904. return NULL;
  3905. }
  3906. }
  3907. #endif // STB_VORBIS_NO_PUSHDATA_API
  3908. unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
  3909. {
  3910. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3911. if (f->push_mode) return 0;
  3912. #endif
  3913. if (USE_MEMORY(f)) return f->stream - f->stream_start;
  3914. #ifndef STB_VORBIS_NO_STDIO
  3915. return ftell(f->f) - f->f_start;
  3916. #endif
  3917. }
  3918. #ifndef STB_VORBIS_NO_PULLDATA_API
  3919. //
  3920. // DATA-PULLING API
  3921. //
  3922. static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
  3923. {
  3924. for(;;) {
  3925. int n;
  3926. if (f->eof) return 0;
  3927. n = get8(f);
  3928. if (n == 0x4f) { // page header
  3929. unsigned int retry_loc = stb_vorbis_get_file_offset(f);
  3930. int i;
  3931. // check if we're off the end of a file_section stream
  3932. if (retry_loc - 25 > f->stream_len)
  3933. return 0;
  3934. // check the rest of the header
  3935. for (i=1; i < 4; ++i)
  3936. if (get8(f) != ogg_page_header[i])
  3937. break;
  3938. if (f->eof) return 0;
  3939. if (i == 4) {
  3940. uint8 header[27];
  3941. uint32 i, crc, goal, len;
  3942. for (i=0; i < 4; ++i)
  3943. header[i] = ogg_page_header[i];
  3944. for (; i < 27; ++i)
  3945. header[i] = get8(f);
  3946. if (f->eof) return 0;
  3947. if (header[4] != 0) goto invalid;
  3948. goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
  3949. for (i=22; i < 26; ++i)
  3950. header[i] = 0;
  3951. crc = 0;
  3952. for (i=0; i < 27; ++i)
  3953. crc = crc32_update(crc, header[i]);
  3954. len = 0;
  3955. for (i=0; i < header[26]; ++i) {
  3956. int s = get8(f);
  3957. crc = crc32_update(crc, s);
  3958. len += s;
  3959. }
  3960. if (len && f->eof) return 0;
  3961. for (i=0; i < len; ++i)
  3962. crc = crc32_update(crc, get8(f));
  3963. // finished parsing probable page
  3964. if (crc == goal) {
  3965. // we could now check that it's either got the last
  3966. // page flag set, OR it's followed by the capture
  3967. // pattern, but I guess TECHNICALLY you could have
  3968. // a file with garbage between each ogg page and recover
  3969. // from it automatically? So even though that paranoia
  3970. // might decrease the chance of an invalid decode by
  3971. // another 2^32, not worth it since it would hose those
  3972. // invalid-but-useful files?
  3973. if (end)
  3974. *end = stb_vorbis_get_file_offset(f);
  3975. if (last)
  3976. if (header[5] & 0x04)
  3977. *last = 1;
  3978. else
  3979. *last = 0;
  3980. set_file_offset(f, retry_loc-1);
  3981. return 1;
  3982. }
  3983. }
  3984. invalid:
  3985. // not a valid page, so rewind and look for next one
  3986. set_file_offset(f, retry_loc);
  3987. }
  3988. }
  3989. }
  3990. // seek is implemented with 'interpolation search'--this is like
  3991. // binary search, but we use the data values to estimate the likely
  3992. // location of the data item (plus a bit of a bias so when the
  3993. // estimation is wrong we don't waste overly much time)
  3994. #define SAMPLE_unknown 0xffffffff
  3995. // ogg vorbis, in its insane infinite wisdom, only provides
  3996. // information about the sample at the END of the page.
  3997. // therefore we COULD have the data we need in the current
  3998. // page, and not know it. we could just use the end location
  3999. // as our only knowledge for bounds, seek back, and eventually
  4000. // the binary search finds it. or we can try to be smart and
  4001. // not waste time trying to locate more pages. we try to be
  4002. // smart, since this data is already in memory anyway, so
  4003. // doing needless I/O would be crazy!
  4004. static int vorbis_analyze_page(stb_vorbis *f, ProbedPage *z)
  4005. {
  4006. uint8 header[27], lacing[255];
  4007. uint8 packet_type[255];
  4008. int num_packet, packet_start, previous =0;
  4009. int i,len;
  4010. uint32 samples;
  4011. // record where the page starts
  4012. z->page_start = stb_vorbis_get_file_offset(f);
  4013. // parse the header
  4014. getn(f, header, 27);
  4015. assert(header[0] == 'O' && header[1] == 'g' && header[2] == 'g' && header[3] == 'S');
  4016. getn(f, lacing, header[26]);
  4017. // determine the length of the payload
  4018. len = 0;
  4019. for (i=0; i < header[26]; ++i)
  4020. len += lacing[i];
  4021. // this implies where the page ends
  4022. z->page_end = z->page_start + 27 + header[26] + len;
  4023. // read the last-decoded sample out of the data
  4024. z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 16);
  4025. if (header[5] & 4) {
  4026. // if this is the last page, it's not possible to work
  4027. // backwards to figure out the first sample! whoops! fuck.
  4028. z->first_decoded_sample = SAMPLE_unknown;
  4029. set_file_offset(f, z->page_start);
  4030. return 1;
  4031. }
  4032. // scan through the frames to determine the sample-count of each one...
  4033. // our goal is the sample # of the first fully-decoded sample on the
  4034. // page, which is the first decoded sample of the 2nd page
  4035. num_packet=0;
  4036. packet_start = ((header[5] & 1) == 0);
  4037. for (i=0; i < header[26]; ++i) {
  4038. if (packet_start) {
  4039. uint8 n,b,m;
  4040. if (lacing[i] == 0) goto bail; // trying to read from zero-length packet
  4041. n = get8(f);
  4042. // if bottom bit is non-zero, we've got corruption
  4043. if (n & 1) goto bail;
  4044. n >>= 1;
  4045. b = ilog(f->mode_count-1);
  4046. m = n >> b;
  4047. n &= (1 << b)-1;
  4048. if (n >= f->mode_count) goto bail;
  4049. if (num_packet == 0 && f->mode_config[n].blockflag)
  4050. previous = (m & 1);
  4051. packet_type[num_packet++] = f->mode_config[n].blockflag;
  4052. skip(f, lacing[i]-1);
  4053. } else
  4054. skip(f, lacing[i]);
  4055. packet_start = (lacing[i] < 255);
  4056. }
  4057. // now that we know the sizes of all the pages, we can start determining
  4058. // how much sample data there is.
  4059. samples = 0;
  4060. // for the last packet, we step by its whole length, because the definition
  4061. // is that we encoded the end sample loc of the 'last packet completed',
  4062. // where 'completed' refers to packets being split, and we are left to guess
  4063. // what 'end sample loc' means. we assume it means ignoring the fact that
  4064. // the last half of the data is useless without windowing against the next
  4065. // packet... (so it's not REALLY complete in that sense)
  4066. if (num_packet > 1)
  4067. samples += f->blocksize[packet_type[num_packet-1]];
  4068. for (i=num_packet-2; i >= 1; --i) {
  4069. // now, for this packet, how many samples do we have that
  4070. // do not overlap the following packet?
  4071. if (packet_type[i] == 1)
  4072. if (packet_type[i+1] == 1)
  4073. samples += f->blocksize_1 >> 1;
  4074. else
  4075. samples += ((f->blocksize_1 - f->blocksize_0) >> 2) + (f->blocksize_0 >> 1);
  4076. else
  4077. samples += f->blocksize_0 >> 1;
  4078. }
  4079. // now, at this point, we've rewound to the very beginning of the
  4080. // _second_ packet. if we entirely discard the first packet after
  4081. // a seek, this will be exactly the right sample number. HOWEVER!
  4082. // we can't as easily compute this number for the LAST page. The
  4083. // only way to get the sample offset of the LAST page is to use
  4084. // the end loc from the previous page. But what that returns us
  4085. // is _exactly_ the place where we get our first non-overlapped
  4086. // sample. (I think. Stupid spec for being ambiguous.) So for
  4087. // consistency it's better to do that here, too. However, that
  4088. // will then require us to NOT discard all of the first frame we
  4089. // decode, in some cases, which means an even weirder frame size
  4090. // and extra code. what a fucking pain.
  4091. // we're going to discard the first packet if we
  4092. // start the seek here, so we don't care about it. (we could actually
  4093. // do better; if the first packet is long, and the previous packet
  4094. // is short, there's actually data in the first half of the first
  4095. // packet that doesn't need discarding... but not worth paying the
  4096. // effort of tracking that of that here and in the seeking logic)
  4097. // except crap, if we infer it from the _previous_ packet's end
  4098. // location, we DO need to use that definition... and we HAVE to
  4099. // infer the start loc of the LAST packet from the previous packet's
  4100. // end location. fuck you, ogg vorbis.
  4101. z->first_decoded_sample = z->last_decoded_sample - samples;
  4102. // restore file state to where we were
  4103. set_file_offset(f, z->page_start);
  4104. return 1;
  4105. // restore file state to where we were
  4106. bail:
  4107. set_file_offset(f, z->page_start);
  4108. return 0;
  4109. }
  4110. static int vorbis_seek_frame_from_page(stb_vorbis *f, uint32 page_start, uint32 first_sample, uint32 target_sample, int fine)
  4111. {
  4112. int left_start, left_end, right_start, right_end, mode,i;
  4113. int frame=0;
  4114. uint32 frame_start;
  4115. int frames_to_skip, data_to_skip;
  4116. // first_sample is the sample # of the first sample that doesn't
  4117. // overlap the previous page... note that this requires us to
  4118. // _partially_ discard the first packet! bleh.
  4119. set_file_offset(f, page_start);
  4120. f->next_seg = -1; // force page resync
  4121. frame_start = first_sample;
  4122. // frame start is where the previous packet's last decoded sample
  4123. // was, which corresponds to left_end... EXCEPT if the previous
  4124. // packet was long and this packet is short? Probably a bug here.
  4125. // now, we can start decoding frames... we'll only FAKE decode them,
  4126. // until we find the frame that contains our sample; then we'll rewind,
  4127. // and try again
  4128. for (;;) {
  4129. int start;
  4130. if (!vorbis_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
  4131. return error(f, VORBIS_seek_failed);
  4132. if (frame == 0)
  4133. start = left_end;
  4134. else
  4135. start = left_start;
  4136. // the window starts at left_start; the last valid sample we generate
  4137. // before the next frame's window start is right_start-1
  4138. if (target_sample < frame_start + right_start-start)
  4139. break;
  4140. flush_packet(f);
  4141. if (f->eof)
  4142. return error(f, VORBIS_seek_failed);
  4143. frame_start += right_start - start;
  4144. ++frame;
  4145. }
  4146. // ok, at this point, the sample we want is contained in frame #'frame'
  4147. // to decode frame #'frame' normally, we have to decode the
  4148. // previous frame first... but if it's the FIRST frame of the page
  4149. // we can't. if it's the first frame, it means it falls in the part
  4150. // of the first frame that doesn't overlap either of the other frames.
  4151. // so, if we have to handle that case for the first frame, we might
  4152. // as well handle it for all of them, so:
  4153. if (target_sample > frame_start + (left_end - left_start)) {
  4154. // so what we want to do is go ahead and just immediately decode
  4155. // this frame, but then make it so the next get_frame_float() uses
  4156. // this already-decoded data? or do we want to go ahead and rewind,
  4157. // and leave a flag saying to skip the first N data? let's do that
  4158. frames_to_skip = frame; // if this is frame #1, skip 1 frame (#0)
  4159. data_to_skip = left_end - left_start;
  4160. } else {
  4161. // otherwise, we want to skip frames 0, 1, 2, ... frame-2
  4162. // (which means frame-2+1 total frames) then decode frame-1,
  4163. // then leave frame pending
  4164. frames_to_skip = frame - 1;
  4165. assert(frames_to_skip >= 0);
  4166. data_to_skip = -1;
  4167. }
  4168. set_file_offset(f, page_start);
  4169. f->next_seg = - 1; // force page resync
  4170. for (i=0; i < frames_to_skip; ++i) {
  4171. maybe_start_packet(f);
  4172. flush_packet(f);
  4173. }
  4174. if (data_to_skip >= 0) {
  4175. int i,j,n = f->blocksize_0 >> 1;
  4176. f->discard_samples_deferred = data_to_skip;
  4177. for (i=0; i < f->channels; ++i)
  4178. for (j=0; j < n; ++j)
  4179. f->previous_window[i][j] = 0;
  4180. f->previous_length = n;
  4181. frame_start += data_to_skip;
  4182. } else {
  4183. f->previous_length = 0;
  4184. vorbis_pump_first_frame(f);
  4185. }
  4186. // at this point, the NEXT decoded frame will generate the desired sample
  4187. if (fine) {
  4188. // so if we're doing sample accurate streaming, we want to go ahead and decode it!
  4189. if (target_sample != frame_start) {
  4190. int n;
  4191. stb_vorbis_get_frame_float(f, &n, NULL);
  4192. assert(target_sample > frame_start);
  4193. assert(f->channel_buffer_start + (int) (target_sample-frame_start) < f->channel_buffer_end);
  4194. f->channel_buffer_start += (target_sample - frame_start);
  4195. }
  4196. }
  4197. return 0;
  4198. }
  4199. static int vorbis_seek_base(stb_vorbis *f, unsigned int sample_number, int fine)
  4200. {
  4201. ProbedPage p[2],q;
  4202. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  4203. // do we know the location of the last page?
  4204. if (f->p_last.page_start == 0) {
  4205. uint32 z = stb_vorbis_stream_length_in_samples(f);
  4206. if (z == 0) return error(f, VORBIS_cant_find_last_page);
  4207. }
  4208. p[0] = f->p_first;
  4209. p[1] = f->p_last;
  4210. if (sample_number >= f->p_last.last_decoded_sample)
  4211. sample_number = f->p_last.last_decoded_sample-1;
  4212. if (sample_number < f->p_first.last_decoded_sample) {
  4213. vorbis_seek_frame_from_page(f, p[0].page_start, 0, sample_number, fine);
  4214. return 0;
  4215. } else {
  4216. int attempts=0;
  4217. while (p[0].page_end < p[1].page_start) {
  4218. uint32 probe;
  4219. uint32 start_offset, end_offset;
  4220. uint32 start_sample, end_sample;
  4221. // copy these into local variables so we can tweak them
  4222. // if any are unknown
  4223. start_offset = p[0].page_end;
  4224. end_offset = p[1].after_previous_page_start; // an address known to seek to page p[1]
  4225. start_sample = p[0].last_decoded_sample;
  4226. end_sample = p[1].last_decoded_sample;
  4227. // currently there is no such tweaking logic needed/possible?
  4228. if (start_sample == SAMPLE_unknown || end_sample == SAMPLE_unknown)
  4229. return error(f, VORBIS_seek_failed);
  4230. // now we want to lerp between these for the target samples...
  4231. // step 1: we need to bias towards the page start...
  4232. if (start_offset + 4000 < end_offset)
  4233. end_offset -= 4000;
  4234. // now compute an interpolated search loc
  4235. probe = start_offset + (int) floor((float) (end_offset - start_offset) / (end_sample - start_sample) * (sample_number - start_sample));
  4236. // next we need to bias towards binary search...
  4237. // code is a little wonky to allow for full 32-bit unsigned values
  4238. if (attempts >= 4) {
  4239. uint32 probe2 = start_offset + ((end_offset - start_offset) >> 1);
  4240. if (attempts >= 8)
  4241. probe = probe2;
  4242. else if (probe < probe2)
  4243. probe = probe + ((probe2 - probe) >> 1);
  4244. else
  4245. probe = probe2 + ((probe - probe2) >> 1);
  4246. }
  4247. ++attempts;
  4248. set_file_offset(f, probe);
  4249. if (!vorbis_find_page(f, NULL, NULL)) return error(f, VORBIS_seek_failed);
  4250. if (!vorbis_analyze_page(f, &q)) return error(f, VORBIS_seek_failed);
  4251. q.after_previous_page_start = probe;
  4252. // it's possible we've just found the last page again
  4253. if (q.page_start == p[1].page_start) {
  4254. p[1] = q;
  4255. continue;
  4256. }
  4257. if (sample_number < q.last_decoded_sample)
  4258. p[1] = q;
  4259. else
  4260. p[0] = q;
  4261. }
  4262. if (p[0].last_decoded_sample <= sample_number && sample_number < p[1].last_decoded_sample) {
  4263. vorbis_seek_frame_from_page(f, p[1].page_start, p[0].last_decoded_sample, sample_number, fine);
  4264. return 0;
  4265. }
  4266. return error(f, VORBIS_seek_failed);
  4267. }
  4268. }
  4269. int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
  4270. {
  4271. return vorbis_seek_base(f, sample_number, FALSE);
  4272. }
  4273. int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
  4274. {
  4275. return vorbis_seek_base(f, sample_number, TRUE);
  4276. }
  4277. void stb_vorbis_seek_start(stb_vorbis *f)
  4278. {
  4279. if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; }
  4280. set_file_offset(f, f->first_audio_page_offset);
  4281. f->previous_length = 0;
  4282. f->first_decode = TRUE;
  4283. f->next_seg = -1;
  4284. vorbis_pump_first_frame(f);
  4285. }
  4286. unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
  4287. {
  4288. unsigned int restore_offset, previous_safe;
  4289. unsigned int end, last_page_loc;
  4290. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  4291. if (!f->total_samples) {
  4292. int last;
  4293. uint32 lo,hi;
  4294. char header[6];
  4295. // first, store the current decode position so we can restore it
  4296. restore_offset = stb_vorbis_get_file_offset(f);
  4297. // now we want to seek back 64K from the end (the last page must
  4298. // be at most a little less than 64K, but let's allow a little slop)
  4299. if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
  4300. previous_safe = f->stream_len - 65536;
  4301. else
  4302. previous_safe = f->first_audio_page_offset;
  4303. set_file_offset(f, previous_safe);
  4304. // previous_safe is now our candidate 'earliest known place that seeking
  4305. // to will lead to the final page'
  4306. if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
  4307. // if we can't find a page, we're hosed!
  4308. f->error = VORBIS_cant_find_last_page;
  4309. f->total_samples = 0xffffffff;
  4310. goto done;
  4311. }
  4312. // check if there are more pages
  4313. last_page_loc = stb_vorbis_get_file_offset(f);
  4314. // stop when the last_page flag is set, not when we reach eof;
  4315. // this allows us to stop short of a 'file_section' end without
  4316. // explicitly checking the length of the section
  4317. while (!last) {
  4318. set_file_offset(f, end);
  4319. if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
  4320. // the last page we found didn't have the 'last page' flag
  4321. // set. whoops!
  4322. break;
  4323. }
  4324. previous_safe = last_page_loc+1;
  4325. last_page_loc = stb_vorbis_get_file_offset(f);
  4326. }
  4327. set_file_offset(f, last_page_loc);
  4328. // parse the header
  4329. getn(f, (unsigned char *)header, 6);
  4330. // extract the absolute granule position
  4331. lo = get32(f);
  4332. hi = get32(f);
  4333. if (lo == 0xffffffff && hi == 0xffffffff) {
  4334. f->error = VORBIS_cant_find_last_page;
  4335. f->total_samples = SAMPLE_unknown;
  4336. goto done;
  4337. }
  4338. if (hi)
  4339. lo = 0xfffffffe; // saturate
  4340. f->total_samples = lo;
  4341. f->p_last.page_start = last_page_loc;
  4342. f->p_last.page_end = end;
  4343. f->p_last.last_decoded_sample = lo;
  4344. f->p_last.first_decoded_sample = SAMPLE_unknown;
  4345. f->p_last.after_previous_page_start = previous_safe;
  4346. done:
  4347. set_file_offset(f, restore_offset);
  4348. }
  4349. return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
  4350. }
  4351. float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
  4352. {
  4353. return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
  4354. }
  4355. int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
  4356. {
  4357. int len, right,left,i;
  4358. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  4359. if (!vorbis_decode_packet(f, &len, &left, &right)) {
  4360. f->channel_buffer_start = f->channel_buffer_end = 0;
  4361. return 0;
  4362. }
  4363. len = vorbis_finish_frame(f, len, left, right);
  4364. for (i=0; i < f->channels; ++i)
  4365. f->outputs[i] = f->channel_buffers[i] + left;
  4366. f->channel_buffer_start = left;
  4367. f->channel_buffer_end = left+len;
  4368. if (channels) *channels = f->channels;
  4369. if (output) *output = f->outputs;
  4370. return len;
  4371. }
  4372. #ifndef STB_VORBIS_NO_STDIO
  4373. stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc, unsigned int length)
  4374. {
  4375. stb_vorbis *f, p;
  4376. vorbis_init(&p, alloc);
  4377. p.f = file;
  4378. p.f_start = ftell(file);
  4379. p.stream_len = length;
  4380. p.close_on_free = close_on_free;
  4381. if (start_decoder(&p)) {
  4382. f = vorbis_alloc(&p);
  4383. if (f) {
  4384. *f = p;
  4385. vorbis_pump_first_frame(f);
  4386. return f;
  4387. }
  4388. }
  4389. if (error) *error = p.error;
  4390. vorbis_deinit(&p);
  4391. return NULL;
  4392. }
  4393. stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc)
  4394. {
  4395. unsigned int len, start;
  4396. start = ftell(file);
  4397. fseek(file, 0, SEEK_END);
  4398. len = ftell(file) - start;
  4399. fseek(file, start, SEEK_SET);
  4400. return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
  4401. }
  4402. stb_vorbis * stb_vorbis_open_filename(char *filename, int *error, stb_vorbis_alloc *alloc)
  4403. {
  4404. FILE *f = fopen(filename, "rb");
  4405. if (f)
  4406. return stb_vorbis_open_file(f, TRUE, error, alloc);
  4407. if (error) *error = VORBIS_file_open_failure;
  4408. return NULL;
  4409. }
  4410. #endif // STB_VORBIS_NO_STDIO
  4411. stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len, int *error, stb_vorbis_alloc *alloc)
  4412. {
  4413. stb_vorbis *f, p;
  4414. if (data == NULL) return NULL;
  4415. vorbis_init(&p, alloc);
  4416. p.stream = data;
  4417. p.stream_end = data + len;
  4418. p.stream_start = p.stream;
  4419. p.stream_len = len;
  4420. p.push_mode = FALSE;
  4421. if (start_decoder(&p)) {
  4422. f = vorbis_alloc(&p);
  4423. if (f) {
  4424. *f = p;
  4425. vorbis_pump_first_frame(f);
  4426. return f;
  4427. }
  4428. }
  4429. if (error) *error = p.error;
  4430. vorbis_deinit(&p);
  4431. return NULL;
  4432. }
  4433. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  4434. #define PLAYBACK_MONO 1
  4435. #define PLAYBACK_LEFT 2
  4436. #define PLAYBACK_RIGHT 4
  4437. #define L (PLAYBACK_LEFT | PLAYBACK_MONO)
  4438. #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
  4439. #define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
  4440. static int8 channel_position[7][6] =
  4441. {
  4442. { 0 },
  4443. { C },
  4444. { L, R },
  4445. { L, C, R },
  4446. { L, R, L, R },
  4447. { L, C, R, L, R },
  4448. { L, C, R, L, R, C },
  4449. };
  4450. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  4451. typedef union {
  4452. float f;
  4453. int i;
  4454. } float_conv;
  4455. typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
  4456. #define FASTDEF(x) float_conv x
  4457. // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
  4458. #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
  4459. #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
  4460. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
  4461. #define check_endianness()
  4462. #else
  4463. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
  4464. #define check_endianness()
  4465. #define FASTDEF(x)
  4466. #endif
  4467. static void copy_samples(short *dest, float *src, int len)
  4468. {
  4469. int i;
  4470. check_endianness();
  4471. for (i=0; i < len; ++i) {
  4472. FASTDEF(temp);
  4473. int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
  4474. if ((unsigned int) (v + 32768) > 65535)
  4475. v = v < 0 ? -32768 : 32767;
  4476. dest[i] = v;
  4477. }
  4478. }
  4479. static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
  4480. {
  4481. #define BUFFER_SIZE 32
  4482. float buffer[BUFFER_SIZE];
  4483. int i,j,o,n = BUFFER_SIZE;
  4484. check_endianness();
  4485. for (o = 0; o < len; o += BUFFER_SIZE) {
  4486. memset(buffer, 0, sizeof(buffer));
  4487. if (o + n > len) n = len - o;
  4488. for (j=0; j < num_c; ++j) {
  4489. if (channel_position[num_c][j] & mask) {
  4490. for (i=0; i < n; ++i)
  4491. buffer[i] += data[j][d_offset+o+i];
  4492. }
  4493. }
  4494. for (i=0; i < n; ++i) {
  4495. FASTDEF(temp);
  4496. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  4497. if ((unsigned int) (v + 32768) > 65535)
  4498. v = v < 0 ? -32768 : 32767;
  4499. output[o+i] = v;
  4500. }
  4501. }
  4502. }
  4503. static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
  4504. static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
  4505. {
  4506. #define BUFFER_SIZE 32
  4507. float buffer[BUFFER_SIZE];
  4508. int i,j,o,n = BUFFER_SIZE >> 1;
  4509. // o is the offset in the source data
  4510. check_endianness();
  4511. for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
  4512. // o2 is the offset in the output data
  4513. int o2 = o << 1;
  4514. memset(buffer, 0, sizeof(buffer));
  4515. if (o + n > len) n = len - o;
  4516. for (j=0; j < num_c; ++j) {
  4517. int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
  4518. if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
  4519. for (i=0; i < n; ++i) {
  4520. buffer[i*2+0] += data[j][d_offset+o+i];
  4521. buffer[i*2+1] += data[j][d_offset+o+i];
  4522. }
  4523. } else if (m == PLAYBACK_LEFT) {
  4524. for (i=0; i < n; ++i) {
  4525. buffer[i*2+0] += data[j][d_offset+o+i];
  4526. }
  4527. } else if (m == PLAYBACK_RIGHT) {
  4528. for (i=0; i < n; ++i) {
  4529. buffer[i*2+1] += data[j][d_offset+o+i];
  4530. }
  4531. }
  4532. }
  4533. for (i=0; i < (n<<1); ++i) {
  4534. FASTDEF(temp);
  4535. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  4536. if ((unsigned int) (v + 32768) > 65535)
  4537. v = v < 0 ? -32768 : 32767;
  4538. output[o2+i] = v;
  4539. }
  4540. }
  4541. }
  4542. static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
  4543. {
  4544. int i;
  4545. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  4546. static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
  4547. for (i=0; i < buf_c; ++i)
  4548. compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
  4549. } else {
  4550. int limit = buf_c < data_c ? buf_c : data_c;
  4551. for (i=0; i < limit; ++i)
  4552. copy_samples(buffer[i]+b_offset, data[i], samples);
  4553. for ( ; i < buf_c; ++i)
  4554. memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
  4555. }
  4556. }
  4557. int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
  4558. {
  4559. float **output;
  4560. int len = stb_vorbis_get_frame_float(f, NULL, &output);
  4561. if (len > num_samples) len = num_samples;
  4562. if (len)
  4563. convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
  4564. return len;
  4565. }
  4566. static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
  4567. {
  4568. int i;
  4569. check_endianness();
  4570. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  4571. assert(buf_c == 2);
  4572. for (i=0; i < buf_c; ++i)
  4573. compute_stereo_samples(buffer, data_c, data, d_offset, len);
  4574. } else {
  4575. int limit = buf_c < data_c ? buf_c : data_c;
  4576. int j;
  4577. for (j=0; j < len; ++j) {
  4578. for (i=0; i < limit; ++i) {
  4579. FASTDEF(temp);
  4580. float f = data[i][d_offset+j];
  4581. int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
  4582. if ((unsigned int) (v + 32768) > 65535)
  4583. v = v < 0 ? -32768 : 32767;
  4584. *buffer++ = v;
  4585. }
  4586. for ( ; i < buf_c; ++i)
  4587. *buffer++ = 0;
  4588. }
  4589. }
  4590. }
  4591. int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
  4592. {
  4593. float **output;
  4594. int len;
  4595. if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
  4596. len = stb_vorbis_get_frame_float(f, NULL, &output);
  4597. if (len) {
  4598. if (len*num_c > num_shorts) len = num_shorts / num_c;
  4599. convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
  4600. }
  4601. return len;
  4602. }
  4603. int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
  4604. {
  4605. float **outputs;
  4606. int len = num_shorts / channels;
  4607. int n=0;
  4608. int z = f->channels;
  4609. if (z > channels) z = channels;
  4610. while (n < len) {
  4611. int k = f->channel_buffer_end - f->channel_buffer_start;
  4612. if (n+k >= len) k = len - n;
  4613. if (k)
  4614. convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  4615. buffer += k*channels;
  4616. n += k;
  4617. f->channel_buffer_start += k;
  4618. if (n == len) break;
  4619. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4620. }
  4621. return n;
  4622. }
  4623. int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
  4624. {
  4625. float **outputs;
  4626. int n=0;
  4627. int z = f->channels;
  4628. if (z > channels) z = channels;
  4629. while (n < len) {
  4630. int k = f->channel_buffer_end - f->channel_buffer_start;
  4631. if (n+k >= len) k = len - n;
  4632. if (k)
  4633. convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  4634. n += k;
  4635. f->channel_buffer_start += k;
  4636. if (n == len) break;
  4637. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4638. }
  4639. return n;
  4640. }
  4641. #ifndef STB_VORBIS_NO_STDIO
  4642. int stb_vorbis_decode_filename(char *filename, int *channels, short **output)
  4643. {
  4644. int data_len, offset, total, limit, error;
  4645. short *data;
  4646. stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
  4647. if (v == NULL) return -1;
  4648. limit = v->channels * 4096;
  4649. *channels = v->channels;
  4650. offset = data_len = 0;
  4651. total = limit;
  4652. data = (short *) malloc(total * sizeof(*data));
  4653. if (data == NULL) {
  4654. stb_vorbis_close(v);
  4655. return -2;
  4656. }
  4657. for (;;) {
  4658. int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
  4659. if (n == 0) break;
  4660. data_len += n;
  4661. offset += n * v->channels;
  4662. if (offset + limit > total) {
  4663. short *data2;
  4664. total *= 2;
  4665. data2 = (short *) realloc(data, total * sizeof(*data));
  4666. if (data2 == NULL) {
  4667. free(data);
  4668. stb_vorbis_close(v);
  4669. return -2;
  4670. }
  4671. data = data2;
  4672. }
  4673. }
  4674. *output = data;
  4675. return data_len;
  4676. }
  4677. #endif // NO_STDIO
  4678. int stb_vorbis_decode_memory(uint8 *mem, int len, int *channels, short **output)
  4679. {
  4680. int data_len, offset, total, limit, error;
  4681. short *data;
  4682. stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
  4683. if (v == NULL) return -1;
  4684. limit = v->channels * 4096;
  4685. *channels = v->channels;
  4686. offset = data_len = 0;
  4687. total = limit;
  4688. data = (short *) malloc(total * sizeof(*data));
  4689. if (data == NULL) {
  4690. stb_vorbis_close(v);
  4691. return -2;
  4692. }
  4693. for (;;) {
  4694. int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
  4695. if (n == 0) break;
  4696. data_len += n;
  4697. offset += n * v->channels;
  4698. if (offset + limit > total) {
  4699. short *data2;
  4700. total *= 2;
  4701. data2 = (short *) realloc(data, total * sizeof(*data));
  4702. if (data2 == NULL) {
  4703. free(data);
  4704. stb_vorbis_close(v);
  4705. return -2;
  4706. }
  4707. data = data2;
  4708. }
  4709. }
  4710. *output = data;
  4711. return data_len;
  4712. }
  4713. #endif
  4714. int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
  4715. {
  4716. float **outputs;
  4717. int len = num_floats / channels;
  4718. int n=0;
  4719. int z = f->channels;
  4720. if (z > channels) z = channels;
  4721. while (n < len) {
  4722. int i,j;
  4723. int k = f->channel_buffer_end - f->channel_buffer_start;
  4724. if (n+k >= len) k = len - n;
  4725. for (j=0; j < k; ++j) {
  4726. for (i=0; i < z; ++i)
  4727. *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
  4728. for ( ; i < channels; ++i)
  4729. *buffer++ = 0;
  4730. }
  4731. n += k;
  4732. f->channel_buffer_start += k;
  4733. if (n == len) break;
  4734. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4735. }
  4736. return n;
  4737. }
  4738. int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
  4739. {
  4740. float **outputs;
  4741. int n=0;
  4742. int z = f->channels;
  4743. if (z > channels) z = channels;
  4744. while (n < num_samples) {
  4745. int i;
  4746. int k = f->channel_buffer_end - f->channel_buffer_start;
  4747. if (n+k >= num_samples) k = num_samples - n;
  4748. if (k) {
  4749. for (i=0; i < z; ++i)
  4750. memcpy(buffer[i]+n, f->channel_buffers+f->channel_buffer_start, sizeof(float)*k);
  4751. for ( ; i < channels; ++i)
  4752. memset(buffer[i]+n, 0, sizeof(float) * k);
  4753. }
  4754. n += k;
  4755. f->channel_buffer_start += k;
  4756. if (n == num_samples) break;
  4757. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4758. }
  4759. return n;
  4760. }
  4761. #endif // STB_VORBIS_NO_PULLDATA_API
  4762. #endif // STB_VORBIS_HEADER_ONLY