stb_vorbis.c 183 KB

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