stb_vorbis.c 167 KB

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