stb_vorbis.c 165 KB

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