stb_vorbis.c 188 KB

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