stb_vorbis.h 183 KB

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