apck.h 353 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578
  1. /*
  2. * apck.h - Asset Pack (unpacker)
  3. * https://gitlab.com/bztsrc/assetpack
  4. *
  5. * Copyright (C) 2024 bzt, MIT license
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to
  9. * deal in the Software without restriction, including without limitation the
  10. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  11. * sell copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ANY
  20. * DEVELOPER OR DISTRIBUTOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  22. * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. *
  24. * @brief Asset Pack single header library
  25. */
  26. #ifndef APCK_H
  27. #define APCK_H
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. #include <stdint.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #define APCK_MAGIC "APCK"
  35. #ifdef _MSC_VER
  36. #pragma pack(push)
  37. #pragma pack(1)
  38. #define _PACK
  39. #else
  40. #define _PACK __attribute__((packed))
  41. #endif
  42. typedef struct {
  43. uint8_t magic[4];
  44. uint32_t hdr_size;
  45. uint8_t engine[12];
  46. uint32_t version;
  47. uint32_t size;
  48. uint32_t chksum;
  49. uint8_t enckey[32];
  50. } _PACK apck_hdr_t;
  51. #ifdef _MSC_VER
  52. #pragma pack(pop)
  53. #endif
  54. #undef _PACK
  55. #ifndef DBG
  56. #define DBG(a)
  57. #endif
  58. #ifndef __THROW
  59. #define __THROW
  60. #endif
  61. int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen);
  62. uint8_t *stbi_load_from_memory(uint8_t const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  63. int stb_vorbis_decode_memory(const uint8_t *mem, int len, int *channels, int *sample_rate, short **output);
  64. enum { APCK_OK, APCK_ERR_BADINP, APCK_ERR_BADPCK, APCK_ERR_NOMEM };
  65. enum { APCK_LOCALE, APCK_FONT = 32, APCK_BGM, APCK_SFX, APCK_VIDEO, APCK_MODEL, APCK_IMAGE, APCK_ATLAS, APCK_SPRITE, APCK_MAP,
  66. APCK_OBJECT = 46, APCK_SCRIPT, APCK_DATA01, APCK_DATA02, APCK_DATA03, APCK_DATA04, APCK_DATA05, APCK_DATA06, APCK_DATA07,
  67. APCK_DATA08, APCK_DATA09, APCK_DATA10, APCK_DATA11, APCK_DATA12, APCK_DATA13, APCK_DATA14, APCK_DATA15, APCK_DATA16,
  68. APCK_NUMTYPES };
  69. enum { APCK_REGULAR = 0, APCK_BOLD = 1, APCK_ITALIC = 2, APCK_UNDERLINE = 16, APCK_STRIKETHROUGH = 32 };
  70. #define APCK_COMPRESSED(c,i) (((c) < APCK_FONT && !(i)) || (c) == APCK_FONT || ((c) >= APCK_SPRITE && (c) <= APCK_SCRIPT))
  71. typedef void* (*apck_initcb_t)(uint8_t *enckey);
  72. typedef int (*apck_readcb_t)(void *enc, uint64_t offs, uint8_t *buf, uint64_t size);
  73. typedef struct {
  74. void *f;
  75. uint64_t size;
  76. uint8_t *str;
  77. uint32_t aidx;
  78. void *enc;
  79. } apck_archive_t;
  80. typedef struct {
  81. int archive, w, h;
  82. char *name;
  83. uint32_t str;
  84. uint64_t offs;
  85. uint64_t size;
  86. uint64_t comp;
  87. uint8_t *buf;
  88. } apck_file_t;
  89. typedef struct {
  90. char engine[16];
  91. uint32_t version;
  92. uint32_t numarchive;
  93. uint32_t numfiles[APCK_NUMTYPES];
  94. apck_initcb_t initcb;
  95. apck_readcb_t readcb;
  96. apck_archive_t *archives;
  97. apck_file_t *files[APCK_NUMTYPES];
  98. uint32_t locale, *msgstr[APCK_FONT];
  99. void *font;
  100. } apck_t;
  101. uint8_t *apck_uleb128(uint8_t *ptr, uint64_t *value);
  102. uint32_t apck_crc32(uint8_t *buf, uint32_t size);
  103. int apck_init(apck_t *ctx, char *engine, uint32_t version, apck_initcb_t initcb, apck_readcb_t readcb);
  104. uint8_t *apck_readbuf(apck_t *ctx, uint32_t archive, uint64_t offs, uint64_t size);
  105. uint64_t apck_read(apck_t *ctx, uint32_t archive, uint64_t offs, uint8_t *buf, uint64_t size);
  106. int apck_load(apck_t *ctx, char *fn);
  107. int apck_free(apck_t *ctx);
  108. int apck_release(apck_t *ctx, int type, char *name);
  109. apck_file_t *apck_lookup(apck_t *ctx, int type, char *name);
  110. uint8_t *apck_asset(apck_t *ctx, int type, char *name, uint64_t *size);
  111. uint32_t *apck_image(apck_t *ctx, int type, char *name, int *w, int *h);
  112. int16_t *apck_audio(apck_t *ctx, int type, char *name, int *numsamples, int *channels);
  113. int apck_font(apck_t *ctx, char *name);
  114. uint32_t *apck_text(apck_t *ctx, char *msgid, uint32_t color, int fontstyle, int fontsize, int *w, int *h);
  115. /**************** embeded apck_file.h ****************/
  116. #ifndef APCK_FILE_H
  117. #define APCK_FILE_H
  118. #ifdef __WIN32__
  119. #include <windows.h>
  120. #include <winnls.h>
  121. #include <fileapi.h>
  122. #include <wchar.h>
  123. void apck_utf8_ucs2(char *fn, wchar_t *szFn);
  124. #else
  125. #include <unistd.h>
  126. #endif
  127. #include <stdio.h>
  128. #include <sys/types.h>
  129. #include <sys/stat.h>
  130. #include <limits.h>
  131. #ifndef PATH_MAX
  132. #define PATH_MAX 4096
  133. #endif
  134. #ifndef FILENAME_MAX
  135. #define FILENAME_MAX 255
  136. #endif
  137. void *apck_fileopen(char *fn, uint64_t *size);
  138. void *apck_fileopenw(char *fn);
  139. uint64_t apck_filewrite(void *f, void *buf, uint64_t size);
  140. uint64_t apck_fileread(void *f, void *buf, uint64_t size);
  141. void apck_fileseek(void *f, uint64_t offs);
  142. void apck_fileclose(void *f);
  143. #ifdef APCK_IMPLEMENTATION
  144. #ifdef __WIN32__
  145. void apck_utf8_ucs2(char *fn, wchar_t *szFn)
  146. {
  147. int i;
  148. memset(szFn, 0, 2*(PATH_MAX + FILENAME_MAX + 1));
  149. MultiByteToWideChar(CP_UTF8, 0, fn, -1, szFn, PATH_MAX + FILENAME_MAX);
  150. for(i = 0; szFn[i]; i++) if(szFn[i] == L'/') szFn[i] = L'\\';
  151. }
  152. #endif
  153. void *apck_fileopen(char *fn, uint64_t *size)
  154. {
  155. #ifdef __WIN32__
  156. struct _stat64 st;
  157. static wchar_t szFn[PATH_MAX + FILENAME_MAX + 1];
  158. HANDLE f;
  159. if(size) *size = 0;
  160. if(!fn || !*fn) return NULL;
  161. apck_utf8_ucs2(fn, (wchar_t*)szFn);
  162. if(_wstat64(szFn, &st) || !S_ISREG(st.st_mode)) return NULL;
  163. f = CreateFileW(szFn, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  164. if(f == INVALID_HANDLE_VALUE) f = NULL;
  165. #else
  166. struct stat st;
  167. FILE *f;
  168. if(size) *size = 0;
  169. if(!fn || !*fn || (size && (stat(fn, &st) || !S_ISREG(st.st_mode)))) return NULL;
  170. f = fopen(fn, "rb");
  171. #endif
  172. if(size) *size = (uint64_t)st.st_size;
  173. return (void*)f;
  174. }
  175. void *apck_fileopenw(char *fn)
  176. {
  177. #ifdef __WIN32__
  178. wchar_t szFn[PATH_MAX + FILENAME_MAX + 1];
  179. HANDLE f;
  180. if(!fn || !*fn) return NULL;
  181. apck_utf8_ucs2(fn, szFn);
  182. f = CreateFileW(szFn, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  183. if(f == INVALID_HANDLE_VALUE) f = NULL;
  184. #else
  185. FILE *f;
  186. if(!fn || !*fn) return NULL;
  187. f = fopen(fn, "wb");
  188. #endif
  189. return (void*)f;
  190. }
  191. uint64_t apck_filewrite(void *f, void *buf, uint64_t size)
  192. {
  193. #ifdef __WIN32__
  194. DWORD t;
  195. if(!f || !buf || !size) return 0;
  196. if(!WriteFile((HANDLE)f, buf, (DWORD)size, &t, NULL)) t = 0;
  197. return (uint64_t)t;
  198. #else
  199. if(!f || !buf || !size) return 0;
  200. return (uint64_t)fwrite(buf, 1, size, (FILE*)f);
  201. #endif
  202. }
  203. uint64_t apck_fileread(void *f, void *buf, uint64_t size)
  204. {
  205. #ifdef __WIN32__
  206. DWORD t;
  207. if(!f || !buf || !size) return 0;
  208. if(!ReadFile((HANDLE)f, buf, (DWORD)size, &t, NULL)) t = 0;
  209. return (uint64_t)t;
  210. #else
  211. if(!f || !buf || !size) return 0;
  212. return (uint64_t)fread(buf, 1, (size_t)size, (FILE*)f);
  213. #endif
  214. }
  215. void apck_fileseek(void *f, uint64_t offs)
  216. {
  217. #ifdef __WIN32__
  218. LARGE_INTEGER pos;
  219. pos.QuadPart = offs;
  220. SetFilePointerEx((HANDLE)f, pos, NULL, FILE_BEGIN);
  221. #else
  222. fseek((FILE*)f, offs, SEEK_SET);
  223. #endif
  224. }
  225. void apck_fileclose(void *f)
  226. {
  227. if(f) {
  228. #ifdef __WIN32__
  229. CloseHandle((HANDLE)f);
  230. #else
  231. fclose((FILE*)f);
  232. #endif
  233. }
  234. }
  235. #endif
  236. #endif
  237. /**************** embeded apck_map.h ****************/
  238. #ifndef APCK_MAP_H
  239. #define APCK_MAP_H
  240. enum { APCK_ORTHOGONAL = 'o', APCK_ISOMETRIC = 'i', APCK_VERTHEX = 'v', APCK_HORIZHEX = 'h' };
  241. typedef struct {
  242. uint8_t *v;
  243. uint32_t x, y;
  244. } apck_map_list_t;
  245. typedef struct {
  246. int type, disptype;
  247. int offX, offY;
  248. int parX, parY;
  249. int movX, movY;
  250. uint32_t size;
  251. uint8_t *data;
  252. } apck_map_layer_t;
  253. typedef struct {
  254. int type, tilew, tileh, w, h, l, proplen;
  255. uint8_t *properties;
  256. apck_map_layer_t *layers;
  257. } apck_map_t;
  258. apck_map_t *apck_map_new(int type, int tilew, int tileh, int w, int h, int proplen, uint8_t *properties);
  259. apck_map_layer_t *apck_map_layer(apck_map_t *map, int type, uint32_t datasize, void *data);
  260. int apck_map_free(apck_map_t *map);
  261. apck_map_t *apck_map_decode(uint8_t *str, uint8_t *buf, uint64_t size);
  262. #ifdef APCK_IMPLEMENTATION
  263. apck_map_t *apck_map_new(int type, int tilew, int tileh, int w, int h, int proplen, uint8_t *properties)
  264. {
  265. apck_map_t *ret;
  266. if(tilew < 1 || tileh < 1 || w < 1 || h < 1 || !(ret = (apck_map_t*)malloc(sizeof(apck_map_t))))
  267. return NULL;
  268. memset(ret, 0, sizeof(apck_map_t));
  269. ret->type = type;
  270. ret->tilew = tilew;
  271. ret->tileh = tileh;
  272. ret->w = w;
  273. ret->h = h;
  274. if(proplen && properties && (ret->properties = (uint8_t*)malloc(proplen))) {
  275. ret->proplen = proplen;
  276. memcpy(ret->properties, properties, proplen);
  277. }
  278. return ret;
  279. }
  280. apck_map_layer_t *apck_map_layer(apck_map_t *map, int type, uint32_t datasize, void *data)
  281. {
  282. int i;
  283. uint32_t l = 0;
  284. if(!map) return NULL;
  285. if(type == APCK_SPRITE) l = datasize * sizeof(apck_map_list_t); else
  286. if(type == APCK_MAP) l = map->w * map->h * sizeof(uint32_t); else {
  287. if(!data) return NULL;
  288. if(type >= APCK_OBJECT) l = datasize;
  289. else l = strlen((char*)data) + 1;
  290. }
  291. i = map->l++;
  292. if(!(map->layers = (apck_map_layer_t*)realloc(map->layers, map->l * sizeof(apck_map_layer_t)))) {
  293. map->l = 0;
  294. return NULL;
  295. }
  296. memset(&map->layers[i], 0, sizeof(apck_map_layer_t));
  297. map->layers[i].type = type;
  298. map->layers[i].parX = map->layers[i].parY = map->layers[i].movX = map->layers[i].movY = 100;
  299. if(l) {
  300. if(!(map->layers[i].data = (uint8_t*)malloc(l))) {
  301. map->l--;
  302. return NULL;
  303. }
  304. memset(map->layers[i].data, 0, l);
  305. map->layers[i].size = l;
  306. if(type != APCK_MAP && type != APCK_SPRITE && data)
  307. memcpy(map->layers[i].data, data, l);
  308. }
  309. return &map->layers[i];
  310. }
  311. int apck_map_free(apck_map_t *map)
  312. {
  313. int i;
  314. if(!map) return APCK_ERR_BADINP;
  315. if(map->layers) {
  316. for(i = 0; i < map->l; i++)
  317. if(map->layers[i].data)
  318. free(map->layers[i].data);
  319. free(map->layers);
  320. }
  321. if(map->properties)
  322. free(map->properties);
  323. free(map);
  324. return APCK_OK;
  325. }
  326. apck_map_t *apck_map_decode(uint8_t *str, uint8_t *buf, uint64_t size)
  327. {
  328. apck_map_t *map = NULL;
  329. apck_map_layer_t *layer;
  330. apck_map_list_t *list;
  331. uint64_t i, j, k, n, s, tw, th, w, h, l, parX, parY, offX, offY, movX, movY, type, disptype;
  332. uint32_t *data;
  333. uint8_t *ptr = buf + 4;
  334. if(!str || !buf || !size || memcmp(buf, "MAP", 3)) return NULL;
  335. ptr = apck_uleb128(ptr, &tw);
  336. ptr = apck_uleb128(ptr, &th);
  337. ptr = apck_uleb128(ptr, &w);
  338. ptr = apck_uleb128(ptr, &h);
  339. ptr = apck_uleb128(ptr, &l);
  340. ptr = apck_uleb128(ptr, &n);
  341. if(!(map = apck_map_new(buf[3], tw, th, w, h, n, ptr)))
  342. return NULL;
  343. ptr += n;
  344. for(j = 0; j < l; j++) {
  345. ptr = apck_uleb128(ptr, &type);
  346. ptr = apck_uleb128(ptr, &disptype);
  347. ptr = apck_uleb128(ptr, &offX);
  348. ptr = apck_uleb128(ptr, &offY);
  349. ptr = apck_uleb128(ptr, &parX);
  350. ptr = apck_uleb128(ptr, &parY);
  351. ptr = apck_uleb128(ptr, &movX);
  352. ptr = apck_uleb128(ptr, &movY);
  353. if(type != APCK_MAP)
  354. ptr = apck_uleb128(ptr, &s);
  355. else
  356. s = 0;
  357. if((layer = apck_map_layer(map, type, s,
  358. type >= APCK_OBJECT ? ptr : (type != APCK_MAP && type != APCK_SPRITE && str && s ? str + s : NULL)))) {
  359. layer->disptype = disptype;
  360. layer->offX = offX; layer->offY = offY;
  361. layer->parX = parX; layer->parY = parY;
  362. layer->movX = movX - 100; layer->movY = movY - 100;
  363. if(type == APCK_MAP) {
  364. data = (uint32_t*)layer->data;
  365. for(i = 0, n = w * h; i < n;) {
  366. s = ((*ptr++) & 0x7F) + 1;
  367. if(ptr[-1] & 0x80) {
  368. ptr = apck_uleb128(ptr, &k);
  369. while(s-- && i < n) { data[i++] = k; }
  370. } else
  371. while(s-- && i < n) { ptr = apck_uleb128(ptr, &k); data[i++] = k; }
  372. }
  373. } else
  374. if(type == APCK_SPRITE) {
  375. list = (apck_map_list_t*)layer->data;
  376. for(i = 0; i < s; i++) {
  377. ptr = apck_uleb128(ptr, &k); list[i].v = str + k;
  378. ptr = apck_uleb128(ptr, &k); list[i].x = k;
  379. ptr = apck_uleb128(ptr, &k); list[i].y = k;
  380. }
  381. } else
  382. if(type >= APCK_OBJECT)
  383. ptr += s;
  384. } else
  385. break;
  386. }
  387. return map;
  388. }
  389. #endif
  390. #endif
  391. /**************** embeded apck_locale.h ****************/
  392. #ifndef APCK_LOCALE_H
  393. #define APCK_LOCALE_H
  394. int apck_setlocale(apck_t *ctx, char *locale);
  395. char *apck_msgstr(apck_t *ctx, char *msgid);
  396. #ifdef APCK_IMPLEMENTATION
  397. static char *_apck_sort_msgid = NULL;
  398. int _apck_msgidcmp(const void *a, const void *b)
  399. {
  400. if(!_apck_sort_msgid) return 0;
  401. return strcmp(_apck_sort_msgid + *((uint32_t*)a), _apck_sort_msgid + *((uint32_t*)b));
  402. }
  403. static int _apck_merge_locale(apck_t *ctx, uint32_t locale, char *str, uint32_t size)
  404. {
  405. char *msgid, *msgstr, *ptr, *end;
  406. int i;
  407. if(!(ctx->files[locale][0].buf = (uint8_t*)realloc(ctx->files[locale][0].buf, ctx->files[locale][0].size + size))) {
  408. DBG(("unable to allocate memory for locale %u strings\n", locale));
  409. return 0;
  410. }
  411. _apck_sort_msgid = (char*)ctx->files[locale][0].buf;
  412. ptr = (char*)ctx->files[locale][0].buf + ctx->files[locale][0].size;
  413. end = ptr + size;
  414. memcpy(ptr, str, size);
  415. ctx->files[locale][0].size += size;
  416. while(ptr < end) {
  417. msgid = ptr; ptr += strlen(ptr) + 1;
  418. msgstr = ptr; ptr += strlen(ptr) + 1;
  419. for(i = 0; i < ctx->files[locale][0].w && strcmp(_apck_sort_msgid + ctx->msgstr[locale][i * 2], msgid); i++);
  420. if(i >= ctx->files[locale][0].w) {
  421. i = ctx->files[locale][0].w++;
  422. if(!(ctx->msgstr[locale] = (uint32_t*)realloc(ctx->msgstr[locale], ctx->files[locale][0].w * 2 * sizeof(uint32_t)))) {
  423. DBG(("unable to allocate memory for locale %u index\n", locale));
  424. ctx->files[locale][0].w = 0;
  425. return 0;
  426. }
  427. ctx->msgstr[locale][i * 2] = msgid - _apck_sort_msgid;
  428. }
  429. ctx->msgstr[locale][i * 2 + 1] = msgstr - _apck_sort_msgid;
  430. }
  431. if(ctx->files[locale][0].w && ctx->msgstr[locale])
  432. qsort(ctx->msgstr[locale], ctx->files[locale][0].w, 2 * sizeof(uint32_t), _apck_msgidcmp);
  433. return 1;
  434. }
  435. int apck_setlocale(apck_t *ctx, char *locale)
  436. {
  437. uint32_t i;
  438. if(!ctx || !locale || !*locale) return APCK_ERR_BADINP;
  439. for(i = 0; i < APCK_FONT && ctx->files[i] && strcmp(ctx->files[i][0].name, locale); i++);
  440. if(i >= APCK_FONT) {
  441. for(i = 0; i < APCK_FONT && ctx->files[i] && memcmp(ctx->files[i][0].name, locale, 2); i++);
  442. if(i >= APCK_FONT) return APCK_ERR_BADINP;
  443. }
  444. if(!ctx->msgstr[i]) return APCK_ERR_BADINP;
  445. ctx->locale = i;
  446. return APCK_OK;
  447. }
  448. char *apck_msgstr(apck_t *ctx, char *msgid)
  449. {
  450. uint32_t *idx;
  451. char *str;
  452. int s = 0, e, h, m;
  453. if(!ctx || !msgid || !*msgid || ctx->locale >= APCK_FONT || !ctx->msgstr[ctx->locale] ||
  454. !ctx->files[ctx->locale] || !ctx->files[ctx->locale][0].w || !ctx->files[ctx->locale][0].buf)
  455. return msgid;
  456. str = (char*)ctx->files[ctx->locale][0].buf;
  457. idx = ctx->msgstr[ctx->locale];
  458. e = ctx->files[ctx->locale][0].w - 1;
  459. while(s <= e) {
  460. h = ((e + s) >> 1);
  461. m = strcmp(str + idx[h * 2], msgid);
  462. if(!m) return str + idx[h * 2 + 1];
  463. if(m > 0) e = h - 1; else s = h + 1;
  464. }
  465. return msgid;
  466. }
  467. #endif
  468. #endif
  469. /**************** embeded apck_sprite.h ****************/
  470. #ifndef APCK_SPRITE_H
  471. #define APCK_SPRITE_H
  472. enum { APCK_ANIM_LOOP, APCK_ANIM_ONCE, APCK_ANIM_BF, APCK_TILE_WANG, APCK_TILE_WALL };
  473. enum { APCK_DIR_S, APCK_DIR_SW, APCK_DIR_W, APCK_DIR_NW, APCK_DIR_N, APCK_DIR_NE, APCK_DIR_E, APCK_DIR_SE, APCK_NUMDIR };
  474. enum { APCK_M_COPY, APCK_M_FLIPV, APCK_M_FLIPH, APCK_M_ROT90, APCK_M_ROT180, APCK_M_ROT270 };
  475. typedef struct {
  476. int atlas, m, w, h, sx, sy, dx, dy, dur;
  477. void *sfx;
  478. } apck_frame_t;
  479. typedef struct {
  480. int type, w, h, nf[APCK_NUMDIR];
  481. apck_frame_t *frames[APCK_NUMDIR];
  482. } apck_sprite_t;
  483. apck_sprite_t *apck_sprite_new(int type, int w, int h);
  484. int apck_sprite_frame(apck_sprite_t *sprite, int dir, int atlas, int m, int w, int h, int sx, int sy, int dx, int dy, int dur, char *sfx);
  485. int apck_sprite_free(apck_sprite_t *sprite);
  486. apck_sprite_t *apck_sprite_decode(uint32_t archive, uint8_t *str, uint8_t *buf, uint64_t size);
  487. void apck_sprite_pose(apck_t *ctx, apck_sprite_t *sprite, int dir, int frame, uint32_t *buf, int x, int y, int w, int h, int p);
  488. #ifdef APCK_IMPLEMENTATION
  489. apck_sprite_t *apck_sprite_new(int type, int w, int h)
  490. {
  491. apck_sprite_t *ret;
  492. if(w < 1 || w > 65535 || h < 1 || h > 65535 || !(ret = (apck_sprite_t*)malloc(sizeof(apck_sprite_t))))
  493. return NULL;
  494. memset(ret, 0, sizeof(apck_sprite_t));
  495. ret->type = type < APCK_ANIM_LOOP || type > APCK_ANIM_BF ? APCK_ANIM_LOOP : type;
  496. ret->w = w;
  497. ret->h = h;
  498. return ret;
  499. }
  500. int apck_sprite_frame(apck_sprite_t *sprite, int dir, int atlas, int m, int w, int h, int sx, int sy, int dx, int dy, int dur, char *sfx)
  501. {
  502. int i;
  503. if(!sprite || dir < APCK_DIR_S || dir >= APCK_NUMDIR || m < APCK_M_COPY || m > APCK_M_ROT270 ||
  504. w < 1 || h < 1 || sx < 0 || sy < 0 || dx < 0 || dx >= sprite->w || dy < 0 || dy >= sprite->h)
  505. return APCK_ERR_BADINP;
  506. if(dur < 1) dur = 1;
  507. if(dur > 65535) dur = 65535;
  508. if(dx + w > sprite->w) w = sprite->w - dx;
  509. if(dy + h > sprite->h) h = sprite->h - dy;
  510. i = sprite->nf[dir]++;
  511. if(!(sprite->frames[dir] = (apck_frame_t*)realloc(sprite->frames[dir], sprite->nf[dir] * sizeof(apck_frame_t)))) {
  512. sprite->nf[dir] = 0;
  513. return APCK_ERR_NOMEM;
  514. }
  515. sprite->frames[dir][i].m = m;
  516. sprite->frames[dir][i].w = w;
  517. sprite->frames[dir][i].h = h;
  518. sprite->frames[dir][i].sx = sx;
  519. sprite->frames[dir][i].sy = sy;
  520. sprite->frames[dir][i].dx = dx;
  521. sprite->frames[dir][i].dy = dy;
  522. sprite->frames[dir][i].dur = dur;
  523. sprite->frames[dir][i].atlas = atlas;
  524. sprite->frames[dir][i].sfx = sfx;
  525. return APCK_OK;
  526. }
  527. int apck_sprite_free(apck_sprite_t *sprite)
  528. {
  529. int i;
  530. if(!sprite) return APCK_ERR_BADINP;
  531. for(i = 0; i < APCK_NUMDIR; i++)
  532. if(sprite->frames[i])
  533. free(sprite->frames[i]);
  534. free(sprite);
  535. return APCK_OK;
  536. }
  537. apck_sprite_t *apck_sprite_decode(uint32_t aidx, uint8_t *str, uint8_t *buf, uint64_t size)
  538. {
  539. apck_sprite_t *sprite = NULL;
  540. uint64_t i, j, k, w, h, t, l;
  541. uint8_t *ptr = buf + 4;
  542. if(!str || !buf || !size || memcmp(buf, "SPFR", 4)) return NULL;
  543. ptr = apck_uleb128(ptr, &t);
  544. ptr = apck_uleb128(ptr, &w);
  545. ptr = apck_uleb128(ptr, &h);
  546. if(!(sprite = apck_sprite_new(t, w, h)))
  547. return NULL;
  548. for(j = 0; j < APCK_NUMDIR; j++) {
  549. ptr = apck_uleb128(ptr, &l);
  550. sprite->nf[j] = l;
  551. if((sprite->frames[j] = (apck_frame_t*)realloc(sprite->frames[j], sprite->nf[j] * sizeof(apck_frame_t)))) {
  552. for(i = 0; i < l; i++) {
  553. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].atlas = aidx + k;
  554. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].m = k;
  555. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].w = k;
  556. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].h = k;
  557. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].sx = k;
  558. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].sy = k;
  559. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].dx = k;
  560. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].dy = k;
  561. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].dur = k;
  562. ptr = apck_uleb128(ptr, &k); sprite->frames[j][i].sfx = str && k ? str + k : NULL;
  563. }
  564. } else
  565. sprite->nf[j] = 0;
  566. }
  567. return sprite;
  568. }
  569. void apck_sprite_pose(apck_t *ctx, apck_sprite_t *sprite, int dir, int frame, uint32_t *buf, int x, int y, int w, int h, int p)
  570. {
  571. apck_file_t *atlas;
  572. apck_frame_t *f;
  573. uint8_t *fbuf;
  574. uint32_t *src, *dst;
  575. int X, Y, W, H;
  576. if(!sprite || dir < APCK_DIR_S || dir >= APCK_NUMDIR || frame < 0 || !sprite->frames[dir] || !buf || w < 1 || h < 1 ||
  577. p < 4 || x >= w || y >= h)
  578. return;
  579. p >>= 2;
  580. f = &sprite->frames[dir][frame % sprite->nf[dir]];
  581. if(f->atlas >= (int)ctx->numfiles[APCK_ATLAS]) return;
  582. atlas = &ctx->files[APCK_ATLAS][f->atlas];
  583. if(!atlas->buf || !atlas->w || !atlas->h) {
  584. if(atlas->size && (fbuf = apck_readbuf(ctx, atlas->archive, atlas->offs, atlas->size))) {
  585. if(!(atlas->buf = (uint8_t*)stbi_load_from_memory(fbuf, atlas->size, &atlas->w, &atlas->h, &W, 4)))
  586. atlas->size = atlas->comp = atlas->w = atlas->h = 0;
  587. free(fbuf);
  588. }
  589. if(!atlas->buf || !atlas->w || !atlas->h) return;
  590. }
  591. W = f->w;
  592. if(x + W > w) W = w - x;
  593. if(f->sx + W > atlas->w) W = atlas->w - f->sx;
  594. H = f->h;
  595. if(y + H > h) H = h - y;
  596. if(f->sy + H > atlas->h) H = atlas->h - f->sy;
  597. if(W < 1 || H < 1) return;
  598. src = (uint32_t*)atlas->buf + f->sy * atlas->w + f->sx;
  599. dst = buf + (y + f->dy) * p + x + f->dx;
  600. switch(f->m) {
  601. case APCK_M_ROT270:
  602. for(Y = 0; Y < H; Y++, dst += p)
  603. for(X = 0; X < W; X++)
  604. dst[X] = src[(H - 1 - X) * atlas->w + Y];
  605. break;
  606. case APCK_M_ROT180:
  607. src += (f->h - 1) * atlas->w;
  608. for(Y = 0; Y < H; Y++, src -= atlas->w, dst += p)
  609. for(X = 0; X < W; X++)
  610. dst[X] = src[f->w - 1 - X];
  611. break;
  612. case APCK_M_ROT90:
  613. for(Y = 0; Y < H; Y++, dst += p)
  614. for(X = 0; X < W; X++)
  615. dst[X] = src[X * atlas->w + f->w - 1 - Y];
  616. break;
  617. case APCK_M_FLIPH:
  618. src += (f->h - 1) * atlas->w;
  619. for(Y = 0; Y < H; Y++, src -= atlas->w, dst += p)
  620. memcpy(dst, src, W * 4);
  621. break;
  622. case APCK_M_FLIPV:
  623. for(Y = 0; Y < H; Y++, src += atlas->w, dst += p)
  624. for(X = 0; X < W; X++)
  625. dst[X] = src[f->w - 1 - X];
  626. break;
  627. default:
  628. for(Y = 0; Y < H; Y++, src += atlas->w, dst += p)
  629. memcpy(dst, src, W * 4);
  630. break;
  631. }
  632. }
  633. #endif
  634. #endif
  635. apck_map_t *apck_map(apck_t *ctx, char *name);
  636. #ifdef APCK_IMPLEMENTATION
  637. #define inline __inline__
  638. #ifndef STB_IMAGE_IMPLEMENTATION
  639. #define STB_IMAGE_IMPLEMENTATION
  640. #define STBI_NO_FAILURE_STRINGS
  641. #define STBI_NO_STDIO
  642. #define STBI_NO_LINEAR
  643. #define STBI_ONLY_PNG
  644. /* stb_image - v2.30 - public domain image loader - http://nothings.org/stb
  645. no warranty implied; use at your own risk
  646. https://github.com/nothings/stb */
  647. /**************** embeded stb_image.h ****************/
  648. #ifndef STBI_INCLUDE_STB_IMAGE_H
  649. #define STBI_INCLUDE_STB_IMAGE_H
  650. #define STBI_VERSION 1
  651. enum
  652. {
  653. STBI_default = 0,
  654. STBI_grey = 1,
  655. STBI_grey_alpha = 2,
  656. STBI_rgb = 3,
  657. STBI_rgb_alpha = 4
  658. };
  659. #include <stdlib.h>
  660. typedef unsigned char stbi_uc;
  661. typedef unsigned short stbi_us;
  662. #ifdef __cplusplus
  663. extern "C" {
  664. #endif
  665. #ifndef STBIDEF
  666. #ifdef STB_IMAGE_STATIC
  667. #define STBIDEF static
  668. #else
  669. #define STBIDEF extern
  670. #endif
  671. #endif
  672. typedef struct
  673. {
  674. int (*read) (void *user,char *data,int size);
  675. void (*skip) (void *user,int n);
  676. int (*eof) (void *user);
  677. } stbi_io_callbacks;
  678. STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels);
  679. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels);
  680. #ifdef STBI_WINDOWS_UTF8
  681. STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
  682. #endif
  683. STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
  684. STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
  685. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  686. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
  687. STBIDEF const char *stbi_failure_reason (void);
  688. STBIDEF void stbi_image_free (void *retval_from_stbi_load);
  689. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
  690. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
  691. STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len);
  692. STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  693. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
  694. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
  695. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
  696. STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
  697. STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
  698. STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
  699. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
  700. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
  701. STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
  702. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  703. STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
  704. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  705. #ifdef __cplusplus
  706. }
  707. #endif
  708. #endif
  709. #ifdef STB_IMAGE_IMPLEMENTATION
  710. #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
  711. || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
  712. || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
  713. || defined(STBI_ONLY_ZLIB)
  714. #ifndef STBI_ONLY_JPEG
  715. #define STBI_NO_JPEG
  716. #endif
  717. #ifndef STBI_ONLY_PNG
  718. #define STBI_NO_PNG
  719. #endif
  720. #ifndef STBI_ONLY_BMP
  721. #define STBI_NO_BMP
  722. #endif
  723. #ifndef STBI_ONLY_PSD
  724. #define STBI_NO_PSD
  725. #endif
  726. #ifndef STBI_ONLY_TGA
  727. #define STBI_NO_TGA
  728. #endif
  729. #ifndef STBI_ONLY_GIF
  730. #define STBI_NO_GIF
  731. #endif
  732. #ifndef STBI_ONLY_HDR
  733. #define STBI_NO_HDR
  734. #endif
  735. #ifndef STBI_ONLY_PIC
  736. #define STBI_NO_PIC
  737. #endif
  738. #ifndef STBI_ONLY_PNM
  739. #define STBI_NO_PNM
  740. #endif
  741. #endif
  742. #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
  743. #define STBI_NO_ZLIB
  744. #endif
  745. #include <stdarg.h>
  746. #include <stddef.h>
  747. #include <stdlib.h>
  748. #include <string.h>
  749. #include <limits.h>
  750. #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
  751. #include <math.h>
  752. #endif
  753. #ifndef STBI_ASSERT
  754. #include <assert.h>
  755. #define STBI_ASSERT(x) assert(x)
  756. #endif
  757. #ifdef __cplusplus
  758. #define STBI_EXTERN extern "C"
  759. #else
  760. #define STBI_EXTERN extern
  761. #endif
  762. #ifndef _MSC_VER
  763. #ifdef __cplusplus
  764. #define stbi_inline inline
  765. #else
  766. #define stbi_inline
  767. #endif
  768. #else
  769. #define stbi_inline __forceinline
  770. #endif
  771. #ifndef STBI_NO_THREAD_LOCALS
  772. #if defined(__cplusplus) && __cplusplus >= 201103L
  773. #define STBI_THREAD_LOCAL thread_local
  774. #elif defined(__GNUC__) && __GNUC__ < 5
  775. #define STBI_THREAD_LOCAL __thread
  776. #elif defined(_MSC_VER)
  777. #define STBI_THREAD_LOCAL __declspec(thread)
  778. #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
  779. #define STBI_THREAD_LOCAL _Thread_local
  780. #endif
  781. #ifndef STBI_THREAD_LOCAL
  782. #if defined(__GNUC__)
  783. #define STBI_THREAD_LOCAL __thread
  784. #endif
  785. #endif
  786. #endif
  787. #if defined(_MSC_VER) || defined(__SYMBIAN32__)
  788. typedef unsigned short stbi__uint16;
  789. typedef signed short stbi__int16;
  790. typedef unsigned int stbi__uint32;
  791. typedef signed int stbi__int32;
  792. #else
  793. #include <stdint.h>
  794. typedef uint16_t stbi__uint16;
  795. typedef int16_t stbi__int16;
  796. typedef uint32_t stbi__uint32;
  797. typedef int32_t stbi__int32;
  798. #endif
  799. typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
  800. #ifdef _MSC_VER
  801. #define STBI_NOTUSED(v) (void)(v)
  802. #else
  803. #define STBI_NOTUSED(v) (void)sizeof(v)
  804. #endif
  805. #ifdef _MSC_VER
  806. #define STBI_HAS_LROTL
  807. #endif
  808. #ifdef STBI_HAS_LROTL
  809. #define stbi_lrot(x,y) _lrotl(x,y)
  810. #else
  811. #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31)))
  812. #endif
  813. #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
  814. #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
  815. #else
  816. #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
  817. #endif
  818. #ifndef STBI_MALLOC
  819. #define STBI_MALLOC(sz) malloc(sz)
  820. #define STBI_REALLOC(p,newsz) realloc(p,newsz)
  821. #define STBI_FREE(p) free(p)
  822. #endif
  823. #ifndef STBI_REALLOC_SIZED
  824. #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)
  825. #endif
  826. #if defined(__x86_64__) || defined(_M_X64)
  827. #define STBI__X64_TARGET
  828. #elif defined(__i386) || defined(_M_IX86)
  829. #define STBI__X86_TARGET
  830. #endif
  831. #if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
  832. #define STBI_NO_SIMD
  833. #endif
  834. #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
  835. #define STBI_NO_SIMD
  836. #endif
  837. #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
  838. #define STBI_SSE2
  839. #include <emmintrin.h>
  840. #ifdef _MSC_VER
  841. #if _MSC_VER >= 1400
  842. #include <intrin.h>
  843. static int stbi__cpuid3(void)
  844. {
  845. int info[4];
  846. __cpuid(info,1);
  847. return info[3];
  848. }
  849. #else
  850. static int stbi__cpuid3(void)
  851. {
  852. int res;
  853. __asm {
  854. mov eax,1
  855. cpuid
  856. mov res,edx
  857. }
  858. return res;
  859. }
  860. #endif
  861. #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
  862. #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
  863. static int stbi__sse2_available(void)
  864. {
  865. int info3 = stbi__cpuid3();
  866. return ((info3 >> 26) & 1) != 0;
  867. }
  868. #endif
  869. #else
  870. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  871. #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
  872. static int stbi__sse2_available(void)
  873. {
  874. return 1;
  875. }
  876. #endif
  877. #endif
  878. #endif
  879. #if defined(STBI_NO_SIMD) && defined(STBI_NEON)
  880. #undef STBI_NEON
  881. #endif
  882. #ifdef STBI_NEON
  883. #include <arm_neon.h>
  884. #ifdef _MSC_VER
  885. #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
  886. #else
  887. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  888. #endif
  889. #endif
  890. #ifndef STBI_SIMD_ALIGN
  891. #define STBI_SIMD_ALIGN(type, name) type name
  892. #endif
  893. #ifndef STBI_MAX_DIMENSIONS
  894. #define STBI_MAX_DIMENSIONS (1 << 24)
  895. #endif
  896. typedef struct
  897. {
  898. stbi__uint32 img_x, img_y;
  899. int img_n, img_out_n;
  900. stbi_io_callbacks io;
  901. void *io_user_data;
  902. int read_from_callbacks;
  903. int buflen;
  904. stbi_uc buffer_start[128];
  905. int callback_already_read;
  906. stbi_uc *img_buffer, *img_buffer_end;
  907. stbi_uc *img_buffer_original, *img_buffer_original_end;
  908. } stbi__context;
  909. static void stbi__refill_buffer(stbi__context *s);
  910. static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
  911. {
  912. s->io.read = NULL;
  913. s->read_from_callbacks = 0;
  914. s->callback_already_read = 0;
  915. s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
  916. s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
  917. }
  918. static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
  919. {
  920. s->io = *c;
  921. s->io_user_data = user;
  922. s->buflen = sizeof(s->buffer_start);
  923. s->read_from_callbacks = 1;
  924. s->callback_already_read = 0;
  925. s->img_buffer = s->img_buffer_original = s->buffer_start;
  926. stbi__refill_buffer(s);
  927. s->img_buffer_original_end = s->img_buffer_end;
  928. }
  929. static void stbi__rewind(stbi__context *s)
  930. {
  931. s->img_buffer = s->img_buffer_original;
  932. s->img_buffer_end = s->img_buffer_original_end;
  933. }
  934. enum
  935. {
  936. STBI_ORDER_RGB,
  937. STBI_ORDER_BGR
  938. };
  939. typedef struct
  940. {
  941. int bits_per_channel;
  942. int num_channels;
  943. int channel_order;
  944. } stbi__result_info;
  945. #ifndef STBI_NO_PNG
  946. static int stbi__png_test(stbi__context *s);
  947. static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
  948. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
  949. static int stbi__png_is16(stbi__context *s);
  950. #endif
  951. static
  952. #ifdef STBI_THREAD_LOCAL
  953. STBI_THREAD_LOCAL
  954. #endif
  955. const char *stbi__g_failure_reason;
  956. STBIDEF const char *stbi_failure_reason(void)
  957. {
  958. return stbi__g_failure_reason;
  959. }
  960. #ifndef STBI_NO_FAILURE_STRINGS
  961. static int stbi__err(const char *str)
  962. {
  963. stbi__g_failure_reason = str;
  964. return 0;
  965. }
  966. #endif
  967. static void *stbi__malloc(size_t size)
  968. {
  969. return STBI_MALLOC(size);
  970. }
  971. static int stbi__addsizes_valid(int a, int b)
  972. {
  973. if (b < 0) return 0;
  974. return a <= INT_MAX - b;
  975. }
  976. static int stbi__mul2sizes_valid(int a, int b)
  977. {
  978. if (a < 0 || b < 0) return 0;
  979. if (b == 0) return 1;
  980. return a <= INT_MAX/b;
  981. }
  982. #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
  983. static int stbi__mad2sizes_valid(int a, int b, int add)
  984. {
  985. return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);
  986. }
  987. #endif
  988. static int stbi__mad3sizes_valid(int a, int b, int c, int add)
  989. {
  990. return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
  991. stbi__addsizes_valid(a*b*c, add);
  992. }
  993. #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
  994. static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
  995. {
  996. return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
  997. stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);
  998. }
  999. #endif
  1000. #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
  1001. static void *stbi__malloc_mad2(int a, int b, int add)
  1002. {
  1003. if (!stbi__mad2sizes_valid(a, b, add)) return NULL;
  1004. return stbi__malloc(a*b + add);
  1005. }
  1006. #endif
  1007. static void *stbi__malloc_mad3(int a, int b, int c, int add)
  1008. {
  1009. if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;
  1010. return stbi__malloc(a*b*c + add);
  1011. }
  1012. #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
  1013. static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)
  1014. {
  1015. if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;
  1016. return stbi__malloc(a*b*c*d + add);
  1017. }
  1018. #endif
  1019. #ifdef STBI_NO_FAILURE_STRINGS
  1020. #define stbi__err(x,y) 0
  1021. #elif defined(STBI_FAILURE_USERMSG)
  1022. #define stbi__err(x,y) stbi__err(y)
  1023. #else
  1024. #define stbi__err(x,y) stbi__err(x)
  1025. #endif
  1026. #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))
  1027. #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))
  1028. STBIDEF void stbi_image_free(void *retval_from_stbi_load)
  1029. {
  1030. STBI_FREE(retval_from_stbi_load);
  1031. }
  1032. static int stbi__vertically_flip_on_load_global = 0;
  1033. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
  1034. {
  1035. stbi__vertically_flip_on_load_global = flag_true_if_should_flip;
  1036. }
  1037. #ifndef STBI_THREAD_LOCAL
  1038. #define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global
  1039. #else
  1040. static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;
  1041. STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)
  1042. {
  1043. stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
  1044. stbi__vertically_flip_on_load_set = 1;
  1045. }
  1046. #define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \
  1047. ? stbi__vertically_flip_on_load_local \
  1048. : stbi__vertically_flip_on_load_global)
  1049. #endif
  1050. static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
  1051. {
  1052. memset(ri, 0, sizeof(*ri));
  1053. ri->bits_per_channel = 8;
  1054. ri->channel_order = STBI_ORDER_RGB;
  1055. ri->num_channels = 0;
  1056. #ifndef STBI_NO_PNG
  1057. if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);
  1058. #endif
  1059. (void)bpc;
  1060. return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
  1061. }
  1062. static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)
  1063. {
  1064. int i;
  1065. int img_len = w * h * channels;
  1066. stbi_uc *reduced;
  1067. reduced = (stbi_uc *) stbi__malloc(img_len);
  1068. if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory");
  1069. for (i = 0; i < img_len; ++i)
  1070. reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF);
  1071. STBI_FREE(orig);
  1072. return reduced;
  1073. }
  1074. static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)
  1075. {
  1076. int i;
  1077. int img_len = w * h * channels;
  1078. stbi__uint16 *enlarged;
  1079. enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);
  1080. if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
  1081. for (i = 0; i < img_len; ++i)
  1082. enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]);
  1083. STBI_FREE(orig);
  1084. return enlarged;
  1085. }
  1086. static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)
  1087. {
  1088. int row;
  1089. size_t bytes_per_row = (size_t)w * bytes_per_pixel;
  1090. stbi_uc temp[2048];
  1091. stbi_uc *bytes = (stbi_uc *)image;
  1092. for (row = 0; row < (h>>1); row++) {
  1093. stbi_uc *row0 = bytes + row*bytes_per_row;
  1094. stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row;
  1095. size_t bytes_left = bytes_per_row;
  1096. while (bytes_left) {
  1097. size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
  1098. memcpy(temp, row0, bytes_copy);
  1099. memcpy(row0, row1, bytes_copy);
  1100. memcpy(row1, temp, bytes_copy);
  1101. row0 += bytes_copy;
  1102. row1 += bytes_copy;
  1103. bytes_left -= bytes_copy;
  1104. }
  1105. }
  1106. }
  1107. static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  1108. {
  1109. stbi__result_info ri;
  1110. void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
  1111. if (result == NULL)
  1112. return NULL;
  1113. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
  1114. if (ri.bits_per_channel != 8) {
  1115. result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
  1116. ri.bits_per_channel = 8;
  1117. }
  1118. if (stbi__vertically_flip_on_load) {
  1119. int channels = req_comp ? req_comp : *comp;
  1120. stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
  1121. }
  1122. return (unsigned char *) result;
  1123. }
  1124. static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  1125. {
  1126. stbi__result_info ri;
  1127. void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
  1128. if (result == NULL)
  1129. return NULL;
  1130. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
  1131. if (ri.bits_per_channel != 16) {
  1132. result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
  1133. ri.bits_per_channel = 16;
  1134. }
  1135. if (stbi__vertically_flip_on_load) {
  1136. int channels = req_comp ? req_comp : *comp;
  1137. stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));
  1138. }
  1139. return (stbi__uint16 *) result;
  1140. }
  1141. #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
  1142. static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
  1143. {
  1144. if (stbi__vertically_flip_on_load && result != NULL) {
  1145. int channels = req_comp ? req_comp : *comp;
  1146. stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
  1147. }
  1148. }
  1149. #endif
  1150. STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels)
  1151. {
  1152. stbi__context s;
  1153. stbi__start_mem(&s,buffer,len);
  1154. return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
  1155. }
  1156. STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels)
  1157. {
  1158. stbi__context s;
  1159. stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
  1160. return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
  1161. }
  1162. STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  1163. {
  1164. stbi__context s;
  1165. stbi__start_mem(&s,buffer,len);
  1166. return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
  1167. }
  1168. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  1169. {
  1170. stbi__context s;
  1171. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  1172. return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
  1173. }
  1174. static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
  1175. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
  1176. STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
  1177. enum
  1178. {
  1179. STBI__SCAN_load=0,
  1180. STBI__SCAN_type,
  1181. STBI__SCAN_header
  1182. };
  1183. static void stbi__refill_buffer(stbi__context *s)
  1184. {
  1185. int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
  1186. s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);
  1187. if (n == 0) {
  1188. s->read_from_callbacks = 0;
  1189. s->img_buffer = s->buffer_start;
  1190. s->img_buffer_end = s->buffer_start+1;
  1191. *s->img_buffer = 0;
  1192. } else {
  1193. s->img_buffer = s->buffer_start;
  1194. s->img_buffer_end = s->buffer_start + n;
  1195. }
  1196. }
  1197. stbi_inline static stbi_uc stbi__get8(stbi__context *s)
  1198. {
  1199. if (s->img_buffer < s->img_buffer_end)
  1200. return *s->img_buffer++;
  1201. if (s->read_from_callbacks) {
  1202. stbi__refill_buffer(s);
  1203. return *s->img_buffer++;
  1204. }
  1205. return 0;
  1206. }
  1207. #if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
  1208. #else
  1209. stbi_inline static int stbi__at_eof(stbi__context *s)
  1210. {
  1211. if (s->io.read) {
  1212. if (!(s->io.eof)(s->io_user_data)) return 0;
  1213. if (s->read_from_callbacks == 0) return 1;
  1214. }
  1215. return s->img_buffer >= s->img_buffer_end;
  1216. }
  1217. #endif
  1218. #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)
  1219. #else
  1220. static void stbi__skip(stbi__context *s, int n)
  1221. {
  1222. if (n == 0) return;
  1223. if (n < 0) {
  1224. s->img_buffer = s->img_buffer_end;
  1225. return;
  1226. }
  1227. if (s->io.read) {
  1228. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1229. if (blen < n) {
  1230. s->img_buffer = s->img_buffer_end;
  1231. (s->io.skip)(s->io_user_data, n - blen);
  1232. return;
  1233. }
  1234. }
  1235. s->img_buffer += n;
  1236. }
  1237. #endif
  1238. #if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)
  1239. #else
  1240. static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
  1241. {
  1242. if (s->io.read) {
  1243. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1244. if (blen < n) {
  1245. int res, count;
  1246. memcpy(buffer, s->img_buffer, blen);
  1247. count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
  1248. res = (count == (n-blen));
  1249. s->img_buffer = s->img_buffer_end;
  1250. return res;
  1251. }
  1252. }
  1253. if (s->img_buffer+n <= s->img_buffer_end) {
  1254. memcpy(buffer, s->img_buffer, n);
  1255. s->img_buffer += n;
  1256. return 1;
  1257. } else
  1258. return 0;
  1259. }
  1260. #endif
  1261. #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
  1262. #else
  1263. static int stbi__get16be(stbi__context *s)
  1264. {
  1265. int z = stbi__get8(s);
  1266. return (z << 8) + stbi__get8(s);
  1267. }
  1268. #endif
  1269. #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
  1270. #else
  1271. static stbi__uint32 stbi__get32be(stbi__context *s)
  1272. {
  1273. stbi__uint32 z = stbi__get16be(s);
  1274. return (z << 16) + stbi__get16be(s);
  1275. }
  1276. #endif
  1277. #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
  1278. #else
  1279. static int stbi__get16le(stbi__context *s)
  1280. {
  1281. int z = stbi__get8(s);
  1282. return z + (stbi__get8(s) << 8);
  1283. }
  1284. #endif
  1285. #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255))
  1286. #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
  1287. #else
  1288. static stbi_uc stbi__compute_y(int r, int g, int b)
  1289. {
  1290. return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
  1291. }
  1292. #endif
  1293. #if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
  1294. #else
  1295. static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
  1296. {
  1297. int i,j;
  1298. unsigned char *good;
  1299. if (req_comp == img_n) return data;
  1300. STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
  1301. good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);
  1302. if (good == NULL) {
  1303. STBI_FREE(data);
  1304. return stbi__errpuc("outofmem", "Out of memory");
  1305. }
  1306. for (j=0; j < (int) y; ++j) {
  1307. unsigned char *src = data + j * x * img_n ;
  1308. unsigned char *dest = good + j * x * req_comp;
  1309. #define STBI__COMBO(a,b) ((a)*8+(b))
  1310. #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  1311. switch (STBI__COMBO(img_n, req_comp)) {
  1312. STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break;
  1313. STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
  1314. STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break;
  1315. STBI__CASE(2,1) { dest[0]=src[0]; } break;
  1316. STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
  1317. STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
  1318. STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break;
  1319. STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
  1320. STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break;
  1321. STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
  1322. STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;
  1323. STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
  1324. default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion");
  1325. }
  1326. #undef STBI__CASE
  1327. }
  1328. STBI_FREE(data);
  1329. return good;
  1330. }
  1331. #endif
  1332. #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
  1333. #else
  1334. static stbi__uint16 stbi__compute_y_16(int r, int g, int b)
  1335. {
  1336. return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8);
  1337. }
  1338. #endif
  1339. #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
  1340. #else
  1341. static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)
  1342. {
  1343. int i,j;
  1344. stbi__uint16 *good;
  1345. if (req_comp == img_n) return data;
  1346. STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
  1347. good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);
  1348. if (good == NULL) {
  1349. STBI_FREE(data);
  1350. return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
  1351. }
  1352. for (j=0; j < (int) y; ++j) {
  1353. stbi__uint16 *src = data + j * x * img_n ;
  1354. stbi__uint16 *dest = good + j * x * req_comp;
  1355. #define STBI__COMBO(a,b) ((a)*8+(b))
  1356. #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  1357. switch (STBI__COMBO(img_n, req_comp)) {
  1358. STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break;
  1359. STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
  1360. STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break;
  1361. STBI__CASE(2,1) { dest[0]=src[0]; } break;
  1362. STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
  1363. STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
  1364. STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break;
  1365. STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
  1366. STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break;
  1367. STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
  1368. STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;
  1369. STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
  1370. default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion");
  1371. }
  1372. #undef STBI__CASE
  1373. }
  1374. STBI_FREE(data);
  1375. return good;
  1376. }
  1377. #endif
  1378. #ifndef STBI_NO_ZLIB
  1379. #define STBI__ZFAST_BITS 9
  1380. #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
  1381. #define STBI__ZNSYMS 288
  1382. typedef struct
  1383. {
  1384. stbi__uint16 fast[1 << STBI__ZFAST_BITS];
  1385. stbi__uint16 firstcode[16];
  1386. int maxcode[17];
  1387. stbi__uint16 firstsymbol[16];
  1388. stbi_uc size[STBI__ZNSYMS];
  1389. stbi__uint16 value[STBI__ZNSYMS];
  1390. } stbi__zhuffman;
  1391. stbi_inline static int stbi__bitreverse16(int n)
  1392. {
  1393. n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
  1394. n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
  1395. n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
  1396. n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
  1397. return n;
  1398. }
  1399. stbi_inline static int stbi__bit_reverse(int v, int bits)
  1400. {
  1401. STBI_ASSERT(bits <= 16);
  1402. return stbi__bitreverse16(v) >> (16-bits);
  1403. }
  1404. static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num)
  1405. {
  1406. int i,k=0;
  1407. int code, next_code[16], sizes[17];
  1408. memset(sizes, 0, sizeof(sizes));
  1409. memset(z->fast, 0, sizeof(z->fast));
  1410. for (i=0; i < num; ++i)
  1411. ++sizes[sizelist[i]];
  1412. sizes[0] = 0;
  1413. for (i=1; i < 16; ++i)
  1414. if (sizes[i] > (1 << i))
  1415. return stbi__err("bad sizes", "Corrupt PNG");
  1416. code = 0;
  1417. for (i=1; i < 16; ++i) {
  1418. next_code[i] = code;
  1419. z->firstcode[i] = (stbi__uint16) code;
  1420. z->firstsymbol[i] = (stbi__uint16) k;
  1421. code = (code + sizes[i]);
  1422. if (sizes[i])
  1423. if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
  1424. z->maxcode[i] = code << (16-i);
  1425. code <<= 1;
  1426. k += sizes[i];
  1427. }
  1428. z->maxcode[16] = 0x10000;
  1429. for (i=0; i < num; ++i) {
  1430. int s = sizelist[i];
  1431. if (s) {
  1432. int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
  1433. stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
  1434. z->size [c] = (stbi_uc ) s;
  1435. z->value[c] = (stbi__uint16) i;
  1436. if (s <= STBI__ZFAST_BITS) {
  1437. int j = stbi__bit_reverse(next_code[s],s);
  1438. while (j < (1 << STBI__ZFAST_BITS)) {
  1439. z->fast[j] = fastv;
  1440. j += (1 << s);
  1441. }
  1442. }
  1443. ++next_code[s];
  1444. }
  1445. }
  1446. return 1;
  1447. }
  1448. typedef struct
  1449. {
  1450. stbi_uc *zbuffer, *zbuffer_end;
  1451. int num_bits;
  1452. int hit_zeof_once;
  1453. stbi__uint32 code_buffer;
  1454. char *zout;
  1455. char *zout_start;
  1456. char *zout_end;
  1457. int z_expandable;
  1458. stbi__zhuffman z_length, z_distance;
  1459. } stbi__zbuf;
  1460. stbi_inline static int stbi__zeof(stbi__zbuf *z)
  1461. {
  1462. return (z->zbuffer >= z->zbuffer_end);
  1463. }
  1464. stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
  1465. {
  1466. return stbi__zeof(z) ? 0 : *z->zbuffer++;
  1467. }
  1468. static void stbi__fill_bits(stbi__zbuf *z)
  1469. {
  1470. do {
  1471. if (z->code_buffer >= (1U << z->num_bits)) {
  1472. z->zbuffer = z->zbuffer_end;
  1473. return;
  1474. }
  1475. z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
  1476. z->num_bits += 8;
  1477. } while (z->num_bits <= 24);
  1478. }
  1479. stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
  1480. {
  1481. unsigned int k;
  1482. if (z->num_bits < n) stbi__fill_bits(z);
  1483. k = z->code_buffer & ((1 << n) - 1);
  1484. z->code_buffer >>= n;
  1485. z->num_bits -= n;
  1486. return k;
  1487. }
  1488. static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
  1489. {
  1490. int b,s,k;
  1491. k = stbi__bit_reverse(a->code_buffer, 16);
  1492. for (s=STBI__ZFAST_BITS+1; ; ++s)
  1493. if (k < z->maxcode[s])
  1494. break;
  1495. if (s >= 16) return -1;
  1496. b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
  1497. if (b >= STBI__ZNSYMS) return -1;
  1498. if (z->size[b] != s) return -1;
  1499. a->code_buffer >>= s;
  1500. a->num_bits -= s;
  1501. return z->value[b];
  1502. }
  1503. stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
  1504. {
  1505. int b,s;
  1506. if (a->num_bits < 16) {
  1507. if (stbi__zeof(a)) {
  1508. if (!a->hit_zeof_once) {
  1509. a->hit_zeof_once = 1;
  1510. a->num_bits += 16;
  1511. } else {
  1512. return -1;
  1513. }
  1514. } else {
  1515. stbi__fill_bits(a);
  1516. }
  1517. }
  1518. b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
  1519. if (b) {
  1520. s = b >> 9;
  1521. a->code_buffer >>= s;
  1522. a->num_bits -= s;
  1523. return b & 511;
  1524. }
  1525. return stbi__zhuffman_decode_slowpath(a, z);
  1526. }
  1527. static int stbi__zexpand(stbi__zbuf *z, char *zout, int n)
  1528. {
  1529. char *q;
  1530. unsigned int cur, limit, old_limit;
  1531. z->zout = zout;
  1532. if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
  1533. cur = (unsigned int) (z->zout - z->zout_start);
  1534. limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
  1535. if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
  1536. while (cur + n > limit) {
  1537. if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
  1538. limit *= 2;
  1539. }
  1540. q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
  1541. STBI_NOTUSED(old_limit);
  1542. if (q == NULL) return stbi__err("outofmem", "Out of memory");
  1543. z->zout_start = q;
  1544. z->zout = q + cur;
  1545. z->zout_end = q + limit;
  1546. return 1;
  1547. }
  1548. static const int stbi__zlength_base[31] = {
  1549. 3,4,5,6,7,8,9,10,11,13,
  1550. 15,17,19,23,27,31,35,43,51,59,
  1551. 67,83,99,115,131,163,195,227,258,0,0 };
  1552. static const int stbi__zlength_extra[31]=
  1553. { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
  1554. static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
  1555. 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1556. static const int stbi__zdist_extra[32] =
  1557. { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  1558. static int stbi__parse_huffman_block(stbi__zbuf *a)
  1559. {
  1560. char *zout = a->zout;
  1561. for(;;) {
  1562. int z = stbi__zhuffman_decode(a, &a->z_length);
  1563. if (z < 256) {
  1564. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");
  1565. if (zout >= a->zout_end) {
  1566. if (!stbi__zexpand(a, zout, 1)) return 0;
  1567. zout = a->zout;
  1568. }
  1569. *zout++ = (char) z;
  1570. } else {
  1571. stbi_uc *p;
  1572. int len,dist;
  1573. if (z == 256) {
  1574. a->zout = zout;
  1575. if (a->hit_zeof_once && a->num_bits < 16) {
  1576. return stbi__err("unexpected end","Corrupt PNG");
  1577. }
  1578. return 1;
  1579. }
  1580. if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG");
  1581. z -= 257;
  1582. len = stbi__zlength_base[z];
  1583. if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
  1584. z = stbi__zhuffman_decode(a, &a->z_distance);
  1585. if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG");
  1586. dist = stbi__zdist_base[z];
  1587. if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
  1588. if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
  1589. if (len > a->zout_end - zout) {
  1590. if (!stbi__zexpand(a, zout, len)) return 0;
  1591. zout = a->zout;
  1592. }
  1593. p = (stbi_uc *) (zout - dist);
  1594. if (dist == 1) {
  1595. stbi_uc v = *p;
  1596. if (len) { do *zout++ = v; while (--len); }
  1597. } else {
  1598. if (len) { do *zout++ = *p++; while (--len); }
  1599. }
  1600. }
  1601. }
  1602. }
  1603. static int stbi__compute_huffman_codes(stbi__zbuf *a)
  1604. {
  1605. static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  1606. stbi__zhuffman z_codelength;
  1607. stbi_uc lencodes[286+32+137];
  1608. stbi_uc codelength_sizes[19];
  1609. int i,n;
  1610. int hlit = stbi__zreceive(a,5) + 257;
  1611. int hdist = stbi__zreceive(a,5) + 1;
  1612. int hclen = stbi__zreceive(a,4) + 4;
  1613. int ntot = hlit + hdist;
  1614. memset(codelength_sizes, 0, sizeof(codelength_sizes));
  1615. for (i=0; i < hclen; ++i) {
  1616. int s = stbi__zreceive(a,3);
  1617. codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
  1618. }
  1619. if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
  1620. n = 0;
  1621. while (n < ntot) {
  1622. int c = stbi__zhuffman_decode(a, &z_codelength);
  1623. if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
  1624. if (c < 16)
  1625. lencodes[n++] = (stbi_uc) c;
  1626. else {
  1627. stbi_uc fill = 0;
  1628. if (c == 16) {
  1629. c = stbi__zreceive(a,2)+3;
  1630. if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
  1631. fill = lencodes[n-1];
  1632. } else if (c == 17) {
  1633. c = stbi__zreceive(a,3)+3;
  1634. } else if (c == 18) {
  1635. c = stbi__zreceive(a,7)+11;
  1636. } else {
  1637. return stbi__err("bad codelengths", "Corrupt PNG");
  1638. }
  1639. if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
  1640. memset(lencodes+n, fill, c);
  1641. n += c;
  1642. }
  1643. }
  1644. if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG");
  1645. if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
  1646. if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
  1647. return 1;
  1648. }
  1649. static int stbi__parse_uncompressed_block(stbi__zbuf *a)
  1650. {
  1651. stbi_uc header[4];
  1652. int len,nlen,k;
  1653. if (a->num_bits & 7)
  1654. stbi__zreceive(a, a->num_bits & 7);
  1655. k = 0;
  1656. while (a->num_bits > 0) {
  1657. header[k++] = (stbi_uc) (a->code_buffer & 255);
  1658. a->code_buffer >>= 8;
  1659. a->num_bits -= 8;
  1660. }
  1661. if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG");
  1662. while (k < 4)
  1663. header[k++] = stbi__zget8(a);
  1664. len = header[1] * 256 + header[0];
  1665. nlen = header[3] * 256 + header[2];
  1666. if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
  1667. if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
  1668. if (a->zout + len > a->zout_end)
  1669. if (!stbi__zexpand(a, a->zout, len)) return 0;
  1670. memcpy(a->zout, a->zbuffer, len);
  1671. a->zbuffer += len;
  1672. a->zout += len;
  1673. return 1;
  1674. }
  1675. static int stbi__parse_zlib_header(stbi__zbuf *a)
  1676. {
  1677. int cmf = stbi__zget8(a);
  1678. int cm = cmf & 15;
  1679. int flg = stbi__zget8(a);
  1680. if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG");
  1681. if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG");
  1682. if (flg & 32) return stbi__err("no preset dict","Corrupt PNG");
  1683. if (cm != 8) return stbi__err("bad compression","Corrupt PNG");
  1684. return 1;
  1685. }
  1686. static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =
  1687. {
  1688. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  1689. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  1690. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  1691. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  1692. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  1693. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  1694. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  1695. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  1696. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8
  1697. };
  1698. static const stbi_uc stbi__zdefault_distance[32] =
  1699. {
  1700. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
  1701. };
  1702. static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
  1703. {
  1704. int final, type;
  1705. if (parse_header)
  1706. if (!stbi__parse_zlib_header(a)) return 0;
  1707. a->num_bits = 0;
  1708. a->code_buffer = 0;
  1709. a->hit_zeof_once = 0;
  1710. do {
  1711. final = stbi__zreceive(a,1);
  1712. type = stbi__zreceive(a,2);
  1713. if (type == 0) {
  1714. if (!stbi__parse_uncompressed_block(a)) return 0;
  1715. } else if (type == 3) {
  1716. return 0;
  1717. } else {
  1718. if (type == 1) {
  1719. if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0;
  1720. if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
  1721. } else {
  1722. if (!stbi__compute_huffman_codes(a)) return 0;
  1723. }
  1724. if (!stbi__parse_huffman_block(a)) return 0;
  1725. }
  1726. } while (!final);
  1727. return 1;
  1728. }
  1729. static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
  1730. {
  1731. a->zout_start = obuf;
  1732. a->zout = obuf;
  1733. a->zout_end = obuf + olen;
  1734. a->z_expandable = exp;
  1735. return stbi__parse_zlib(a, parse_header);
  1736. }
  1737. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
  1738. {
  1739. stbi__zbuf a;
  1740. char *p = (char *) stbi__malloc(initial_size);
  1741. if (p == NULL) return NULL;
  1742. a.zbuffer = (stbi_uc *) buffer;
  1743. a.zbuffer_end = (stbi_uc *) buffer + len;
  1744. if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
  1745. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  1746. return a.zout_start;
  1747. } else {
  1748. STBI_FREE(a.zout_start);
  1749. return NULL;
  1750. }
  1751. }
  1752. STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
  1753. {
  1754. return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
  1755. }
  1756. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
  1757. {
  1758. stbi__zbuf a;
  1759. char *p = (char *) stbi__malloc(initial_size);
  1760. if (p == NULL) return NULL;
  1761. a.zbuffer = (stbi_uc *) buffer;
  1762. a.zbuffer_end = (stbi_uc *) buffer + len;
  1763. if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
  1764. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  1765. return a.zout_start;
  1766. } else {
  1767. STBI_FREE(a.zout_start);
  1768. return NULL;
  1769. }
  1770. }
  1771. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
  1772. {
  1773. stbi__zbuf a;
  1774. a.zbuffer = (stbi_uc *) ibuffer;
  1775. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  1776. if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
  1777. return (int) (a.zout - a.zout_start);
  1778. else
  1779. return -1;
  1780. }
  1781. STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
  1782. {
  1783. stbi__zbuf a;
  1784. char *p = (char *) stbi__malloc(16384);
  1785. if (p == NULL) return NULL;
  1786. a.zbuffer = (stbi_uc *) buffer;
  1787. a.zbuffer_end = (stbi_uc *) buffer+len;
  1788. if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
  1789. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  1790. return a.zout_start;
  1791. } else {
  1792. STBI_FREE(a.zout_start);
  1793. return NULL;
  1794. }
  1795. }
  1796. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
  1797. {
  1798. stbi__zbuf a;
  1799. a.zbuffer = (stbi_uc *) ibuffer;
  1800. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  1801. if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
  1802. return (int) (a.zout - a.zout_start);
  1803. else
  1804. return -1;
  1805. }
  1806. #endif
  1807. #ifndef STBI_NO_PNG
  1808. typedef struct
  1809. {
  1810. stbi__uint32 length;
  1811. stbi__uint32 type;
  1812. } stbi__pngchunk;
  1813. static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
  1814. {
  1815. stbi__pngchunk c;
  1816. c.length = stbi__get32be(s);
  1817. c.type = stbi__get32be(s);
  1818. return c;
  1819. }
  1820. static int stbi__check_png_header(stbi__context *s)
  1821. {
  1822. static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
  1823. int i;
  1824. for (i=0; i < 8; ++i)
  1825. if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
  1826. return 1;
  1827. }
  1828. typedef struct
  1829. {
  1830. stbi__context *s;
  1831. stbi_uc *idata, *expanded, *out;
  1832. int depth;
  1833. } stbi__png;
  1834. enum {
  1835. STBI__F_none=0,
  1836. STBI__F_sub=1,
  1837. STBI__F_up=2,
  1838. STBI__F_avg=3,
  1839. STBI__F_paeth=4,
  1840. STBI__F_avg_first
  1841. };
  1842. static stbi_uc first_row_filter[5] =
  1843. {
  1844. STBI__F_none,
  1845. STBI__F_sub,
  1846. STBI__F_none,
  1847. STBI__F_avg_first,
  1848. STBI__F_sub
  1849. };
  1850. static int stbi__paeth(int a, int b, int c)
  1851. {
  1852. int thresh = c*3 - (a + b);
  1853. int lo = a < b ? a : b;
  1854. int hi = a < b ? b : a;
  1855. int t0 = (hi <= thresh) ? lo : c;
  1856. int t1 = (thresh <= lo) ? hi : t0;
  1857. return t1;
  1858. }
  1859. static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
  1860. static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)
  1861. {
  1862. int i;
  1863. if (img_n == 1) {
  1864. for (i=x-1; i >= 0; --i) {
  1865. dest[i*2+1] = 255;
  1866. dest[i*2+0] = src[i];
  1867. }
  1868. } else {
  1869. STBI_ASSERT(img_n == 3);
  1870. for (i=x-1; i >= 0; --i) {
  1871. dest[i*4+3] = 255;
  1872. dest[i*4+2] = src[i*3+2];
  1873. dest[i*4+1] = src[i*3+1];
  1874. dest[i*4+0] = src[i*3+0];
  1875. }
  1876. }
  1877. }
  1878. static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
  1879. {
  1880. int bytes = (depth == 16 ? 2 : 1);
  1881. stbi__context *s = a->s;
  1882. stbi__uint32 i,j,stride = x*out_n*bytes;
  1883. stbi__uint32 img_len, img_width_bytes;
  1884. stbi_uc *filter_buf;
  1885. int all_ok = 1;
  1886. int k;
  1887. int img_n = s->img_n;
  1888. int output_bytes = out_n*bytes;
  1889. int filter_bytes = img_n*bytes;
  1890. int width = x;
  1891. STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
  1892. a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0);
  1893. if (!a->out) return stbi__err("outofmem", "Out of memory");
  1894. if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG");
  1895. img_width_bytes = (((img_n * x * depth) + 7) >> 3);
  1896. if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG");
  1897. img_len = (img_width_bytes + 1) * y;
  1898. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
  1899. filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);
  1900. if (!filter_buf) return stbi__err("outofmem", "Out of memory");
  1901. if (depth < 8) {
  1902. filter_bytes = 1;
  1903. width = img_width_bytes;
  1904. }
  1905. for (j=0; j < y; ++j) {
  1906. stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;
  1907. stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;
  1908. stbi_uc *dest = a->out + stride*j;
  1909. int nk = width * filter_bytes;
  1910. int filter = *raw++;
  1911. if (filter > 4) {
  1912. all_ok = stbi__err("invalid filter","Corrupt PNG");
  1913. break;
  1914. }
  1915. if (j == 0) filter = first_row_filter[filter];
  1916. switch (filter) {
  1917. case STBI__F_none:
  1918. memcpy(cur, raw, nk);
  1919. break;
  1920. case STBI__F_sub:
  1921. memcpy(cur, raw, filter_bytes);
  1922. for (k = filter_bytes; k < nk; ++k)
  1923. cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);
  1924. break;
  1925. case STBI__F_up:
  1926. for (k = 0; k < nk; ++k)
  1927. cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
  1928. break;
  1929. case STBI__F_avg:
  1930. for (k = 0; k < filter_bytes; ++k)
  1931. cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));
  1932. for (k = filter_bytes; k < nk; ++k)
  1933. cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));
  1934. break;
  1935. case STBI__F_paeth:
  1936. for (k = 0; k < filter_bytes; ++k)
  1937. cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
  1938. for (k = filter_bytes; k < nk; ++k)
  1939. cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));
  1940. break;
  1941. case STBI__F_avg_first:
  1942. memcpy(cur, raw, filter_bytes);
  1943. for (k = filter_bytes; k < nk; ++k)
  1944. cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));
  1945. break;
  1946. }
  1947. raw += nk;
  1948. if (depth < 8) {
  1949. stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1;
  1950. stbi_uc *in = cur;
  1951. stbi_uc *out = dest;
  1952. stbi_uc inb = 0;
  1953. stbi__uint32 nsmp = x*img_n;
  1954. if (depth == 4) {
  1955. for (i=0; i < nsmp; ++i) {
  1956. if ((i & 1) == 0) inb = *in++;
  1957. *out++ = scale * (inb >> 4);
  1958. inb <<= 4;
  1959. }
  1960. } else if (depth == 2) {
  1961. for (i=0; i < nsmp; ++i) {
  1962. if ((i & 3) == 0) inb = *in++;
  1963. *out++ = scale * (inb >> 6);
  1964. inb <<= 2;
  1965. }
  1966. } else {
  1967. STBI_ASSERT(depth == 1);
  1968. for (i=0; i < nsmp; ++i) {
  1969. if ((i & 7) == 0) inb = *in++;
  1970. *out++ = scale * (inb >> 7);
  1971. inb <<= 1;
  1972. }
  1973. }
  1974. if (img_n != out_n)
  1975. stbi__create_png_alpha_expand8(dest, dest, x, img_n);
  1976. } else if (depth == 8) {
  1977. if (img_n == out_n)
  1978. memcpy(dest, cur, x*img_n);
  1979. else
  1980. stbi__create_png_alpha_expand8(dest, cur, x, img_n);
  1981. } else if (depth == 16) {
  1982. stbi__uint16 *dest16 = (stbi__uint16*)dest;
  1983. stbi__uint32 nsmp = x*img_n;
  1984. if (img_n == out_n) {
  1985. for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)
  1986. *dest16 = (cur[0] << 8) | cur[1];
  1987. } else {
  1988. STBI_ASSERT(img_n+1 == out_n);
  1989. if (img_n == 1) {
  1990. for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {
  1991. dest16[0] = (cur[0] << 8) | cur[1];
  1992. dest16[1] = 0xffff;
  1993. }
  1994. } else {
  1995. STBI_ASSERT(img_n == 3);
  1996. for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {
  1997. dest16[0] = (cur[0] << 8) | cur[1];
  1998. dest16[1] = (cur[2] << 8) | cur[3];
  1999. dest16[2] = (cur[4] << 8) | cur[5];
  2000. dest16[3] = 0xffff;
  2001. }
  2002. }
  2003. }
  2004. }
  2005. }
  2006. STBI_FREE(filter_buf);
  2007. if (!all_ok) return 0;
  2008. return 1;
  2009. }
  2010. static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
  2011. {
  2012. int bytes = (depth == 16 ? 2 : 1);
  2013. int out_bytes = out_n * bytes;
  2014. stbi_uc *final;
  2015. int p;
  2016. if (!interlaced)
  2017. return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
  2018. final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
  2019. if (!final) return stbi__err("outofmem", "Out of memory");
  2020. for (p=0; p < 7; ++p) {
  2021. int xorig[] = { 0,4,0,2,0,1,0 };
  2022. int yorig[] = { 0,0,4,0,2,0,1 };
  2023. int xspc[] = { 8,8,4,4,2,2,1 };
  2024. int yspc[] = { 8,8,8,4,4,2,2 };
  2025. int i,j,x,y;
  2026. x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
  2027. y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
  2028. if (x && y) {
  2029. stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
  2030. if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
  2031. STBI_FREE(final);
  2032. return 0;
  2033. }
  2034. for (j=0; j < y; ++j) {
  2035. for (i=0; i < x; ++i) {
  2036. int out_y = j*yspc[p]+yorig[p];
  2037. int out_x = i*xspc[p]+xorig[p];
  2038. memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,
  2039. a->out + (j*x+i)*out_bytes, out_bytes);
  2040. }
  2041. }
  2042. STBI_FREE(a->out);
  2043. image_data += img_len;
  2044. image_data_len -= img_len;
  2045. }
  2046. }
  2047. a->out = final;
  2048. return 1;
  2049. }
  2050. static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
  2051. {
  2052. stbi__context *s = z->s;
  2053. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  2054. stbi_uc *p = z->out;
  2055. STBI_ASSERT(out_n == 2 || out_n == 4);
  2056. if (out_n == 2) {
  2057. for (i=0; i < pixel_count; ++i) {
  2058. p[1] = (p[0] == tc[0] ? 0 : 255);
  2059. p += 2;
  2060. }
  2061. } else {
  2062. for (i=0; i < pixel_count; ++i) {
  2063. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  2064. p[3] = 0;
  2065. p += 4;
  2066. }
  2067. }
  2068. return 1;
  2069. }
  2070. static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)
  2071. {
  2072. stbi__context *s = z->s;
  2073. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  2074. stbi__uint16 *p = (stbi__uint16*) z->out;
  2075. STBI_ASSERT(out_n == 2 || out_n == 4);
  2076. if (out_n == 2) {
  2077. for (i = 0; i < pixel_count; ++i) {
  2078. p[1] = (p[0] == tc[0] ? 0 : 65535);
  2079. p += 2;
  2080. }
  2081. } else {
  2082. for (i = 0; i < pixel_count; ++i) {
  2083. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  2084. p[3] = 0;
  2085. p += 4;
  2086. }
  2087. }
  2088. return 1;
  2089. }
  2090. static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
  2091. {
  2092. stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
  2093. stbi_uc *p, *temp_out, *orig = a->out;
  2094. p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);
  2095. if (p == NULL) return stbi__err("outofmem", "Out of memory");
  2096. temp_out = p;
  2097. if (pal_img_n == 3) {
  2098. for (i=0; i < pixel_count; ++i) {
  2099. int n = orig[i]*4;
  2100. p[0] = palette[n ];
  2101. p[1] = palette[n+1];
  2102. p[2] = palette[n+2];
  2103. p += 3;
  2104. }
  2105. } else {
  2106. for (i=0; i < pixel_count; ++i) {
  2107. int n = orig[i]*4;
  2108. p[0] = palette[n ];
  2109. p[1] = palette[n+1];
  2110. p[2] = palette[n+2];
  2111. p[3] = palette[n+3];
  2112. p += 4;
  2113. }
  2114. }
  2115. STBI_FREE(a->out);
  2116. a->out = temp_out;
  2117. STBI_NOTUSED(len);
  2118. return 1;
  2119. }
  2120. static int stbi__unpremultiply_on_load_global = 0;
  2121. static int stbi__de_iphone_flag_global = 0;
  2122. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
  2123. {
  2124. stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
  2125. }
  2126. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
  2127. {
  2128. stbi__de_iphone_flag_global = flag_true_if_should_convert;
  2129. }
  2130. #ifndef STBI_THREAD_LOCAL
  2131. #define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global
  2132. #define stbi__de_iphone_flag stbi__de_iphone_flag_global
  2133. #else
  2134. static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
  2135. static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
  2136. STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
  2137. {
  2138. stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
  2139. stbi__unpremultiply_on_load_set = 1;
  2140. }
  2141. STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
  2142. {
  2143. stbi__de_iphone_flag_local = flag_true_if_should_convert;
  2144. stbi__de_iphone_flag_set = 1;
  2145. }
  2146. #define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \
  2147. ? stbi__unpremultiply_on_load_local \
  2148. : stbi__unpremultiply_on_load_global)
  2149. #define stbi__de_iphone_flag (stbi__de_iphone_flag_set \
  2150. ? stbi__de_iphone_flag_local \
  2151. : stbi__de_iphone_flag_global)
  2152. #endif
  2153. static void stbi__de_iphone(stbi__png *z)
  2154. {
  2155. stbi__context *s = z->s;
  2156. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  2157. stbi_uc *p = z->out;
  2158. if (s->img_out_n == 3) {
  2159. for (i=0; i < pixel_count; ++i) {
  2160. stbi_uc t = p[0];
  2161. p[0] = p[2];
  2162. p[2] = t;
  2163. p += 3;
  2164. }
  2165. } else {
  2166. STBI_ASSERT(s->img_out_n == 4);
  2167. if (stbi__unpremultiply_on_load) {
  2168. for (i=0; i < pixel_count; ++i) {
  2169. stbi_uc a = p[3];
  2170. stbi_uc t = p[0];
  2171. if (a) {
  2172. stbi_uc half = a / 2;
  2173. p[0] = (p[2] * 255 + half) / a;
  2174. p[1] = (p[1] * 255 + half) / a;
  2175. p[2] = ( t * 255 + half) / a;
  2176. } else {
  2177. p[0] = p[2];
  2178. p[2] = t;
  2179. }
  2180. p += 4;
  2181. }
  2182. } else {
  2183. for (i=0; i < pixel_count; ++i) {
  2184. stbi_uc t = p[0];
  2185. p[0] = p[2];
  2186. p[2] = t;
  2187. p += 4;
  2188. }
  2189. }
  2190. }
  2191. }
  2192. #define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))
  2193. static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
  2194. {
  2195. stbi_uc palette[1024], pal_img_n=0;
  2196. stbi_uc has_trans=0, tc[3]={0};
  2197. stbi__uint16 tc16[3];
  2198. stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
  2199. int first=1,k,interlace=0, color=0, is_iphone=0;
  2200. stbi__context *s = z->s;
  2201. z->expanded = NULL;
  2202. z->idata = NULL;
  2203. z->out = NULL;
  2204. if (!stbi__check_png_header(s)) return 0;
  2205. if (scan == STBI__SCAN_type) return 1;
  2206. for (;;) {
  2207. stbi__pngchunk c = stbi__get_chunk_header(s);
  2208. switch (c.type) {
  2209. case STBI__PNG_TYPE('C','g','B','I'):
  2210. is_iphone = 1;
  2211. stbi__skip(s, c.length);
  2212. break;
  2213. case STBI__PNG_TYPE('I','H','D','R'): {
  2214. int comp,filter;
  2215. if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
  2216. first = 0;
  2217. if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
  2218. s->img_x = stbi__get32be(s);
  2219. s->img_y = stbi__get32be(s);
  2220. if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
  2221. if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
  2222. z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
  2223. color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
  2224. if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG");
  2225. if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
  2226. comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
  2227. filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
  2228. interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
  2229. if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
  2230. if (!pal_img_n) {
  2231. s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
  2232. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  2233. } else {
  2234. s->img_n = 1;
  2235. if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
  2236. }
  2237. break;
  2238. }
  2239. case STBI__PNG_TYPE('P','L','T','E'): {
  2240. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2241. if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
  2242. pal_len = c.length / 3;
  2243. if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
  2244. for (i=0; i < pal_len; ++i) {
  2245. palette[i*4+0] = stbi__get8(s);
  2246. palette[i*4+1] = stbi__get8(s);
  2247. palette[i*4+2] = stbi__get8(s);
  2248. palette[i*4+3] = 255;
  2249. }
  2250. break;
  2251. }
  2252. case STBI__PNG_TYPE('t','R','N','S'): {
  2253. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2254. if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
  2255. if (pal_img_n) {
  2256. if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
  2257. if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
  2258. if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
  2259. pal_img_n = 4;
  2260. for (i=0; i < c.length; ++i)
  2261. palette[i*4+3] = stbi__get8(s);
  2262. } else {
  2263. if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
  2264. if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
  2265. has_trans = 1;
  2266. if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }
  2267. if (z->depth == 16) {
  2268. for (k = 0; k < s->img_n && k < 3; ++k)
  2269. tc16[k] = (stbi__uint16)stbi__get16be(s);
  2270. } else {
  2271. for (k = 0; k < s->img_n && k < 3; ++k)
  2272. tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth];
  2273. }
  2274. }
  2275. break;
  2276. }
  2277. case STBI__PNG_TYPE('I','D','A','T'): {
  2278. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2279. if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
  2280. if (scan == STBI__SCAN_header) {
  2281. if (pal_img_n)
  2282. s->img_n = pal_img_n;
  2283. return 1;
  2284. }
  2285. if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
  2286. if ((int)(ioff + c.length) < (int)ioff) return 0;
  2287. if (ioff + c.length > idata_limit) {
  2288. stbi__uint32 idata_limit_old = idata_limit;
  2289. stbi_uc *p;
  2290. if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
  2291. while (ioff + c.length > idata_limit)
  2292. idata_limit *= 2;
  2293. STBI_NOTUSED(idata_limit_old);
  2294. p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
  2295. z->idata = p;
  2296. }
  2297. if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
  2298. ioff += c.length;
  2299. break;
  2300. }
  2301. case STBI__PNG_TYPE('I','E','N','D'): {
  2302. stbi__uint32 raw_len, bpl;
  2303. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2304. if (scan != STBI__SCAN_load) return 1;
  2305. if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
  2306. bpl = (s->img_x * z->depth + 7) / 8;
  2307. raw_len = bpl * s->img_y * s->img_n + s->img_y;
  2308. z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
  2309. if (z->expanded == NULL) return 0;
  2310. STBI_FREE(z->idata); z->idata = NULL;
  2311. if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
  2312. s->img_out_n = s->img_n+1;
  2313. else
  2314. s->img_out_n = s->img_n;
  2315. if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;
  2316. if (has_trans) {
  2317. if (z->depth == 16) {
  2318. if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
  2319. } else {
  2320. if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
  2321. }
  2322. }
  2323. if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
  2324. stbi__de_iphone(z);
  2325. if (pal_img_n) {
  2326. s->img_n = pal_img_n;
  2327. s->img_out_n = pal_img_n;
  2328. if (req_comp >= 3) s->img_out_n = req_comp;
  2329. if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
  2330. return 0;
  2331. } else if (has_trans) {
  2332. ++s->img_n;
  2333. }
  2334. STBI_FREE(z->expanded); z->expanded = NULL;
  2335. stbi__get32be(s);
  2336. return 1;
  2337. }
  2338. default:
  2339. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2340. if ((c.type & (1 << 29)) == 0) {
  2341. #ifndef STBI_NO_FAILURE_STRINGS
  2342. static char invalid_chunk[] = "XXXX PNG chunk not known";
  2343. invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
  2344. invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
  2345. invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
  2346. invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
  2347. #endif
  2348. return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
  2349. }
  2350. stbi__skip(s, c.length);
  2351. break;
  2352. }
  2353. stbi__get32be(s);
  2354. }
  2355. }
  2356. static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)
  2357. {
  2358. void *result=NULL;
  2359. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  2360. if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
  2361. if (p->depth <= 8)
  2362. ri->bits_per_channel = 8;
  2363. else if (p->depth == 16)
  2364. ri->bits_per_channel = 16;
  2365. else
  2366. return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
  2367. result = p->out;
  2368. p->out = NULL;
  2369. if (req_comp && req_comp != p->s->img_out_n) {
  2370. if (ri->bits_per_channel == 8)
  2371. result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  2372. else
  2373. result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  2374. p->s->img_out_n = req_comp;
  2375. if (result == NULL) return result;
  2376. }
  2377. *x = p->s->img_x;
  2378. *y = p->s->img_y;
  2379. if (n) *n = p->s->img_n;
  2380. }
  2381. STBI_FREE(p->out); p->out = NULL;
  2382. STBI_FREE(p->expanded); p->expanded = NULL;
  2383. STBI_FREE(p->idata); p->idata = NULL;
  2384. return result;
  2385. }
  2386. static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
  2387. {
  2388. stbi__png p;
  2389. p.s = s;
  2390. return stbi__do_png(&p, x,y,comp,req_comp, ri);
  2391. }
  2392. static int stbi__png_test(stbi__context *s)
  2393. {
  2394. int r;
  2395. r = stbi__check_png_header(s);
  2396. stbi__rewind(s);
  2397. return r;
  2398. }
  2399. static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
  2400. {
  2401. if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
  2402. stbi__rewind( p->s );
  2403. return 0;
  2404. }
  2405. if (x) *x = p->s->img_x;
  2406. if (y) *y = p->s->img_y;
  2407. if (comp) *comp = p->s->img_n;
  2408. return 1;
  2409. }
  2410. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
  2411. {
  2412. stbi__png p;
  2413. p.s = s;
  2414. return stbi__png_info_raw(&p, x, y, comp);
  2415. }
  2416. static int stbi__png_is16(stbi__context *s)
  2417. {
  2418. stbi__png p;
  2419. p.s = s;
  2420. if (!stbi__png_info_raw(&p, NULL, NULL, NULL))
  2421. return 0;
  2422. if (p.depth != 16) {
  2423. stbi__rewind(p.s);
  2424. return 0;
  2425. }
  2426. return 1;
  2427. }
  2428. #endif
  2429. static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
  2430. {
  2431. #ifndef STBI_NO_PNG
  2432. if (stbi__png_info(s, x, y, comp)) return 1;
  2433. #endif
  2434. return stbi__err("unknown image type", "Image not of any known type, or corrupt");
  2435. }
  2436. static int stbi__is_16_main(stbi__context *s)
  2437. {
  2438. #ifndef STBI_NO_PNG
  2439. if (stbi__png_is16(s)) return 1;
  2440. #endif
  2441. return 0;
  2442. }
  2443. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
  2444. {
  2445. stbi__context s;
  2446. stbi__start_mem(&s,buffer,len);
  2447. return stbi__info_main(&s,x,y,comp);
  2448. }
  2449. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
  2450. {
  2451. stbi__context s;
  2452. stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
  2453. return stbi__info_main(&s,x,y,comp);
  2454. }
  2455. STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len)
  2456. {
  2457. stbi__context s;
  2458. stbi__start_mem(&s,buffer,len);
  2459. return stbi__is_16_main(&s);
  2460. }
  2461. STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user)
  2462. {
  2463. stbi__context s;
  2464. stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
  2465. return stbi__is_16_main(&s);
  2466. }
  2467. #endif
  2468. #endif
  2469. #ifndef APCK_OGG
  2470. #define APCK_OGG stb_vorbis_decode_memory
  2471. #define STB_VORBIS_NO_STDIO
  2472. #define STB_VORBIS_NO_PUSHDATA_API
  2473. #define STB_VORBIS_MAX_CHANNELS 8
  2474. /* Ogg Vorbis audio decoder - v1.22 - public domain
  2475. https://github.com/nothings/stb */
  2476. /**************** embeded stb_vorbis.h ****************/
  2477. #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
  2478. #define STB_VORBIS_INCLUDE_STB_VORBIS_H
  2479. #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
  2480. #define STB_VORBIS_NO_STDIO 1
  2481. #endif
  2482. #ifdef __cplusplus
  2483. extern "C" {
  2484. #endif
  2485. typedef struct
  2486. {
  2487. char *alloc_buffer;
  2488. int alloc_buffer_length_in_bytes;
  2489. } stb_vorbis_alloc;
  2490. typedef struct stb_vorbis stb_vorbis;
  2491. typedef struct
  2492. {
  2493. unsigned int sample_rate;
  2494. int channels;
  2495. unsigned int setup_memory_required;
  2496. unsigned int setup_temp_memory_required;
  2497. unsigned int temp_memory_required;
  2498. int max_frame_size;
  2499. } stb_vorbis_info;
  2500. typedef struct
  2501. {
  2502. char *vendor;
  2503. int comment_list_length;
  2504. char **comment_list;
  2505. } stb_vorbis_comment;
  2506. extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
  2507. extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);
  2508. extern int stb_vorbis_get_error(stb_vorbis *f);
  2509. extern void stb_vorbis_close(stb_vorbis *f);
  2510. extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
  2511. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
  2512. #ifndef STB_VORBIS_NO_PULLDATA_API
  2513. #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
  2514. extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
  2515. #endif
  2516. #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
  2517. extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
  2518. #endif
  2519. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
  2520. int *error, const stb_vorbis_alloc *alloc_buffer);
  2521. extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
  2522. extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
  2523. extern int stb_vorbis_seek_start(stb_vorbis *f);
  2524. extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
  2525. extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
  2526. extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
  2527. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  2528. extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
  2529. extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
  2530. #endif
  2531. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
  2532. extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
  2533. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  2534. extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
  2535. extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
  2536. #endif
  2537. #endif
  2538. enum STBVorbisError
  2539. {
  2540. VORBIS__no_error,
  2541. VORBIS_need_more_data=1,
  2542. VORBIS_invalid_api_mixing,
  2543. VORBIS_outofmem,
  2544. VORBIS_feature_not_supported,
  2545. VORBIS_too_many_channels,
  2546. VORBIS_file_open_failure,
  2547. VORBIS_seek_without_length,
  2548. VORBIS_unexpected_eof=10,
  2549. VORBIS_seek_invalid,
  2550. VORBIS_invalid_setup=20,
  2551. VORBIS_invalid_stream,
  2552. VORBIS_missing_capture_pattern=30,
  2553. VORBIS_invalid_stream_structure_version,
  2554. VORBIS_continued_packet_flag_invalid,
  2555. VORBIS_incorrect_stream_serial_number,
  2556. VORBIS_invalid_first_page,
  2557. VORBIS_bad_packet_type,
  2558. VORBIS_cant_find_last_page,
  2559. VORBIS_seek_failed,
  2560. VORBIS_ogg_skeleton_not_supported
  2561. };
  2562. #ifdef __cplusplus
  2563. }
  2564. #endif
  2565. #endif
  2566. #ifndef STB_VORBIS_HEADER_ONLY
  2567. #ifndef STB_VORBIS_MAX_CHANNELS
  2568. #define STB_VORBIS_MAX_CHANNELS 16
  2569. #endif
  2570. #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
  2571. #define STB_VORBIS_PUSHDATA_CRC_COUNT 4
  2572. #endif
  2573. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
  2574. #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
  2575. #endif
  2576. #ifndef STB_VORBIS_FAST_HUFFMAN_INT
  2577. #define STB_VORBIS_FAST_HUFFMAN_SHORT
  2578. #endif
  2579. #ifdef STB_VORBIS_CODEBOOK_SHORTS
  2580. #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
  2581. #endif
  2582. #ifdef STB_VORBIS_NO_PULLDATA_API
  2583. #define STB_VORBIS_NO_INTEGER_CONVERSION
  2584. #define STB_VORBIS_NO_STDIO
  2585. #endif
  2586. #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
  2587. #define STB_VORBIS_NO_STDIO 1
  2588. #endif
  2589. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  2590. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  2591. #ifndef STB_VORBIS_BIG_ENDIAN
  2592. #define STB_VORBIS_ENDIAN 0
  2593. #else
  2594. #define STB_VORBIS_ENDIAN 1
  2595. #endif
  2596. #endif
  2597. #endif
  2598. #ifndef STB_VORBIS_NO_CRT
  2599. #include <stdlib.h>
  2600. #include <string.h>
  2601. #include <assert.h>
  2602. #include <math.h>
  2603. #if defined(_MSC_VER) || defined(__MINGW32__)
  2604. #include <malloc.h>
  2605. #endif
  2606. #if defined(__linux__) || defined(__linux) || defined(__sun__) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)
  2607. #include <alloca.h>
  2608. #endif
  2609. #else
  2610. #define NULL 0
  2611. #define malloc(s) 0
  2612. #define free(s) ((void) 0)
  2613. #define realloc(s) 0
  2614. #endif
  2615. #include <limits.h>
  2616. #ifdef __MINGW32__
  2617. #ifdef __forceinline
  2618. #undef __forceinline
  2619. #endif
  2620. #define __forceinline
  2621. #ifndef alloca
  2622. #define alloca __builtin_alloca
  2623. #endif
  2624. #elif !defined(_MSC_VER)
  2625. #if __GNUC__
  2626. #define __forceinline inline
  2627. #else
  2628. #define __forceinline
  2629. #endif
  2630. #endif
  2631. #if STB_VORBIS_MAX_CHANNELS > 256
  2632. #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
  2633. #endif
  2634. #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
  2635. #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
  2636. #endif
  2637. #if 0
  2638. #include <crtdbg.h>
  2639. #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
  2640. #else
  2641. #define CHECK(f) ((void) 0)
  2642. #endif
  2643. #define MAX_BLOCKSIZE_LOG 13
  2644. #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
  2645. typedef unsigned char uint8;
  2646. typedef signed char int8;
  2647. typedef unsigned short uint16;
  2648. typedef signed short int16;
  2649. typedef unsigned int uint32;
  2650. typedef signed int int32;
  2651. #ifndef TRUE
  2652. #define TRUE 1
  2653. #define FALSE 0
  2654. #endif
  2655. typedef float codetype;
  2656. #ifdef _MSC_VER
  2657. #define STBV_NOTUSED(v) (void)(v)
  2658. #else
  2659. #define STBV_NOTUSED(v) (void)sizeof(v)
  2660. #endif
  2661. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
  2662. #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
  2663. typedef struct
  2664. {
  2665. int dimensions, entries;
  2666. uint8 *codeword_lengths;
  2667. float minimum_value;
  2668. float delta_value;
  2669. uint8 value_bits;
  2670. uint8 lookup_type;
  2671. uint8 sequence_p;
  2672. uint8 sparse;
  2673. uint32 lookup_values;
  2674. codetype *multiplicands;
  2675. uint32 *codewords;
  2676. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  2677. int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  2678. #else
  2679. int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  2680. #endif
  2681. uint32 *sorted_codewords;
  2682. int *sorted_values;
  2683. int sorted_entries;
  2684. } Codebook;
  2685. typedef struct
  2686. {
  2687. uint8 order;
  2688. uint16 rate;
  2689. uint16 bark_map_size;
  2690. uint8 amplitude_bits;
  2691. uint8 amplitude_offset;
  2692. uint8 number_of_books;
  2693. uint8 book_list[16];
  2694. } Floor0;
  2695. typedef struct
  2696. {
  2697. uint8 partitions;
  2698. uint8 partition_class_list[32];
  2699. uint8 class_dimensions[16];
  2700. uint8 class_subclasses[16];
  2701. uint8 class_masterbooks[16];
  2702. int16 subclass_books[16][8];
  2703. uint16 Xlist[31*8+2];
  2704. uint8 sorted_order[31*8+2];
  2705. uint8 neighbors[31*8+2][2];
  2706. uint8 floor1_multiplier;
  2707. uint8 rangebits;
  2708. int values;
  2709. } Floor1;
  2710. typedef union
  2711. {
  2712. Floor0 floor0;
  2713. Floor1 floor1;
  2714. } Floor;
  2715. typedef struct
  2716. {
  2717. uint32 begin, end;
  2718. uint32 part_size;
  2719. uint8 classifications;
  2720. uint8 classbook;
  2721. uint8 **classdata;
  2722. int16 (*residue_books)[8];
  2723. } Residue;
  2724. typedef struct
  2725. {
  2726. uint8 magnitude;
  2727. uint8 angle;
  2728. uint8 mux;
  2729. } MappingChannel;
  2730. typedef struct
  2731. {
  2732. uint16 coupling_steps;
  2733. MappingChannel *chan;
  2734. uint8 submaps;
  2735. uint8 submap_floor[15];
  2736. uint8 submap_residue[15];
  2737. } Mapping;
  2738. typedef struct
  2739. {
  2740. uint8 blockflag;
  2741. uint8 mapping;
  2742. uint16 windowtype;
  2743. uint16 transformtype;
  2744. } Mode;
  2745. typedef struct
  2746. {
  2747. uint32 goal_crc;
  2748. int bytes_left;
  2749. uint32 crc_so_far;
  2750. int bytes_done;
  2751. uint32 sample_loc;
  2752. } CRCscan;
  2753. typedef struct
  2754. {
  2755. uint32 page_start, page_end;
  2756. uint32 last_decoded_sample;
  2757. } ProbedPage;
  2758. struct stb_vorbis
  2759. {
  2760. unsigned int sample_rate;
  2761. int channels;
  2762. unsigned int setup_memory_required;
  2763. unsigned int temp_memory_required;
  2764. unsigned int setup_temp_memory_required;
  2765. char *vendor;
  2766. int comment_list_length;
  2767. char **comment_list;
  2768. uint8 *stream;
  2769. uint8 *stream_start;
  2770. uint8 *stream_end;
  2771. uint32 stream_len;
  2772. uint8 push_mode;
  2773. uint32 first_audio_page_offset;
  2774. ProbedPage p_first, p_last;
  2775. stb_vorbis_alloc alloc;
  2776. int setup_offset;
  2777. int temp_offset;
  2778. int eof;
  2779. enum STBVorbisError error;
  2780. int blocksize[2];
  2781. int blocksize_0, blocksize_1;
  2782. int codebook_count;
  2783. Codebook *codebooks;
  2784. int floor_count;
  2785. uint16 floor_types[64];
  2786. Floor *floor_config;
  2787. int residue_count;
  2788. uint16 residue_types[64];
  2789. Residue *residue_config;
  2790. int mapping_count;
  2791. Mapping *mapping;
  2792. int mode_count;
  2793. Mode mode_config[64];
  2794. uint32 total_samples;
  2795. float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
  2796. float *outputs [STB_VORBIS_MAX_CHANNELS];
  2797. float *previous_window[STB_VORBIS_MAX_CHANNELS];
  2798. int previous_length;
  2799. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2800. int16 *finalY[STB_VORBIS_MAX_CHANNELS];
  2801. #else
  2802. float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
  2803. #endif
  2804. uint32 current_loc;
  2805. int current_loc_valid;
  2806. float *A[2],*B[2],*C[2];
  2807. float *window[2];
  2808. uint16 *bit_reverse[2];
  2809. uint32 serial;
  2810. int last_page;
  2811. int segment_count;
  2812. uint8 segments[255];
  2813. uint8 page_flag;
  2814. uint8 bytes_in_seg;
  2815. uint8 first_decode;
  2816. int next_seg;
  2817. int last_seg;
  2818. int last_seg_which;
  2819. uint32 acc;
  2820. int valid_bits;
  2821. int packet_bytes;
  2822. int end_seg_with_known_loc;
  2823. uint32 known_loc_for_packet;
  2824. int discard_samples_deferred;
  2825. uint32 samples_output;
  2826. int page_crc_tests;
  2827. int channel_buffer_start;
  2828. int channel_buffer_end;
  2829. };
  2830. #if defined(STB_VORBIS_NO_PUSHDATA_API)
  2831. #define IS_PUSH_MODE(f) FALSE
  2832. #elif defined(STB_VORBIS_NO_PULLDATA_API)
  2833. #define IS_PUSH_MODE(f) TRUE
  2834. #else
  2835. #define IS_PUSH_MODE(f) ((f)->push_mode)
  2836. #endif
  2837. typedef struct stb_vorbis vorb;
  2838. static int error(vorb *f, enum STBVorbisError e)
  2839. {
  2840. f->error = e;
  2841. if (!f->eof && e != VORBIS_need_more_data) {
  2842. f->error=e;
  2843. }
  2844. return 0;
  2845. }
  2846. #define array_size_required(count,size) (count*(sizeof(void *)+(size)))
  2847. #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
  2848. #define temp_free(f,p) (void)0
  2849. #define temp_alloc_save(f) ((f)->temp_offset)
  2850. #define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
  2851. #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
  2852. static void *make_block_array(void *mem, int count, int size)
  2853. {
  2854. int i;
  2855. void ** p = (void **) mem;
  2856. char *q = (char *) (p + count);
  2857. for (i=0; i < count; ++i) {
  2858. p[i] = q;
  2859. q += size;
  2860. }
  2861. return p;
  2862. }
  2863. static void *setup_malloc(vorb *f, int sz)
  2864. {
  2865. sz = (sz+7) & ~7;
  2866. f->setup_memory_required += sz;
  2867. if (f->alloc.alloc_buffer) {
  2868. void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
  2869. if (f->setup_offset + sz > f->temp_offset) return NULL;
  2870. f->setup_offset += sz;
  2871. return p;
  2872. }
  2873. return sz ? malloc(sz) : NULL;
  2874. }
  2875. static void setup_free(vorb *f, void *p)
  2876. {
  2877. if (f->alloc.alloc_buffer) return;
  2878. free(p);
  2879. }
  2880. static void *setup_temp_malloc(vorb *f, int sz)
  2881. {
  2882. sz = (sz+7) & ~7;
  2883. if (f->alloc.alloc_buffer) {
  2884. if (f->temp_offset - sz < f->setup_offset) return NULL;
  2885. f->temp_offset -= sz;
  2886. return (char *) f->alloc.alloc_buffer + f->temp_offset;
  2887. }
  2888. return malloc(sz);
  2889. }
  2890. static void setup_temp_free(vorb *f, void *p, int sz)
  2891. {
  2892. if (f->alloc.alloc_buffer) {
  2893. f->temp_offset += (sz+7)&~7;
  2894. return;
  2895. }
  2896. free(p);
  2897. }
  2898. #define CRC32_POLY 0x04c11db7
  2899. static uint32 crc_table[256];
  2900. static void crc32_init(void)
  2901. {
  2902. int i,j;
  2903. uint32 s;
  2904. for(i=0; i < 256; i++) {
  2905. for (s=(uint32) i << 24, j=0; j < 8; ++j)
  2906. s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
  2907. crc_table[i] = s;
  2908. }
  2909. }
  2910. static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
  2911. {
  2912. return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
  2913. }
  2914. static unsigned int bit_reverse(unsigned int n)
  2915. {
  2916. n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
  2917. n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
  2918. n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
  2919. n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
  2920. return (n >> 16) | (n << 16);
  2921. }
  2922. static float square(float x)
  2923. {
  2924. return x*x;
  2925. }
  2926. static int ilog(int32 n)
  2927. {
  2928. static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
  2929. if (n < 0) return 0;
  2930. if (n < (1 << 14))
  2931. if (n < (1 << 4)) return 0 + log2_4[n ];
  2932. else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
  2933. else return 10 + log2_4[n >> 10];
  2934. else if (n < (1 << 24))
  2935. if (n < (1 << 19)) return 15 + log2_4[n >> 15];
  2936. else return 20 + log2_4[n >> 20];
  2937. else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
  2938. else return 30 + log2_4[n >> 30];
  2939. }
  2940. #ifndef M_PI
  2941. #define M_PI 3.14159265358979323846264f
  2942. #endif
  2943. #define NO_CODE 255
  2944. static float float32_unpack(uint32 x)
  2945. {
  2946. uint32 mantissa = x & 0x1fffff;
  2947. uint32 sign = x & 0x80000000;
  2948. uint32 exp = (x & 0x7fe00000) >> 21;
  2949. double res = sign ? -(double)mantissa : (double)mantissa;
  2950. return (float) ldexp((float)res, (int)exp-788);
  2951. }
  2952. static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
  2953. {
  2954. if (!c->sparse) {
  2955. c->codewords [symbol] = huff_code;
  2956. } else {
  2957. c->codewords [count] = huff_code;
  2958. c->codeword_lengths[count] = len;
  2959. values [count] = symbol;
  2960. }
  2961. }
  2962. static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
  2963. {
  2964. int i,k,m=0;
  2965. uint32 available[32];
  2966. memset(available, 0, sizeof(available));
  2967. for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
  2968. if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
  2969. assert(len[k] < 32);
  2970. add_entry(c, 0, k, m++, len[k], values);
  2971. for (i=1; i <= len[k]; ++i)
  2972. available[i] = 1U << (32-i);
  2973. for (i=k+1; i < n; ++i) {
  2974. uint32 res;
  2975. int z = len[i], y;
  2976. if (z == NO_CODE) continue;
  2977. assert(z < 32);
  2978. while (z > 0 && !available[z]) --z;
  2979. if (z == 0) { return FALSE; }
  2980. res = available[z];
  2981. available[z] = 0;
  2982. add_entry(c, bit_reverse(res), i, m++, len[i], values);
  2983. if (z != len[i]) {
  2984. for (y=len[i]; y > z; --y) {
  2985. assert(available[y] == 0);
  2986. available[y] = res + (1 << (32-y));
  2987. }
  2988. }
  2989. }
  2990. return TRUE;
  2991. }
  2992. static void compute_accelerated_huffman(Codebook *c)
  2993. {
  2994. int i, len;
  2995. for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
  2996. c->fast_huffman[i] = -1;
  2997. len = c->sparse ? c->sorted_entries : c->entries;
  2998. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  2999. if (len > 32767) len = 32767;
  3000. #endif
  3001. for (i=0; i < len; ++i) {
  3002. if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
  3003. uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
  3004. while (z < FAST_HUFFMAN_TABLE_SIZE) {
  3005. c->fast_huffman[z] = i;
  3006. z += 1 << c->codeword_lengths[i];
  3007. }
  3008. }
  3009. }
  3010. }
  3011. #ifdef _MSC_VER
  3012. #define STBV_CDECL __cdecl
  3013. #else
  3014. #define STBV_CDECL
  3015. #endif
  3016. static int STBV_CDECL uint32_compare(const void *p, const void *q)
  3017. {
  3018. uint32 x = * (uint32 *) p;
  3019. uint32 y = * (uint32 *) q;
  3020. return x < y ? -1 : x > y;
  3021. }
  3022. static int include_in_sort(Codebook *c, uint8 len)
  3023. {
  3024. if (c->sparse) { assert(len != NO_CODE); return TRUE; }
  3025. if (len == NO_CODE) return FALSE;
  3026. if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
  3027. return FALSE;
  3028. }
  3029. static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
  3030. {
  3031. int i, len;
  3032. if (!c->sparse) {
  3033. int k = 0;
  3034. for (i=0; i < c->entries; ++i)
  3035. if (include_in_sort(c, lengths[i]))
  3036. c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
  3037. assert(k == c->sorted_entries);
  3038. } else {
  3039. for (i=0; i < c->sorted_entries; ++i)
  3040. c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
  3041. }
  3042. qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
  3043. c->sorted_codewords[c->sorted_entries] = 0xffffffff;
  3044. len = c->sparse ? c->sorted_entries : c->entries;
  3045. for (i=0; i < len; ++i) {
  3046. int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
  3047. if (include_in_sort(c,huff_len)) {
  3048. uint32 code = bit_reverse(c->codewords[i]);
  3049. int x=0, n=c->sorted_entries;
  3050. while (n > 1) {
  3051. int m = x + (n >> 1);
  3052. if (c->sorted_codewords[m] <= code) {
  3053. x = m;
  3054. n -= (n>>1);
  3055. } else {
  3056. n >>= 1;
  3057. }
  3058. }
  3059. assert(c->sorted_codewords[x] == code);
  3060. if (c->sparse) {
  3061. c->sorted_values[x] = values[i];
  3062. c->codeword_lengths[x] = huff_len;
  3063. } else {
  3064. c->sorted_values[x] = i;
  3065. }
  3066. }
  3067. }
  3068. }
  3069. static int vorbis_validate(uint8 *data)
  3070. {
  3071. static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
  3072. return memcmp(data, vorbis, 6) == 0;
  3073. }
  3074. static int lookup1_values(int entries, int dim)
  3075. {
  3076. int r = (int) floor(exp((float) log((float) entries) / dim));
  3077. if ((int) floor(pow((float) r+1, dim)) <= entries)
  3078. ++r;
  3079. if (pow((float) r+1, dim) <= entries)
  3080. return -1;
  3081. if ((int) floor(pow((float) r, dim)) > entries)
  3082. return -1;
  3083. return r;
  3084. }
  3085. static void compute_twiddle_factors(int n, float *A, float *B, float *C)
  3086. {
  3087. int n4 = n >> 2, n8 = n >> 3;
  3088. int k,k2;
  3089. for (k=k2=0; k < n4; ++k,k2+=2) {
  3090. A[k2 ] = (float) cos(4*k*M_PI/n);
  3091. A[k2+1] = (float) -sin(4*k*M_PI/n);
  3092. B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
  3093. B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
  3094. }
  3095. for (k=k2=0; k < n8; ++k,k2+=2) {
  3096. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  3097. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  3098. }
  3099. }
  3100. static void compute_window(int n, float *window)
  3101. {
  3102. int n2 = n >> 1, i;
  3103. for (i=0; i < n2; ++i)
  3104. window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
  3105. }
  3106. static void compute_bitreverse(int n, uint16 *rev)
  3107. {
  3108. int ld = ilog(n) - 1;
  3109. int i, n8 = n >> 3;
  3110. for (i=0; i < n8; ++i)
  3111. rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
  3112. }
  3113. static int init_blocksize(vorb *f, int b, int n)
  3114. {
  3115. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
  3116. f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  3117. f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  3118. f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
  3119. if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
  3120. compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
  3121. f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  3122. if (!f->window[b]) return error(f, VORBIS_outofmem);
  3123. compute_window(n, f->window[b]);
  3124. f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
  3125. if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
  3126. compute_bitreverse(n, f->bit_reverse[b]);
  3127. return TRUE;
  3128. }
  3129. static void neighbors(uint16 *x, int n, int *plow, int *phigh)
  3130. {
  3131. int low = -1;
  3132. int high = 65536;
  3133. int i;
  3134. for (i=0; i < n; ++i) {
  3135. if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
  3136. if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
  3137. }
  3138. }
  3139. typedef struct
  3140. {
  3141. uint16 x,id;
  3142. } stbv__floor_ordering;
  3143. static int STBV_CDECL point_compare(const void *p, const void *q)
  3144. {
  3145. stbv__floor_ordering *a = (stbv__floor_ordering *) p;
  3146. stbv__floor_ordering *b = (stbv__floor_ordering *) q;
  3147. return a->x < b->x ? -1 : a->x > b->x;
  3148. }
  3149. #if defined(STB_VORBIS_NO_STDIO)
  3150. #define USE_MEMORY(z) TRUE
  3151. #else
  3152. #define USE_MEMORY(z) ((z)->stream)
  3153. #endif
  3154. static uint8 get8(vorb *z)
  3155. {
  3156. if (USE_MEMORY(z)) {
  3157. if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
  3158. return *z->stream++;
  3159. }
  3160. }
  3161. static uint32 get32(vorb *f)
  3162. {
  3163. uint32 x;
  3164. x = get8(f);
  3165. x += get8(f) << 8;
  3166. x += get8(f) << 16;
  3167. x += (uint32) get8(f) << 24;
  3168. return x;
  3169. }
  3170. static int getn(vorb *z, uint8 *data, int n)
  3171. {
  3172. if (USE_MEMORY(z)) {
  3173. if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
  3174. memcpy(data, z->stream, n);
  3175. z->stream += n;
  3176. return 1;
  3177. }
  3178. }
  3179. static void skip(vorb *z, int n)
  3180. {
  3181. if (USE_MEMORY(z)) {
  3182. z->stream += n;
  3183. if (z->stream >= z->stream_end) z->eof = 1;
  3184. return;
  3185. }
  3186. }
  3187. static int set_file_offset(stb_vorbis *f, unsigned int loc)
  3188. {
  3189. f->eof = 0;
  3190. if (USE_MEMORY(f)) {
  3191. if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
  3192. f->stream = f->stream_end;
  3193. f->eof = 1;
  3194. return 0;
  3195. } else {
  3196. f->stream = f->stream_start + loc;
  3197. return 1;
  3198. }
  3199. }
  3200. }
  3201. static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
  3202. static int capture_pattern(vorb *f)
  3203. {
  3204. if (0x4f != get8(f)) return FALSE;
  3205. if (0x67 != get8(f)) return FALSE;
  3206. if (0x67 != get8(f)) return FALSE;
  3207. if (0x53 != get8(f)) return FALSE;
  3208. return TRUE;
  3209. }
  3210. #define PAGEFLAG_continued_packet 1
  3211. #define PAGEFLAG_first_page 2
  3212. #define PAGEFLAG_last_page 4
  3213. static int start_page_no_capturepattern(vorb *f)
  3214. {
  3215. uint32 loc0,loc1,n;
  3216. if (f->first_decode && !IS_PUSH_MODE(f)) {
  3217. f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;
  3218. }
  3219. if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
  3220. f->page_flag = get8(f);
  3221. loc0 = get32(f);
  3222. loc1 = get32(f);
  3223. get32(f);
  3224. n = get32(f);
  3225. f->last_page = n;
  3226. get32(f);
  3227. f->segment_count = get8(f);
  3228. if (!getn(f, f->segments, f->segment_count))
  3229. return error(f, VORBIS_unexpected_eof);
  3230. f->end_seg_with_known_loc = -2;
  3231. if (loc0 != ~0U || loc1 != ~0U) {
  3232. int i;
  3233. for (i=f->segment_count-1; i >= 0; --i)
  3234. if (f->segments[i] < 255)
  3235. break;
  3236. if (i >= 0) {
  3237. f->end_seg_with_known_loc = i;
  3238. f->known_loc_for_packet = loc0;
  3239. }
  3240. }
  3241. if (f->first_decode) {
  3242. int i,len;
  3243. len = 0;
  3244. for (i=0; i < f->segment_count; ++i)
  3245. len += f->segments[i];
  3246. len += 27 + f->segment_count;
  3247. f->p_first.page_end = f->p_first.page_start + len;
  3248. f->p_first.last_decoded_sample = loc0;
  3249. }
  3250. f->next_seg = 0;
  3251. return TRUE;
  3252. }
  3253. static int start_page(vorb *f)
  3254. {
  3255. if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
  3256. return start_page_no_capturepattern(f);
  3257. }
  3258. static int start_packet(vorb *f)
  3259. {
  3260. while (f->next_seg == -1) {
  3261. if (!start_page(f)) return FALSE;
  3262. if (f->page_flag & PAGEFLAG_continued_packet)
  3263. return error(f, VORBIS_continued_packet_flag_invalid);
  3264. }
  3265. f->last_seg = FALSE;
  3266. f->valid_bits = 0;
  3267. f->packet_bytes = 0;
  3268. f->bytes_in_seg = 0;
  3269. return TRUE;
  3270. }
  3271. static int maybe_start_packet(vorb *f)
  3272. {
  3273. if (f->next_seg == -1) {
  3274. int x = get8(f);
  3275. if (f->eof) return FALSE;
  3276. if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
  3277. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  3278. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  3279. if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  3280. if (!start_page_no_capturepattern(f)) return FALSE;
  3281. if (f->page_flag & PAGEFLAG_continued_packet) {
  3282. f->last_seg = FALSE;
  3283. f->bytes_in_seg = 0;
  3284. return error(f, VORBIS_continued_packet_flag_invalid);
  3285. }
  3286. }
  3287. return start_packet(f);
  3288. }
  3289. static int next_segment(vorb *f)
  3290. {
  3291. int len;
  3292. if (f->last_seg) return 0;
  3293. if (f->next_seg == -1) {
  3294. f->last_seg_which = f->segment_count-1;
  3295. if (!start_page(f)) { f->last_seg = 1; return 0; }
  3296. if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
  3297. }
  3298. len = f->segments[f->next_seg++];
  3299. if (len < 255) {
  3300. f->last_seg = TRUE;
  3301. f->last_seg_which = f->next_seg-1;
  3302. }
  3303. if (f->next_seg >= f->segment_count)
  3304. f->next_seg = -1;
  3305. assert(f->bytes_in_seg == 0);
  3306. f->bytes_in_seg = len;
  3307. return len;
  3308. }
  3309. #define EOP (-1)
  3310. #define INVALID_BITS (-1)
  3311. static int get8_packet_raw(vorb *f)
  3312. {
  3313. if (!f->bytes_in_seg) {
  3314. if (f->last_seg) return EOP;
  3315. else if (!next_segment(f)) return EOP;
  3316. }
  3317. assert(f->bytes_in_seg > 0);
  3318. --f->bytes_in_seg;
  3319. ++f->packet_bytes;
  3320. return get8(f);
  3321. }
  3322. static int get8_packet(vorb *f)
  3323. {
  3324. int x = get8_packet_raw(f);
  3325. f->valid_bits = 0;
  3326. return x;
  3327. }
  3328. static int get32_packet(vorb *f)
  3329. {
  3330. uint32 x;
  3331. x = get8_packet(f);
  3332. x += get8_packet(f) << 8;
  3333. x += get8_packet(f) << 16;
  3334. x += (uint32) get8_packet(f) << 24;
  3335. return x;
  3336. }
  3337. static void flush_packet(vorb *f)
  3338. {
  3339. while (get8_packet_raw(f) != EOP);
  3340. }
  3341. static uint32 get_bits(vorb *f, int n)
  3342. {
  3343. uint32 z;
  3344. if (f->valid_bits < 0) return 0;
  3345. if (f->valid_bits < n) {
  3346. if (n > 24) {
  3347. z = get_bits(f, 24);
  3348. z += get_bits(f, n-24) << 24;
  3349. return z;
  3350. }
  3351. if (f->valid_bits == 0) f->acc = 0;
  3352. while (f->valid_bits < n) {
  3353. int z = get8_packet_raw(f);
  3354. if (z == EOP) {
  3355. f->valid_bits = INVALID_BITS;
  3356. return 0;
  3357. }
  3358. f->acc += z << f->valid_bits;
  3359. f->valid_bits += 8;
  3360. }
  3361. }
  3362. assert(f->valid_bits >= n);
  3363. z = f->acc & ((1 << n)-1);
  3364. f->acc >>= n;
  3365. f->valid_bits -= n;
  3366. return z;
  3367. }
  3368. static __forceinline void prep_huffman(vorb *f)
  3369. {
  3370. if (f->valid_bits <= 24) {
  3371. if (f->valid_bits == 0) f->acc = 0;
  3372. do {
  3373. int z;
  3374. if (f->last_seg && !f->bytes_in_seg) return;
  3375. z = get8_packet_raw(f);
  3376. if (z == EOP) return;
  3377. f->acc += (unsigned) z << f->valid_bits;
  3378. f->valid_bits += 8;
  3379. } while (f->valid_bits <= 24);
  3380. }
  3381. }
  3382. enum
  3383. {
  3384. VORBIS_packet_id = 1,
  3385. VORBIS_packet_comment = 3,
  3386. VORBIS_packet_setup = 5
  3387. };
  3388. static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
  3389. {
  3390. int i;
  3391. prep_huffman(f);
  3392. if (c->codewords == NULL && c->sorted_codewords == NULL)
  3393. return -1;
  3394. if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
  3395. uint32 code = bit_reverse(f->acc);
  3396. int x=0, n=c->sorted_entries, len;
  3397. while (n > 1) {
  3398. int m = x + (n >> 1);
  3399. if (c->sorted_codewords[m] <= code) {
  3400. x = m;
  3401. n -= (n>>1);
  3402. } else {
  3403. n >>= 1;
  3404. }
  3405. }
  3406. if (!c->sparse) x = c->sorted_values[x];
  3407. len = c->codeword_lengths[x];
  3408. if (f->valid_bits >= len) {
  3409. f->acc >>= len;
  3410. f->valid_bits -= len;
  3411. return x;
  3412. }
  3413. f->valid_bits = 0;
  3414. return -1;
  3415. }
  3416. assert(!c->sparse);
  3417. for (i=0; i < c->entries; ++i) {
  3418. if (c->codeword_lengths[i] == NO_CODE) continue;
  3419. if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
  3420. if (f->valid_bits >= c->codeword_lengths[i]) {
  3421. f->acc >>= c->codeword_lengths[i];
  3422. f->valid_bits -= c->codeword_lengths[i];
  3423. return i;
  3424. }
  3425. f->valid_bits = 0;
  3426. return -1;
  3427. }
  3428. }
  3429. error(f, VORBIS_invalid_stream);
  3430. f->valid_bits = 0;
  3431. return -1;
  3432. }
  3433. #ifndef STB_VORBIS_NO_INLINE_DECODE
  3434. #define DECODE_RAW(var, f,c) \
  3435. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
  3436. prep_huffman(f); \
  3437. var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
  3438. var = c->fast_huffman[var]; \
  3439. if (var >= 0) { \
  3440. int n = c->codeword_lengths[var]; \
  3441. f->acc >>= n; \
  3442. f->valid_bits -= n; \
  3443. if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
  3444. } else { \
  3445. var = codebook_decode_scalar_raw(f,c); \
  3446. }
  3447. #else
  3448. static int codebook_decode_scalar(vorb *f, Codebook *c)
  3449. {
  3450. int i;
  3451. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
  3452. prep_huffman(f);
  3453. i = f->acc & FAST_HUFFMAN_TABLE_MASK;
  3454. i = c->fast_huffman[i];
  3455. if (i >= 0) {
  3456. f->acc >>= c->codeword_lengths[i];
  3457. f->valid_bits -= c->codeword_lengths[i];
  3458. if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
  3459. return i;
  3460. }
  3461. return codebook_decode_scalar_raw(f,c);
  3462. }
  3463. #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
  3464. #endif
  3465. #define DECODE(var,f,c) \
  3466. DECODE_RAW(var,f,c) \
  3467. if (c->sparse) var = c->sorted_values[var];
  3468. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3469. #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
  3470. #else
  3471. #define DECODE_VQ(var,f,c) DECODE(var,f,c)
  3472. #endif
  3473. #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
  3474. #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
  3475. #define CODEBOOK_ELEMENT_BASE(c) (0)
  3476. static int codebook_decode_start(vorb *f, Codebook *c)
  3477. {
  3478. int z = -1;
  3479. if (c->lookup_type == 0)
  3480. error(f, VORBIS_invalid_stream);
  3481. else {
  3482. DECODE_VQ(z,f,c);
  3483. if (c->sparse) assert(z < c->sorted_entries);
  3484. if (z < 0) {
  3485. if (!f->bytes_in_seg)
  3486. if (f->last_seg)
  3487. return z;
  3488. error(f, VORBIS_invalid_stream);
  3489. }
  3490. }
  3491. return z;
  3492. }
  3493. static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
  3494. {
  3495. int i,z = codebook_decode_start(f,c);
  3496. if (z < 0) return FALSE;
  3497. if (len > c->dimensions) len = c->dimensions;
  3498. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3499. if (c->lookup_type == 1) {
  3500. float last = CODEBOOK_ELEMENT_BASE(c);
  3501. int div = 1;
  3502. for (i=0; i < len; ++i) {
  3503. int off = (z / div) % c->lookup_values;
  3504. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  3505. output[i] += val;
  3506. if (c->sequence_p) last = val + c->minimum_value;
  3507. div *= c->lookup_values;
  3508. }
  3509. return TRUE;
  3510. }
  3511. #endif
  3512. z *= c->dimensions;
  3513. if (c->sequence_p) {
  3514. float last = CODEBOOK_ELEMENT_BASE(c);
  3515. for (i=0; i < len; ++i) {
  3516. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  3517. output[i] += val;
  3518. last = val + c->minimum_value;
  3519. }
  3520. } else {
  3521. float last = CODEBOOK_ELEMENT_BASE(c);
  3522. for (i=0; i < len; ++i) {
  3523. output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  3524. }
  3525. }
  3526. return TRUE;
  3527. }
  3528. static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
  3529. {
  3530. int i,z = codebook_decode_start(f,c);
  3531. float last = CODEBOOK_ELEMENT_BASE(c);
  3532. if (z < 0) return FALSE;
  3533. if (len > c->dimensions) len = c->dimensions;
  3534. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3535. if (c->lookup_type == 1) {
  3536. int div = 1;
  3537. for (i=0; i < len; ++i) {
  3538. int off = (z / div) % c->lookup_values;
  3539. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  3540. output[i*step] += val;
  3541. if (c->sequence_p) last = val;
  3542. div *= c->lookup_values;
  3543. }
  3544. return TRUE;
  3545. }
  3546. #endif
  3547. z *= c->dimensions;
  3548. for (i=0; i < len; ++i) {
  3549. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  3550. output[i*step] += val;
  3551. if (c->sequence_p) last = val;
  3552. }
  3553. return TRUE;
  3554. }
  3555. 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)
  3556. {
  3557. int c_inter = *c_inter_p;
  3558. int p_inter = *p_inter_p;
  3559. int i,z, effective = c->dimensions;
  3560. if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
  3561. while (total_decode > 0) {
  3562. float last = CODEBOOK_ELEMENT_BASE(c);
  3563. DECODE_VQ(z,f,c);
  3564. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3565. assert(!c->sparse || z < c->sorted_entries);
  3566. #endif
  3567. if (z < 0) {
  3568. if (!f->bytes_in_seg)
  3569. if (f->last_seg) return FALSE;
  3570. return error(f, VORBIS_invalid_stream);
  3571. }
  3572. if (c_inter + p_inter*ch + effective > len * ch) {
  3573. effective = len*ch - (p_inter*ch - c_inter);
  3574. }
  3575. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3576. if (c->lookup_type == 1) {
  3577. int div = 1;
  3578. for (i=0; i < effective; ++i) {
  3579. int off = (z / div) % c->lookup_values;
  3580. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  3581. if (outputs[c_inter])
  3582. outputs[c_inter][p_inter] += val;
  3583. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  3584. if (c->sequence_p) last = val;
  3585. div *= c->lookup_values;
  3586. }
  3587. } else
  3588. #endif
  3589. {
  3590. z *= c->dimensions;
  3591. if (c->sequence_p) {
  3592. for (i=0; i < effective; ++i) {
  3593. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  3594. if (outputs[c_inter])
  3595. outputs[c_inter][p_inter] += val;
  3596. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  3597. last = val;
  3598. }
  3599. } else {
  3600. for (i=0; i < effective; ++i) {
  3601. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  3602. if (outputs[c_inter])
  3603. outputs[c_inter][p_inter] += val;
  3604. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  3605. }
  3606. }
  3607. }
  3608. total_decode -= effective;
  3609. }
  3610. *c_inter_p = c_inter;
  3611. *p_inter_p = p_inter;
  3612. return TRUE;
  3613. }
  3614. static int predict_point(int x, int x0, int x1, int y0, int y1)
  3615. {
  3616. int dy = y1 - y0;
  3617. int adx = x1 - x0;
  3618. int err = abs(dy) * (x - x0);
  3619. int off = err / adx;
  3620. return dy < 0 ? y0 - off : y0 + off;
  3621. }
  3622. static float inverse_db_table[256] =
  3623. {
  3624. 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
  3625. 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
  3626. 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
  3627. 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
  3628. 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
  3629. 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
  3630. 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
  3631. 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
  3632. 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
  3633. 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
  3634. 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
  3635. 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
  3636. 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
  3637. 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
  3638. 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
  3639. 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
  3640. 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
  3641. 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
  3642. 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
  3643. 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
  3644. 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
  3645. 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
  3646. 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
  3647. 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
  3648. 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
  3649. 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
  3650. 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
  3651. 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
  3652. 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
  3653. 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
  3654. 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
  3655. 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
  3656. 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
  3657. 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
  3658. 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
  3659. 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
  3660. 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
  3661. 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
  3662. 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
  3663. 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
  3664. 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
  3665. 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
  3666. 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
  3667. 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
  3668. 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
  3669. 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
  3670. 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
  3671. 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
  3672. 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
  3673. 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
  3674. 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
  3675. 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
  3676. 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
  3677. 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
  3678. 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
  3679. 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
  3680. 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
  3681. 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
  3682. 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
  3683. 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
  3684. 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
  3685. 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
  3686. 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
  3687. 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
  3688. };
  3689. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  3690. #define LINE_OP(a,b) a *= b
  3691. #else
  3692. #define LINE_OP(a,b) a = b
  3693. #endif
  3694. #ifdef STB_VORBIS_DIVIDE_TABLE
  3695. #define DIVTAB_NUMER 32
  3696. #define DIVTAB_DENOM 64
  3697. int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM];
  3698. #endif
  3699. static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
  3700. {
  3701. int dy = y1 - y0;
  3702. int adx = x1 - x0;
  3703. int ady = abs(dy);
  3704. int base;
  3705. int x=x0,y=y0;
  3706. int err = 0;
  3707. int sy;
  3708. #ifdef STB_VORBIS_DIVIDE_TABLE
  3709. if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
  3710. if (dy < 0) {
  3711. base = -integer_divide_table[ady][adx];
  3712. sy = base-1;
  3713. } else {
  3714. base = integer_divide_table[ady][adx];
  3715. sy = base+1;
  3716. }
  3717. } else {
  3718. base = dy / adx;
  3719. if (dy < 0)
  3720. sy = base - 1;
  3721. else
  3722. sy = base+1;
  3723. }
  3724. #else
  3725. base = dy / adx;
  3726. if (dy < 0)
  3727. sy = base - 1;
  3728. else
  3729. sy = base+1;
  3730. #endif
  3731. ady -= abs(base) * adx;
  3732. if (x1 > n) x1 = n;
  3733. if (x < x1) {
  3734. LINE_OP(output[x], inverse_db_table[y&255]);
  3735. for (++x; x < x1; ++x) {
  3736. err += ady;
  3737. if (err >= adx) {
  3738. err -= adx;
  3739. y += sy;
  3740. } else
  3741. y += base;
  3742. LINE_OP(output[x], inverse_db_table[y&255]);
  3743. }
  3744. }
  3745. }
  3746. static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
  3747. {
  3748. int k;
  3749. if (rtype == 0) {
  3750. int step = n / book->dimensions;
  3751. for (k=0; k < step; ++k)
  3752. if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
  3753. return FALSE;
  3754. } else {
  3755. for (k=0; k < n; ) {
  3756. if (!codebook_decode(f, book, target+offset, n-k))
  3757. return FALSE;
  3758. k += book->dimensions;
  3759. offset += book->dimensions;
  3760. }
  3761. }
  3762. return TRUE;
  3763. }
  3764. static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
  3765. {
  3766. int i,j,pass;
  3767. Residue *r = f->residue_config + rn;
  3768. int rtype = f->residue_types[rn];
  3769. int c = r->classbook;
  3770. int classwords = f->codebooks[c].dimensions;
  3771. unsigned int actual_size = rtype == 2 ? n*2 : n;
  3772. unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
  3773. unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
  3774. int n_read = limit_r_end - limit_r_begin;
  3775. int part_read = n_read / r->part_size;
  3776. int temp_alloc_point = temp_alloc_save(f);
  3777. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3778. uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
  3779. #else
  3780. int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
  3781. #endif
  3782. CHECK(f);
  3783. for (i=0; i < ch; ++i)
  3784. if (!do_not_decode[i])
  3785. memset(residue_buffers[i], 0, sizeof(float) * n);
  3786. if (rtype == 2 && ch != 1) {
  3787. for (j=0; j < ch; ++j)
  3788. if (!do_not_decode[j])
  3789. break;
  3790. if (j == ch)
  3791. goto done;
  3792. for (pass=0; pass < 8; ++pass) {
  3793. int pcount = 0, class_set = 0;
  3794. if (ch == 2) {
  3795. while (pcount < part_read) {
  3796. int z = r->begin + pcount*r->part_size;
  3797. int c_inter = (z & 1), p_inter = z>>1;
  3798. if (pass == 0) {
  3799. Codebook *c = f->codebooks+r->classbook;
  3800. int q;
  3801. DECODE(q,f,c);
  3802. if (q == EOP) goto done;
  3803. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3804. part_classdata[0][class_set] = r->classdata[q];
  3805. #else
  3806. for (i=classwords-1; i >= 0; --i) {
  3807. classifications[0][i+pcount] = q % r->classifications;
  3808. q /= r->classifications;
  3809. }
  3810. #endif
  3811. }
  3812. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  3813. int z = r->begin + pcount*r->part_size;
  3814. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3815. int c = part_classdata[0][class_set][i];
  3816. #else
  3817. int c = classifications[0][pcount];
  3818. #endif
  3819. int b = r->residue_books[c][pass];
  3820. if (b >= 0) {
  3821. Codebook *book = f->codebooks + b;
  3822. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3823. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  3824. goto done;
  3825. #else
  3826. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  3827. goto done;
  3828. #endif
  3829. } else {
  3830. z += r->part_size;
  3831. c_inter = z & 1;
  3832. p_inter = z >> 1;
  3833. }
  3834. }
  3835. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3836. ++class_set;
  3837. #endif
  3838. }
  3839. } else if (ch > 2) {
  3840. while (pcount < part_read) {
  3841. int z = r->begin + pcount*r->part_size;
  3842. int c_inter = z % ch, p_inter = z/ch;
  3843. if (pass == 0) {
  3844. Codebook *c = f->codebooks+r->classbook;
  3845. int q;
  3846. DECODE(q,f,c);
  3847. if (q == EOP) goto done;
  3848. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3849. part_classdata[0][class_set] = r->classdata[q];
  3850. #else
  3851. for (i=classwords-1; i >= 0; --i) {
  3852. classifications[0][i+pcount] = q % r->classifications;
  3853. q /= r->classifications;
  3854. }
  3855. #endif
  3856. }
  3857. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  3858. int z = r->begin + pcount*r->part_size;
  3859. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3860. int c = part_classdata[0][class_set][i];
  3861. #else
  3862. int c = classifications[0][pcount];
  3863. #endif
  3864. int b = r->residue_books[c][pass];
  3865. if (b >= 0) {
  3866. Codebook *book = f->codebooks + b;
  3867. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  3868. goto done;
  3869. } else {
  3870. z += r->part_size;
  3871. c_inter = z % ch;
  3872. p_inter = z / ch;
  3873. }
  3874. }
  3875. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3876. ++class_set;
  3877. #endif
  3878. }
  3879. }
  3880. }
  3881. goto done;
  3882. }
  3883. CHECK(f);
  3884. for (pass=0; pass < 8; ++pass) {
  3885. int pcount = 0, class_set=0;
  3886. while (pcount < part_read) {
  3887. if (pass == 0) {
  3888. for (j=0; j < ch; ++j) {
  3889. if (!do_not_decode[j]) {
  3890. Codebook *c = f->codebooks+r->classbook;
  3891. int temp;
  3892. DECODE(temp,f,c);
  3893. if (temp == EOP) goto done;
  3894. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3895. part_classdata[j][class_set] = r->classdata[temp];
  3896. #else
  3897. for (i=classwords-1; i >= 0; --i) {
  3898. classifications[j][i+pcount] = temp % r->classifications;
  3899. temp /= r->classifications;
  3900. }
  3901. #endif
  3902. }
  3903. }
  3904. }
  3905. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  3906. for (j=0; j < ch; ++j) {
  3907. if (!do_not_decode[j]) {
  3908. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3909. int c = part_classdata[j][class_set][i];
  3910. #else
  3911. int c = classifications[j][pcount];
  3912. #endif
  3913. int b = r->residue_books[c][pass];
  3914. if (b >= 0) {
  3915. float *target = residue_buffers[j];
  3916. int offset = r->begin + pcount * r->part_size;
  3917. int n = r->part_size;
  3918. Codebook *book = f->codebooks + b;
  3919. if (!residue_decode(f, book, target, offset, n, rtype))
  3920. goto done;
  3921. }
  3922. }
  3923. }
  3924. }
  3925. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3926. ++class_set;
  3927. #endif
  3928. }
  3929. }
  3930. done:
  3931. CHECK(f);
  3932. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3933. temp_free(f,part_classdata);
  3934. #else
  3935. temp_free(f,classifications);
  3936. #endif
  3937. temp_alloc_restore(f,temp_alloc_point);
  3938. }
  3939. #if 0
  3940. void inverse_mdct_slow(float *buffer, int n)
  3941. {
  3942. int i,j;
  3943. int n2 = n >> 1;
  3944. float *x = (float *) malloc(sizeof(*x) * n2);
  3945. memcpy(x, buffer, sizeof(*x) * n2);
  3946. for (i=0; i < n; ++i) {
  3947. float acc = 0;
  3948. for (j=0; j < n2; ++j)
  3949. acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
  3950. buffer[i] = acc;
  3951. }
  3952. free(x);
  3953. }
  3954. #elif 0
  3955. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  3956. {
  3957. float mcos[16384];
  3958. int i,j;
  3959. int n2 = n >> 1, nmask = (n << 2) -1;
  3960. float *x = (float *) malloc(sizeof(*x) * n2);
  3961. memcpy(x, buffer, sizeof(*x) * n2);
  3962. for (i=0; i < 4*n; ++i)
  3963. mcos[i] = (float) cos(M_PI / 2 * i / n);
  3964. for (i=0; i < n; ++i) {
  3965. float acc = 0;
  3966. for (j=0; j < n2; ++j)
  3967. acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
  3968. buffer[i] = acc;
  3969. }
  3970. free(x);
  3971. }
  3972. #elif 0
  3973. void dct_iv_slow(float *buffer, int n)
  3974. {
  3975. float mcos[16384];
  3976. float x[2048];
  3977. int i,j;
  3978. int n2 = n >> 1, nmask = (n << 3) - 1;
  3979. memcpy(x, buffer, sizeof(*x) * n);
  3980. for (i=0; i < 8*n; ++i)
  3981. mcos[i] = (float) cos(M_PI / 4 * i / n);
  3982. for (i=0; i < n; ++i) {
  3983. float acc = 0;
  3984. for (j=0; j < n; ++j)
  3985. acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
  3986. buffer[i] = acc;
  3987. }
  3988. }
  3989. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  3990. {
  3991. int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
  3992. float temp[4096];
  3993. memcpy(temp, buffer, n2 * sizeof(float));
  3994. dct_iv_slow(temp, n2);
  3995. for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4];
  3996. for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1];
  3997. for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4];
  3998. }
  3999. #endif
  4000. #ifndef LIBVORBIS_MDCT
  4001. #define LIBVORBIS_MDCT 0
  4002. #endif
  4003. #if LIBVORBIS_MDCT
  4004. typedef struct
  4005. {
  4006. int n;
  4007. int log2n;
  4008. float *trig;
  4009. int *bitrev;
  4010. float scale;
  4011. } mdct_lookup;
  4012. extern void mdct_init(mdct_lookup *lookup, int n);
  4013. extern void mdct_clear(mdct_lookup *l);
  4014. extern void mdct_backward(mdct_lookup *init, float *in, float *out);
  4015. mdct_lookup M1,M2;
  4016. void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  4017. {
  4018. mdct_lookup *M;
  4019. if (M1.n == n) M = &M1;
  4020. else if (M2.n == n) M = &M2;
  4021. else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
  4022. else {
  4023. if (M2.n) __asm int 3;
  4024. mdct_init(&M2, n);
  4025. M = &M2;
  4026. }
  4027. mdct_backward(M, buffer, buffer);
  4028. }
  4029. #endif
  4030. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
  4031. {
  4032. float *ee0 = e + i_off;
  4033. float *ee2 = ee0 + k_off;
  4034. int i;
  4035. assert((n & 3) == 0);
  4036. for (i=(n>>2); i > 0; --i) {
  4037. float k00_20, k01_21;
  4038. k00_20 = ee0[ 0] - ee2[ 0];
  4039. k01_21 = ee0[-1] - ee2[-1];
  4040. ee0[ 0] += ee2[ 0];
  4041. ee0[-1] += ee2[-1];
  4042. ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
  4043. ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
  4044. A += 8;
  4045. k00_20 = ee0[-2] - ee2[-2];
  4046. k01_21 = ee0[-3] - ee2[-3];
  4047. ee0[-2] += ee2[-2];
  4048. ee0[-3] += ee2[-3];
  4049. ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
  4050. ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
  4051. A += 8;
  4052. k00_20 = ee0[-4] - ee2[-4];
  4053. k01_21 = ee0[-5] - ee2[-5];
  4054. ee0[-4] += ee2[-4];
  4055. ee0[-5] += ee2[-5];
  4056. ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
  4057. ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
  4058. A += 8;
  4059. k00_20 = ee0[-6] - ee2[-6];
  4060. k01_21 = ee0[-7] - ee2[-7];
  4061. ee0[-6] += ee2[-6];
  4062. ee0[-7] += ee2[-7];
  4063. ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
  4064. ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
  4065. A += 8;
  4066. ee0 -= 8;
  4067. ee2 -= 8;
  4068. }
  4069. }
  4070. static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
  4071. {
  4072. int i;
  4073. float k00_20, k01_21;
  4074. float *e0 = e + d0;
  4075. float *e2 = e0 + k_off;
  4076. for (i=lim >> 2; i > 0; --i) {
  4077. k00_20 = e0[-0] - e2[-0];
  4078. k01_21 = e0[-1] - e2[-1];
  4079. e0[-0] += e2[-0];
  4080. e0[-1] += e2[-1];
  4081. e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
  4082. e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
  4083. A += k1;
  4084. k00_20 = e0[-2] - e2[-2];
  4085. k01_21 = e0[-3] - e2[-3];
  4086. e0[-2] += e2[-2];
  4087. e0[-3] += e2[-3];
  4088. e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
  4089. e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
  4090. A += k1;
  4091. k00_20 = e0[-4] - e2[-4];
  4092. k01_21 = e0[-5] - e2[-5];
  4093. e0[-4] += e2[-4];
  4094. e0[-5] += e2[-5];
  4095. e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
  4096. e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
  4097. A += k1;
  4098. k00_20 = e0[-6] - e2[-6];
  4099. k01_21 = e0[-7] - e2[-7];
  4100. e0[-6] += e2[-6];
  4101. e0[-7] += e2[-7];
  4102. e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
  4103. e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
  4104. e0 -= 8;
  4105. e2 -= 8;
  4106. A += k1;
  4107. }
  4108. }
  4109. static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
  4110. {
  4111. int i;
  4112. float A0 = A[0];
  4113. float A1 = A[0+1];
  4114. float A2 = A[0+a_off];
  4115. float A3 = A[0+a_off+1];
  4116. float A4 = A[0+a_off*2+0];
  4117. float A5 = A[0+a_off*2+1];
  4118. float A6 = A[0+a_off*3+0];
  4119. float A7 = A[0+a_off*3+1];
  4120. float k00,k11;
  4121. float *ee0 = e +i_off;
  4122. float *ee2 = ee0+k_off;
  4123. for (i=n; i > 0; --i) {
  4124. k00 = ee0[ 0] - ee2[ 0];
  4125. k11 = ee0[-1] - ee2[-1];
  4126. ee0[ 0] = ee0[ 0] + ee2[ 0];
  4127. ee0[-1] = ee0[-1] + ee2[-1];
  4128. ee2[ 0] = (k00) * A0 - (k11) * A1;
  4129. ee2[-1] = (k11) * A0 + (k00) * A1;
  4130. k00 = ee0[-2] - ee2[-2];
  4131. k11 = ee0[-3] - ee2[-3];
  4132. ee0[-2] = ee0[-2] + ee2[-2];
  4133. ee0[-3] = ee0[-3] + ee2[-3];
  4134. ee2[-2] = (k00) * A2 - (k11) * A3;
  4135. ee2[-3] = (k11) * A2 + (k00) * A3;
  4136. k00 = ee0[-4] - ee2[-4];
  4137. k11 = ee0[-5] - ee2[-5];
  4138. ee0[-4] = ee0[-4] + ee2[-4];
  4139. ee0[-5] = ee0[-5] + ee2[-5];
  4140. ee2[-4] = (k00) * A4 - (k11) * A5;
  4141. ee2[-5] = (k11) * A4 + (k00) * A5;
  4142. k00 = ee0[-6] - ee2[-6];
  4143. k11 = ee0[-7] - ee2[-7];
  4144. ee0[-6] = ee0[-6] + ee2[-6];
  4145. ee0[-7] = ee0[-7] + ee2[-7];
  4146. ee2[-6] = (k00) * A6 - (k11) * A7;
  4147. ee2[-7] = (k11) * A6 + (k00) * A7;
  4148. ee0 -= k0;
  4149. ee2 -= k0;
  4150. }
  4151. }
  4152. static __forceinline void iter_54(float *z)
  4153. {
  4154. float k00,k11,k22,k33;
  4155. float y0,y1,y2,y3;
  4156. k00 = z[ 0] - z[-4];
  4157. y0 = z[ 0] + z[-4];
  4158. y2 = z[-2] + z[-6];
  4159. k22 = z[-2] - z[-6];
  4160. z[-0] = y0 + y2;
  4161. z[-2] = y0 - y2;
  4162. k33 = z[-3] - z[-7];
  4163. z[-4] = k00 + k33;
  4164. z[-6] = k00 - k33;
  4165. k11 = z[-1] - z[-5];
  4166. y1 = z[-1] + z[-5];
  4167. y3 = z[-3] + z[-7];
  4168. z[-1] = y1 + y3;
  4169. z[-3] = y1 - y3;
  4170. z[-5] = k11 - k22;
  4171. z[-7] = k11 + k22;
  4172. }
  4173. static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
  4174. {
  4175. int a_off = base_n >> 3;
  4176. float A2 = A[0+a_off];
  4177. float *z = e + i_off;
  4178. float *base = z - 16 * n;
  4179. while (z > base) {
  4180. float k00,k11;
  4181. float l00,l11;
  4182. k00 = z[-0] - z[ -8];
  4183. k11 = z[-1] - z[ -9];
  4184. l00 = z[-2] - z[-10];
  4185. l11 = z[-3] - z[-11];
  4186. z[ -0] = z[-0] + z[ -8];
  4187. z[ -1] = z[-1] + z[ -9];
  4188. z[ -2] = z[-2] + z[-10];
  4189. z[ -3] = z[-3] + z[-11];
  4190. z[ -8] = k00;
  4191. z[ -9] = k11;
  4192. z[-10] = (l00+l11) * A2;
  4193. z[-11] = (l11-l00) * A2;
  4194. k00 = z[ -4] - z[-12];
  4195. k11 = z[ -5] - z[-13];
  4196. l00 = z[ -6] - z[-14];
  4197. l11 = z[ -7] - z[-15];
  4198. z[ -4] = z[ -4] + z[-12];
  4199. z[ -5] = z[ -5] + z[-13];
  4200. z[ -6] = z[ -6] + z[-14];
  4201. z[ -7] = z[ -7] + z[-15];
  4202. z[-12] = k11;
  4203. z[-13] = -k00;
  4204. z[-14] = (l11-l00) * A2;
  4205. z[-15] = (l00+l11) * -A2;
  4206. iter_54(z);
  4207. iter_54(z-8);
  4208. z -= 16;
  4209. }
  4210. }
  4211. static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  4212. {
  4213. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  4214. int ld;
  4215. int save_point = temp_alloc_save(f);
  4216. float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
  4217. float *u=NULL,*v=NULL;
  4218. float *A = f->A[blocktype];
  4219. {
  4220. float *d,*e, *AA, *e_stop;
  4221. d = &buf2[n2-2];
  4222. AA = A;
  4223. e = &buffer[0];
  4224. e_stop = &buffer[n2];
  4225. while (e != e_stop) {
  4226. d[1] = (e[0] * AA[0] - e[2]*AA[1]);
  4227. d[0] = (e[0] * AA[1] + e[2]*AA[0]);
  4228. d -= 2;
  4229. AA += 2;
  4230. e += 4;
  4231. }
  4232. e = &buffer[n2-3];
  4233. while (d >= buf2) {
  4234. d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
  4235. d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
  4236. d -= 2;
  4237. AA += 2;
  4238. e -= 4;
  4239. }
  4240. }
  4241. u = buffer;
  4242. v = buf2;
  4243. {
  4244. float *AA = &A[n2-8];
  4245. float *d0,*d1, *e0, *e1;
  4246. e0 = &v[n4];
  4247. e1 = &v[0];
  4248. d0 = &u[n4];
  4249. d1 = &u[0];
  4250. while (AA >= A) {
  4251. float v40_20, v41_21;
  4252. v41_21 = e0[1] - e1[1];
  4253. v40_20 = e0[0] - e1[0];
  4254. d0[1] = e0[1] + e1[1];
  4255. d0[0] = e0[0] + e1[0];
  4256. d1[1] = v41_21*AA[4] - v40_20*AA[5];
  4257. d1[0] = v40_20*AA[4] + v41_21*AA[5];
  4258. v41_21 = e0[3] - e1[3];
  4259. v40_20 = e0[2] - e1[2];
  4260. d0[3] = e0[3] + e1[3];
  4261. d0[2] = e0[2] + e1[2];
  4262. d1[3] = v41_21*AA[0] - v40_20*AA[1];
  4263. d1[2] = v40_20*AA[0] + v41_21*AA[1];
  4264. AA -= 8;
  4265. d0 += 4;
  4266. d1 += 4;
  4267. e0 += 4;
  4268. e1 += 4;
  4269. }
  4270. }
  4271. ld = ilog(n) - 1;
  4272. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
  4273. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
  4274. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
  4275. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
  4276. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
  4277. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
  4278. l=2;
  4279. for (; l < (ld-3)>>1; ++l) {
  4280. int k0 = n >> (l+2), k0_2 = k0>>1;
  4281. int lim = 1 << (l+1);
  4282. int i;
  4283. for (i=0; i < lim; ++i)
  4284. imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
  4285. }
  4286. for (; l < ld-6; ++l) {
  4287. int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
  4288. int rlim = n >> (l+6), r;
  4289. int lim = 1 << (l+1);
  4290. int i_off;
  4291. float *A0 = A;
  4292. i_off = n2-1;
  4293. for (r=rlim; r > 0; --r) {
  4294. imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
  4295. A0 += k1*4;
  4296. i_off -= 8;
  4297. }
  4298. }
  4299. imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
  4300. {
  4301. uint16 *bitrev = f->bit_reverse[blocktype];
  4302. float *d0 = &v[n4-4];
  4303. float *d1 = &v[n2-4];
  4304. while (d0 >= v) {
  4305. int k4;
  4306. k4 = bitrev[0];
  4307. d1[3] = u[k4+0];
  4308. d1[2] = u[k4+1];
  4309. d0[3] = u[k4+2];
  4310. d0[2] = u[k4+3];
  4311. k4 = bitrev[1];
  4312. d1[1] = u[k4+0];
  4313. d1[0] = u[k4+1];
  4314. d0[1] = u[k4+2];
  4315. d0[0] = u[k4+3];
  4316. d0 -= 4;
  4317. d1 -= 4;
  4318. bitrev += 2;
  4319. }
  4320. }
  4321. assert(v == buf2);
  4322. {
  4323. float *C = f->C[blocktype];
  4324. float *d, *e;
  4325. d = v;
  4326. e = v + n2 - 4;
  4327. while (d < e) {
  4328. float a02,a11,b0,b1,b2,b3;
  4329. a02 = d[0] - e[2];
  4330. a11 = d[1] + e[3];
  4331. b0 = C[1]*a02 + C[0]*a11;
  4332. b1 = C[1]*a11 - C[0]*a02;
  4333. b2 = d[0] + e[ 2];
  4334. b3 = d[1] - e[ 3];
  4335. d[0] = b2 + b0;
  4336. d[1] = b3 + b1;
  4337. e[2] = b2 - b0;
  4338. e[3] = b1 - b3;
  4339. a02 = d[2] - e[0];
  4340. a11 = d[3] + e[1];
  4341. b0 = C[3]*a02 + C[2]*a11;
  4342. b1 = C[3]*a11 - C[2]*a02;
  4343. b2 = d[2] + e[ 0];
  4344. b3 = d[3] - e[ 1];
  4345. d[2] = b2 + b0;
  4346. d[3] = b3 + b1;
  4347. e[0] = b2 - b0;
  4348. e[1] = b1 - b3;
  4349. C += 4;
  4350. d += 4;
  4351. e -= 4;
  4352. }
  4353. }
  4354. {
  4355. float *d0,*d1,*d2,*d3;
  4356. float *B = f->B[blocktype] + n2 - 8;
  4357. float *e = buf2 + n2 - 8;
  4358. d0 = &buffer[0];
  4359. d1 = &buffer[n2-4];
  4360. d2 = &buffer[n2];
  4361. d3 = &buffer[n-4];
  4362. while (e >= v) {
  4363. float p0,p1,p2,p3;
  4364. p3 = e[6]*B[7] - e[7]*B[6];
  4365. p2 = -e[6]*B[6] - e[7]*B[7];
  4366. d0[0] = p3;
  4367. d1[3] = - p3;
  4368. d2[0] = p2;
  4369. d3[3] = p2;
  4370. p1 = e[4]*B[5] - e[5]*B[4];
  4371. p0 = -e[4]*B[4] - e[5]*B[5];
  4372. d0[1] = p1;
  4373. d1[2] = - p1;
  4374. d2[1] = p0;
  4375. d3[2] = p0;
  4376. p3 = e[2]*B[3] - e[3]*B[2];
  4377. p2 = -e[2]*B[2] - e[3]*B[3];
  4378. d0[2] = p3;
  4379. d1[1] = - p3;
  4380. d2[2] = p2;
  4381. d3[1] = p2;
  4382. p1 = e[0]*B[1] - e[1]*B[0];
  4383. p0 = -e[0]*B[0] - e[1]*B[1];
  4384. d0[3] = p1;
  4385. d1[0] = - p1;
  4386. d2[3] = p0;
  4387. d3[0] = p0;
  4388. B -= 8;
  4389. e -= 8;
  4390. d0 += 4;
  4391. d2 += 4;
  4392. d1 -= 4;
  4393. d3 -= 4;
  4394. }
  4395. }
  4396. temp_free(f,buf2);
  4397. temp_alloc_restore(f,save_point);
  4398. }
  4399. #if 0
  4400. void inverse_mdct_naive(float *buffer, int n)
  4401. {
  4402. float s;
  4403. float A[1 << 12], B[1 << 12], C[1 << 11];
  4404. int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  4405. int n3_4 = n - n4, ld;
  4406. float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
  4407. for (k=k2=0; k < n4; ++k,k2+=2) {
  4408. A[k2 ] = (float) cos(4*k*M_PI/n);
  4409. A[k2+1] = (float) -sin(4*k*M_PI/n);
  4410. B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
  4411. B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
  4412. }
  4413. for (k=k2=0; k < n8; ++k,k2+=2) {
  4414. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  4415. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  4416. }
  4417. for (k=0; k < n2; ++k) u[k] = buffer[k];
  4418. for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
  4419. for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
  4420. v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
  4421. v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
  4422. }
  4423. for (k=k4=0; k < n8; k+=1, k4+=4) {
  4424. w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
  4425. w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
  4426. 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];
  4427. 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];
  4428. }
  4429. ld = ilog(n) - 1;
  4430. for (l=0; l < ld-3; ++l) {
  4431. int k0 = n >> (l+2), k1 = 1 << (l+3);
  4432. int rlim = n >> (l+4), r4, r;
  4433. int s2lim = 1 << (l+2), s2;
  4434. for (r=r4=0; r < rlim; r4+=4,++r) {
  4435. for (s2=0; s2 < s2lim; s2+=2) {
  4436. u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
  4437. u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
  4438. u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
  4439. - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
  4440. u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
  4441. + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
  4442. }
  4443. }
  4444. if (l+1 < ld-3) {
  4445. memcpy(w, u, sizeof(u));
  4446. }
  4447. }
  4448. for (i=0; i < n8; ++i) {
  4449. int j = bit_reverse(i) >> (32-ld+3);
  4450. assert(j < n8);
  4451. if (i == j) {
  4452. int i8 = i << 3;
  4453. v[i8+1] = u[i8+1];
  4454. v[i8+3] = u[i8+3];
  4455. v[i8+5] = u[i8+5];
  4456. v[i8+7] = u[i8+7];
  4457. } else if (i < j) {
  4458. int i8 = i << 3, j8 = j << 3;
  4459. v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
  4460. v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
  4461. v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
  4462. v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
  4463. }
  4464. }
  4465. for (k=0; k < n2; ++k) {
  4466. w[k] = v[k*2+1];
  4467. }
  4468. for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
  4469. u[n-1-k2] = w[k4];
  4470. u[n-2-k2] = w[k4+1];
  4471. u[n3_4 - 1 - k2] = w[k4+2];
  4472. u[n3_4 - 2 - k2] = w[k4+3];
  4473. }
  4474. for (k=k2=0; k < n8; ++k, k2 += 2) {
  4475. 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;
  4476. 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;
  4477. 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;
  4478. 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;
  4479. }
  4480. for (k=k2=0; k < n4; ++k,k2 += 2) {
  4481. X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
  4482. X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
  4483. }
  4484. s = 0.5;
  4485. for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
  4486. for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
  4487. for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
  4488. }
  4489. #endif
  4490. static float *get_window(vorb *f, int len)
  4491. {
  4492. len <<= 1;
  4493. if (len == f->blocksize_0) return f->window[0];
  4494. if (len == f->blocksize_1) return f->window[1];
  4495. return NULL;
  4496. }
  4497. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  4498. typedef int16 YTYPE;
  4499. #else
  4500. typedef int YTYPE;
  4501. #endif
  4502. static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
  4503. {
  4504. int n2 = n >> 1;
  4505. int s = map->chan[i].mux, floor;
  4506. floor = map->submap_floor[s];
  4507. if (f->floor_types[floor] == 0) {
  4508. return error(f, VORBIS_invalid_stream);
  4509. } else {
  4510. Floor1 *g = &f->floor_config[floor].floor1;
  4511. int j,q;
  4512. int lx = 0, ly = finalY[0] * g->floor1_multiplier;
  4513. for (q=1; q < g->values; ++q) {
  4514. j = g->sorted_order[q];
  4515. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  4516. STBV_NOTUSED(step2_flag);
  4517. if (finalY[j] >= 0)
  4518. #else
  4519. if (step2_flag[j])
  4520. #endif
  4521. {
  4522. int hy = finalY[j] * g->floor1_multiplier;
  4523. int hx = g->Xlist[j];
  4524. if (lx != hx)
  4525. draw_line(target, lx,ly, hx,hy, n2);
  4526. CHECK(f);
  4527. lx = hx, ly = hy;
  4528. }
  4529. }
  4530. if (lx < n2) {
  4531. for (j=lx; j < n2; ++j)
  4532. LINE_OP(target[j], inverse_db_table[ly]);
  4533. CHECK(f);
  4534. }
  4535. }
  4536. return TRUE;
  4537. }
  4538. 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)
  4539. {
  4540. Mode *m;
  4541. int i, n, prev, next, window_center;
  4542. f->channel_buffer_start = f->channel_buffer_end = 0;
  4543. retry:
  4544. if (f->eof) return FALSE;
  4545. if (!maybe_start_packet(f))
  4546. return FALSE;
  4547. if (get_bits(f,1) != 0) {
  4548. if (IS_PUSH_MODE(f))
  4549. return error(f,VORBIS_bad_packet_type);
  4550. while (EOP != get8_packet(f));
  4551. goto retry;
  4552. }
  4553. if (f->alloc.alloc_buffer)
  4554. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  4555. i = get_bits(f, ilog(f->mode_count-1));
  4556. if (i == EOP) return FALSE;
  4557. if (i >= f->mode_count) return FALSE;
  4558. *mode = i;
  4559. m = f->mode_config + i;
  4560. if (m->blockflag) {
  4561. n = f->blocksize_1;
  4562. prev = get_bits(f,1);
  4563. next = get_bits(f,1);
  4564. } else {
  4565. prev = next = 0;
  4566. n = f->blocksize_0;
  4567. }
  4568. window_center = n >> 1;
  4569. if (m->blockflag && !prev) {
  4570. *p_left_start = (n - f->blocksize_0) >> 2;
  4571. *p_left_end = (n + f->blocksize_0) >> 2;
  4572. } else {
  4573. *p_left_start = 0;
  4574. *p_left_end = window_center;
  4575. }
  4576. if (m->blockflag && !next) {
  4577. *p_right_start = (n*3 - f->blocksize_0) >> 2;
  4578. *p_right_end = (n*3 + f->blocksize_0) >> 2;
  4579. } else {
  4580. *p_right_start = window_center;
  4581. *p_right_end = n;
  4582. }
  4583. return TRUE;
  4584. }
  4585. 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)
  4586. {
  4587. Mapping *map;
  4588. int i,j,k,n,n2;
  4589. int zero_channel[256];
  4590. int really_zero_channel[256];
  4591. STBV_NOTUSED(left_end);
  4592. n = f->blocksize[m->blockflag];
  4593. map = &f->mapping[m->mapping];
  4594. n2 = n >> 1;
  4595. CHECK(f);
  4596. for (i=0; i < f->channels; ++i) {
  4597. int s = map->chan[i].mux, floor;
  4598. zero_channel[i] = FALSE;
  4599. floor = map->submap_floor[s];
  4600. if (f->floor_types[floor] == 0) {
  4601. return error(f, VORBIS_invalid_stream);
  4602. } else {
  4603. Floor1 *g = &f->floor_config[floor].floor1;
  4604. if (get_bits(f, 1)) {
  4605. short *finalY;
  4606. uint8 step2_flag[256];
  4607. static int range_list[4] = { 256, 128, 86, 64 };
  4608. int range = range_list[g->floor1_multiplier-1];
  4609. int offset = 2;
  4610. finalY = f->finalY[i];
  4611. finalY[0] = get_bits(f, ilog(range)-1);
  4612. finalY[1] = get_bits(f, ilog(range)-1);
  4613. for (j=0; j < g->partitions; ++j) {
  4614. int pclass = g->partition_class_list[j];
  4615. int cdim = g->class_dimensions[pclass];
  4616. int cbits = g->class_subclasses[pclass];
  4617. int csub = (1 << cbits)-1;
  4618. int cval = 0;
  4619. if (cbits) {
  4620. Codebook *c = f->codebooks + g->class_masterbooks[pclass];
  4621. DECODE(cval,f,c);
  4622. }
  4623. for (k=0; k < cdim; ++k) {
  4624. int book = g->subclass_books[pclass][cval & csub];
  4625. cval = cval >> cbits;
  4626. if (book >= 0) {
  4627. int temp;
  4628. Codebook *c = f->codebooks + book;
  4629. DECODE(temp,f,c);
  4630. finalY[offset++] = temp;
  4631. } else
  4632. finalY[offset++] = 0;
  4633. }
  4634. }
  4635. if (f->valid_bits == INVALID_BITS) goto error;
  4636. step2_flag[0] = step2_flag[1] = 1;
  4637. for (j=2; j < g->values; ++j) {
  4638. int low, high, pred, highroom, lowroom, room, val;
  4639. low = g->neighbors[j][0];
  4640. high = g->neighbors[j][1];
  4641. pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
  4642. val = finalY[j];
  4643. highroom = range - pred;
  4644. lowroom = pred;
  4645. if (highroom < lowroom)
  4646. room = highroom * 2;
  4647. else
  4648. room = lowroom * 2;
  4649. if (val) {
  4650. step2_flag[low] = step2_flag[high] = 1;
  4651. step2_flag[j] = 1;
  4652. if (val >= room)
  4653. if (highroom > lowroom)
  4654. finalY[j] = val - lowroom + pred;
  4655. else
  4656. finalY[j] = pred - val + highroom - 1;
  4657. else
  4658. if (val & 1)
  4659. finalY[j] = pred - ((val+1)>>1);
  4660. else
  4661. finalY[j] = pred + (val>>1);
  4662. } else {
  4663. step2_flag[j] = 0;
  4664. finalY[j] = pred;
  4665. }
  4666. }
  4667. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  4668. do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
  4669. #else
  4670. for (j=0; j < g->values; ++j) {
  4671. if (!step2_flag[j])
  4672. finalY[j] = -1;
  4673. }
  4674. #endif
  4675. } else {
  4676. error:
  4677. zero_channel[i] = TRUE;
  4678. }
  4679. }
  4680. }
  4681. CHECK(f);
  4682. if (f->alloc.alloc_buffer)
  4683. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  4684. memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
  4685. for (i=0; i < map->coupling_steps; ++i)
  4686. if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
  4687. zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
  4688. }
  4689. CHECK(f);
  4690. for (i=0; i < map->submaps; ++i) {
  4691. float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
  4692. int r;
  4693. uint8 do_not_decode[256];
  4694. int ch = 0;
  4695. for (j=0; j < f->channels; ++j) {
  4696. if (map->chan[j].mux == i) {
  4697. if (zero_channel[j]) {
  4698. do_not_decode[ch] = TRUE;
  4699. residue_buffers[ch] = NULL;
  4700. } else {
  4701. do_not_decode[ch] = FALSE;
  4702. residue_buffers[ch] = f->channel_buffers[j];
  4703. }
  4704. ++ch;
  4705. }
  4706. }
  4707. r = map->submap_residue[i];
  4708. decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
  4709. }
  4710. if (f->alloc.alloc_buffer)
  4711. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  4712. CHECK(f);
  4713. for (i = map->coupling_steps-1; i >= 0; --i) {
  4714. int n2 = n >> 1;
  4715. float *m = f->channel_buffers[map->chan[i].magnitude];
  4716. float *a = f->channel_buffers[map->chan[i].angle ];
  4717. for (j=0; j < n2; ++j) {
  4718. float a2,m2;
  4719. if (m[j] > 0)
  4720. if (a[j] > 0)
  4721. m2 = m[j], a2 = m[j] - a[j];
  4722. else
  4723. a2 = m[j], m2 = m[j] + a[j];
  4724. else
  4725. if (a[j] > 0)
  4726. m2 = m[j], a2 = m[j] + a[j];
  4727. else
  4728. a2 = m[j], m2 = m[j] - a[j];
  4729. m[j] = m2;
  4730. a[j] = a2;
  4731. }
  4732. }
  4733. CHECK(f);
  4734. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  4735. for (i=0; i < f->channels; ++i) {
  4736. if (really_zero_channel[i]) {
  4737. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  4738. } else {
  4739. do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
  4740. }
  4741. }
  4742. #else
  4743. for (i=0; i < f->channels; ++i) {
  4744. if (really_zero_channel[i]) {
  4745. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  4746. } else {
  4747. for (j=0; j < n2; ++j)
  4748. f->channel_buffers[i][j] *= f->floor_buffers[i][j];
  4749. }
  4750. }
  4751. #endif
  4752. CHECK(f);
  4753. for (i=0; i < f->channels; ++i)
  4754. inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
  4755. CHECK(f);
  4756. flush_packet(f);
  4757. if (f->first_decode) {
  4758. f->current_loc = 0u - n2;
  4759. f->discard_samples_deferred = n - right_end;
  4760. f->current_loc_valid = TRUE;
  4761. f->first_decode = FALSE;
  4762. } else if (f->discard_samples_deferred) {
  4763. if (f->discard_samples_deferred >= right_start - left_start) {
  4764. f->discard_samples_deferred -= (right_start - left_start);
  4765. left_start = right_start;
  4766. *p_left = left_start;
  4767. } else {
  4768. left_start += f->discard_samples_deferred;
  4769. *p_left = left_start;
  4770. f->discard_samples_deferred = 0;
  4771. }
  4772. } else if (f->previous_length == 0 && f->current_loc_valid) {
  4773. }
  4774. if (f->last_seg_which == f->end_seg_with_known_loc) {
  4775. if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
  4776. uint32 current_end = f->known_loc_for_packet;
  4777. if (current_end < f->current_loc + (right_end-left_start)) {
  4778. if (current_end < f->current_loc) {
  4779. *len = 0;
  4780. } else {
  4781. *len = current_end - f->current_loc;
  4782. }
  4783. *len += left_start;
  4784. if (*len > right_end) *len = right_end;
  4785. f->current_loc += *len;
  4786. return TRUE;
  4787. }
  4788. }
  4789. f->current_loc = f->known_loc_for_packet - (n2-left_start);
  4790. f->current_loc_valid = TRUE;
  4791. }
  4792. if (f->current_loc_valid)
  4793. f->current_loc += (right_start - left_start);
  4794. if (f->alloc.alloc_buffer)
  4795. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  4796. *len = right_end;
  4797. CHECK(f);
  4798. return TRUE;
  4799. }
  4800. static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
  4801. {
  4802. int mode, left_end, right_end;
  4803. if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
  4804. return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
  4805. }
  4806. static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
  4807. {
  4808. int prev,i,j;
  4809. if (f->previous_length) {
  4810. int i,j, n = f->previous_length;
  4811. float *w = get_window(f, n);
  4812. if (w == NULL) return 0;
  4813. for (i=0; i < f->channels; ++i) {
  4814. for (j=0; j < n; ++j)
  4815. f->channel_buffers[i][left+j] =
  4816. f->channel_buffers[i][left+j]*w[ j] +
  4817. f->previous_window[i][ j]*w[n-1-j];
  4818. }
  4819. }
  4820. prev = f->previous_length;
  4821. f->previous_length = len - right;
  4822. for (i=0; i < f->channels; ++i)
  4823. for (j=0; right+j < len; ++j)
  4824. f->previous_window[i][j] = f->channel_buffers[i][right+j];
  4825. if (!prev)
  4826. return 0;
  4827. if (len < right) right = len;
  4828. f->samples_output += right-left;
  4829. return right - left;
  4830. }
  4831. static int vorbis_pump_first_frame(stb_vorbis *f)
  4832. {
  4833. int len, right, left, res;
  4834. res = vorbis_decode_packet(f, &len, &left, &right);
  4835. if (res)
  4836. vorbis_finish_frame(f, len, left, right);
  4837. return res;
  4838. }
  4839. static int start_decoder(vorb *f)
  4840. {
  4841. uint8 header[6], x,y;
  4842. int len,i,j,k, max_submaps = 0;
  4843. int longest_floorlist=0;
  4844. f->first_decode = TRUE;
  4845. if (!start_page(f)) return FALSE;
  4846. if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
  4847. if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
  4848. if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
  4849. if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
  4850. if (f->segments[0] != 30) {
  4851. if (f->segments[0] == 64 &&
  4852. getn(f, header, 6) &&
  4853. header[0] == 'f' &&
  4854. header[1] == 'i' &&
  4855. header[2] == 's' &&
  4856. header[3] == 'h' &&
  4857. header[4] == 'e' &&
  4858. header[5] == 'a' &&
  4859. get8(f) == 'd' &&
  4860. get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
  4861. else
  4862. return error(f, VORBIS_invalid_first_page);
  4863. }
  4864. if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
  4865. if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
  4866. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
  4867. if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
  4868. f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
  4869. if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
  4870. f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
  4871. get32(f);
  4872. get32(f);
  4873. get32(f);
  4874. x = get8(f);
  4875. {
  4876. int log0,log1;
  4877. log0 = x & 15;
  4878. log1 = x >> 4;
  4879. f->blocksize_0 = 1 << log0;
  4880. f->blocksize_1 = 1 << log1;
  4881. if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
  4882. if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
  4883. if (log0 > log1) return error(f, VORBIS_invalid_setup);
  4884. }
  4885. x = get8(f);
  4886. if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
  4887. if (!start_page(f)) return FALSE;
  4888. if (!start_packet(f)) return FALSE;
  4889. if (!next_segment(f)) return FALSE;
  4890. if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup);
  4891. for (i=0; i < 6; ++i) header[i] = get8_packet(f);
  4892. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
  4893. len = get32_packet(f);
  4894. f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1));
  4895. if (f->vendor == NULL) return error(f, VORBIS_outofmem);
  4896. for(i=0; i < len; ++i) {
  4897. f->vendor[i] = get8_packet(f);
  4898. }
  4899. f->vendor[len] = (char)'\0';
  4900. f->comment_list_length = get32_packet(f);
  4901. f->comment_list = NULL;
  4902. if (f->comment_list_length > 0)
  4903. {
  4904. f->comment_list = (char**) setup_malloc(f, sizeof(char*) * (f->comment_list_length));
  4905. if (f->comment_list == NULL) return error(f, VORBIS_outofmem);
  4906. }
  4907. for(i=0; i < f->comment_list_length; ++i) {
  4908. len = get32_packet(f);
  4909. f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1));
  4910. if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem);
  4911. for(j=0; j < len; ++j) {
  4912. f->comment_list[i][j] = get8_packet(f);
  4913. }
  4914. f->comment_list[i][len] = (char)'\0';
  4915. }
  4916. x = get8_packet(f);
  4917. if (!(x & 1)) return error(f, VORBIS_invalid_setup);
  4918. skip(f, f->bytes_in_seg);
  4919. f->bytes_in_seg = 0;
  4920. do {
  4921. len = next_segment(f);
  4922. skip(f, len);
  4923. f->bytes_in_seg = 0;
  4924. } while (len);
  4925. if (!start_packet(f)) return FALSE;
  4926. crc32_init();
  4927. if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
  4928. for (i=0; i < 6; ++i) header[i] = get8_packet(f);
  4929. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
  4930. f->codebook_count = get_bits(f,8) + 1;
  4931. f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
  4932. if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
  4933. memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
  4934. for (i=0; i < f->codebook_count; ++i) {
  4935. uint32 *values;
  4936. int ordered, sorted_count;
  4937. int total=0;
  4938. uint8 *lengths;
  4939. Codebook *c = f->codebooks+i;
  4940. CHECK(f);
  4941. x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
  4942. x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
  4943. x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
  4944. x = get_bits(f, 8);
  4945. c->dimensions = (get_bits(f, 8)<<8) + x;
  4946. x = get_bits(f, 8);
  4947. y = get_bits(f, 8);
  4948. c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
  4949. ordered = get_bits(f,1);
  4950. c->sparse = ordered ? 0 : get_bits(f,1);
  4951. if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
  4952. if (c->sparse)
  4953. lengths = (uint8 *) setup_temp_malloc(f, c->entries);
  4954. else
  4955. lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  4956. if (!lengths) return error(f, VORBIS_outofmem);
  4957. if (ordered) {
  4958. int current_entry = 0;
  4959. int current_length = get_bits(f,5) + 1;
  4960. while (current_entry < c->entries) {
  4961. int limit = c->entries - current_entry;
  4962. int n = get_bits(f, ilog(limit));
  4963. if (current_length >= 32) return error(f, VORBIS_invalid_setup);
  4964. if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
  4965. memset(lengths + current_entry, current_length, n);
  4966. current_entry += n;
  4967. ++current_length;
  4968. }
  4969. } else {
  4970. for (j=0; j < c->entries; ++j) {
  4971. int present = c->sparse ? get_bits(f,1) : 1;
  4972. if (present) {
  4973. lengths[j] = get_bits(f, 5) + 1;
  4974. ++total;
  4975. if (lengths[j] == 32)
  4976. return error(f, VORBIS_invalid_setup);
  4977. } else {
  4978. lengths[j] = NO_CODE;
  4979. }
  4980. }
  4981. }
  4982. if (c->sparse && total >= c->entries >> 2) {
  4983. if (c->entries > (int) f->setup_temp_memory_required)
  4984. f->setup_temp_memory_required = c->entries;
  4985. c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  4986. if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
  4987. memcpy(c->codeword_lengths, lengths, c->entries);
  4988. setup_temp_free(f, lengths, c->entries);
  4989. lengths = c->codeword_lengths;
  4990. c->sparse = 0;
  4991. }
  4992. if (c->sparse) {
  4993. sorted_count = total;
  4994. } else {
  4995. sorted_count = 0;
  4996. #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  4997. for (j=0; j < c->entries; ++j)
  4998. if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
  4999. ++sorted_count;
  5000. #endif
  5001. }
  5002. c->sorted_entries = sorted_count;
  5003. values = NULL;
  5004. CHECK(f);
  5005. if (!c->sparse) {
  5006. c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
  5007. if (!c->codewords) return error(f, VORBIS_outofmem);
  5008. } else {
  5009. unsigned int size;
  5010. if (c->sorted_entries) {
  5011. c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
  5012. if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
  5013. c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
  5014. if (!c->codewords) return error(f, VORBIS_outofmem);
  5015. values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
  5016. if (!values) return error(f, VORBIS_outofmem);
  5017. }
  5018. size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
  5019. if (size > f->setup_temp_memory_required)
  5020. f->setup_temp_memory_required = size;
  5021. }
  5022. if (!compute_codewords(c, lengths, c->entries, values)) {
  5023. if (c->sparse) setup_temp_free(f, values, 0);
  5024. return error(f, VORBIS_invalid_setup);
  5025. }
  5026. if (c->sorted_entries) {
  5027. c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
  5028. if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
  5029. c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
  5030. if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
  5031. ++c->sorted_values;
  5032. c->sorted_values[-1] = -1;
  5033. compute_sorted_huffman(c, lengths, values);
  5034. }
  5035. if (c->sparse) {
  5036. setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
  5037. setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
  5038. setup_temp_free(f, lengths, c->entries);
  5039. c->codewords = NULL;
  5040. }
  5041. compute_accelerated_huffman(c);
  5042. CHECK(f);
  5043. c->lookup_type = get_bits(f, 4);
  5044. if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
  5045. if (c->lookup_type > 0) {
  5046. uint16 *mults;
  5047. c->minimum_value = float32_unpack(get_bits(f, 32));
  5048. c->delta_value = float32_unpack(get_bits(f, 32));
  5049. c->value_bits = get_bits(f, 4)+1;
  5050. c->sequence_p = get_bits(f,1);
  5051. if (c->lookup_type == 1) {
  5052. int values = lookup1_values(c->entries, c->dimensions);
  5053. if (values < 0) return error(f, VORBIS_invalid_setup);
  5054. c->lookup_values = (uint32) values;
  5055. } else {
  5056. c->lookup_values = c->entries * c->dimensions;
  5057. }
  5058. if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
  5059. mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
  5060. if (mults == NULL) return error(f, VORBIS_outofmem);
  5061. for (j=0; j < (int) c->lookup_values; ++j) {
  5062. int q = get_bits(f, c->value_bits);
  5063. if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
  5064. mults[j] = q;
  5065. }
  5066. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  5067. if (c->lookup_type == 1) {
  5068. int len, sparse = c->sparse;
  5069. float last=0;
  5070. if (sparse) {
  5071. if (c->sorted_entries == 0) goto skip;
  5072. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
  5073. } else
  5074. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
  5075. if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
  5076. len = sparse ? c->sorted_entries : c->entries;
  5077. for (j=0; j < len; ++j) {
  5078. unsigned int z = sparse ? c->sorted_values[j] : j;
  5079. unsigned int div=1;
  5080. for (k=0; k < c->dimensions; ++k) {
  5081. int off = (z / div) % c->lookup_values;
  5082. float val = mults[off]*c->delta_value + c->minimum_value + last;
  5083. c->multiplicands[j*c->dimensions + k] = val;
  5084. if (c->sequence_p)
  5085. last = val;
  5086. if (k+1 < c->dimensions) {
  5087. if (div > UINT_MAX / (unsigned int) c->lookup_values) {
  5088. setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
  5089. return error(f, VORBIS_invalid_setup);
  5090. }
  5091. div *= c->lookup_values;
  5092. }
  5093. }
  5094. }
  5095. c->lookup_type = 2;
  5096. }
  5097. else
  5098. #endif
  5099. {
  5100. float last=0;
  5101. CHECK(f);
  5102. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
  5103. if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
  5104. for (j=0; j < (int) c->lookup_values; ++j) {
  5105. float val = mults[j] * c->delta_value + c->minimum_value + last;
  5106. c->multiplicands[j] = val;
  5107. if (c->sequence_p)
  5108. last = val;
  5109. }
  5110. }
  5111. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  5112. skip:;
  5113. #endif
  5114. setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
  5115. CHECK(f);
  5116. }
  5117. CHECK(f);
  5118. }
  5119. x = get_bits(f, 6) + 1;
  5120. for (i=0; i < x; ++i) {
  5121. uint32 z = get_bits(f, 16);
  5122. if (z != 0) return error(f, VORBIS_invalid_setup);
  5123. }
  5124. f->floor_count = get_bits(f, 6)+1;
  5125. f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
  5126. if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
  5127. for (i=0; i < f->floor_count; ++i) {
  5128. f->floor_types[i] = get_bits(f, 16);
  5129. if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
  5130. if (f->floor_types[i] == 0) {
  5131. Floor0 *g = &f->floor_config[i].floor0;
  5132. g->order = get_bits(f,8);
  5133. g->rate = get_bits(f,16);
  5134. g->bark_map_size = get_bits(f,16);
  5135. g->amplitude_bits = get_bits(f,6);
  5136. g->amplitude_offset = get_bits(f,8);
  5137. g->number_of_books = get_bits(f,4) + 1;
  5138. for (j=0; j < g->number_of_books; ++j)
  5139. g->book_list[j] = get_bits(f,8);
  5140. return error(f, VORBIS_feature_not_supported);
  5141. } else {
  5142. stbv__floor_ordering p[31*8+2];
  5143. Floor1 *g = &f->floor_config[i].floor1;
  5144. int max_class = -1;
  5145. g->partitions = get_bits(f, 5);
  5146. for (j=0; j < g->partitions; ++j) {
  5147. g->partition_class_list[j] = get_bits(f, 4);
  5148. if (g->partition_class_list[j] > max_class)
  5149. max_class = g->partition_class_list[j];
  5150. }
  5151. for (j=0; j <= max_class; ++j) {
  5152. g->class_dimensions[j] = get_bits(f, 3)+1;
  5153. g->class_subclasses[j] = get_bits(f, 2);
  5154. if (g->class_subclasses[j]) {
  5155. g->class_masterbooks[j] = get_bits(f, 8);
  5156. if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  5157. }
  5158. for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
  5159. g->subclass_books[j][k] = (int16)get_bits(f,8)-1;
  5160. if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  5161. }
  5162. }
  5163. g->floor1_multiplier = get_bits(f,2)+1;
  5164. g->rangebits = get_bits(f,4);
  5165. g->Xlist[0] = 0;
  5166. g->Xlist[1] = 1 << g->rangebits;
  5167. g->values = 2;
  5168. for (j=0; j < g->partitions; ++j) {
  5169. int c = g->partition_class_list[j];
  5170. for (k=0; k < g->class_dimensions[c]; ++k) {
  5171. g->Xlist[g->values] = get_bits(f, g->rangebits);
  5172. ++g->values;
  5173. }
  5174. }
  5175. for (j=0; j < g->values; ++j) {
  5176. p[j].x = g->Xlist[j];
  5177. p[j].id = j;
  5178. }
  5179. qsort(p, g->values, sizeof(p[0]), point_compare);
  5180. for (j=0; j < g->values-1; ++j)
  5181. if (p[j].x == p[j+1].x)
  5182. return error(f, VORBIS_invalid_setup);
  5183. for (j=0; j < g->values; ++j)
  5184. g->sorted_order[j] = (uint8) p[j].id;
  5185. for (j=2; j < g->values; ++j) {
  5186. int low = 0,hi = 0;
  5187. neighbors(g->Xlist, j, &low,&hi);
  5188. g->neighbors[j][0] = low;
  5189. g->neighbors[j][1] = hi;
  5190. }
  5191. if (g->values > longest_floorlist)
  5192. longest_floorlist = g->values;
  5193. }
  5194. }
  5195. f->residue_count = get_bits(f, 6)+1;
  5196. f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
  5197. if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
  5198. memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
  5199. for (i=0; i < f->residue_count; ++i) {
  5200. uint8 residue_cascade[64];
  5201. Residue *r = f->residue_config+i;
  5202. f->residue_types[i] = get_bits(f, 16);
  5203. if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
  5204. r->begin = get_bits(f, 24);
  5205. r->end = get_bits(f, 24);
  5206. if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
  5207. r->part_size = get_bits(f,24)+1;
  5208. r->classifications = get_bits(f,6)+1;
  5209. r->classbook = get_bits(f,8);
  5210. if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  5211. for (j=0; j < r->classifications; ++j) {
  5212. uint8 high_bits=0;
  5213. uint8 low_bits=get_bits(f,3);
  5214. if (get_bits(f,1))
  5215. high_bits = get_bits(f,5);
  5216. residue_cascade[j] = high_bits*8 + low_bits;
  5217. }
  5218. r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
  5219. if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
  5220. for (j=0; j < r->classifications; ++j) {
  5221. for (k=0; k < 8; ++k) {
  5222. if (residue_cascade[j] & (1 << k)) {
  5223. r->residue_books[j][k] = get_bits(f, 8);
  5224. if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  5225. } else {
  5226. r->residue_books[j][k] = -1;
  5227. }
  5228. }
  5229. }
  5230. r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  5231. if (!r->classdata) return error(f, VORBIS_outofmem);
  5232. memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  5233. for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
  5234. int classwords = f->codebooks[r->classbook].dimensions;
  5235. int temp = j;
  5236. r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
  5237. if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
  5238. for (k=classwords-1; k >= 0; --k) {
  5239. r->classdata[j][k] = temp % r->classifications;
  5240. temp /= r->classifications;
  5241. }
  5242. }
  5243. }
  5244. f->mapping_count = get_bits(f,6)+1;
  5245. f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
  5246. if (f->mapping == NULL) return error(f, VORBIS_outofmem);
  5247. memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
  5248. for (i=0; i < f->mapping_count; ++i) {
  5249. Mapping *m = f->mapping + i;
  5250. int mapping_type = get_bits(f,16);
  5251. if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
  5252. m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
  5253. if (m->chan == NULL) return error(f, VORBIS_outofmem);
  5254. if (get_bits(f,1))
  5255. m->submaps = get_bits(f,4)+1;
  5256. else
  5257. m->submaps = 1;
  5258. if (m->submaps > max_submaps)
  5259. max_submaps = m->submaps;
  5260. if (get_bits(f,1)) {
  5261. m->coupling_steps = get_bits(f,8)+1;
  5262. if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);
  5263. for (k=0; k < m->coupling_steps; ++k) {
  5264. m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
  5265. m->chan[k].angle = get_bits(f, ilog(f->channels-1));
  5266. if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
  5267. if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
  5268. if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
  5269. }
  5270. } else
  5271. m->coupling_steps = 0;
  5272. if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
  5273. if (m->submaps > 1) {
  5274. for (j=0; j < f->channels; ++j) {
  5275. m->chan[j].mux = get_bits(f, 4);
  5276. if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
  5277. }
  5278. } else
  5279. for (j=0; j < f->channels; ++j)
  5280. m->chan[j].mux = 0;
  5281. for (j=0; j < m->submaps; ++j) {
  5282. get_bits(f,8);
  5283. m->submap_floor[j] = get_bits(f,8);
  5284. m->submap_residue[j] = get_bits(f,8);
  5285. if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
  5286. if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
  5287. }
  5288. }
  5289. f->mode_count = get_bits(f, 6)+1;
  5290. for (i=0; i < f->mode_count; ++i) {
  5291. Mode *m = f->mode_config+i;
  5292. m->blockflag = get_bits(f,1);
  5293. m->windowtype = get_bits(f,16);
  5294. m->transformtype = get_bits(f,16);
  5295. m->mapping = get_bits(f,8);
  5296. if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
  5297. if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
  5298. if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
  5299. }
  5300. flush_packet(f);
  5301. f->previous_length = 0;
  5302. for (i=0; i < f->channels; ++i) {
  5303. f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
  5304. f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  5305. f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
  5306. if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
  5307. memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
  5308. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  5309. f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  5310. if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
  5311. #endif
  5312. }
  5313. if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
  5314. if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
  5315. f->blocksize[0] = f->blocksize_0;
  5316. f->blocksize[1] = f->blocksize_1;
  5317. #ifdef STB_VORBIS_DIVIDE_TABLE
  5318. if (integer_divide_table[1][1]==0)
  5319. for (i=0; i < DIVTAB_NUMER; ++i)
  5320. for (j=1; j < DIVTAB_DENOM; ++j)
  5321. integer_divide_table[i][j] = i / j;
  5322. #endif
  5323. {
  5324. uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
  5325. uint32 classify_mem;
  5326. int i,max_part_read=0;
  5327. for (i=0; i < f->residue_count; ++i) {
  5328. Residue *r = f->residue_config + i;
  5329. unsigned int actual_size = f->blocksize_1 / 2;
  5330. unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
  5331. unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
  5332. int n_read = limit_r_end - limit_r_begin;
  5333. int part_read = n_read / r->part_size;
  5334. if (part_read > max_part_read)
  5335. max_part_read = part_read;
  5336. }
  5337. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  5338. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
  5339. #else
  5340. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
  5341. #endif
  5342. f->temp_memory_required = classify_mem;
  5343. if (imdct_mem > f->temp_memory_required)
  5344. f->temp_memory_required = imdct_mem;
  5345. }
  5346. if (f->alloc.alloc_buffer) {
  5347. assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
  5348. if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
  5349. return error(f, VORBIS_outofmem);
  5350. }
  5351. if (f->next_seg == -1) {
  5352. f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
  5353. } else {
  5354. f->first_audio_page_offset = 0;
  5355. }
  5356. return TRUE;
  5357. }
  5358. static void vorbis_deinit(stb_vorbis *p)
  5359. {
  5360. int i,j;
  5361. setup_free(p, p->vendor);
  5362. for (i=0; i < p->comment_list_length; ++i) {
  5363. setup_free(p, p->comment_list[i]);
  5364. }
  5365. setup_free(p, p->comment_list);
  5366. if (p->residue_config) {
  5367. for (i=0; i < p->residue_count; ++i) {
  5368. Residue *r = p->residue_config+i;
  5369. if (r->classdata) {
  5370. for (j=0; j < p->codebooks[r->classbook].entries; ++j)
  5371. setup_free(p, r->classdata[j]);
  5372. setup_free(p, r->classdata);
  5373. }
  5374. setup_free(p, r->residue_books);
  5375. }
  5376. }
  5377. if (p->codebooks) {
  5378. CHECK(p);
  5379. for (i=0; i < p->codebook_count; ++i) {
  5380. Codebook *c = p->codebooks + i;
  5381. setup_free(p, c->codeword_lengths);
  5382. setup_free(p, c->multiplicands);
  5383. setup_free(p, c->codewords);
  5384. setup_free(p, c->sorted_codewords);
  5385. setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
  5386. }
  5387. setup_free(p, p->codebooks);
  5388. }
  5389. setup_free(p, p->floor_config);
  5390. setup_free(p, p->residue_config);
  5391. if (p->mapping) {
  5392. for (i=0; i < p->mapping_count; ++i)
  5393. setup_free(p, p->mapping[i].chan);
  5394. setup_free(p, p->mapping);
  5395. }
  5396. CHECK(p);
  5397. for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
  5398. setup_free(p, p->channel_buffers[i]);
  5399. setup_free(p, p->previous_window[i]);
  5400. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  5401. setup_free(p, p->floor_buffers[i]);
  5402. #endif
  5403. setup_free(p, p->finalY[i]);
  5404. }
  5405. for (i=0; i < 2; ++i) {
  5406. setup_free(p, p->A[i]);
  5407. setup_free(p, p->B[i]);
  5408. setup_free(p, p->C[i]);
  5409. setup_free(p, p->window[i]);
  5410. setup_free(p, p->bit_reverse[i]);
  5411. }
  5412. }
  5413. void stb_vorbis_close(stb_vorbis *p)
  5414. {
  5415. if (p == NULL) return;
  5416. vorbis_deinit(p);
  5417. setup_free(p,p);
  5418. }
  5419. static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
  5420. {
  5421. memset(p, 0, sizeof(*p));
  5422. if (z) {
  5423. p->alloc = *z;
  5424. p->alloc.alloc_buffer_length_in_bytes &= ~7;
  5425. p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
  5426. }
  5427. p->eof = 0;
  5428. p->error = VORBIS__no_error;
  5429. p->stream = NULL;
  5430. p->codebooks = NULL;
  5431. p->page_crc_tests = -1;
  5432. }
  5433. int stb_vorbis_get_sample_offset(stb_vorbis *f)
  5434. {
  5435. if (f->current_loc_valid)
  5436. return f->current_loc;
  5437. else
  5438. return -1;
  5439. }
  5440. stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
  5441. {
  5442. stb_vorbis_info d;
  5443. d.channels = f->channels;
  5444. d.sample_rate = f->sample_rate;
  5445. d.setup_memory_required = f->setup_memory_required;
  5446. d.setup_temp_memory_required = f->setup_temp_memory_required;
  5447. d.temp_memory_required = f->temp_memory_required;
  5448. d.max_frame_size = f->blocksize_1 >> 1;
  5449. return d;
  5450. }
  5451. stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f)
  5452. {
  5453. stb_vorbis_comment d;
  5454. d.vendor = f->vendor;
  5455. d.comment_list_length = f->comment_list_length;
  5456. d.comment_list = f->comment_list;
  5457. return d;
  5458. }
  5459. int stb_vorbis_get_error(stb_vorbis *f)
  5460. {
  5461. int e = f->error;
  5462. f->error = VORBIS__no_error;
  5463. return e;
  5464. }
  5465. static stb_vorbis * vorbis_alloc(stb_vorbis *f)
  5466. {
  5467. stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
  5468. return p;
  5469. }
  5470. unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
  5471. {
  5472. if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
  5473. }
  5474. #ifndef STB_VORBIS_NO_PULLDATA_API
  5475. static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
  5476. {
  5477. for(;;) {
  5478. int n;
  5479. if (f->eof) return 0;
  5480. n = get8(f);
  5481. if (n == 0x4f) {
  5482. unsigned int retry_loc = stb_vorbis_get_file_offset(f);
  5483. int i;
  5484. if (retry_loc - 25 > f->stream_len)
  5485. return 0;
  5486. for (i=1; i < 4; ++i)
  5487. if (get8(f) != ogg_page_header[i])
  5488. break;
  5489. if (f->eof) return 0;
  5490. if (i == 4) {
  5491. uint8 header[27];
  5492. uint32 i, crc, goal, len;
  5493. for (i=0; i < 4; ++i)
  5494. header[i] = ogg_page_header[i];
  5495. for (; i < 27; ++i)
  5496. header[i] = get8(f);
  5497. if (f->eof) return 0;
  5498. if (header[4] != 0) goto invalid;
  5499. goal = header[22] + (header[23] << 8) + (header[24]<<16) + ((uint32)header[25]<<24);
  5500. for (i=22; i < 26; ++i)
  5501. header[i] = 0;
  5502. crc = 0;
  5503. for (i=0; i < 27; ++i)
  5504. crc = crc32_update(crc, header[i]);
  5505. len = 0;
  5506. for (i=0; i < header[26]; ++i) {
  5507. int s = get8(f);
  5508. crc = crc32_update(crc, s);
  5509. len += s;
  5510. }
  5511. if (len && f->eof) return 0;
  5512. for (i=0; i < len; ++i)
  5513. crc = crc32_update(crc, get8(f));
  5514. if (crc == goal) {
  5515. if (end)
  5516. *end = stb_vorbis_get_file_offset(f);
  5517. if (last) {
  5518. if (header[5] & 0x04)
  5519. *last = 1;
  5520. else
  5521. *last = 0;
  5522. }
  5523. set_file_offset(f, retry_loc-1);
  5524. return 1;
  5525. }
  5526. }
  5527. invalid:
  5528. set_file_offset(f, retry_loc);
  5529. }
  5530. }
  5531. }
  5532. #define SAMPLE_unknown 0xffffffff
  5533. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
  5534. {
  5535. uint8 header[27] = { 0 }, lacing[255];
  5536. int i,len;
  5537. z->page_start = stb_vorbis_get_file_offset(f);
  5538. getn(f, header, 27);
  5539. if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
  5540. return 0;
  5541. getn(f, lacing, header[26]);
  5542. len = 0;
  5543. for (i=0; i < header[26]; ++i)
  5544. len += lacing[i];
  5545. z->page_end = z->page_start + 27 + header[26] + len;
  5546. z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
  5547. set_file_offset(f, z->page_start);
  5548. return 1;
  5549. }
  5550. static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
  5551. {
  5552. unsigned int previous_safe, end;
  5553. if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
  5554. previous_safe = limit_offset - 65536;
  5555. else
  5556. previous_safe = f->first_audio_page_offset;
  5557. set_file_offset(f, previous_safe);
  5558. while (vorbis_find_page(f, &end, NULL)) {
  5559. if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
  5560. return 1;
  5561. set_file_offset(f, end);
  5562. }
  5563. return 0;
  5564. }
  5565. static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
  5566. {
  5567. ProbedPage left, right, mid;
  5568. int i, start_seg_with_known_loc, end_pos, page_start;
  5569. uint32 delta, stream_length, padding, last_sample_limit;
  5570. double offset = 0.0, bytes_per_sample = 0.0;
  5571. int probe = 0;
  5572. stream_length = stb_vorbis_stream_length_in_samples(f);
  5573. if (stream_length == 0) return error(f, VORBIS_seek_without_length);
  5574. if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
  5575. padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
  5576. if (sample_number < padding)
  5577. last_sample_limit = 0;
  5578. else
  5579. last_sample_limit = sample_number - padding;
  5580. left = f->p_first;
  5581. while (left.last_decoded_sample == ~0U) {
  5582. set_file_offset(f, left.page_end);
  5583. if (!get_seek_page_info(f, &left)) goto error;
  5584. }
  5585. right = f->p_last;
  5586. assert(right.last_decoded_sample != ~0U);
  5587. if (last_sample_limit <= left.last_decoded_sample) {
  5588. if (stb_vorbis_seek_start(f)) {
  5589. if (f->current_loc > sample_number)
  5590. return error(f, VORBIS_seek_failed);
  5591. return 1;
  5592. }
  5593. return 0;
  5594. }
  5595. while (left.page_end != right.page_start) {
  5596. assert(left.page_end < right.page_start);
  5597. delta = right.page_start - left.page_end;
  5598. if (delta <= 65536) {
  5599. set_file_offset(f, left.page_end);
  5600. } else {
  5601. if (probe < 2) {
  5602. if (probe == 0) {
  5603. double data_bytes = right.page_end - left.page_start;
  5604. bytes_per_sample = data_bytes / right.last_decoded_sample;
  5605. offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample);
  5606. } else {
  5607. double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample;
  5608. if (error >= 0 && error < 8000) error = 8000;
  5609. if (error < 0 && error > -8000) error = -8000;
  5610. offset += error * 2;
  5611. }
  5612. if (offset < left.page_end)
  5613. offset = left.page_end;
  5614. if (offset > right.page_start - 65536)
  5615. offset = right.page_start - 65536;
  5616. set_file_offset(f, (unsigned int) offset);
  5617. } else {
  5618. set_file_offset(f, left.page_end + (delta / 2) - 32768);
  5619. }
  5620. if (!vorbis_find_page(f, NULL, NULL)) goto error;
  5621. }
  5622. for (;;) {
  5623. if (!get_seek_page_info(f, &mid)) goto error;
  5624. if (mid.last_decoded_sample != ~0U) break;
  5625. set_file_offset(f, mid.page_end);
  5626. assert(mid.page_start < right.page_start);
  5627. }
  5628. if (mid.page_start == right.page_start) {
  5629. if (probe >= 2 || delta <= 65536)
  5630. break;
  5631. } else {
  5632. if (last_sample_limit < mid.last_decoded_sample)
  5633. right = mid;
  5634. else
  5635. left = mid;
  5636. }
  5637. ++probe;
  5638. }
  5639. page_start = left.page_start;
  5640. set_file_offset(f, page_start);
  5641. if (!start_page(f)) return error(f, VORBIS_seek_failed);
  5642. end_pos = f->end_seg_with_known_loc;
  5643. assert(end_pos >= 0);
  5644. for (;;) {
  5645. for (i = end_pos; i > 0; --i)
  5646. if (f->segments[i-1] != 255)
  5647. break;
  5648. start_seg_with_known_loc = i;
  5649. if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
  5650. break;
  5651. if (!go_to_page_before(f, page_start))
  5652. goto error;
  5653. page_start = stb_vorbis_get_file_offset(f);
  5654. if (!start_page(f)) goto error;
  5655. end_pos = f->segment_count - 1;
  5656. }
  5657. f->current_loc_valid = FALSE;
  5658. f->last_seg = FALSE;
  5659. f->valid_bits = 0;
  5660. f->packet_bytes = 0;
  5661. f->bytes_in_seg = 0;
  5662. f->previous_length = 0;
  5663. f->next_seg = start_seg_with_known_loc;
  5664. for (i = 0; i < start_seg_with_known_loc; i++)
  5665. skip(f, f->segments[i]);
  5666. if (!vorbis_pump_first_frame(f))
  5667. return 0;
  5668. if (f->current_loc > sample_number)
  5669. return error(f, VORBIS_seek_failed);
  5670. return 1;
  5671. error:
  5672. stb_vorbis_seek_start(f);
  5673. return error(f, VORBIS_seek_failed);
  5674. }
  5675. 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)
  5676. {
  5677. int bits_read, bytes_read;
  5678. if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
  5679. return 0;
  5680. bits_read = 1 + ilog(f->mode_count-1);
  5681. if (f->mode_config[*mode].blockflag)
  5682. bits_read += 2;
  5683. bytes_read = (bits_read + 7) / 8;
  5684. f->bytes_in_seg += bytes_read;
  5685. f->packet_bytes -= bytes_read;
  5686. skip(f, -bytes_read);
  5687. if (f->next_seg == -1)
  5688. f->next_seg = f->segment_count - 1;
  5689. else
  5690. f->next_seg--;
  5691. f->valid_bits = 0;
  5692. return 1;
  5693. }
  5694. int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
  5695. {
  5696. uint32 max_frame_samples;
  5697. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  5698. if (!seek_to_sample_coarse(f, sample_number))
  5699. return 0;
  5700. assert(f->current_loc_valid);
  5701. assert(f->current_loc <= sample_number);
  5702. max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
  5703. while (f->current_loc < sample_number) {
  5704. int left_start, left_end, right_start, right_end, mode, frame_samples;
  5705. if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
  5706. return error(f, VORBIS_seek_failed);
  5707. frame_samples = right_start - left_start;
  5708. if (f->current_loc + frame_samples > sample_number) {
  5709. return 1;
  5710. } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
  5711. vorbis_pump_first_frame(f);
  5712. } else {
  5713. f->current_loc += frame_samples;
  5714. f->previous_length = 0;
  5715. maybe_start_packet(f);
  5716. flush_packet(f);
  5717. }
  5718. }
  5719. if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed);
  5720. return 1;
  5721. }
  5722. int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
  5723. {
  5724. if (!stb_vorbis_seek_frame(f, sample_number))
  5725. return 0;
  5726. if (sample_number != f->current_loc) {
  5727. int n;
  5728. uint32 frame_start = f->current_loc;
  5729. stb_vorbis_get_frame_float(f, &n, NULL);
  5730. assert(sample_number > frame_start);
  5731. assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
  5732. f->channel_buffer_start += (sample_number - frame_start);
  5733. }
  5734. return 1;
  5735. }
  5736. int stb_vorbis_seek_start(stb_vorbis *f)
  5737. {
  5738. if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }
  5739. set_file_offset(f, f->first_audio_page_offset);
  5740. f->previous_length = 0;
  5741. f->first_decode = TRUE;
  5742. f->next_seg = -1;
  5743. return vorbis_pump_first_frame(f);
  5744. }
  5745. unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
  5746. {
  5747. unsigned int restore_offset, previous_safe;
  5748. unsigned int end, last_page_loc;
  5749. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  5750. if (!f->total_samples) {
  5751. unsigned int last;
  5752. uint32 lo,hi;
  5753. char header[6];
  5754. restore_offset = stb_vorbis_get_file_offset(f);
  5755. if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
  5756. previous_safe = f->stream_len - 65536;
  5757. else
  5758. previous_safe = f->first_audio_page_offset;
  5759. set_file_offset(f, previous_safe);
  5760. if (!vorbis_find_page(f, &end, &last)) {
  5761. f->error = VORBIS_cant_find_last_page;
  5762. f->total_samples = 0xffffffff;
  5763. goto done;
  5764. }
  5765. last_page_loc = stb_vorbis_get_file_offset(f);
  5766. while (!last) {
  5767. set_file_offset(f, end);
  5768. if (!vorbis_find_page(f, &end, &last)) {
  5769. break;
  5770. }
  5771. last_page_loc = stb_vorbis_get_file_offset(f);
  5772. }
  5773. set_file_offset(f, last_page_loc);
  5774. getn(f, (unsigned char *)header, 6);
  5775. lo = get32(f);
  5776. hi = get32(f);
  5777. if (lo == 0xffffffff && hi == 0xffffffff) {
  5778. f->error = VORBIS_cant_find_last_page;
  5779. f->total_samples = SAMPLE_unknown;
  5780. goto done;
  5781. }
  5782. if (hi)
  5783. lo = 0xfffffffe;
  5784. f->total_samples = lo;
  5785. f->p_last.page_start = last_page_loc;
  5786. f->p_last.page_end = end;
  5787. f->p_last.last_decoded_sample = lo;
  5788. done:
  5789. set_file_offset(f, restore_offset);
  5790. }
  5791. return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
  5792. }
  5793. float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
  5794. {
  5795. return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
  5796. }
  5797. int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
  5798. {
  5799. int len, right,left,i;
  5800. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  5801. if (!vorbis_decode_packet(f, &len, &left, &right)) {
  5802. f->channel_buffer_start = f->channel_buffer_end = 0;
  5803. return 0;
  5804. }
  5805. len = vorbis_finish_frame(f, len, left, right);
  5806. for (i=0; i < f->channels; ++i)
  5807. f->outputs[i] = f->channel_buffers[i] + left;
  5808. f->channel_buffer_start = left;
  5809. f->channel_buffer_end = left+len;
  5810. if (channels) *channels = f->channels;
  5811. if (output) *output = f->outputs;
  5812. return len;
  5813. }
  5814. stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
  5815. {
  5816. stb_vorbis *f, p;
  5817. if (!data) {
  5818. if (error) *error = VORBIS_unexpected_eof;
  5819. return NULL;
  5820. }
  5821. vorbis_init(&p, alloc);
  5822. p.stream = (uint8 *) data;
  5823. p.stream_end = (uint8 *) data + len;
  5824. p.stream_start = (uint8 *) p.stream;
  5825. p.stream_len = len;
  5826. p.push_mode = FALSE;
  5827. if (start_decoder(&p)) {
  5828. f = vorbis_alloc(&p);
  5829. if (f) {
  5830. *f = p;
  5831. vorbis_pump_first_frame(f);
  5832. if (error) *error = VORBIS__no_error;
  5833. return f;
  5834. }
  5835. }
  5836. if (error) *error = p.error;
  5837. vorbis_deinit(&p);
  5838. return NULL;
  5839. }
  5840. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  5841. #define PLAYBACK_MONO 1
  5842. #define PLAYBACK_LEFT 2
  5843. #define PLAYBACK_RIGHT 4
  5844. #define L (PLAYBACK_LEFT | PLAYBACK_MONO)
  5845. #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
  5846. #define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
  5847. static int8 channel_position[7][6] =
  5848. {
  5849. { 0 },
  5850. { C },
  5851. { L, R },
  5852. { L, C, R },
  5853. { L, R, L, R },
  5854. { L, C, R, L, R },
  5855. { L, C, R, L, R, C },
  5856. };
  5857. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  5858. typedef union {
  5859. float f;
  5860. int i;
  5861. } float_conv;
  5862. typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
  5863. #define FASTDEF(x) float_conv x
  5864. #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
  5865. #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
  5866. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
  5867. #define check_endianness()
  5868. #else
  5869. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
  5870. #define check_endianness()
  5871. #define FASTDEF(x)
  5872. #endif
  5873. static void copy_samples(short *dest, float *src, int len)
  5874. {
  5875. int i;
  5876. check_endianness();
  5877. for (i=0; i < len; ++i) {
  5878. FASTDEF(temp);
  5879. int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
  5880. if ((unsigned int) (v + 32768) > 65535)
  5881. v = v < 0 ? -32768 : 32767;
  5882. dest[i] = v;
  5883. }
  5884. }
  5885. static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
  5886. {
  5887. #define STB_BUFFER_SIZE 32
  5888. float buffer[STB_BUFFER_SIZE];
  5889. int i,j,o,n = STB_BUFFER_SIZE;
  5890. check_endianness();
  5891. for (o = 0; o < len; o += STB_BUFFER_SIZE) {
  5892. memset(buffer, 0, sizeof(buffer));
  5893. if (o + n > len) n = len - o;
  5894. for (j=0; j < num_c; ++j) {
  5895. if (channel_position[num_c][j] & mask) {
  5896. for (i=0; i < n; ++i)
  5897. buffer[i] += data[j][d_offset+o+i];
  5898. }
  5899. }
  5900. for (i=0; i < n; ++i) {
  5901. FASTDEF(temp);
  5902. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  5903. if ((unsigned int) (v + 32768) > 65535)
  5904. v = v < 0 ? -32768 : 32767;
  5905. output[o+i] = v;
  5906. }
  5907. }
  5908. #undef STB_BUFFER_SIZE
  5909. }
  5910. static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
  5911. {
  5912. #define STB_BUFFER_SIZE 32
  5913. float buffer[STB_BUFFER_SIZE];
  5914. int i,j,o,n = STB_BUFFER_SIZE >> 1;
  5915. check_endianness();
  5916. for (o = 0; o < len; o += STB_BUFFER_SIZE >> 1) {
  5917. int o2 = o << 1;
  5918. memset(buffer, 0, sizeof(buffer));
  5919. if (o + n > len) n = len - o;
  5920. for (j=0; j < num_c; ++j) {
  5921. int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
  5922. if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
  5923. for (i=0; i < n; ++i) {
  5924. buffer[i*2+0] += data[j][d_offset+o+i];
  5925. buffer[i*2+1] += data[j][d_offset+o+i];
  5926. }
  5927. } else if (m == PLAYBACK_LEFT) {
  5928. for (i=0; i < n; ++i) {
  5929. buffer[i*2+0] += data[j][d_offset+o+i];
  5930. }
  5931. } else if (m == PLAYBACK_RIGHT) {
  5932. for (i=0; i < n; ++i) {
  5933. buffer[i*2+1] += data[j][d_offset+o+i];
  5934. }
  5935. }
  5936. }
  5937. for (i=0; i < (n<<1); ++i) {
  5938. FASTDEF(temp);
  5939. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  5940. if ((unsigned int) (v + 32768) > 65535)
  5941. v = v < 0 ? -32768 : 32767;
  5942. output[o2+i] = v;
  5943. }
  5944. }
  5945. #undef STB_BUFFER_SIZE
  5946. }
  5947. static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
  5948. {
  5949. int i;
  5950. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  5951. static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
  5952. for (i=0; i < buf_c; ++i)
  5953. compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
  5954. } else {
  5955. int limit = buf_c < data_c ? buf_c : data_c;
  5956. for (i=0; i < limit; ++i)
  5957. copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
  5958. for ( ; i < buf_c; ++i)
  5959. memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
  5960. }
  5961. }
  5962. int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
  5963. {
  5964. float **output = NULL;
  5965. int len = stb_vorbis_get_frame_float(f, NULL, &output);
  5966. if (len > num_samples) len = num_samples;
  5967. if (len)
  5968. convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
  5969. return len;
  5970. }
  5971. static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
  5972. {
  5973. int i;
  5974. check_endianness();
  5975. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  5976. assert(buf_c == 2);
  5977. for (i=0; i < buf_c; ++i)
  5978. compute_stereo_samples(buffer, data_c, data, d_offset, len);
  5979. } else {
  5980. int limit = buf_c < data_c ? buf_c : data_c;
  5981. int j;
  5982. for (j=0; j < len; ++j) {
  5983. for (i=0; i < limit; ++i) {
  5984. FASTDEF(temp);
  5985. float f = data[i][d_offset+j];
  5986. int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);
  5987. if ((unsigned int) (v + 32768) > 65535)
  5988. v = v < 0 ? -32768 : 32767;
  5989. *buffer++ = v;
  5990. }
  5991. for ( ; i < buf_c; ++i)
  5992. *buffer++ = 0;
  5993. }
  5994. }
  5995. }
  5996. int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
  5997. {
  5998. float **output;
  5999. int len;
  6000. if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
  6001. len = stb_vorbis_get_frame_float(f, NULL, &output);
  6002. if (len) {
  6003. if (len*num_c > num_shorts) len = num_shorts / num_c;
  6004. convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
  6005. }
  6006. return len;
  6007. }
  6008. int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
  6009. {
  6010. float **outputs;
  6011. int len = num_shorts / channels;
  6012. int n=0;
  6013. while (n < len) {
  6014. int k = f->channel_buffer_end - f->channel_buffer_start;
  6015. if (n+k >= len) k = len - n;
  6016. if (k)
  6017. convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  6018. buffer += k*channels;
  6019. n += k;
  6020. f->channel_buffer_start += k;
  6021. if (n == len) break;
  6022. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  6023. }
  6024. return n;
  6025. }
  6026. int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
  6027. {
  6028. float **outputs;
  6029. int n=0;
  6030. while (n < len) {
  6031. int k = f->channel_buffer_end - f->channel_buffer_start;
  6032. if (n+k >= len) k = len - n;
  6033. if (k)
  6034. convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  6035. n += k;
  6036. f->channel_buffer_start += k;
  6037. if (n == len) break;
  6038. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  6039. }
  6040. return n;
  6041. }
  6042. int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
  6043. {
  6044. int data_len, offset, total, limit, error;
  6045. short *data;
  6046. stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
  6047. if (v == NULL) return -1;
  6048. limit = v->channels * 4096;
  6049. *channels = v->channels;
  6050. if (sample_rate)
  6051. *sample_rate = v->sample_rate;
  6052. offset = data_len = 0;
  6053. total = limit;
  6054. data = (short *) malloc(total * sizeof(*data));
  6055. if (data == NULL) {
  6056. stb_vorbis_close(v);
  6057. return -2;
  6058. }
  6059. for (;;) {
  6060. int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
  6061. if (n == 0) break;
  6062. data_len += n;
  6063. offset += n * v->channels;
  6064. if (offset + limit > total) {
  6065. short *data2;
  6066. total *= 2;
  6067. data2 = (short *) realloc(data, total * sizeof(*data));
  6068. if (data2 == NULL) {
  6069. free(data);
  6070. stb_vorbis_close(v);
  6071. return -2;
  6072. }
  6073. data = data2;
  6074. }
  6075. }
  6076. *output = data;
  6077. stb_vorbis_close(v);
  6078. return data_len;
  6079. }
  6080. #endif
  6081. int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
  6082. {
  6083. float **outputs;
  6084. int len = num_floats / channels;
  6085. int n=0;
  6086. int z = f->channels;
  6087. if (z > channels) z = channels;
  6088. while (n < len) {
  6089. int i,j;
  6090. int k = f->channel_buffer_end - f->channel_buffer_start;
  6091. if (n+k >= len) k = len - n;
  6092. for (j=0; j < k; ++j) {
  6093. for (i=0; i < z; ++i)
  6094. *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
  6095. for ( ; i < channels; ++i)
  6096. *buffer++ = 0;
  6097. }
  6098. n += k;
  6099. f->channel_buffer_start += k;
  6100. if (n == len)
  6101. break;
  6102. if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
  6103. break;
  6104. }
  6105. return n;
  6106. }
  6107. int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
  6108. {
  6109. float **outputs;
  6110. int n=0;
  6111. int z = f->channels;
  6112. if (z > channels) z = channels;
  6113. while (n < num_samples) {
  6114. int i;
  6115. int k = f->channel_buffer_end - f->channel_buffer_start;
  6116. if (n+k >= num_samples) k = num_samples - n;
  6117. if (k) {
  6118. for (i=0; i < z; ++i)
  6119. memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
  6120. for ( ; i < channels; ++i)
  6121. memset(buffer[i]+n, 0, sizeof(float) * k);
  6122. }
  6123. n += k;
  6124. f->channel_buffer_start += k;
  6125. if (n == num_samples)
  6126. break;
  6127. if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
  6128. break;
  6129. }
  6130. return n;
  6131. }
  6132. #endif
  6133. #endif
  6134. #endif
  6135. #if !defined(SSFN_HEADERONLY) && !defined(SSFN_IMPLEMENTATION)
  6136. #define SSFN_IMPLEMENTATION
  6137. #define SSFN_MAXLINES 1024
  6138. #endif
  6139. /* ssfn.h - Scalable Screen Font - MIT license
  6140. https://gitlab.com/bztsrc/scalable-font2 */
  6141. /**************** embeded ssfn.h ****************/
  6142. #ifndef _SSFN_H_
  6143. #define _SSFN_H_
  6144. #define SSFN_VERSION 0x0200
  6145. #ifndef _STDINT_H
  6146. typedef unsigned char uint8_t;
  6147. typedef unsigned short int uint16_t;
  6148. typedef short int int16_t;
  6149. typedef unsigned int uint32_t;
  6150. #ifndef _UINT64_T
  6151. typedef unsigned long int uint64_t;
  6152. #endif
  6153. #endif
  6154. #define SSFN_MAGIC "SFN2"
  6155. #define SSFN_COLLECTION "SFNC"
  6156. #define SSFN_ENDMAGIC "2NFS"
  6157. #define SSFN_LIG_FIRST 0xF000
  6158. #define SSFN_LIG_LAST 0xF8FF
  6159. #define SSFN_TYPE_FAMILY(x) ((x)&15)
  6160. #define SSFN_FAMILY_SERIF 0
  6161. #define SSFN_FAMILY_SANS 1
  6162. #define SSFN_FAMILY_DECOR 2
  6163. #define SSFN_FAMILY_MONOSPACE 3
  6164. #define SSFN_FAMILY_HAND 4
  6165. #define SSFN_TYPE_STYLE(x) (((x)>>4)&15)
  6166. #define SSFN_STYLE_REGULAR 0
  6167. #define SSFN_STYLE_BOLD 1
  6168. #define SSFN_STYLE_ITALIC 2
  6169. #define SSFN_STYLE_USRDEF1 4
  6170. #define SSFN_STYLE_USRDEF2 8
  6171. #define SSFN_CONTOUR_MOVE 0
  6172. #define SSFN_CONTOUR_LINE 1
  6173. #define SSFN_CONTOUR_QUAD 2
  6174. #define SSFN_CONTOUR_CUBIC 3
  6175. #define SSFN_FRAG_CONTOUR 0
  6176. #define SSFN_FRAG_BITMAP 1
  6177. #define SSFN_FRAG_PIXMAP 2
  6178. #define SSFN_FRAG_KERNING 3
  6179. #define SSFN_FRAG_HINTING 4
  6180. #ifndef _MSC_VER
  6181. #define _pack __attribute__((packed))
  6182. #else
  6183. #define _pack
  6184. #pragma pack(push)
  6185. #pragma pack(1)
  6186. #endif
  6187. typedef struct {
  6188. uint8_t magic[4];
  6189. uint32_t size;
  6190. uint8_t type;
  6191. uint8_t features;
  6192. uint8_t width;
  6193. uint8_t height;
  6194. uint8_t baseline;
  6195. uint8_t underline;
  6196. uint16_t fragments_offs;
  6197. uint32_t characters_offs;
  6198. uint32_t ligature_offs;
  6199. uint32_t kerning_offs;
  6200. uint32_t cmap_offs;
  6201. } _pack ssfn_font_t;
  6202. #ifdef _MSC_VER
  6203. #pragma pack(pop)
  6204. #endif
  6205. #define SSFN_FAMILY_ANY 0xff
  6206. #define SSFN_FAMILY_BYNAME 0xfe
  6207. #define SSFN_STYLE_UNDERLINE 16
  6208. #define SSFN_STYLE_STHROUGH 32
  6209. #define SSFN_STYLE_NOAA 64
  6210. #define SSFN_STYLE_NOKERN 128
  6211. #define SSFN_STYLE_NODEFGLYPH 256
  6212. #define SSFN_STYLE_NOCACHE 512
  6213. #define SSFN_STYLE_NOHINTING 1024
  6214. #define SSFN_STYLE_RTL 2048
  6215. #define SSFN_STYLE_ABS_SIZE 4096
  6216. #define SSFN_STYLE_NOSMOOTH 8192
  6217. #define SSFN_OK 0
  6218. #define SSFN_ERR_ALLOC -1
  6219. #define SSFN_ERR_BADFILE -2
  6220. #define SSFN_ERR_NOFACE -3
  6221. #define SSFN_ERR_INVINP -4
  6222. #define SSFN_ERR_BADSTYLE -5
  6223. #define SSFN_ERR_BADSIZE -6
  6224. #define SSFN_ERR_NOGLYPH -7
  6225. #define SSFN_SIZE_MAX 192
  6226. #define SSFN_ITALIC_DIV 4
  6227. #define SSFN_PREC 4
  6228. typedef struct {
  6229. uint8_t *ptr;
  6230. int w;
  6231. int h;
  6232. uint16_t p;
  6233. int x;
  6234. int y;
  6235. uint32_t fg;
  6236. uint32_t bg;
  6237. } ssfn_buf_t;
  6238. #define SSFN_DATA_MAX 65536
  6239. typedef struct {
  6240. uint16_t p;
  6241. uint8_t h;
  6242. uint8_t o;
  6243. uint8_t x;
  6244. uint8_t y;
  6245. uint8_t a;
  6246. uint8_t d;
  6247. uint8_t data[SSFN_DATA_MAX];
  6248. } ssfn_glyph_t;
  6249. typedef struct {
  6250. uint8_t t;
  6251. uint8_t n;
  6252. uint8_t w;
  6253. uint8_t h;
  6254. uint8_t x;
  6255. uint8_t y;
  6256. } ssfn_chr_t;
  6257. #ifdef SSFN_PROFILING
  6258. #include <string.h>
  6259. #include <sys/time.h>
  6260. #endif
  6261. typedef struct {
  6262. #ifdef SSFN_MAXLINES
  6263. const ssfn_font_t *fnt[5][16];
  6264. #else
  6265. const ssfn_font_t **fnt[5];
  6266. #endif
  6267. const ssfn_font_t *s;
  6268. const ssfn_font_t *f;
  6269. ssfn_glyph_t ga;
  6270. ssfn_glyph_t *g;
  6271. #ifdef SSFN_MAXLINES
  6272. uint16_t p[SSFN_MAXLINES*2];
  6273. #else
  6274. ssfn_glyph_t ***c[17];
  6275. uint16_t *p;
  6276. char **bufs;
  6277. #endif
  6278. ssfn_chr_t *rc;
  6279. int numbuf, lenbuf, np, ap, ox, oy, ax;
  6280. int mx, my, lx, ly;
  6281. int len[5];
  6282. int family;
  6283. int style;
  6284. int size;
  6285. int line;
  6286. #ifdef SSFN_PROFILING
  6287. uint64_t lookup, raster, blit, kern;
  6288. #endif
  6289. } ssfn_t;
  6290. uint32_t ssfn_utf8(char **str);
  6291. int ssfn_load(ssfn_t *ctx, const void *data);
  6292. int ssfn_select(ssfn_t *ctx, int family, const char *name, int style, int size);
  6293. int ssfn_render(ssfn_t *ctx, ssfn_buf_t *dst, const char *str);
  6294. int ssfn_bbox(ssfn_t *ctx, const char *str, int *w, int *h, int *left, int *top);
  6295. ssfn_buf_t *ssfn_text(ssfn_t *ctx, const char *str, unsigned int fg);
  6296. int ssfn_mem(ssfn_t *ctx);
  6297. void ssfn_free(ssfn_t *ctx);
  6298. #define ssfn_error(err) (err<0&&err>=-7?ssfn_errstr[-err]:"Unknown error")
  6299. extern const char *ssfn_errstr[];
  6300. extern ssfn_font_t *ssfn_src;
  6301. extern ssfn_buf_t ssfn_dst;
  6302. int ssfn_putc(uint32_t unicode);
  6303. #if (defined(SSFN_IMPLEMENTATION) || defined(SSFN_CONSOLEBITMAP_PALETTE) || \
  6304. defined(SSFN_CONSOLEBITMAP_HICOLOR) || defined(SSFN_CONSOLEBITMAP_TRUECOLOR)) && !defined(SSFN_COMMON)
  6305. #define SSFN_COMMON
  6306. const char *ssfn_errstr[] = { "",
  6307. "Memory allocation error",
  6308. "Bad file format",
  6309. "No font face found",
  6310. "Invalid input value",
  6311. "Invalid style",
  6312. "Invalid size",
  6313. "Glyph not found"
  6314. };
  6315. uint32_t ssfn_utf8(char **s)
  6316. {
  6317. uint32_t c = **s;
  6318. if((**s & 128) != 0) {
  6319. if(!(**s & 32)) { c = ((**s & 0x1F)<<6)|(*(*s+1) & 0x3F); *s += 1; } else
  6320. if(!(**s & 16)) { c = ((**s & 0xF)<<12)|((*(*s+1) & 0x3F)<<6)|(*(*s+2) & 0x3F); *s += 2; } else
  6321. if(!(**s & 8)) { c = ((**s & 0x7)<<18)|((*(*s+1) & 0x3F)<<12)|((*(*s+2) & 0x3F)<<6)|(*(*s+3) & 0x3F); *s += 3; }
  6322. else c = 0;
  6323. }
  6324. (*s)++;
  6325. return c;
  6326. }
  6327. #endif
  6328. #ifdef SSFN_IMPLEMENTATION
  6329. # ifndef NULL
  6330. # define NULL (void*)0
  6331. # endif
  6332. # ifndef size_t
  6333. typedef __SIZE_TYPE__ size_t;
  6334. # endif
  6335. # ifndef inline
  6336. # define inline __inline__
  6337. # endif
  6338. #ifndef _STRING_H_
  6339. extern int memcmp (const void *__s1, const void *__s2, size_t __n) __THROW;
  6340. extern void *memset (void *__s, int __c, size_t __n) __THROW;
  6341. #endif
  6342. # ifndef SSFN_memcmp
  6343. # ifdef __builtin_memcmp
  6344. # define SSFN_memcmp __builtin_memcmp
  6345. # else
  6346. # ifndef SSFN_MAXLINES
  6347. # define SSFN_memcmp memcmp
  6348. # else
  6349. static int SSFN_memcmp(const void *__s1, const void *__s2, size_t __n)
  6350. { unsigned char *a = (unsigned char *)__s1, *b = (unsigned char *)__s2;
  6351. if(__n > 0) { while(__n-- > 0) { if(*a != *b) { return *a - *b; } a++; b++; } } return 0; }
  6352. # endif
  6353. # endif
  6354. # endif
  6355. # ifndef SSFN_memset
  6356. # ifdef __builtin_memset
  6357. # define SSFN_memset __builtin_memset
  6358. # else
  6359. # ifndef SSFN_MAXLINES
  6360. # define SSFN_memset memset
  6361. # else
  6362. static void *SSFN_memset(void *__s, int __c, size_t __n)
  6363. { unsigned char *a = __s; if(__n > 0) { while(__n-- > 0) *a++ = __c; } return __s; }
  6364. # endif
  6365. # endif
  6366. # endif
  6367. # ifndef SSFN_MAXLINES
  6368. # ifndef SSFN_realloc
  6369. # ifdef __builtin_realloc
  6370. # define SSFN_realloc __builtin_realloc
  6371. # else
  6372. # define SSFN_realloc realloc
  6373. extern void *realloc (void *__ptr, size_t __size) __THROW;
  6374. # endif
  6375. # endif
  6376. # ifndef SSFN_free
  6377. # ifdef __builtin_free
  6378. # define SSFN_free __builtin_free
  6379. # else
  6380. # define SSFN_free free
  6381. extern void free (void *p) __THROW;
  6382. # endif
  6383. # endif
  6384. # endif
  6385. static uint8_t *_ssfn_c(const ssfn_font_t *font, const char *str, int *len, uint32_t *unicode)
  6386. {
  6387. uint32_t i, j, u = -1U;
  6388. uint16_t *l;
  6389. uint8_t *ptr, *s;
  6390. *len = 0; *unicode = 0;
  6391. if(!font || !font->characters_offs || !str || !*str) return NULL;
  6392. if(font->ligature_offs) {
  6393. for(l = (uint16_t*)((uint8_t*)font + font->ligature_offs), i = 0; l[i] && u == -1U; i++) {
  6394. for(ptr = (uint8_t*)font + l[i], s = (uint8_t*)str; *ptr && *ptr == *s; ptr++, s++);
  6395. if(!*ptr) { u = SSFN_LIG_FIRST + i; break; }
  6396. }
  6397. }
  6398. if(u == -1U) {
  6399. s = (uint8_t*)str; u = *s;
  6400. if((*s & 128) != 0) {
  6401. if(!(*s & 32)) { u = ((*s & 0x1F)<<6)|(*(s+1) & 0x3F); s++; } else
  6402. if(!(*s & 16)) { u = ((*s & 0xF)<<12)|((*(s+1) & 0x3F)<<6)|(*(s+2) & 0x3F); s += 2; } else
  6403. if(!(*s & 8)) { u = ((*s & 0x7)<<18)|((*(s+1) & 0x3F)<<12)|((*(s+2) & 0x3F)<<6)|(*(s+3) & 0x3F); s += 3; }
  6404. else u = 0;
  6405. }
  6406. s++;
  6407. }
  6408. *len = (int)(s - (uint8_t*)str);
  6409. *unicode = u;
  6410. for(ptr = (uint8_t*)font + font->characters_offs, i = 0; i < 0x110000; i++) {
  6411. if(ptr[0] == 0xFF) { i += 65535; ptr++; }
  6412. else if((ptr[0] & 0xC0) == 0xC0) { j = (((ptr[0] & 0x3F) << 8) | ptr[1]); i += j; ptr += 2; }
  6413. else if((ptr[0] & 0xC0) == 0x80) { j = (ptr[0] & 0x3F); i += j; ptr++; }
  6414. else {
  6415. if(i == u) return ptr;
  6416. ptr += 6 + ptr[1] * (ptr[0] & 0x40 ? 6 : 5);
  6417. }
  6418. }
  6419. return NULL;
  6420. }
  6421. static void _ssfn_l(ssfn_t *ctx, int p, int h, int x, int y)
  6422. {
  6423. if(x < 0 || y < 0 || x >= p || y >= h || (
  6424. ((ctx->lx + (1 << (SSFN_PREC-1))) >> SSFN_PREC) == ((x + (1 << (SSFN_PREC-1))) >> SSFN_PREC) &&
  6425. ((ctx->ly + (1 << (SSFN_PREC-1))) >> SSFN_PREC) == ((y + (1 << (SSFN_PREC-1))) >> SSFN_PREC))) return;
  6426. #ifdef SSFN_MAXLINES
  6427. if(ctx->np >= SSFN_MAXLINES*2-2) return;
  6428. #else
  6429. if(ctx->ap <= ctx->np) {
  6430. ctx->ap = ctx->np + 512;
  6431. ctx->p = (uint16_t*)SSFN_realloc(ctx->p, ctx->ap * sizeof(uint16_t));
  6432. if(!ctx->p) { ctx->ap = ctx->np = 0; return; }
  6433. }
  6434. #endif
  6435. if(!ctx->np) {
  6436. ctx->p[0] = ctx->mx;
  6437. ctx->p[1] = ctx->my;
  6438. ctx->np += 2;
  6439. }
  6440. ctx->p[ctx->np+0] = x;
  6441. ctx->p[ctx->np+1] = y;
  6442. ctx->np += 2;
  6443. ctx->lx = x; ctx->ly = y;
  6444. }
  6445. static void _ssfn_b(ssfn_t *ctx, int p,int h, int x0,int y0, int x1,int y1, int x2,int y2, int x3,int y3, int l)
  6446. {
  6447. int m0x, m0y, m1x, m1y, m2x, m2y, m3x, m3y, m4x, m4y,m5x, m5y;
  6448. if(l<4 && (x0!=x3 || y0!=y3)) {
  6449. m0x = ((x1-x0)/2) + x0; m0y = ((y1-y0)/2) + y0;
  6450. m1x = ((x2-x1)/2) + x1; m1y = ((y2-y1)/2) + y1;
  6451. m2x = ((x3-x2)/2) + x2; m2y = ((y3-y2)/2) + y2;
  6452. m3x = ((m1x-m0x)/2) + m0x; m3y = ((m1y-m0y)/2) + m0y;
  6453. m4x = ((m2x-m1x)/2) + m1x; m4y = ((m2y-m1y)/2) + m1y;
  6454. m5x = ((m4x-m3x)/2) + m3x; m5y = ((m4y-m3y)/2) + m3y;
  6455. _ssfn_b(ctx, p,h, x0,y0, m0x,m0y, m3x,m3y, m5x,m5y, l+1);
  6456. _ssfn_b(ctx, p,h, m5x,m5y, m4x,m4y, m2x,m2y, x3,y3, l+1);
  6457. }
  6458. if(l) _ssfn_l(ctx, p,h, x3, y3);
  6459. }
  6460. int ssfn_load(ssfn_t *ctx, const void *data)
  6461. {
  6462. const ssfn_font_t *font = (const ssfn_font_t *)data;
  6463. ssfn_font_t *fnt, *end;
  6464. int family;
  6465. if(!ctx || !font)
  6466. return SSFN_ERR_INVINP;
  6467. if(((uint8_t *)font)[0] == 0x1f && ((uint8_t *)font)[1] == 0x8b) {
  6468. #ifdef SSFN_MAXLINES
  6469. return SSFN_ERR_BADFILE;
  6470. #else
  6471. ptr += 2;
  6472. if(*ptr++ != 8) return SSFN_ERR_BADFILE;
  6473. c = *ptr++; ptr += 6;
  6474. if(c & 4) { r = *ptr++; r += (*ptr++ << 8); ptr += r; }
  6475. if(c & 8) { while(*ptr++ != 0); }
  6476. if(c & 16) { while(*ptr++ != 0); }
  6477. font = (ssfn_font_t*)_ssfn_zlib_decode((const char*)ptr);
  6478. if(!font) return SSFN_ERR_BADFILE;
  6479. ctx->bufs = (char**)SSFN_realloc(ctx->bufs, (ctx->numbuf + 1) * sizeof(char*));
  6480. if(!ctx->bufs) { ctx->numbuf = 0; return SSFN_ERR_ALLOC; }
  6481. ctx->bufs[ctx->numbuf++] = (char*)font;
  6482. ctx->lenbuf += font->size;
  6483. #endif
  6484. }
  6485. if(!SSFN_memcmp(font->magic, SSFN_COLLECTION, 4)) {
  6486. end = (ssfn_font_t*)((uint8_t*)font + font->size);
  6487. for(fnt = (ssfn_font_t*)((uint8_t*)font + 8); fnt < end && !ssfn_load(ctx, (const void *)fnt);
  6488. fnt = (ssfn_font_t*)((uint8_t*)fnt + fnt->size));
  6489. } else {
  6490. family = SSFN_TYPE_FAMILY(font->type);
  6491. if(SSFN_memcmp(font->magic, SSFN_MAGIC, 4) || SSFN_memcmp((uint8_t*)font + font->size - 4, SSFN_ENDMAGIC, 4) ||
  6492. family > SSFN_FAMILY_HAND || font->fragments_offs >= font->size || font->characters_offs >= font->size ||
  6493. font->ligature_offs >= font->size || font->kerning_offs >= font->size || font->cmap_offs >= font->size ||
  6494. font->fragments_offs >= font->characters_offs) {
  6495. return SSFN_ERR_BADFILE;
  6496. } else {
  6497. ctx->len[family]++;
  6498. #ifdef SSFN_MAXLINES
  6499. if(ctx->len[family] > 15) return SSFN_ERR_ALLOC;
  6500. #else
  6501. ctx->fnt[family] = (const ssfn_font_t**)SSFN_realloc(ctx->fnt[family], ctx->len[family]*sizeof(void*));
  6502. if(!ctx->fnt[family]) {
  6503. ctx->len[family] = 0;
  6504. return SSFN_ERR_ALLOC;
  6505. } else
  6506. #endif
  6507. ctx->fnt[family][ctx->len[family]-1] = font;
  6508. }
  6509. }
  6510. return SSFN_OK;
  6511. }
  6512. void ssfn_free(ssfn_t *ctx)
  6513. {
  6514. if(!ctx) return;
  6515. SSFN_memset(ctx, 0, sizeof(ssfn_t));
  6516. }
  6517. int ssfn_mem(ssfn_t *ctx)
  6518. {
  6519. #ifdef SSFN_MAXLINES
  6520. return ctx ? sizeof(ssfn_t) : 0;
  6521. #else
  6522. int i, j, k, ret = sizeof(ssfn_t);
  6523. if(!ctx) return 0;
  6524. for(i = 0; i < 5; i++) ret += ctx->len[i] * sizeof(ssfn_font_t*);
  6525. ret += ctx->lenbuf;
  6526. for(k = 0; k <= 16; k++) {
  6527. if(ctx->c[k]) {
  6528. for(j = 0; j < 256; j++)
  6529. if(ctx->c[k][j]) {
  6530. for(i = 0; i < 256; i++)
  6531. if(ctx->c[k][j][i]) ret += 8 + ctx->c[k][j][i]->p * ctx->c[k][j][i]->h;
  6532. ret += 256 * sizeof(void*);
  6533. }
  6534. ret += 256 * sizeof(void*);
  6535. }
  6536. }
  6537. if(ctx->p) ret += ctx->ap * sizeof(uint16_t);
  6538. return ret;
  6539. #endif
  6540. }
  6541. int ssfn_select(ssfn_t *ctx, int family, const char *name, int style, int size)
  6542. {
  6543. int i, j, l;
  6544. if(!ctx) return SSFN_ERR_INVINP;
  6545. if((style & ~0x5FFF)) return SSFN_ERR_BADSTYLE;
  6546. if(size < 8 || size > SSFN_SIZE_MAX) return SSFN_ERR_BADSIZE;
  6547. if(family == SSFN_FAMILY_BYNAME) {
  6548. if(!name || !name[0]) return SSFN_ERR_INVINP;
  6549. for(l=0; name[l]; l++);
  6550. for(i=0; i < 5; i++) {
  6551. for(j=0; j < ctx->len[i]; j++) {
  6552. if(!SSFN_memcmp(name, (uint8_t*)&ctx->fnt[i][j]->magic + sizeof(ssfn_font_t), l)) {
  6553. ctx->s = ctx->fnt[i][j];
  6554. goto familyfound;
  6555. }
  6556. }
  6557. }
  6558. return SSFN_ERR_NOFACE;
  6559. } else {
  6560. if(family != SSFN_FAMILY_ANY && (family > SSFN_FAMILY_HAND || !ctx->len[family])) return SSFN_ERR_NOFACE;
  6561. ctx->s = NULL;
  6562. }
  6563. familyfound:
  6564. ctx->f = NULL;
  6565. ctx->family = family;
  6566. ctx->style = style;
  6567. ctx->size = size;
  6568. ctx->line = 0;
  6569. return SSFN_OK;
  6570. }
  6571. int ssfn_render(ssfn_t *ctx, ssfn_buf_t *dst, const char *str)
  6572. {
  6573. ssfn_font_t **fl;
  6574. uint8_t *ptr = NULL, *frg, *end, *tmp, color, ci = 0, cb = 0, cs, dec[65536];
  6575. uint16_t r[640];
  6576. uint32_t unicode, P, O, *Op, *Ol, sR, sG, sB, sA, bA;
  6577. int ret = 0, i, j, k, l, p, m, n, o, s, x, y, w, h, H, a, A, b, B, nr, uix, uax;
  6578. int ox, oy, y0, y1, Y0, Y1, x0, x1, X0, X1, X2, xs, ys, yp, pc, fB, fG, fR, fA, bB, bG, bR, dB, dG, dR, dA;
  6579. #ifdef SSFN_PROFILING
  6580. struct timeval tv0, tv1, tvd;
  6581. gettimeofday(&tv0, NULL);
  6582. #endif
  6583. #define PUTPIXEL O = *Ol;bR = (O >> (16 - cs)) & 0xFF; bG = (O >> 8) & 0xFF; bB = (O >> cs) & 0xFF; bA = (O >> 24) & 0xFF;\
  6584. bB += ((fB - bB) * fA) >> 8; bG += ((fG - bG) * fA) >> 8; bR += ((fR - bR) * fA) >> 8; bA += ((fA - bA) * fA) >> 8;\
  6585. *Ol = (bA << 24) | (bR << (16 - cs)) | (bG << 8) | (bB << cs);
  6586. if(!ctx || !str) return SSFN_ERR_INVINP;
  6587. if(!*str) return 0;
  6588. if(*str == '\r') { dst->x = 0; return 1; }
  6589. if(*str == '\n') { dst->x = 0; dst->y += ctx->line ? ctx->line : ctx->size; return 1; }
  6590. if(ctx->s) {
  6591. ctx->f = ctx->s;
  6592. ptr = _ssfn_c(ctx->f, str, &ret, &unicode);
  6593. } else {
  6594. p = ctx->family;
  6595. ctx->f = NULL;
  6596. again: if(p >= SSFN_FAMILY_BYNAME) { n = 0; m = 4; } else n = m = p;
  6597. for(; n <= m; n++) {
  6598. fl = (ssfn_font_t **)ctx->fnt[n];
  6599. if(ctx->style & 3) {
  6600. for(i=0;i<ctx->len[n];i++)
  6601. if(((fl[i]->type>>4) & 3) == (ctx->style & 3) && fl[i]->height == ctx->size &&
  6602. (ptr = _ssfn_c(fl[i], str, &ret, &unicode))) { ctx->f = fl[i]; break; }
  6603. if(!ptr)
  6604. for(i=0;i<ctx->len[n];i++)
  6605. if(fl[i]->height == ctx->size && (ptr = _ssfn_c(fl[i], str, &ret, &unicode))) { ctx->f = fl[i]; break; }
  6606. if(!ptr)
  6607. for(i=0;i<ctx->len[n];i++)
  6608. if(((fl[i]->type>>4) & 3) == (ctx->style & 3) && (ptr = _ssfn_c(fl[i], str, &ret, &unicode)))
  6609. { ctx->f = fl[i]; break; }
  6610. if(!ptr && (ctx->style & 3) == 3)
  6611. for(i=0;i<ctx->len[n];i++)
  6612. if(((fl[i]->type>>4) & 3) && (ptr = _ssfn_c(fl[i], str, &ret, &unicode))) { ctx->f = fl[i]; break; }
  6613. }
  6614. if(!ptr) {
  6615. for(i=0;i<ctx->len[n];i++)
  6616. if((ptr = _ssfn_c(fl[i], str, &ret, &unicode))) { ctx->f = fl[i]; break; }
  6617. }
  6618. }
  6619. if(!ptr && p != SSFN_FAMILY_ANY) { p = SSFN_FAMILY_ANY; goto again; }
  6620. }
  6621. if(!ptr) {
  6622. if(ctx->style & SSFN_STYLE_NODEFGLYPH) return SSFN_ERR_NOGLYPH;
  6623. else {
  6624. unicode = 0;
  6625. if(ctx->family >= SSFN_FAMILY_BYNAME) { n = 0; m = 4; } else n = m = ctx->family;
  6626. for(; n <= m && !ptr; n++)
  6627. if(ctx->len[n] && ctx->fnt[n][0] && !(*((uint8_t*)ctx->fnt[n][0] + ctx->fnt[n][0]->characters_offs) & 0x80))
  6628. { ctx->f = ctx->fnt[n][0]; ptr = (uint8_t*)ctx->f + ctx->f->characters_offs; }
  6629. }
  6630. if(!ptr) return SSFN_ERR_NOGLYPH;
  6631. }
  6632. if(!ctx->f || !ctx->f->height || !ctx->size) return SSFN_ERR_NOFACE;
  6633. if((unicode >> 16) > 0x10) return SSFN_ERR_INVINP;
  6634. ctx->rc = (ssfn_chr_t*)ptr; ptr += sizeof(ssfn_chr_t);
  6635. H = (ctx->style & SSFN_STYLE_ABS_SIZE) || SSFN_TYPE_FAMILY(ctx->f->type) == SSFN_FAMILY_MONOSPACE || !ctx->f->baseline ?
  6636. ctx->size : ctx->size * ctx->f->height / ctx->f->baseline;
  6637. #ifdef SSFN_PROFILING
  6638. gettimeofday(&tv1, NULL); tvd.tv_sec = tv1.tv_sec - tv0.tv_sec; tvd.tv_usec = tv1.tv_usec - tv0.tv_usec;
  6639. if(tvd.tv_usec < 0) { tvd.tv_sec--; tvd.tv_usec += 1000000L; }
  6640. ctx->lookup += tvd.tv_sec * 1000000L + tvd.tv_usec;
  6641. memcpy(&tv0, &tv1, sizeof(struct timeval));
  6642. #endif
  6643. {
  6644. h = ctx->style & SSFN_STYLE_NOAA ? H : (ctx->size > ctx->f->height ? (ctx->size + 4) & ~3 : ctx->f->height);
  6645. ci = (ctx->style & SSFN_STYLE_ITALIC) && !(SSFN_TYPE_STYLE(ctx->f->type) & SSFN_STYLE_ITALIC);
  6646. cb = (ctx->style & SSFN_STYLE_BOLD) && !(SSFN_TYPE_STYLE(ctx->f->type) & SSFN_STYLE_BOLD) ? (ctx->f->height+64)>>6 : 0;
  6647. w = (ctx->rc->w * h + ctx->f->height - 1) / ctx->f->height;
  6648. if(w > SSFN_SIZE_MAX) { h = h * SSFN_SIZE_MAX / w; w = SSFN_SIZE_MAX; }
  6649. p = w + (ci ? h / SSFN_ITALIC_DIV : 0) + cb;
  6650. if(p * h >= SSFN_DATA_MAX) return SSFN_ERR_BADSIZE;
  6651. ctx->g = &ctx->ga;
  6652. x = (ctx->rc->x > 0 && ci ? (ctx->f->height - ctx->f->baseline) * h / SSFN_ITALIC_DIV / ctx->f->height : 0);
  6653. ctx->g->p = p;
  6654. ctx->g->h = h;
  6655. ctx->g->x = (ctx->rc->x + x > 255 ? 255 : ctx->rc->x + x);
  6656. ctx->g->y = ctx->rc->y;
  6657. ctx->g->o = (ctx->rc->t & 0x3F) + x;
  6658. SSFN_memset(&ctx->g->data, 0xFF, p * h);
  6659. color = 0xFE; ctx->g->a = ctx->g->d = 0;
  6660. for(n = 0; n < ctx->rc->n; n++) {
  6661. if(ptr[0] == 255 && ptr[1] == 255) { color = ptr[2]; ptr += ctx->rc->t & 0x40 ? 6 : 5; continue; }
  6662. x = ((ptr[0] + cb) << SSFN_PREC) * h / ctx->f->height; y = (ptr[1] << SSFN_PREC) * h / ctx->f->height;
  6663. if(ctx->rc->t & 0x40) { m = (ptr[5] << 24) | (ptr[4] << 16) | (ptr[3] << 8) | ptr[2]; ptr += 6; }
  6664. else { m = (ptr[4] << 16) | (ptr[3] << 8) | ptr[2]; ptr += 5; }
  6665. frg = (uint8_t*)ctx->f + m;
  6666. if(!(frg[0] & 0x80)) {
  6667. j = (frg[0] & 0x3F);
  6668. if(frg[0] & 0x40) { j <<= 8; j |= frg[1]; frg++; }
  6669. j++; frg++; tmp = frg; frg += (j+3)/4; ctx->np = 0;
  6670. for(i = 0; i < j; i++) {
  6671. k = (frg[0] << SSFN_PREC) * h / ctx->f->height + x; m = (frg[1] << SSFN_PREC) * h / ctx->f->height + y;
  6672. switch((tmp[i >> 2] >> ((i & 3) << 1)) & 3) {
  6673. case SSFN_CONTOUR_MOVE: ctx->mx = ctx->lx = k; ctx->my = ctx->ly = m; frg += 2; break;
  6674. case SSFN_CONTOUR_LINE: _ssfn_l(ctx, p << SSFN_PREC, h << SSFN_PREC, k, m); frg += 2; break;
  6675. case SSFN_CONTOUR_QUAD:
  6676. a = (frg[2] << SSFN_PREC) * h / ctx->f->height + x; A = (frg[3] << SSFN_PREC) * h / ctx->f->height + y;
  6677. _ssfn_b(ctx, p << SSFN_PREC,h << SSFN_PREC, ctx->lx,ctx->ly, ((a-ctx->lx)/2)+ctx->lx,
  6678. ((A-ctx->ly)/2)+ctx->ly, ((k-a)/2)+a,((A-m)/2)+m, k,m, 0);
  6679. frg += 4;
  6680. break;
  6681. case SSFN_CONTOUR_CUBIC:
  6682. a = (frg[2] << SSFN_PREC) * h / ctx->f->height + x; A = (frg[3] << SSFN_PREC) * h / ctx->f->height + y;
  6683. b = (frg[4] << SSFN_PREC) * h / ctx->f->height + x; B = (frg[5] << SSFN_PREC) * h / ctx->f->height + y;
  6684. _ssfn_b(ctx, p << SSFN_PREC,h << SSFN_PREC, ctx->lx,ctx->ly, a,A, b,B, k,m, 0);
  6685. frg += 6;
  6686. break;
  6687. }
  6688. }
  6689. if(ctx->mx != ctx->lx || ctx->my != ctx->ly) { ctx->p[ctx->np+0] = ctx->mx; ctx->p[ctx->np+1] = ctx->my; ctx->np += 2; }
  6690. if(ctx->np > 4) {
  6691. for(b = A = B = o = 0; b < h; b++, B += p) {
  6692. a = b << SSFN_PREC;
  6693. for(nr = 0, i = 0; i < ctx->np - 3; i += 2) {
  6694. if( (ctx->p[i+1] < a && ctx->p[i+3] >= a) ||
  6695. (ctx->p[i+3] < a && ctx->p[i+1] >= a)) {
  6696. if((ctx->p[i+1] >> SSFN_PREC) == (ctx->p[i+3] >> SSFN_PREC))
  6697. x = (((int)ctx->p[i]+(int)ctx->p[i+2])>>1);
  6698. else
  6699. x = ((int)ctx->p[i]) + ((a - (int)ctx->p[i+1])*
  6700. ((int)ctx->p[i+2] - (int)ctx->p[i])/
  6701. ((int)ctx->p[i+3] - (int)ctx->p[i+1]));
  6702. x >>= SSFN_PREC;
  6703. if(ci) x += (h - b) / SSFN_ITALIC_DIV;
  6704. if(cb && !o) {
  6705. if(ctx->g->data[B + x] != color) { o = -cb; A = cb; }
  6706. else { o = cb; A = -cb; }
  6707. }
  6708. for(k = 0; k < nr && x > r[k]; k++);
  6709. for(l = nr; l > k; l--) r[l] = r[l-1];
  6710. r[k] = x;
  6711. nr++;
  6712. }
  6713. }
  6714. if(nr > 1 && nr & 1) { r[nr - 2] = r[nr - 1]; nr--; }
  6715. if(nr) {
  6716. if(ctx->g->d < y + b) ctx->g->d = y + b;
  6717. for(i = 0; i < nr - 1; i += 2) {
  6718. l = r[i] + o; m = r[i + 1] + A;
  6719. if(l < 0) l = 0;
  6720. if(m > p) m = p;
  6721. if(i > 0 && l < r[i - 1] + A) l = r[i - 1] + A;
  6722. for(; l < m; l++)
  6723. ctx->g->data[B + l] = ctx->g->data[B + l] == color ? 0xFF : color;
  6724. }
  6725. }
  6726. }
  6727. }
  6728. } else if((frg[0] & 0x60) == 0x00) {
  6729. B = ((frg[0] & 0x1F) + 1) << 3; A = frg[1] + 1; x >>= SSFN_PREC; y >>= SSFN_PREC;
  6730. b = B * h / ctx->f->height; a = A * h / ctx->f->height;
  6731. if(ctx->g->d < y + a) ctx->g->d = y + a;
  6732. frg += 2;
  6733. for(j = 0; j < a; j++) {
  6734. k = j * A / a;
  6735. l = (y + j) * p + x + (ci ? (h - y - j) / SSFN_ITALIC_DIV : 0);
  6736. for(i = 0; i < b; i++) {
  6737. m = i * B / b;
  6738. if(frg[(k * B + m) >> 3] & (1 << (m & 7))) {
  6739. for(o = 0; o <= cb; o++)
  6740. ctx->g->data[l + i + o] = color;
  6741. }
  6742. }
  6743. }
  6744. if(!(ctx->style & (SSFN_STYLE_NOAA|SSFN_STYLE_NOSMOOTH))) {
  6745. m = color == 0xFD ? 0xFC : 0xFD; o = y * p + p + x;
  6746. for(k = h; k > ctx->f->height + 4; k -= 2*ctx->f->height) {
  6747. for(j = 1, l = o; j < a - 1; j++, l += p)
  6748. for(i = 1; i < b - 1; i++) {
  6749. if(ctx->g->data[l + i] == 0xFF && (ctx->g->data[l + i - p] == color ||
  6750. ctx->g->data[l + i + p] == color) && (ctx->g->data[l + i - 1] == color ||
  6751. ctx->g->data[l + i + 1] == color)) ctx->g->data[l + i] = m;
  6752. }
  6753. for(j = 1, l = o; j < a - 1; j++, l += p)
  6754. for(i = 1; i < b - 1; i++) {
  6755. if(ctx->g->data[l + i] == m) ctx->g->data[l + i] = color;
  6756. }
  6757. }
  6758. }
  6759. } else if((frg[0] & 0x60) == 0x20) {
  6760. k = (((frg[0] & 0x1F) << 8) | frg[1]) + 1; B = frg[2] + 1; A = frg[3] + 1; x >>= SSFN_PREC; y >>= SSFN_PREC;
  6761. b = B * h / ctx->f->height; a = A * h / ctx->f->height;
  6762. if(ctx->g->d < y + a) ctx->g->d = y + a;
  6763. frg += 4; end = frg + k; i = 0;
  6764. while(frg < end) {
  6765. l = ((*frg++) & 0x7F) + 1;
  6766. if(frg[-1] & 0x80) {
  6767. while(l--) dec[i++] = *frg;
  6768. frg++;
  6769. } else while(l--) dec[i++] = *frg++;
  6770. }
  6771. for(j = 0; j < a; j++) {
  6772. k = j * A / a * B;
  6773. l = (y + j) * p + x + (ci ? (h - y - j) / SSFN_ITALIC_DIV : 0);
  6774. for(i = 0; i < b; i++) {
  6775. m = dec[k + i * B / b];
  6776. if(m != 0xFF) ctx->g->data[l + i] = m;
  6777. }
  6778. }
  6779. }
  6780. color = 0xFE;
  6781. }
  6782. ctx->g->a = ctx->f->baseline;
  6783. if(ctx->g->d > ctx->g->a + 1) ctx->g->d -= ctx->g->a + 1; else ctx->g->d = 0;
  6784. #ifdef SSFN_DEBUGGLYPH
  6785. printf("\nU+%06X size %d p %d h %d base %d under %d overlap %d ascender %d descender %d advance x %d advance y %d cb %d\n",
  6786. unicode, ctx->size,p,h,ctx->f->baseline,ctx->f->underline,ctx->g->o,ctx->g->a,ctx->g->d,ctx->g->x,ctx->g->y,cb);
  6787. for(j = 0; j < h; j++) { printf("%3d: ", j); for(i = 0; i < p; i++) { if(ctx->g->data[j*p+i] == 0xFF) printf(j == ctx->g->a ? "_" : "."); else printf("%x", ctx->g->data[j*p+i] & 0xF); } printf("\n"); }
  6788. #endif
  6789. #ifdef SSFN_PROFILING
  6790. gettimeofday(&tv1, NULL); tvd.tv_sec = tv1.tv_sec - tv0.tv_sec; tvd.tv_usec = tv1.tv_usec - tv0.tv_usec;
  6791. if(tvd.tv_usec < 0) { tvd.tv_sec--; tvd.tv_usec += 1000000L; }
  6792. ctx->raster += tvd.tv_sec * 1000000L + tvd.tv_usec;
  6793. memcpy(&tv0, &tv1, sizeof(struct timeval));
  6794. #endif
  6795. }
  6796. if(dst) {
  6797. h = H;
  6798. if(h > ctx->line) ctx->line = h;
  6799. w = ctx->g->p * h / ctx->g->h;
  6800. s = ((ctx->g->x - ctx->g->o) * h + ctx->f->height - 1) / ctx->f->height;
  6801. n = ctx->size > 16 ? 2 : 1;
  6802. if(w < n) w = n;
  6803. if(s < n) s = n;
  6804. if(ctx->g->x) {
  6805. ctx->ox = ox = ((ctx->g->o * h + ctx->f->height - 1) / ctx->f->height) + (ctx->style & SSFN_STYLE_RTL ? w : 0);
  6806. ctx->oy = oy = (ctx->g->a * h + ctx->f->height - 1) / ctx->f->height;
  6807. } else { ctx->ox = ox = w / 2; ctx->oy = oy = 0; }
  6808. if(dst->ptr) {
  6809. j = dst->w < 0 ? -dst->w : dst->w;
  6810. cs = dst->w < 0 ? 16 : 0;
  6811. cb = (h + 64) >> 6; uix = w > s ? w : s; uax = 0;
  6812. n = (ctx->f->underline * h + ctx->f->height - 1) / ctx->f->height;
  6813. #ifdef SSFN_DEBUGGLYPH
  6814. printf("Scaling to w %d h %d (glyph %d %d, cache %d %d, font %d)\n",
  6815. w,h,ctx->rc->w,ctx->rc->h,ctx->g->p,ctx->g->h,ctx->f->height);
  6816. #endif
  6817. fR = (dst->fg >> 16) & 0xFF; fG = (dst->fg >> 8) & 0xFF; fB = (dst->fg >> 0) & 0xFF; fA = (dst->fg >> 24) & 0xFF;
  6818. bR = (dst->bg >> 16) & 0xFF; bG = (dst->bg >> 8) & 0xFF; bB = (dst->bg >> 0) & 0xFF; O = 0xFF000000;
  6819. Op = (uint32_t*)(dst->ptr + dst->p * (dst->y - oy) + ((dst->x - ox) << 2));
  6820. for (y = 0; y < h && dst->y + y - oy < dst->h; y++, Op += dst->p >> 2) {
  6821. if(dst->y + y - oy < 0) continue;
  6822. y0 = (y << 8) * ctx->g->h / h; Y0 = y0 >> 8; y1 = ((y + 1) << 8) * ctx->g->h / h; Y1 = y1 >> 8; Ol = Op;
  6823. for (x = 0; x < w && dst->x + x - ox < j; x++, Ol++) {
  6824. if(dst->x + x - ox < 0) continue;
  6825. m = 0; sR = sG = sB = sA = bA = 0;
  6826. if(!dst->bg) {
  6827. O = *Ol;
  6828. bA = (O >> 24) & 0xFF;
  6829. bR = (O >> (16 - cs)) & 0xFF;
  6830. bG = (O >> 8) & 0xFF;
  6831. bB = (O >> cs) & 0xFF;
  6832. }
  6833. x0 = (x << 8) * ctx->g->p / w; X0 = x0 >> 8; x1 = ((x + 1) << 8) * ctx->g->p / w; X1 = x1 >> 8;
  6834. for(ys = y0; ys < y1; ys += 256) {
  6835. if(ys >> 8 == Y0) { yp = 256 - (ys & 0xFF); ys &= ~0xFF; if(yp > y1 - y0) yp = y1 - y0; }
  6836. else if(ys >> 8 == Y1) yp = y1 & 0xFF; else yp = 256;
  6837. X2 = (ys >> 8) * ctx->g->p;
  6838. for(xs = x0; xs < x1; xs += 256) {
  6839. if (xs >> 8 == X0) {
  6840. k = 256 - (xs & 0xFF); xs &= ~0xFF; if(k > x1 - x0) k = x1 - x0; pc = k == 256 ? yp : (k * yp)>>8;
  6841. } else
  6842. if (xs >> 8 == X1) { k = x1 & 0xFF; pc = k == 256 ? yp : (k * yp) >> 8; }
  6843. else pc = yp;
  6844. m += pc;
  6845. k = ctx->g->data[X2 + (xs >> 8)];
  6846. if(k == 0xFF) {
  6847. sB += bB * pc; sG += bG * pc; sR += bR * pc; sA += 255;
  6848. } else {
  6849. if(k == 0xFE || !ctx->f->cmap_offs) {
  6850. dB = fB; dG = fG; dR = fR; dA = fA;
  6851. } else {
  6852. P = *((uint32_t*)((uint8_t*)ctx->f + ctx->f->cmap_offs + (k << 2)));
  6853. dR = (P >> 16) & 0xFF; dG = (P >> 8) & 0xFF; dB = (P >> 0) & 0xFF; dA = (P >> 24) & 0xFF;
  6854. }
  6855. if(dA == 255) {
  6856. sB += dB * pc; sG += dG * pc; sR += dR * pc; sA += dA * pc;
  6857. } else {
  6858. sB += (dB * dA + bB * (255 - dA)) * pc / 255; sG += (dG * dA + bG * (255 - dA)) * pc / 255;
  6859. sR += (dR * dA + bR * (255 - dA)) * pc / 255; sA += dA * pc;
  6860. }
  6861. }
  6862. }
  6863. }
  6864. if(m) { sR /= m; sG /= m; sB /= m; sA /= m; } else { sR >>= 8; sG >>= 8; sB >>= 8; sA >>= 8; }
  6865. if(ctx->style & SSFN_STYLE_NOAA) sA = sA > 127 ? 255 : 0;
  6866. if(sA > 15) {
  6867. *Ol = ((sA > 255 ? 255 : (sA > bA ? sA : bA)) << 24) |
  6868. ((sR > 255 ? 255 : sR) << (16 - cs)) | ((sG > 255 ? 255 : sG) << 8) | ((sB > 255 ? 255 : sB) << cs);
  6869. if(y == n) { if(uix > x) { uix = x; } if(uax < x) { uax = x; } }
  6870. }
  6871. }
  6872. }
  6873. if(ctx->style & SSFN_STYLE_UNDERLINE) {
  6874. uix -= cb + 1; uax += cb + 2;
  6875. if(uax < uix) uax = uix + 1;
  6876. k = (w > s ? w : s);
  6877. Op = (uint32_t*)(dst->ptr + dst->p * (dst->y - oy + n) + ((dst->x - ox - 1) << 2));
  6878. for (y = n; y < n + cb && dst->y + y - oy < dst->h; y++, Op += dst->p >> 2) {
  6879. if(dst->y + y - oy < 0) continue;
  6880. for (Ol = Op, x = 0; x <= k && dst->x + x - ox < j; x++, Ol++) {
  6881. if(dst->x + x - ox < 0 || (x > uix && x < uax)) continue;
  6882. PUTPIXEL;
  6883. }
  6884. }
  6885. }
  6886. if(ctx->style & SSFN_STYLE_STHROUGH) {
  6887. n = (h >> 1); k = (w > s ? w : s) + 1;
  6888. Op = (uint32_t*)(dst->ptr + dst->p * (dst->y - oy + n) + ((dst->x - ox - 1) << 2));
  6889. for (y = n; y < n + cb && dst->y + y - oy < dst->h; y++, Op += dst->p >> 2) {
  6890. if(dst->y + y - oy < 0) continue;
  6891. for (Ol = Op, x = 0; x <= k && dst->x + x - ox < j; x++, Ol++) {
  6892. if(dst->x + x - ox < 0) continue;
  6893. PUTPIXEL;
  6894. }
  6895. }
  6896. }
  6897. #ifdef SSFN_PROFILING
  6898. gettimeofday(&tv1, NULL); tvd.tv_sec = tv1.tv_sec - tv0.tv_sec;tvd.tv_usec = tv1.tv_usec - tv0.tv_usec;
  6899. if(tvd.tv_usec < 0) { tvd.tv_sec--; tvd.tv_usec += 1000000L; }
  6900. ctx->blit += tvd.tv_sec * 1000000L + tvd.tv_usec;
  6901. memcpy(&tv0, &tv1, sizeof(struct timeval));
  6902. #endif
  6903. }
  6904. ctx->ax = (ctx->style & SSFN_STYLE_RTL ? -s : s);
  6905. dst->x += ctx->ax;
  6906. dst->y += (ctx->g->y * h + ctx->f->height - 1) / ctx->f->height;
  6907. ptr = (uint8_t*)str + ret;
  6908. if(!(ctx->style & SSFN_STYLE_NOKERN) && ctx->f->kerning_offs && _ssfn_c(ctx->f, (const char*)ptr, &i, &P) && P > 32) {
  6909. ptr = (uint8_t*)ctx->rc + sizeof(ssfn_chr_t);
  6910. for(n = 0; n < ctx->rc->n; n++) {
  6911. if(ptr[0] == 255 && ptr[1] == 255) { ptr += ctx->rc->t & 0x40 ? 6 : 5; continue; }
  6912. x = ptr[0];
  6913. if(ctx->rc->t & 0x40) { m = (ptr[5] << 24) | (ptr[4] << 16) | (ptr[3] << 8) | ptr[2]; ptr += 6; }
  6914. else { m = (ptr[4] << 16) | (ptr[3] << 8) | ptr[2]; ptr += 5; }
  6915. frg = (uint8_t*)ctx->f + m;
  6916. if((frg[0] & 0xE0) == 0xC0) {
  6917. k = (((frg[0] & 0x1F) << 8) | frg[1]) + 1; frg += 2;
  6918. while(k--) {
  6919. m = ((frg[2] & 0xF) << 16) | (frg[1] << 8) | frg[0];
  6920. if(P >= (uint32_t)m && P <= (uint32_t)(((frg[5] & 0xF) << 16) | (frg[4] << 8) | frg[3])) {
  6921. P -= m;
  6922. m = ctx->f->kerning_offs + ((((frg[2] >> 4) & 0xF) << 24) | (((frg[5] >> 4) & 0xF) << 16) |
  6923. (frg[7] << 8) | frg[6]);
  6924. tmp = (uint8_t*)ctx->f + m;
  6925. while(tmp < (uint8_t*)ctx->f + ctx->f->size - 4) {
  6926. if((tmp[0] & 0x7F) < P) {
  6927. P -= (tmp[0] & 0x7F) + 1;
  6928. tmp += 2 + (tmp[0] & 0x80 ? 0 : tmp[0] & 0x7F);
  6929. } else {
  6930. y = (int)((signed char)tmp[1 + ((tmp[0] & 0x80) ? 0 : P)]) * h / ctx->f->height;
  6931. if(x) dst->x += y; else dst->y += y;
  6932. break;
  6933. }
  6934. }
  6935. break;
  6936. }
  6937. frg += 8;
  6938. }
  6939. }
  6940. }
  6941. #ifdef SSFN_PROFILING
  6942. gettimeofday(&tv1, NULL); tvd.tv_sec = tv1.tv_sec - tv0.tv_sec; tvd.tv_usec = tv1.tv_usec - tv0.tv_usec;
  6943. if(tvd.tv_usec < 0) { tvd.tv_sec--; tvd.tv_usec += 1000000L; }
  6944. ctx->kern += tvd.tv_sec * 1000000L + tvd.tv_usec;
  6945. #endif
  6946. }
  6947. }
  6948. return ret;
  6949. }
  6950. int ssfn_bbox(ssfn_t *ctx, const char *str, int *w, int *h, int *left, int *top)
  6951. {
  6952. ssfn_buf_t buf;
  6953. int ret, f = 1, l = 0, t = 0;
  6954. if(!ctx || !str) return SSFN_ERR_INVINP;
  6955. if(w) {*w = 0;} if(h) {*h = 0;} if(top) {*top = 0;} if(left) {*left = 0;}
  6956. if(!*str) return SSFN_OK;
  6957. SSFN_memset(&buf, 0, sizeof(ssfn_buf_t)); ctx->line = 0;
  6958. while((ret = ssfn_render(ctx, &buf, str))) {
  6959. if(ret < 0 || !ctx->g) return ret;
  6960. if(f) { f = 0; l = ctx->ox; buf.x += l; }
  6961. if(ctx->g->x) {
  6962. if(ctx->oy > t) t = ctx->oy;
  6963. } else {
  6964. if(buf.w < ctx->g->p) buf.w = ctx->g->p;
  6965. buf.h += ctx->g->y ? ctx->g->y : ctx->g->h;
  6966. }
  6967. str += ret;
  6968. }
  6969. if((ctx->style & SSFN_STYLE_ITALIC) && !(SSFN_TYPE_STYLE(ctx->f->type) & SSFN_STYLE_ITALIC))
  6970. buf.x += ctx->size / SSFN_ITALIC_DIV - l;
  6971. if(ctx->g->x) { if(w) {*w = buf.x;} if(h) {*h = ctx->line;} if(left) {*left = l;} if(top) {*top = t;} }
  6972. else { if(w) {*w = buf.w;} if(h) {*h = buf.y;} if(top) {*top = 0;} if(left) {*left = 0;} }
  6973. return SSFN_OK;
  6974. }
  6975. ssfn_buf_t *ssfn_text(ssfn_t *ctx, const char *str, unsigned int fg)
  6976. {
  6977. (void)ctx;
  6978. (void)str;
  6979. (void)fg;
  6980. return NULL;
  6981. }
  6982. #endif
  6983. #if defined(SSFN_CONSOLEBITMAP_PALETTE) || defined(SSFN_CONSOLEBITMAP_HICOLOR) || defined(SSFN_CONSOLEBITMAP_TRUECOLOR)
  6984. ssfn_font_t *ssfn_src;
  6985. ssfn_buf_t ssfn_dst;
  6986. int ssfn_putc(uint32_t unicode)
  6987. {
  6988. # ifdef SSFN_CONSOLEBITMAP_PALETTE
  6989. # define SSFN_PIXEL uint8_t
  6990. # else
  6991. # ifdef SSFN_CONSOLEBITMAP_HICOLOR
  6992. # define SSFN_PIXEL uint16_t
  6993. # else
  6994. # define SSFN_PIXEL uint32_t
  6995. # endif
  6996. # endif
  6997. register SSFN_PIXEL *o, *p;
  6998. register uint8_t *ptr, *chr = NULL, *frg;
  6999. register int i, j, k, l, m, y = 0, w, s = ssfn_dst.p / sizeof(SSFN_PIXEL);
  7000. if(!ssfn_src || ssfn_src->magic[0] != 'S' || ssfn_src->magic[1] != 'F' || ssfn_src->magic[2] != 'N' ||
  7001. ssfn_src->magic[3] != '2' || !ssfn_dst.ptr || !ssfn_dst.p) return SSFN_ERR_INVINP;
  7002. w = ssfn_dst.w < 0 ? -ssfn_dst.w : ssfn_dst.w;
  7003. for(ptr = (uint8_t*)ssfn_src + ssfn_src->characters_offs, i = 0; i < 0x110000; i++) {
  7004. if(ptr[0] == 0xFF) { i += 65535; ptr++; }
  7005. else if((ptr[0] & 0xC0) == 0xC0) { j = (((ptr[0] & 0x3F) << 8) | ptr[1]); i += j; ptr += 2; }
  7006. else if((ptr[0] & 0xC0) == 0x80) { j = (ptr[0] & 0x3F); i += j; ptr++; }
  7007. else { if((uint32_t)i == unicode) { chr = ptr; break; } ptr += 6 + ptr[1] * (ptr[0] & 0x40 ? 6 : 5); }
  7008. }
  7009. #ifdef SSFN_CONSOLEBITMAP_CONTROL
  7010. i = ssfn_src->height; j = ssfn_dst.h - i - (ssfn_dst.h % i);
  7011. if(chr && w) {
  7012. if(unicode == '\t') ssfn_dst.x -= ssfn_dst.x % chr[4];
  7013. if(ssfn_dst.x + chr[4] > w) { ssfn_dst.x = 0; ssfn_dst.y += i; }
  7014. }
  7015. if(unicode == '\n') ssfn_dst.y += i;
  7016. if(j > 0 && ssfn_dst.y > j) {
  7017. ssfn_dst.y = j;
  7018. for(k = 0; k < j; k++)
  7019. for(l = 0; l < ssfn_dst.p; l++) ssfn_dst.ptr[k * ssfn_dst.p + l] = ssfn_dst.ptr[(k + i) * ssfn_dst.p + l];
  7020. }
  7021. if(unicode == '\r' || unicode == '\n') { ssfn_dst.x = 0; return SSFN_OK; }
  7022. #endif
  7023. if(!chr) return SSFN_ERR_NOGLYPH;
  7024. ptr = chr + 6; o = (SSFN_PIXEL*)(ssfn_dst.ptr + ssfn_dst.y * ssfn_dst.p + ssfn_dst.x * sizeof(SSFN_PIXEL));
  7025. for(i = 0; i < chr[1]; i++, ptr += chr[0] & 0x40 ? 6 : 5) {
  7026. if(ptr[0] == 255 && ptr[1] == 255) continue;
  7027. frg = (uint8_t*)ssfn_src + (chr[0] & 0x40 ? ((ptr[5] << 24) | (ptr[4] << 16) | (ptr[3] << 8) | ptr[2]) :
  7028. ((ptr[4] << 16) | (ptr[3] << 8) | ptr[2]));
  7029. if((frg[0] & 0xE0) != 0x80) continue;
  7030. if(ssfn_dst.bg) {
  7031. for(; y < ptr[1] && (!ssfn_dst.h || ssfn_dst.y + y < ssfn_dst.h); y++, o += s) {
  7032. for(p = o, j = 0; j < chr[2] && (!w || ssfn_dst.x + j < w); j++, p++)
  7033. *p = ssfn_dst.bg;
  7034. }
  7035. } else { o += (int)(ptr[1] - y) * s; y = ptr[1]; }
  7036. k = ((frg[0] & 0x1F) + 1) << 3; j = frg[1] + 1; frg += 2;
  7037. for(m = 1; j && (!ssfn_dst.h || ssfn_dst.y + y < ssfn_dst.h); j--, y++, o += s)
  7038. for(p = o, l = 0; l < k; l++, p++, m <<= 1) {
  7039. if(m > 0x80) { frg++; m = 1; }
  7040. if(ssfn_dst.x + l >= 0 && (!w || ssfn_dst.x + l < w)) {
  7041. if(*frg & m) *p = ssfn_dst.fg; else
  7042. if(ssfn_dst.bg) *p = ssfn_dst.bg;
  7043. }
  7044. }
  7045. }
  7046. if(ssfn_dst.bg)
  7047. for(; y < chr[3] && (!ssfn_dst.h || ssfn_dst.y + y < ssfn_dst.h); y++, o += s) {
  7048. for(p = o, j = 0; j < chr[2] && (!w || ssfn_dst.x + j < w); j++, p++)
  7049. *p = ssfn_dst.bg;
  7050. }
  7051. ssfn_dst.x += chr[4]; ssfn_dst.y += chr[5];
  7052. return SSFN_OK;
  7053. }
  7054. #endif
  7055. #endif
  7056. #if !defined(M3D_HEADERONLY) && !defined(M3D_IMPLEMENTATION)
  7057. #define M3D_IMPLEMENTATION
  7058. #define M3D_NOTEXTURE
  7059. #endif
  7060. #endif /* APCK_IMPLEMENTATION */
  7061. /* m3d.h - Model3D - MIT license
  7062. https://bztsrc.gitlab.com/model3d */
  7063. /**************** embeded m3d.h ****************/
  7064. #ifndef _M3D_H_
  7065. #define _M3D_H_
  7066. #include <stdint.h>
  7067. #ifndef M3D_MALLOC
  7068. # define M3D_MALLOC(sz) malloc(sz)
  7069. #endif
  7070. #ifndef M3D_REALLOC
  7071. # define M3D_REALLOC(p,nsz) realloc(p,nsz)
  7072. #endif
  7073. #ifndef M3D_FREE
  7074. # define M3D_FREE(p) free(p)
  7075. #endif
  7076. #ifndef M3D_LOG
  7077. # define M3D_LOG(x)
  7078. #endif
  7079. #ifndef M3D_APIVERSION
  7080. #define M3D_APIVERSION 0x0100
  7081. #ifndef M3D_DOUBLE
  7082. typedef float M3D_FLOAT;
  7083. #ifndef M3D_EPSILON
  7084. #define M3D_EPSILON ((M3D_FLOAT)1e-7)
  7085. #endif
  7086. #else
  7087. typedef double M3D_FLOAT;
  7088. #ifndef M3D_EPSILON
  7089. #define M3D_EPSILON ((M3D_FLOAT)1e-14)
  7090. #endif
  7091. #endif
  7092. #if !defined(M3D_SMALLINDEX)
  7093. typedef uint32_t M3D_INDEX;
  7094. typedef uint16_t M3D_VOXEL;
  7095. #define M3D_UNDEF 0xffffffff
  7096. #define M3D_INDEXMAX 0xfffffffe
  7097. #define M3D_VOXUNDEF 0xffff
  7098. #define M3D_VOXCLEAR 0xfffe
  7099. #else
  7100. typedef uint16_t M3D_INDEX;
  7101. typedef uint8_t M3D_VOXEL;
  7102. #define M3D_UNDEF 0xffff
  7103. #define M3D_INDEXMAX 0xfffe
  7104. #define M3D_VOXUNDEF 0xff
  7105. #define M3D_VOXCLEAR 0xfe
  7106. #endif
  7107. #define M3D_NOTDEFINED 0xffffffff
  7108. #ifndef M3D_NUMBONE
  7109. #define M3D_NUMBONE 4
  7110. #endif
  7111. #ifndef M3D_BONEMAXLEVEL
  7112. #define M3D_BONEMAXLEVEL 64
  7113. #endif
  7114. #ifndef _MSC_VER
  7115. #ifndef _inline
  7116. #define _inline __inline__
  7117. #endif
  7118. #define _pack __attribute__((packed))
  7119. #define _unused __attribute__((unused))
  7120. #else
  7121. #define _inline
  7122. #define _pack
  7123. #define _unused __pragma(warning(suppress:4100))
  7124. #endif
  7125. #ifndef __cplusplus
  7126. #define _register register
  7127. #else
  7128. #define _register
  7129. #endif
  7130. #ifdef _MSC_VER
  7131. #pragma pack(push)
  7132. #pragma pack(1)
  7133. #endif
  7134. typedef struct {
  7135. char magic[4];
  7136. uint32_t length;
  7137. float scale;
  7138. uint32_t types;
  7139. } _pack m3dhdr_t;
  7140. typedef struct {
  7141. char magic[4];
  7142. uint32_t length;
  7143. } _pack m3dchunk_t;
  7144. #ifdef _MSC_VER
  7145. #pragma pack(pop)
  7146. #endif
  7147. typedef struct {
  7148. M3D_FLOAT u;
  7149. M3D_FLOAT v;
  7150. } m3dti_t;
  7151. #define m3d_textureindex_t m3dti_t
  7152. typedef struct {
  7153. char *name;
  7154. uint8_t *d;
  7155. uint16_t w;
  7156. uint16_t h;
  7157. uint8_t f;
  7158. } m3dtx_t;
  7159. #define m3d_texturedata_t m3dtx_t
  7160. typedef struct {
  7161. M3D_INDEX vertexid;
  7162. M3D_FLOAT weight;
  7163. } m3dw_t;
  7164. #define m3d_weight_t m3dw_t
  7165. typedef struct {
  7166. M3D_INDEX parent;
  7167. char *name;
  7168. M3D_INDEX pos;
  7169. M3D_INDEX ori;
  7170. M3D_INDEX numweight;
  7171. m3dw_t *weight;
  7172. M3D_FLOAT mat4[16];
  7173. } m3db_t;
  7174. #define m3d_bone_t m3db_t
  7175. typedef struct {
  7176. M3D_INDEX boneid[M3D_NUMBONE];
  7177. M3D_FLOAT weight[M3D_NUMBONE];
  7178. } m3ds_t;
  7179. #define m3d_skin_t m3ds_t
  7180. typedef struct {
  7181. M3D_FLOAT x;
  7182. M3D_FLOAT y;
  7183. M3D_FLOAT z;
  7184. M3D_FLOAT w;
  7185. uint32_t color;
  7186. M3D_INDEX skinid;
  7187. #ifdef M3D_VERTEXTYPE
  7188. uint8_t type;
  7189. #endif
  7190. } m3dv_t;
  7191. #define m3d_vertex_t m3dv_t
  7192. enum {
  7193. m3dpf_color,
  7194. m3dpf_uint8,
  7195. m3dpf_uint16,
  7196. m3dpf_uint32,
  7197. m3dpf_float,
  7198. m3dpf_map
  7199. };
  7200. typedef struct {
  7201. uint8_t format;
  7202. uint8_t id;
  7203. #ifndef M3D_ASCII
  7204. #define M3D_PROPERTYDEF(f,i,n) { (f), (i) }
  7205. #endif
  7206. } m3dpd_t;
  7207. enum {
  7208. m3dp_Kd = 0,
  7209. m3dp_Ka,
  7210. m3dp_Ks,
  7211. m3dp_Ns,
  7212. m3dp_Ke,
  7213. m3dp_Tf,
  7214. m3dp_Km,
  7215. m3dp_d,
  7216. m3dp_il,
  7217. m3dp_Pr = 64,
  7218. m3dp_Pm,
  7219. m3dp_Ps,
  7220. m3dp_Ni,
  7221. m3dp_Nt,
  7222. m3dp_map_Kd = 128,
  7223. m3dp_map_Ka,
  7224. m3dp_map_Ks,
  7225. m3dp_map_Ns,
  7226. m3dp_map_Ke,
  7227. m3dp_map_Tf,
  7228. m3dp_map_Km,
  7229. m3dp_map_D,
  7230. m3dp_map_N,
  7231. m3dp_map_Pr = 192,
  7232. m3dp_map_Pm,
  7233. m3dp_map_Ps,
  7234. m3dp_map_Ni,
  7235. m3dp_map_Nt
  7236. };
  7237. enum {
  7238. m3dp_bump = m3dp_map_Km,
  7239. m3dp_map_il = m3dp_map_N,
  7240. m3dp_refl = m3dp_map_Pm
  7241. };
  7242. typedef struct {
  7243. uint8_t type;
  7244. union {
  7245. uint32_t color;
  7246. uint32_t num;
  7247. float fnum;
  7248. M3D_INDEX textureid;
  7249. } value;
  7250. } m3dp_t;
  7251. #define m3d_property_t m3dp_t
  7252. typedef struct {
  7253. char *name;
  7254. uint8_t numprop;
  7255. m3dp_t *prop;
  7256. } m3dm_t;
  7257. #define m3d_material_t m3dm_t
  7258. typedef struct {
  7259. M3D_INDEX materialid;
  7260. M3D_INDEX vertex[3];
  7261. M3D_INDEX normal[3];
  7262. M3D_INDEX texcoord[3];
  7263. #ifdef M3D_VERTEXMAX
  7264. M3D_INDEX paramid;
  7265. M3D_INDEX vertmax[3];
  7266. #endif
  7267. } m3df_t;
  7268. #define m3d_face_t m3df_t
  7269. typedef struct {
  7270. uint16_t count;
  7271. char *name;
  7272. } m3dvi_t;
  7273. #define m3d_voxelitem_t m3dvi_t
  7274. #define m3d_parameter_t m3dvi_t
  7275. typedef struct {
  7276. char *name;
  7277. uint8_t rotation;
  7278. uint16_t voxshape;
  7279. M3D_INDEX materialid;
  7280. uint32_t color;
  7281. M3D_INDEX skinid;
  7282. uint8_t numitem;
  7283. m3dvi_t *item;
  7284. } m3dvt_t;
  7285. #define m3d_voxeltype_t m3dvt_t
  7286. typedef struct {
  7287. char *name;
  7288. int32_t x, y, z;
  7289. uint32_t w, h, d;
  7290. uint8_t uncertain;
  7291. uint8_t groupid;
  7292. M3D_VOXEL *data;
  7293. } m3dvx_t;
  7294. #define m3d_voxel_t m3dvx_t
  7295. enum {
  7296. m3dc_use = 0,
  7297. m3dc_inc,
  7298. m3dc_mesh,
  7299. m3dc_div,
  7300. m3dc_sub,
  7301. m3dc_len,
  7302. m3dc_dist,
  7303. m3dc_degu,
  7304. m3dc_deg,
  7305. m3dc_rangeu,
  7306. m3dc_range,
  7307. m3dc_paru,
  7308. m3dc_parv,
  7309. m3dc_trim,
  7310. m3dc_hole,
  7311. m3dc_scrv,
  7312. m3dc_sp,
  7313. m3dc_bez1,
  7314. m3dc_bsp1,
  7315. m3dc_bez2,
  7316. m3dc_bsp2,
  7317. m3dc_bezun,
  7318. m3dc_bezu,
  7319. m3dc_bezn,
  7320. m3dc_bez,
  7321. m3dc_nurbsun,
  7322. m3dc_nurbsu,
  7323. m3dc_nurbsn,
  7324. m3dc_nurbs,
  7325. m3dc_conn,
  7326. m3dc_line,
  7327. m3dc_polygon,
  7328. m3dc_circle,
  7329. m3dc_cylinder,
  7330. m3dc_shpere,
  7331. m3dc_torus,
  7332. m3dc_cone,
  7333. m3dc_cube
  7334. };
  7335. enum {
  7336. m3dcp_mi_t = 1,
  7337. m3dcp_hi_t,
  7338. m3dcp_fi_t,
  7339. m3dcp_ti_t,
  7340. m3dcp_vi_t,
  7341. m3dcp_qi_t,
  7342. m3dcp_vc_t,
  7343. m3dcp_i1_t,
  7344. m3dcp_i2_t,
  7345. m3dcp_i4_t,
  7346. m3dcp_va_t
  7347. };
  7348. #define M3D_CMDMAXARG 8
  7349. typedef struct {
  7350. #ifndef M3D_ASCII
  7351. #define M3D_CMDDEF(t,n,p,a,b,c,d,e,f,g,h) { (p), { (a), (b), (c), (d), (e), (f), (g), (h) } }
  7352. #endif
  7353. uint8_t p;
  7354. uint8_t a[M3D_CMDMAXARG];
  7355. } m3dcd_t;
  7356. typedef struct {
  7357. uint16_t type;
  7358. uint32_t *arg;
  7359. } m3dc_t;
  7360. #define m3d_shapecommand_t m3dc_t
  7361. typedef struct {
  7362. char *name;
  7363. M3D_INDEX group;
  7364. uint32_t numcmd;
  7365. m3dc_t *cmd;
  7366. } m3dh_t;
  7367. #define m3d_shape_t m3dh_t
  7368. typedef struct {
  7369. char *name;
  7370. char *lang;
  7371. char *text;
  7372. uint32_t color;
  7373. M3D_INDEX vertexid;
  7374. } m3dl_t;
  7375. #define m3d_label_t m3dl_t
  7376. typedef struct {
  7377. M3D_INDEX boneid;
  7378. M3D_INDEX pos;
  7379. M3D_INDEX ori;
  7380. } m3dtr_t;
  7381. #define m3d_transform_t m3dtr_t
  7382. typedef struct {
  7383. uint32_t msec;
  7384. M3D_INDEX numtransform;
  7385. m3dtr_t *transform;
  7386. } m3dfr_t;
  7387. #define m3d_frame_t m3dfr_t
  7388. typedef struct {
  7389. char *name;
  7390. uint32_t durationmsec;
  7391. M3D_INDEX numframe;
  7392. m3dfr_t *frame;
  7393. } m3da_t;
  7394. #define m3d_action_t m3da_t
  7395. typedef struct {
  7396. char *name;
  7397. uint8_t *data;
  7398. uint32_t length;
  7399. } m3di_t;
  7400. #define m3d_inlinedasset_t m3di_t
  7401. #define M3D_FLG_FREERAW (1<<0)
  7402. #define M3D_FLG_FREESTR (1<<1)
  7403. #define M3D_FLG_MTLLIB (1<<2)
  7404. #define M3D_FLG_GENNORM (1<<3)
  7405. typedef struct {
  7406. m3dhdr_t *raw;
  7407. char flags;
  7408. signed char errcode;
  7409. char vc_s, vi_s, si_s, ci_s, ti_s, bi_s, nb_s, sk_s, fc_s, hi_s, fi_s, vd_s, vp_s;
  7410. char *name;
  7411. char *license;
  7412. char *author;
  7413. char *desc;
  7414. M3D_FLOAT scale;
  7415. M3D_INDEX numcmap;
  7416. uint32_t *cmap;
  7417. M3D_INDEX numtmap;
  7418. m3dti_t *tmap;
  7419. M3D_INDEX numtexture;
  7420. m3dtx_t *texture;
  7421. M3D_INDEX numbone;
  7422. m3db_t *bone;
  7423. M3D_INDEX numvertex;
  7424. m3dv_t *vertex;
  7425. M3D_INDEX numskin;
  7426. m3ds_t *skin;
  7427. M3D_INDEX nummaterial;
  7428. m3dm_t *material;
  7429. #ifdef M3D_VERTEXMAX
  7430. M3D_INDEX numparam;
  7431. m3dvi_t *param;
  7432. #endif
  7433. M3D_INDEX numface;
  7434. m3df_t *face;
  7435. M3D_INDEX numvoxtype;
  7436. m3dvt_t *voxtype;
  7437. M3D_INDEX numvoxel;
  7438. m3dvx_t *voxel;
  7439. M3D_INDEX numshape;
  7440. m3dh_t *shape;
  7441. M3D_INDEX numlabel;
  7442. m3dl_t *label;
  7443. M3D_INDEX numaction;
  7444. m3da_t *action;
  7445. M3D_INDEX numinlined;
  7446. m3di_t *inlined;
  7447. M3D_INDEX numextra;
  7448. m3dchunk_t **extra;
  7449. m3di_t preview;
  7450. } m3d_t;
  7451. #define M3D_EXP_INT8 0
  7452. #define M3D_EXP_INT16 1
  7453. #define M3D_EXP_FLOAT 2
  7454. #define M3D_EXP_DOUBLE 3
  7455. #define M3D_EXP_NOCMAP (1<<0)
  7456. #define M3D_EXP_NOMATERIAL (1<<1)
  7457. #define M3D_EXP_NOFACE (1<<2)
  7458. #define M3D_EXP_NONORMAL (1<<3)
  7459. #define M3D_EXP_NOTXTCRD (1<<4)
  7460. #define M3D_EXP_FLIPTXTCRD (1<<5)
  7461. #define M3D_EXP_NORECALC (1<<6)
  7462. #define M3D_EXP_IDOSUCK (1<<7)
  7463. #define M3D_EXP_NOBONE (1<<8)
  7464. #define M3D_EXP_NOACTION (1<<9)
  7465. #define M3D_EXP_INLINE (1<<10)
  7466. #define M3D_EXP_EXTRA (1<<11)
  7467. #define M3D_EXP_NOZLIB (1<<14)
  7468. #define M3D_EXP_ASCII (1<<15)
  7469. #define M3D_EXP_NOVRTMAX (1<<16)
  7470. #define M3D_SUCCESS 0
  7471. #define M3D_ERR_ALLOC -1
  7472. #define M3D_ERR_BADFILE -2
  7473. #define M3D_ERR_UNIMPL -65
  7474. #define M3D_ERR_UNKPROP -66
  7475. #define M3D_ERR_UNKMESH -67
  7476. #define M3D_ERR_UNKIMG -68
  7477. #define M3D_ERR_UNKFRAME -69
  7478. #define M3D_ERR_UNKCMD -70
  7479. #define M3D_ERR_UNKVOX -71
  7480. #define M3D_ERR_TRUNC -72
  7481. #define M3D_ERR_CMAP -73
  7482. #define M3D_ERR_TMAP -74
  7483. #define M3D_ERR_VRTS -75
  7484. #define M3D_ERR_BONE -76
  7485. #define M3D_ERR_MTRL -77
  7486. #define M3D_ERR_SHPE -78
  7487. #define M3D_ERR_VOXT -79
  7488. #define M3D_ERR_ISFATAL(x) ((x) < 0 && (x) > -65)
  7489. typedef unsigned char *(*m3dread_t)(char *filename, unsigned int *size);
  7490. typedef void (*m3dfree_t)(void *buffer);
  7491. typedef int (*m3dtxsc_t)(const char *name, const void *script, uint32_t len, m3dtx_t *output);
  7492. typedef int (*m3dprsc_t)(const char *name, const void *script, uint32_t len, m3d_t *model);
  7493. #endif
  7494. m3d_t *m3d_load(unsigned char *data, m3dread_t readfilecb, m3dfree_t freecb, m3d_t *mtllib);
  7495. unsigned char *m3d_save(m3d_t *model, int quality, int flags, unsigned int *size);
  7496. void m3d_free(m3d_t *model);
  7497. m3dtr_t *m3d_frame(m3d_t *model, M3D_INDEX actionid, M3D_INDEX frameid, m3dtr_t *skeleton);
  7498. m3db_t *m3d_pose(m3d_t *model, M3D_INDEX actionid, uint32_t msec);
  7499. char *_m3d_safestr(char *in, int morelines);
  7500. #ifdef M3D_IMPLEMENTATION
  7501. #if !defined(M3D_NOIMPORTER) || defined(M3D_EXPORTER)
  7502. static m3dpd_t m3d_propertytypes[] = {
  7503. M3D_PROPERTYDEF(m3dpf_color, m3dp_Kd, "Kd"),
  7504. M3D_PROPERTYDEF(m3dpf_color, m3dp_Ka, "Ka"),
  7505. M3D_PROPERTYDEF(m3dpf_color, m3dp_Ks, "Ks"),
  7506. M3D_PROPERTYDEF(m3dpf_float, m3dp_Ns, "Ns"),
  7507. M3D_PROPERTYDEF(m3dpf_color, m3dp_Ke, "Ke"),
  7508. M3D_PROPERTYDEF(m3dpf_color, m3dp_Tf, "Tf"),
  7509. M3D_PROPERTYDEF(m3dpf_float, m3dp_Km, "Km"),
  7510. M3D_PROPERTYDEF(m3dpf_float, m3dp_d, "d"),
  7511. M3D_PROPERTYDEF(m3dpf_uint8, m3dp_il, "il"),
  7512. M3D_PROPERTYDEF(m3dpf_float, m3dp_Pr, "Pr"),
  7513. M3D_PROPERTYDEF(m3dpf_float, m3dp_Pm, "Pm"),
  7514. M3D_PROPERTYDEF(m3dpf_float, m3dp_Ps, "Ps"),
  7515. M3D_PROPERTYDEF(m3dpf_float, m3dp_Ni, "Ni"),
  7516. M3D_PROPERTYDEF(m3dpf_float, m3dp_Nt, "Nt"),
  7517. M3D_PROPERTYDEF(m3dpf_map, m3dp_map_Km, "bump"),
  7518. M3D_PROPERTYDEF(m3dpf_map, m3dp_map_N, "map_N"),
  7519. M3D_PROPERTYDEF(m3dpf_map, m3dp_map_Pm, "refl")
  7520. };
  7521. static m3dcd_t m3d_commandtypes[] = {
  7522. M3D_CMDDEF(m3dc_use, "use", 1, m3dcp_mi_t, 0, 0, 0, 0, 0, 0, 0),
  7523. M3D_CMDDEF(m3dc_inc, "inc", 3, m3dcp_hi_t, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vi_t, 0, 0, 0, 0),
  7524. M3D_CMDDEF(m3dc_mesh, "mesh", 1, m3dcp_fi_t, m3dcp_fi_t, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vi_t, 0, 0, 0),
  7525. M3D_CMDDEF(m3dc_div, "div", 1, m3dcp_vc_t, 0, 0, 0, 0, 0, 0, 0),
  7526. M3D_CMDDEF(m3dc_sub, "sub", 2, m3dcp_vc_t, m3dcp_vc_t, 0, 0, 0, 0, 0, 0),
  7527. M3D_CMDDEF(m3dc_len, "len", 1, m3dcp_vc_t, 0, 0, 0, 0, 0, 0, 0),
  7528. M3D_CMDDEF(m3dc_dist, "dist", 2, m3dcp_vc_t, m3dcp_vc_t, 0, 0, 0, 0, 0, 0),
  7529. M3D_CMDDEF(m3dc_degu, "degu", 1, m3dcp_i1_t, 0, 0, 0, 0, 0, 0, 0),
  7530. M3D_CMDDEF(m3dc_deg, "deg", 2, m3dcp_i1_t, m3dcp_i1_t, 0, 0, 0, 0, 0, 0),
  7531. M3D_CMDDEF(m3dc_rangeu, "rangeu", 1, m3dcp_ti_t, 0, 0, 0, 0, 0, 0, 0),
  7532. M3D_CMDDEF(m3dc_range, "range", 2, m3dcp_ti_t, m3dcp_ti_t, 0, 0, 0, 0, 0, 0),
  7533. M3D_CMDDEF(m3dc_paru, "paru", 2, m3dcp_va_t, m3dcp_vc_t, 0, 0, 0, 0, 0, 0),
  7534. M3D_CMDDEF(m3dc_parv, "parv", 2, m3dcp_va_t, m3dcp_vc_t, 0, 0, 0, 0, 0, 0),
  7535. M3D_CMDDEF(m3dc_trim, "trim", 3, m3dcp_va_t, m3dcp_ti_t, m3dcp_i2_t, 0, 0, 0, 0, 0),
  7536. M3D_CMDDEF(m3dc_hole, "hole", 3, m3dcp_va_t, m3dcp_ti_t, m3dcp_i2_t, 0, 0, 0, 0, 0),
  7537. M3D_CMDDEF(m3dc_scrv, "scrv", 3, m3dcp_va_t, m3dcp_ti_t, m3dcp_i2_t, 0, 0, 0, 0, 0),
  7538. M3D_CMDDEF(m3dc_sp, "sp", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7539. M3D_CMDDEF(m3dc_bez1, "bez1", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7540. M3D_CMDDEF(m3dc_bsp1, "bsp1", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7541. M3D_CMDDEF(m3dc_bez2, "bez2", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7542. M3D_CMDDEF(m3dc_bsp2, "bsp2", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7543. M3D_CMDDEF(m3dc_bezun, "bezun", 4, m3dcp_va_t, m3dcp_vi_t, m3dcp_ti_t, m3dcp_vi_t, 0, 0, 0, 0),
  7544. M3D_CMDDEF(m3dc_bezu, "bezu", 3, m3dcp_va_t, m3dcp_vi_t, m3dcp_ti_t, 0, 0, 0, 0, 0),
  7545. M3D_CMDDEF(m3dc_bezn, "bezn", 3, m3dcp_va_t, m3dcp_vi_t, m3dcp_vi_t, 0, 0, 0, 0, 0),
  7546. M3D_CMDDEF(m3dc_bez, "bez", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7547. M3D_CMDDEF(m3dc_nurbsun, "nurbsun", 4, m3dcp_va_t, m3dcp_vi_t, m3dcp_ti_t, m3dcp_vi_t, 0, 0, 0, 0),
  7548. M3D_CMDDEF(m3dc_nurbsu, "nurbsu", 3, m3dcp_va_t, m3dcp_vi_t, m3dcp_ti_t, 0, 0, 0, 0, 0),
  7549. M3D_CMDDEF(m3dc_nurbsn, "nurbsn", 3, m3dcp_va_t, m3dcp_vi_t, m3dcp_vi_t, 0, 0, 0, 0, 0),
  7550. M3D_CMDDEF(m3dc_nurbs, "nurbs", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7551. M3D_CMDDEF(m3dc_conn, "conn", 6, m3dcp_i2_t, m3dcp_ti_t, m3dcp_i2_t, m3dcp_i2_t, m3dcp_ti_t, m3dcp_i2_t, 0, 0),
  7552. M3D_CMDDEF(m3dc_line, "line", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7553. M3D_CMDDEF(m3dc_polygon, "polygon", 2, m3dcp_va_t, m3dcp_vi_t, 0, 0, 0, 0, 0, 0),
  7554. M3D_CMDDEF(m3dc_circle, "circle", 3, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vc_t, 0, 0, 0, 0, 0),
  7555. M3D_CMDDEF(m3dc_cylinder,"cylinder",6, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vc_t, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vc_t, 0, 0),
  7556. M3D_CMDDEF(m3dc_shpere, "shpere", 2, m3dcp_vi_t, m3dcp_vc_t, 0, 0, 0, 0, 0, 0),
  7557. M3D_CMDDEF(m3dc_torus, "torus", 4, m3dcp_vi_t, m3dcp_qi_t, m3dcp_vc_t, m3dcp_vc_t, 0, 0, 0, 0),
  7558. M3D_CMDDEF(m3dc_cone, "cone", 3, m3dcp_vi_t, m3dcp_vi_t, m3dcp_vi_t, 0, 0, 0, 0, 0),
  7559. M3D_CMDDEF(m3dc_cube, "cube", 3, m3dcp_vi_t, m3dcp_vi_t, m3dcp_vi_t, 0, 0, 0, 0, 0)
  7560. };
  7561. #endif
  7562. #include <stdlib.h>
  7563. #include <string.h>
  7564. char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
  7565. #define M3D_CHUNKMAGIC(m, a,b,c,d) ((m)[0]==(a) && (m)[1]==(b) && (m)[2]==(c) && (m)[3]==(d))
  7566. #ifndef M3D_NOIMPORTER
  7567. M3D_INDEX _m3d_gettx(m3d_t *model, m3dread_t readfilecb, m3dfree_t freecb, char *fn)
  7568. {
  7569. unsigned int i, len = 0;
  7570. unsigned char *buff = NULL;
  7571. char *fn2;
  7572. if(!fn || !*fn) return M3D_UNDEF;
  7573. for(i = 0; i < model->numtexture; i++)
  7574. if(!strcmp(fn, model->texture[i].name)) return i;
  7575. if(model->inlined) {
  7576. for(i = 0; i < model->numinlined; i++)
  7577. if(!strcmp(fn, model->inlined[i].name)) {
  7578. buff = model->inlined[i].data;
  7579. len = model->inlined[i].length;
  7580. freecb = NULL;
  7581. break;
  7582. }
  7583. }
  7584. if(!buff && readfilecb) {
  7585. i = (unsigned int)strlen(fn);
  7586. if(i < 5 || fn[i - 4] != '.') {
  7587. fn2 = (char*)M3D_MALLOC(i + 5);
  7588. if(!fn2) { model->errcode = M3D_ERR_ALLOC; return M3D_UNDEF; }
  7589. memcpy(fn2, fn, i);
  7590. memcpy(fn2+i, ".png", 5);
  7591. buff = (*readfilecb)(fn2, &len);
  7592. M3D_FREE(fn2);
  7593. }
  7594. if(!buff) {
  7595. buff = (*readfilecb)(fn, &len);
  7596. if(!buff) return M3D_UNDEF;
  7597. }
  7598. }
  7599. i = model->numtexture++;
  7600. model->texture = (m3dtx_t*)M3D_REALLOC(model->texture, model->numtexture * sizeof(m3dtx_t));
  7601. if(!model->texture) {
  7602. if(buff && freecb) (*freecb)(buff);
  7603. model->errcode = M3D_ERR_ALLOC;
  7604. model->numtexture = 0;
  7605. return M3D_UNDEF;
  7606. }
  7607. memset(&model->texture[i], 0, sizeof(m3dtx_t));
  7608. model->texture[i].name = fn;
  7609. if(buff) {
  7610. if(buff[0] == 0x89 && buff[1] == 'P' && buff[2] == 'N' && buff[3] == 'G') {
  7611. } else {
  7612. #ifdef M3D_TX_INTERP
  7613. if((model->errcode = M3D_TX_INTERP(fn, buff, len, &model->texture[i])) != M3D_SUCCESS) {
  7614. M3D_LOG("Unable to generate texture");
  7615. M3D_LOG(fn);
  7616. }
  7617. #else
  7618. M3D_LOG("Unimplemented interpreter");
  7619. M3D_LOG(fn);
  7620. #endif
  7621. }
  7622. if(freecb) (*freecb)(buff);
  7623. }
  7624. if(!model->texture[i].d)
  7625. model->errcode = M3D_ERR_UNKIMG;
  7626. return i;
  7627. }
  7628. void _m3d_getpr(m3d_t *model, _unused m3dread_t readfilecb, _unused m3dfree_t freecb, _unused char *fn)
  7629. {
  7630. #ifdef M3D_PR_INTERP
  7631. unsigned int i, len = 0;
  7632. unsigned char *buff = readfilecb && fn && *fn ? (*readfilecb)(fn, &len) : NULL;
  7633. if(!buff && fn && *fn && model->inlined) {
  7634. for(i = 0; i < model->numinlined; i++)
  7635. if(!strcmp(fn, model->inlined[i].name)) {
  7636. buff = model->inlined[i].data;
  7637. len = model->inlined[i].length;
  7638. freecb = NULL;
  7639. break;
  7640. }
  7641. }
  7642. if(!buff || !len || (model->errcode = M3D_PR_INTERP(fn, buff, len, model)) != M3D_SUCCESS) {
  7643. M3D_LOG("Unable to generate procedural surface");
  7644. M3D_LOG(fn);
  7645. model->errcode = M3D_ERR_UNKIMG;
  7646. }
  7647. if(freecb && buff) (*freecb)(buff);
  7648. #else
  7649. (void)readfilecb;
  7650. (void)freecb;
  7651. (void)fn;
  7652. M3D_LOG("Unimplemented interpreter");
  7653. M3D_LOG(fn);
  7654. model->errcode = M3D_ERR_UNIMPL;
  7655. #endif
  7656. }
  7657. #define M3D_GETSTR(x) do{offs=0;data=_m3d_getidx(data,model->si_s,&offs);x=offs?((char*)model->raw+16+offs):NULL;}while(0)
  7658. _inline static unsigned char *_m3d_getidx(unsigned char *data, char type, M3D_INDEX *idx)
  7659. {
  7660. switch(type) {
  7661. case 1: *idx = data[0] > 253 ? (int8_t)data[0] : data[0]; data++; break;
  7662. case 2: *idx = *((uint16_t*)data) > 65533 ? *((int16_t*)data) : *((uint16_t*)data); data += 2; break;
  7663. case 4: *idx = *((int32_t*)data); data += 4; break;
  7664. }
  7665. return data;
  7666. }
  7667. #ifndef M3D_NOANIMATION
  7668. void _m3d_mul(M3D_FLOAT *r, M3D_FLOAT *a, M3D_FLOAT *b)
  7669. {
  7670. r[ 0] = b[ 0] * a[ 0] + b[ 4] * a[ 1] + b[ 8] * a[ 2] + b[12] * a[ 3];
  7671. r[ 1] = b[ 1] * a[ 0] + b[ 5] * a[ 1] + b[ 9] * a[ 2] + b[13] * a[ 3];
  7672. r[ 2] = b[ 2] * a[ 0] + b[ 6] * a[ 1] + b[10] * a[ 2] + b[14] * a[ 3];
  7673. r[ 3] = b[ 3] * a[ 0] + b[ 7] * a[ 1] + b[11] * a[ 2] + b[15] * a[ 3];
  7674. r[ 4] = b[ 0] * a[ 4] + b[ 4] * a[ 5] + b[ 8] * a[ 6] + b[12] * a[ 7];
  7675. r[ 5] = b[ 1] * a[ 4] + b[ 5] * a[ 5] + b[ 9] * a[ 6] + b[13] * a[ 7];
  7676. r[ 6] = b[ 2] * a[ 4] + b[ 6] * a[ 5] + b[10] * a[ 6] + b[14] * a[ 7];
  7677. r[ 7] = b[ 3] * a[ 4] + b[ 7] * a[ 5] + b[11] * a[ 6] + b[15] * a[ 7];
  7678. r[ 8] = b[ 0] * a[ 8] + b[ 4] * a[ 9] + b[ 8] * a[10] + b[12] * a[11];
  7679. r[ 9] = b[ 1] * a[ 8] + b[ 5] * a[ 9] + b[ 9] * a[10] + b[13] * a[11];
  7680. r[10] = b[ 2] * a[ 8] + b[ 6] * a[ 9] + b[10] * a[10] + b[14] * a[11];
  7681. r[11] = b[ 3] * a[ 8] + b[ 7] * a[ 9] + b[11] * a[10] + b[15] * a[11];
  7682. r[12] = b[ 0] * a[12] + b[ 4] * a[13] + b[ 8] * a[14] + b[12] * a[15];
  7683. r[13] = b[ 1] * a[12] + b[ 5] * a[13] + b[ 9] * a[14] + b[13] * a[15];
  7684. r[14] = b[ 2] * a[12] + b[ 6] * a[13] + b[10] * a[14] + b[14] * a[15];
  7685. r[15] = b[ 3] * a[12] + b[ 7] * a[13] + b[11] * a[14] + b[15] * a[15];
  7686. }
  7687. void _m3d_inv(M3D_FLOAT *m)
  7688. {
  7689. M3D_FLOAT r[16];
  7690. M3D_FLOAT det =
  7691. m[ 0]*m[ 5]*m[10]*m[15] - m[ 0]*m[ 5]*m[11]*m[14] + m[ 0]*m[ 6]*m[11]*m[13] - m[ 0]*m[ 6]*m[ 9]*m[15]
  7692. + m[ 0]*m[ 7]*m[ 9]*m[14] - m[ 0]*m[ 7]*m[10]*m[13] - m[ 1]*m[ 6]*m[11]*m[12] + m[ 1]*m[ 6]*m[ 8]*m[15]
  7693. - m[ 1]*m[ 7]*m[ 8]*m[14] + m[ 1]*m[ 7]*m[10]*m[12] - m[ 1]*m[ 4]*m[10]*m[15] + m[ 1]*m[ 4]*m[11]*m[14]
  7694. + m[ 2]*m[ 7]*m[ 8]*m[13] - m[ 2]*m[ 7]*m[ 9]*m[12] + m[ 2]*m[ 4]*m[ 9]*m[15] - m[ 2]*m[ 4]*m[11]*m[13]
  7695. + m[ 2]*m[ 5]*m[11]*m[12] - m[ 2]*m[ 5]*m[ 8]*m[15] - m[ 3]*m[ 4]*m[ 9]*m[14] + m[ 3]*m[ 4]*m[10]*m[13]
  7696. - m[ 3]*m[ 5]*m[10]*m[12] + m[ 3]*m[ 5]*m[ 8]*m[14] - m[ 3]*m[ 6]*m[ 8]*m[13] + m[ 3]*m[ 6]*m[ 9]*m[12];
  7697. if(det == (M3D_FLOAT)0.0 || det == (M3D_FLOAT)-0.0) det = (M3D_FLOAT)1.0; else det = (M3D_FLOAT)1.0 / det;
  7698. r[ 0] = det *(m[ 5]*(m[10]*m[15] - m[11]*m[14]) + m[ 6]*(m[11]*m[13] - m[ 9]*m[15]) + m[ 7]*(m[ 9]*m[14] - m[10]*m[13]));
  7699. r[ 1] = -det*(m[ 1]*(m[10]*m[15] - m[11]*m[14]) + m[ 2]*(m[11]*m[13] - m[ 9]*m[15]) + m[ 3]*(m[ 9]*m[14] - m[10]*m[13]));
  7700. r[ 2] = det *(m[ 1]*(m[ 6]*m[15] - m[ 7]*m[14]) + m[ 2]*(m[ 7]*m[13] - m[ 5]*m[15]) + m[ 3]*(m[ 5]*m[14] - m[ 6]*m[13]));
  7701. r[ 3] = -det*(m[ 1]*(m[ 6]*m[11] - m[ 7]*m[10]) + m[ 2]*(m[ 7]*m[ 9] - m[ 5]*m[11]) + m[ 3]*(m[ 5]*m[10] - m[ 6]*m[ 9]));
  7702. r[ 4] = -det*(m[ 4]*(m[10]*m[15] - m[11]*m[14]) + m[ 6]*(m[11]*m[12] - m[ 8]*m[15]) + m[ 7]*(m[ 8]*m[14] - m[10]*m[12]));
  7703. r[ 5] = det *(m[ 0]*(m[10]*m[15] - m[11]*m[14]) + m[ 2]*(m[11]*m[12] - m[ 8]*m[15]) + m[ 3]*(m[ 8]*m[14] - m[10]*m[12]));
  7704. r[ 6] = -det*(m[ 0]*(m[ 6]*m[15] - m[ 7]*m[14]) + m[ 2]*(m[ 7]*m[12] - m[ 4]*m[15]) + m[ 3]*(m[ 4]*m[14] - m[ 6]*m[12]));
  7705. r[ 7] = det *(m[ 0]*(m[ 6]*m[11] - m[ 7]*m[10]) + m[ 2]*(m[ 7]*m[ 8] - m[ 4]*m[11]) + m[ 3]*(m[ 4]*m[10] - m[ 6]*m[ 8]));
  7706. r[ 8] = det *(m[ 4]*(m[ 9]*m[15] - m[11]*m[13]) + m[ 5]*(m[11]*m[12] - m[ 8]*m[15]) + m[ 7]*(m[ 8]*m[13] - m[ 9]*m[12]));
  7707. r[ 9] = -det*(m[ 0]*(m[ 9]*m[15] - m[11]*m[13]) + m[ 1]*(m[11]*m[12] - m[ 8]*m[15]) + m[ 3]*(m[ 8]*m[13] - m[ 9]*m[12]));
  7708. r[10] = det *(m[ 0]*(m[ 5]*m[15] - m[ 7]*m[13]) + m[ 1]*(m[ 7]*m[12] - m[ 4]*m[15]) + m[ 3]*(m[ 4]*m[13] - m[ 5]*m[12]));
  7709. r[11] = -det*(m[ 0]*(m[ 5]*m[11] - m[ 7]*m[ 9]) + m[ 1]*(m[ 7]*m[ 8] - m[ 4]*m[11]) + m[ 3]*(m[ 4]*m[ 9] - m[ 5]*m[ 8]));
  7710. r[12] = -det*(m[ 4]*(m[ 9]*m[14] - m[10]*m[13]) + m[ 5]*(m[10]*m[12] - m[ 8]*m[14]) + m[ 6]*(m[ 8]*m[13] - m[ 9]*m[12]));
  7711. r[13] = det *(m[ 0]*(m[ 9]*m[14] - m[10]*m[13]) + m[ 1]*(m[10]*m[12] - m[ 8]*m[14]) + m[ 2]*(m[ 8]*m[13] - m[ 9]*m[12]));
  7712. r[14] = -det*(m[ 0]*(m[ 5]*m[14] - m[ 6]*m[13]) + m[ 1]*(m[ 6]*m[12] - m[ 4]*m[14]) + m[ 2]*(m[ 4]*m[13] - m[ 5]*m[12]));
  7713. r[15] = det *(m[ 0]*(m[ 5]*m[10] - m[ 6]*m[ 9]) + m[ 1]*(m[ 6]*m[ 8] - m[ 4]*m[10]) + m[ 2]*(m[ 4]*m[ 9] - m[ 5]*m[ 8]));
  7714. memcpy(m, &r, sizeof(r));
  7715. }
  7716. void _m3d_mat(M3D_FLOAT *r, m3dv_t *p, m3dv_t *q)
  7717. {
  7718. if(q->x == (M3D_FLOAT)0.0 && q->y == (M3D_FLOAT)0.0 && q->z >=(M3D_FLOAT) 0.7071065 && q->z <= (M3D_FLOAT)0.7071075 &&
  7719. q->w == (M3D_FLOAT)0.0) {
  7720. r[ 1] = r[ 2] = r[ 4] = r[ 6] = r[ 8] = r[ 9] = (M3D_FLOAT)0.0;
  7721. r[ 0] = r[ 5] = r[10] = (M3D_FLOAT)-1.0;
  7722. } else {
  7723. r[ 0] = 1 - 2 * (q->y * q->y + q->z * q->z); if(r[ 0]>-M3D_EPSILON && r[ 0]<M3D_EPSILON) r[ 0]=(M3D_FLOAT)0.0;
  7724. r[ 1] = 2 * (q->x * q->y - q->z * q->w); if(r[ 1]>-M3D_EPSILON && r[ 1]<M3D_EPSILON) r[ 1]=(M3D_FLOAT)0.0;
  7725. r[ 2] = 2 * (q->x * q->z + q->y * q->w); if(r[ 2]>-M3D_EPSILON && r[ 2]<M3D_EPSILON) r[ 2]=(M3D_FLOAT)0.0;
  7726. r[ 4] = 2 * (q->x * q->y + q->z * q->w); if(r[ 4]>-M3D_EPSILON && r[ 4]<M3D_EPSILON) r[ 4]=(M3D_FLOAT)0.0;
  7727. r[ 5] = 1 - 2 * (q->x * q->x + q->z * q->z); if(r[ 5]>-M3D_EPSILON && r[ 5]<M3D_EPSILON) r[ 5]=(M3D_FLOAT)0.0;
  7728. r[ 6] = 2 * (q->y * q->z - q->x * q->w); if(r[ 6]>-M3D_EPSILON && r[ 6]<M3D_EPSILON) r[ 6]=(M3D_FLOAT)0.0;
  7729. r[ 8] = 2 * (q->x * q->z - q->y * q->w); if(r[ 8]>-M3D_EPSILON && r[ 8]<M3D_EPSILON) r[ 8]=(M3D_FLOAT)0.0;
  7730. r[ 9] = 2 * (q->y * q->z + q->x * q->w); if(r[ 9]>-M3D_EPSILON && r[ 9]<M3D_EPSILON) r[ 9]=(M3D_FLOAT)0.0;
  7731. r[10] = 1 - 2 * (q->x * q->x + q->y * q->y); if(r[10]>-M3D_EPSILON && r[10]<M3D_EPSILON) r[10]=(M3D_FLOAT)0.0;
  7732. }
  7733. r[ 3] = p->x; r[ 7] = p->y; r[11] = p->z;
  7734. r[12] = 0; r[13] = 0; r[14] = 0; r[15] = 1;
  7735. }
  7736. #endif
  7737. #if !defined(M3D_NOANIMATION) || !defined(M3D_NONORMALS)
  7738. static M3D_FLOAT _m3d_rsq(M3D_FLOAT x)
  7739. {
  7740. #ifdef M3D_DOUBLE
  7741. return ((M3D_FLOAT)15.0/(M3D_FLOAT)8.0) + ((M3D_FLOAT)-5.0/(M3D_FLOAT)4.0)*x + ((M3D_FLOAT)3.0/(M3D_FLOAT)8.0)*x*x;
  7742. #else
  7743. float x2 = x * 0.5f;
  7744. uint32_t *i = (uint32_t*)&x;
  7745. *i = (0x5f3759df - (*i >> 1));
  7746. return x * (1.5f - (x2 * x * x));
  7747. #endif
  7748. }
  7749. #endif
  7750. m3d_t *m3d_load(unsigned char *data, m3dread_t readfilecb, m3dfree_t freecb, m3d_t *mtllib)
  7751. {
  7752. unsigned char *end, *chunk, *buff, weights[8];
  7753. unsigned int i, j, k, l, n, am, len = 0, reclen, offs;
  7754. #ifndef M3D_NOVOXELS
  7755. int32_t min_x, min_y, min_z, max_x, max_y, max_z, sx, sy, sz, x, y, z;
  7756. M3D_INDEX edge[8], enorm;
  7757. #endif
  7758. char *name, *lang;
  7759. float f;
  7760. m3d_t *model;
  7761. M3D_INDEX mi;
  7762. #ifdef M3D_VERTEXMAX
  7763. M3D_INDEX pi;
  7764. #endif
  7765. M3D_FLOAT w;
  7766. m3dcd_t *cd;
  7767. m3dtx_t *tx;
  7768. m3dh_t *h;
  7769. m3dm_t *m;
  7770. m3da_t *a;
  7771. m3di_t *t;
  7772. #ifndef M3D_NONORMALS
  7773. char neednorm = 0;
  7774. m3dv_t *norm = NULL, *v0, *v1, *v2, va, vb;
  7775. #endif
  7776. #ifndef M3D_NOANIMATION
  7777. M3D_FLOAT r[16];
  7778. #endif
  7779. #if !defined(M3D_NOWEIGHTS) || !defined(M3D_NOANIMATION)
  7780. m3db_t *b;
  7781. #endif
  7782. #ifndef M3D_NOWEIGHTS
  7783. m3ds_t *sk;
  7784. #endif
  7785. if(!data || (!M3D_CHUNKMAGIC(data, '3','D','M','O')
  7786. )) return NULL;
  7787. model = (m3d_t*)M3D_MALLOC(sizeof(m3d_t));
  7788. if(!model) {
  7789. M3D_LOG("Out of memory");
  7790. return NULL;
  7791. }
  7792. memset(model, 0, sizeof(m3d_t));
  7793. if(mtllib) {
  7794. model->nummaterial = mtllib->nummaterial;
  7795. model->material = mtllib->material;
  7796. model->numtexture = mtllib->numtexture;
  7797. model->texture = mtllib->texture;
  7798. model->flags |= M3D_FLG_MTLLIB;
  7799. }
  7800. len = ((m3dhdr_t*)data)->length - 8;
  7801. data += 8;
  7802. if(M3D_CHUNKMAGIC(data, 'P','R','V','W')) {
  7803. model->preview.length = ((m3dchunk_t*)data)->length;
  7804. model->preview.data = data + sizeof(m3dchunk_t);
  7805. data += model->preview.length;
  7806. len -= model->preview.length;
  7807. }
  7808. if(!M3D_CHUNKMAGIC(data, 'H','E','A','D')) {
  7809. buff = (unsigned char *)stbi_zlib_decode_malloc_guesssize_headerflag((const char*)data, len, 4096, (int*)&len, 1);
  7810. if(!buff || !len || !M3D_CHUNKMAGIC(buff, 'H','E','A','D')) {
  7811. if(buff) M3D_FREE(buff);
  7812. M3D_FREE(model);
  7813. return NULL;
  7814. }
  7815. buff = (unsigned char*)M3D_REALLOC(buff, len);
  7816. model->flags |= M3D_FLG_FREERAW;
  7817. data = buff;
  7818. }
  7819. model->raw = (m3dhdr_t*)data;
  7820. end = data + len;
  7821. data += sizeof(m3dhdr_t);
  7822. M3D_LOG((char*)data);
  7823. model->name = (char*)data;
  7824. for(; data < end && *data; data++) {}; data++;
  7825. model->license = (char*)data;
  7826. for(; data < end && *data; data++) {}; data++;
  7827. model->author = (char*)data;
  7828. for(; data < end && *data; data++) {}; data++;
  7829. model->desc = (char*)data;
  7830. chunk = (unsigned char*)model->raw + model->raw->length;
  7831. model->scale = (M3D_FLOAT)model->raw->scale;
  7832. if(model->scale <= (M3D_FLOAT)0.0) model->scale = (M3D_FLOAT)1.0;
  7833. model->vc_s = 1 << ((model->raw->types >> 0) & 3);
  7834. model->vi_s = 1 << ((model->raw->types >> 2) & 3);
  7835. model->si_s = 1 << ((model->raw->types >> 4) & 3);
  7836. model->ci_s = 1 << ((model->raw->types >> 6) & 3);
  7837. model->ti_s = 1 << ((model->raw->types >> 8) & 3);
  7838. model->bi_s = 1 << ((model->raw->types >>10) & 3);
  7839. model->nb_s = 1 << ((model->raw->types >>12) & 3);
  7840. model->sk_s = 1 << ((model->raw->types >>14) & 3);
  7841. model->fc_s = 1 << ((model->raw->types >>16) & 3);
  7842. model->hi_s = 1 << ((model->raw->types >>18) & 3);
  7843. model->fi_s = 1 << ((model->raw->types >>20) & 3);
  7844. model->vd_s = 1 << ((model->raw->types >>22) & 3);
  7845. model->vp_s = 1 << ((model->raw->types >>24) & 3);
  7846. if(model->ci_s == 8) model->ci_s = 0;
  7847. if(model->ti_s == 8) model->ti_s = 0;
  7848. if(model->bi_s == 8) model->bi_s = 0;
  7849. if(model->sk_s == 8) model->sk_s = 0;
  7850. if(model->fc_s == 8) model->fc_s = 0;
  7851. if(model->hi_s == 8) model->hi_s = 0;
  7852. if(model->fi_s == 8) model->fi_s = 0;
  7853. if(sizeof(M3D_FLOAT) == 4 && model->vc_s > 4) {
  7854. M3D_LOG("Double precision coordinates not supported, truncating to float...");
  7855. model->errcode = M3D_ERR_TRUNC;
  7856. }
  7857. if((sizeof(M3D_INDEX) == 2 && (model->vi_s > 2 || model->si_s > 2 || model->ci_s > 2 || model->ti_s > 2 ||
  7858. model->bi_s > 2 || model->sk_s > 2 || model->fc_s > 2 || model->hi_s > 2 || model->fi_s > 2)) ||
  7859. (sizeof(M3D_VOXEL) < (size_t)model->vp_s && model->vp_s != 8)) {
  7860. M3D_LOG("32 bit indices not supported, unable to load model");
  7861. M3D_FREE(model);
  7862. return NULL;
  7863. }
  7864. if(model->vi_s > 4 || model->si_s > 4 || model->vp_s == 4) {
  7865. M3D_LOG("Invalid index size, unable to load model");
  7866. M3D_FREE(model);
  7867. return NULL;
  7868. }
  7869. if(!M3D_CHUNKMAGIC(end - 4, 'O','M','D','3')) {
  7870. M3D_LOG("Missing end chunk");
  7871. M3D_FREE(model);
  7872. return NULL;
  7873. }
  7874. if(model->nb_s > M3D_NUMBONE) {
  7875. M3D_LOG("Model has more bones per vertex than what importer was configured to support");
  7876. model->errcode = M3D_ERR_TRUNC;
  7877. }
  7878. buff = chunk;
  7879. while(buff < end && !M3D_CHUNKMAGIC(buff, 'O','M','D','3')) {
  7880. data = buff;
  7881. len = ((m3dchunk_t*)data)->length;
  7882. buff += len;
  7883. if(len < sizeof(m3dchunk_t) || buff >= end) {
  7884. M3D_LOG("Invalid chunk size");
  7885. break;
  7886. }
  7887. len -= sizeof(m3dchunk_t) + model->si_s;
  7888. if(M3D_CHUNKMAGIC(data, 'A','S','E','T') && len > 0) {
  7889. M3D_LOG("Inlined asset");
  7890. i = model->numinlined++;
  7891. model->inlined = (m3di_t*)M3D_REALLOC(model->inlined, model->numinlined * sizeof(m3di_t));
  7892. if(!model->inlined) {
  7893. memerr: M3D_LOG("Out of memory");
  7894. model->errcode = M3D_ERR_ALLOC;
  7895. return model;
  7896. }
  7897. data += sizeof(m3dchunk_t);
  7898. t = &model->inlined[i];
  7899. M3D_GETSTR(t->name);
  7900. M3D_LOG(t->name);
  7901. t->data = (uint8_t*)data;
  7902. t->length = len;
  7903. }
  7904. }
  7905. while(chunk < end && !M3D_CHUNKMAGIC(chunk, 'O','M','D','3')) {
  7906. data = chunk;
  7907. len = ((m3dchunk_t*)chunk)->length;
  7908. chunk += len;
  7909. if(len < sizeof(m3dchunk_t) || chunk >= end) {
  7910. M3D_LOG("Invalid chunk size");
  7911. break;
  7912. }
  7913. len -= sizeof(m3dchunk_t);
  7914. if(M3D_CHUNKMAGIC(data, 'C','M','A','P')) {
  7915. M3D_LOG("Color map");
  7916. if(model->cmap) { M3D_LOG("More color map chunks, should be unique"); model->errcode = M3D_ERR_CMAP; continue; }
  7917. if(!model->ci_s) { M3D_LOG("Color map chunk, shouldn't be any"); model->errcode = M3D_ERR_CMAP; continue; }
  7918. model->numcmap = len / sizeof(uint32_t);
  7919. model->cmap = (uint32_t*)(data + sizeof(m3dchunk_t));
  7920. } else
  7921. if(M3D_CHUNKMAGIC(data, 'T','M','A','P')) {
  7922. M3D_LOG("Texture map");
  7923. if(model->tmap) { M3D_LOG("More texture map chunks, should be unique"); model->errcode = M3D_ERR_TMAP; continue; }
  7924. if(!model->ti_s) { M3D_LOG("Texture map chunk, shouldn't be any"); model->errcode = M3D_ERR_TMAP; continue; }
  7925. reclen = model->vc_s + model->vc_s;
  7926. model->numtmap = len / reclen;
  7927. model->tmap = (m3dti_t*)M3D_MALLOC(model->numtmap * sizeof(m3dti_t));
  7928. if(!model->tmap) goto memerr;
  7929. for(i = 0, data += sizeof(m3dchunk_t); data < chunk; i++) {
  7930. switch(model->vc_s) {
  7931. case 1:
  7932. model->tmap[i].u = (M3D_FLOAT)((uint8_t)data[0]) / (M3D_FLOAT)255.0;
  7933. model->tmap[i].v = (M3D_FLOAT)((uint8_t)data[1]) / (M3D_FLOAT)255.0;
  7934. break;
  7935. case 2:
  7936. model->tmap[i].u = (M3D_FLOAT)(*((uint16_t*)(data+0))) / (M3D_FLOAT)65535.0;
  7937. model->tmap[i].v = (M3D_FLOAT)(*((uint16_t*)(data+2))) / (M3D_FLOAT)65535.0;
  7938. break;
  7939. case 4:
  7940. model->tmap[i].u = (M3D_FLOAT)(*((float*)(data+0)));
  7941. model->tmap[i].v = (M3D_FLOAT)(*((float*)(data+4)));
  7942. break;
  7943. case 8:
  7944. model->tmap[i].u = (M3D_FLOAT)(*((double*)(data+0)));
  7945. model->tmap[i].v = (M3D_FLOAT)(*((double*)(data+8)));
  7946. break;
  7947. }
  7948. data += reclen;
  7949. }
  7950. } else
  7951. if(M3D_CHUNKMAGIC(data, 'V','R','T','S')) {
  7952. M3D_LOG("Vertex list");
  7953. if(model->vertex) { M3D_LOG("More vertex chunks, should be unique"); model->errcode = M3D_ERR_VRTS; continue; }
  7954. if(model->ci_s && model->ci_s < 4 && !model->cmap) model->errcode = M3D_ERR_CMAP;
  7955. reclen = model->ci_s + model->sk_s + 4 * model->vc_s;
  7956. model->numvertex = len / reclen;
  7957. model->vertex = (m3dv_t*)M3D_MALLOC(model->numvertex * sizeof(m3dv_t));
  7958. if(!model->vertex) goto memerr;
  7959. memset(model->vertex, 0, model->numvertex * sizeof(m3dv_t));
  7960. for(i = 0, data += sizeof(m3dchunk_t); data < chunk && i < model->numvertex; i++) {
  7961. switch(model->vc_s) {
  7962. case 1:
  7963. model->vertex[i].x = (M3D_FLOAT)((int8_t)data[0]) / (M3D_FLOAT)127.0;
  7964. model->vertex[i].y = (M3D_FLOAT)((int8_t)data[1]) / (M3D_FLOAT)127.0;
  7965. model->vertex[i].z = (M3D_FLOAT)((int8_t)data[2]) / (M3D_FLOAT)127.0;
  7966. model->vertex[i].w = (M3D_FLOAT)((int8_t)data[3]) / (M3D_FLOAT)127.0;
  7967. data += 4;
  7968. break;
  7969. case 2:
  7970. model->vertex[i].x = (M3D_FLOAT)(*((int16_t*)(data+0))) / (M3D_FLOAT)32767.0;
  7971. model->vertex[i].y = (M3D_FLOAT)(*((int16_t*)(data+2))) / (M3D_FLOAT)32767.0;
  7972. model->vertex[i].z = (M3D_FLOAT)(*((int16_t*)(data+4))) / (M3D_FLOAT)32767.0;
  7973. model->vertex[i].w = (M3D_FLOAT)(*((int16_t*)(data+6))) / (M3D_FLOAT)32767.0;
  7974. data += 8;
  7975. break;
  7976. case 4:
  7977. model->vertex[i].x = (M3D_FLOAT)(*((float*)(data+0)));
  7978. model->vertex[i].y = (M3D_FLOAT)(*((float*)(data+4)));
  7979. model->vertex[i].z = (M3D_FLOAT)(*((float*)(data+8)));
  7980. model->vertex[i].w = (M3D_FLOAT)(*((float*)(data+12)));
  7981. data += 16;
  7982. break;
  7983. case 8:
  7984. model->vertex[i].x = (M3D_FLOAT)(*((double*)(data+0)));
  7985. model->vertex[i].y = (M3D_FLOAT)(*((double*)(data+8)));
  7986. model->vertex[i].z = (M3D_FLOAT)(*((double*)(data+16)));
  7987. model->vertex[i].w = (M3D_FLOAT)(*((double*)(data+24)));
  7988. data += 32;
  7989. break;
  7990. }
  7991. switch(model->ci_s) {
  7992. case 1: model->vertex[i].color = model->cmap ? model->cmap[data[0]] : 0; data++; break;
  7993. case 2: model->vertex[i].color = model->cmap ? model->cmap[*((uint16_t*)data)] : 0; data += 2; break;
  7994. case 4: model->vertex[i].color = *((uint32_t*)data); data += 4; break;
  7995. }
  7996. model->vertex[i].skinid = M3D_UNDEF;
  7997. data = _m3d_getidx(data, model->sk_s, &model->vertex[i].skinid);
  7998. }
  7999. } else
  8000. if(M3D_CHUNKMAGIC(data, 'B','O','N','E')) {
  8001. M3D_LOG("Skeleton");
  8002. if(model->bone) { M3D_LOG("More bone chunks, should be unique"); model->errcode = M3D_ERR_BONE; continue; }
  8003. if(!model->bi_s) { M3D_LOG("Bone chunk, shouldn't be any"); model->errcode=M3D_ERR_BONE; continue; }
  8004. if(!model->vertex) { M3D_LOG("No vertex chunk before bones"); model->errcode = M3D_ERR_VRTS; break; }
  8005. data += sizeof(m3dchunk_t);
  8006. model->numbone = 0;
  8007. data = _m3d_getidx(data, model->bi_s, &model->numbone);
  8008. if(model->numbone) {
  8009. model->bone = (m3db_t*)M3D_MALLOC(model->numbone * sizeof(m3db_t));
  8010. if(!model->bone) goto memerr;
  8011. }
  8012. model->numskin = 0;
  8013. data = _m3d_getidx(data, model->sk_s, &model->numskin);
  8014. for(i = 0; data < chunk && i < model->numbone; i++) {
  8015. data = _m3d_getidx(data, model->bi_s, &model->bone[i].parent);
  8016. M3D_GETSTR(model->bone[i].name);
  8017. data = _m3d_getidx(data, model->vi_s, &model->bone[i].pos);
  8018. data = _m3d_getidx(data, model->vi_s, &model->bone[i].ori);
  8019. model->bone[i].numweight = 0;
  8020. model->bone[i].weight = NULL;
  8021. }
  8022. if(i != model->numbone) { M3D_LOG("Truncated bone chunk"); model->numbone = i; model->numskin = 0; model->errcode = M3D_ERR_BONE; }
  8023. if(model->numskin) {
  8024. model->skin = (m3ds_t*)M3D_MALLOC(model->numskin * sizeof(m3ds_t));
  8025. if(!model->skin) goto memerr;
  8026. for(i = 0; data < chunk && i < model->numskin; i++) {
  8027. for(j = 0; j < M3D_NUMBONE; j++) {
  8028. model->skin[i].boneid[j] = M3D_UNDEF;
  8029. model->skin[i].weight[j] = (M3D_FLOAT)0.0;
  8030. }
  8031. memset(&weights, 0, sizeof(weights));
  8032. if(model->nb_s == 1) weights[0] = 255;
  8033. else {
  8034. memcpy(&weights, data, model->nb_s);
  8035. data += model->nb_s;
  8036. }
  8037. for(j = 0, w = (M3D_FLOAT)0.0; j < (unsigned int)model->nb_s; j++) {
  8038. if(weights[j]) {
  8039. if(j >= M3D_NUMBONE)
  8040. data += model->bi_s;
  8041. else {
  8042. model->skin[i].weight[j] = (M3D_FLOAT)(weights[j]) / (M3D_FLOAT)255.0;
  8043. w += model->skin[i].weight[j];
  8044. data = _m3d_getidx(data, model->bi_s, &model->skin[i].boneid[j]);
  8045. }
  8046. }
  8047. }
  8048. if(w != (M3D_FLOAT)1.0 && w != (M3D_FLOAT)0.0) {
  8049. for(j = 0; j < M3D_NUMBONE; j++)
  8050. model->skin[i].weight[j] /= w;
  8051. }
  8052. }
  8053. if(i != model->numskin) { M3D_LOG("Truncated skin in bone chunk"); model->numskin = i; model->errcode = M3D_ERR_BONE; }
  8054. }
  8055. } else
  8056. if(M3D_CHUNKMAGIC(data, 'M','T','R','L')) {
  8057. data += sizeof(m3dchunk_t);
  8058. M3D_GETSTR(name);
  8059. M3D_LOG("Material");
  8060. M3D_LOG(name);
  8061. if(model->ci_s < 4 && !model->numcmap) model->errcode = M3D_ERR_CMAP;
  8062. for(i = 0; i < model->nummaterial; i++)
  8063. if(!strcmp(name, model->material[i].name)) {
  8064. model->errcode = M3D_ERR_MTRL;
  8065. M3D_LOG("Multiple definitions for material");
  8066. M3D_LOG(name);
  8067. name = NULL;
  8068. break;
  8069. }
  8070. if(name) {
  8071. i = model->nummaterial++;
  8072. if(model->flags & M3D_FLG_MTLLIB) {
  8073. m = model->material;
  8074. model->material = (m3dm_t*)M3D_MALLOC(model->nummaterial * sizeof(m3dm_t));
  8075. if(!model->material) goto memerr;
  8076. memcpy(model->material, m, (model->nummaterial - 1) * sizeof(m3dm_t));
  8077. if(model->texture) {
  8078. tx = model->texture;
  8079. model->texture = (m3dtx_t*)M3D_MALLOC(model->numtexture * sizeof(m3dtx_t));
  8080. if(!model->texture) goto memerr;
  8081. memcpy(model->texture, tx, model->numtexture * sizeof(m3dm_t));
  8082. }
  8083. model->flags &= ~M3D_FLG_MTLLIB;
  8084. } else {
  8085. model->material = (m3dm_t*)M3D_REALLOC(model->material, model->nummaterial * sizeof(m3dm_t));
  8086. if(!model->material) goto memerr;
  8087. }
  8088. m = &model->material[i];
  8089. m->numprop = 0;
  8090. m->name = name;
  8091. m->prop = (m3dp_t*)M3D_MALLOC((len / 2) * sizeof(m3dp_t));
  8092. if(!m->prop) goto memerr;
  8093. while(data < chunk) {
  8094. i = m->numprop++;
  8095. m->prop[i].type = *data++;
  8096. m->prop[i].value.num = 0;
  8097. if(m->prop[i].type >= 128)
  8098. k = m3dpf_map;
  8099. else {
  8100. for(k = 256, j = 0; j < sizeof(m3d_propertytypes)/sizeof(m3d_propertytypes[0]); j++)
  8101. if(m->prop[i].type == m3d_propertytypes[j].id) { k = m3d_propertytypes[j].format; break; }
  8102. }
  8103. switch(k) {
  8104. case m3dpf_color:
  8105. switch(model->ci_s) {
  8106. case 1: m->prop[i].value.color = model->cmap ? model->cmap[data[0]] : 0; data++; break;
  8107. case 2: m->prop[i].value.color = model->cmap ? model->cmap[*((uint16_t*)data)] : 0; data += 2; break;
  8108. case 4: m->prop[i].value.color = *((uint32_t*)data); data += 4; break;
  8109. }
  8110. break;
  8111. case m3dpf_uint8: m->prop[i].value.num = *data++; break;
  8112. case m3dpf_uint16:m->prop[i].value.num = *((uint16_t*)data); data += 2; break;
  8113. case m3dpf_uint32:m->prop[i].value.num = *((uint32_t*)data); data += 4; break;
  8114. case m3dpf_float: m->prop[i].value.fnum = *((float*)data); data += 4; break;
  8115. case m3dpf_map:
  8116. M3D_GETSTR(name);
  8117. m->prop[i].value.textureid = _m3d_gettx(model, readfilecb, freecb, name);
  8118. if(model->errcode == M3D_ERR_ALLOC) goto memerr;
  8119. if(m->prop[i].value.textureid == M3D_UNDEF) {
  8120. M3D_LOG("Texture not found");
  8121. M3D_LOG(m->name);
  8122. m->numprop--;
  8123. }
  8124. break;
  8125. default:
  8126. M3D_LOG("Unknown material property in");
  8127. M3D_LOG(m->name);
  8128. model->errcode = M3D_ERR_UNKPROP;
  8129. data = chunk;
  8130. break;
  8131. }
  8132. }
  8133. m->prop = (m3dp_t*)M3D_REALLOC(m->prop, m->numprop * sizeof(m3dp_t));
  8134. if(!m->prop) goto memerr;
  8135. }
  8136. } else
  8137. if(M3D_CHUNKMAGIC(data, 'P','R','O','C')) {
  8138. M3D_GETSTR(name);
  8139. M3D_LOG("Procedural surface");
  8140. M3D_LOG(name);
  8141. _m3d_getpr(model, readfilecb, freecb, name);
  8142. } else
  8143. if(M3D_CHUNKMAGIC(data, 'M','E','S','H')) {
  8144. M3D_LOG("Mesh data");
  8145. if(!model->vertex) { M3D_LOG("No vertex chunk before mesh"); model->errcode = M3D_ERR_VRTS; }
  8146. data += sizeof(m3dchunk_t);
  8147. mi = M3D_UNDEF;
  8148. #ifdef M3D_VERTEXMAX
  8149. pi = M3D_UNDEF;
  8150. #endif
  8151. am = model->numface;
  8152. while(data < chunk) {
  8153. k = *data++;
  8154. n = k >> 4;
  8155. k &= 15;
  8156. if(!n) {
  8157. if(!k) {
  8158. mi = M3D_UNDEF;
  8159. M3D_GETSTR(name);
  8160. if(name) {
  8161. for(j = 0; j < model->nummaterial; j++)
  8162. if(!strcmp(name, model->material[j].name)) {
  8163. mi = (M3D_INDEX)j;
  8164. break;
  8165. }
  8166. if(mi == M3D_UNDEF) model->errcode = M3D_ERR_MTRL;
  8167. }
  8168. } else {
  8169. M3D_GETSTR(name);
  8170. #ifdef M3D_VERTEXMAX
  8171. pi = M3D_UNDEF;
  8172. if(name) {
  8173. for(j = 0; j < model->numparam; j++)
  8174. if(!strcmp(name, model->param[j].name)) {
  8175. pi = (M3D_INDEX)j;
  8176. break;
  8177. }
  8178. if(pi == M3D_UNDEF) {
  8179. pi = model->numparam++;
  8180. model->param = (m3dvi_t*)M3D_REALLOC(model->param, model->numparam * sizeof(m3dvi_t));
  8181. if(!model->param) goto memerr;
  8182. model->param[pi].name = name;
  8183. model->param[pi].count = 0;
  8184. }
  8185. }
  8186. #endif
  8187. }
  8188. continue;
  8189. }
  8190. if(n != 3) { M3D_LOG("Only triangle mesh supported for now"); model->errcode = M3D_ERR_UNKMESH; return model; }
  8191. i = model->numface++;
  8192. if(model->numface > am) {
  8193. am = model->numface + 4095;
  8194. model->face = (m3df_t*)M3D_REALLOC(model->face, am * sizeof(m3df_t));
  8195. if(!model->face) goto memerr;
  8196. }
  8197. memset(&model->face[i], 255, sizeof(m3df_t));
  8198. model->face[i].materialid = mi;
  8199. #ifdef M3D_VERTEXMAX
  8200. model->face[i].paramid = pi;
  8201. #endif
  8202. for(j = 0; data < chunk && j < n; j++) {
  8203. data = _m3d_getidx(data, model->vi_s, &model->face[i].vertex[j]);
  8204. if(k & 1)
  8205. data = _m3d_getidx(data, model->ti_s, &model->face[i].texcoord[j]);
  8206. if(k & 2)
  8207. data = _m3d_getidx(data, model->vi_s, &model->face[i].normal[j]);
  8208. #ifndef M3D_NONORMALS
  8209. if(model->face[i].normal[j] == M3D_UNDEF) neednorm = 1;
  8210. #endif
  8211. if(k & 4)
  8212. #ifdef M3D_VERTEXMAX
  8213. data = _m3d_getidx(data, model->vi_s, &model->face[i].vertmax[j]);
  8214. #else
  8215. data += model->vi_s;
  8216. #endif
  8217. }
  8218. if(j != n) { M3D_LOG("Invalid mesh"); model->numface = 0; model->errcode = M3D_ERR_UNKMESH; return model; }
  8219. }
  8220. model->face = (m3df_t*)M3D_REALLOC(model->face, model->numface * sizeof(m3df_t));
  8221. } else
  8222. if(M3D_CHUNKMAGIC(data, 'V','O','X','T')) {
  8223. M3D_LOG("Voxel types list");
  8224. if(model->voxtype) { M3D_LOG("More voxel type chunks, should be unique"); model->errcode = M3D_ERR_VOXT; continue; }
  8225. if(model->ci_s && model->ci_s < 4 && !model->cmap) model->errcode = M3D_ERR_CMAP;
  8226. reclen = model->ci_s + model->si_s + 3 + model->sk_s;
  8227. k = len / reclen;
  8228. model->voxtype = (m3dvt_t*)M3D_MALLOC(k * sizeof(m3dvt_t));
  8229. if(!model->voxtype) goto memerr;
  8230. memset(model->voxtype, 0, k * sizeof(m3dvt_t));
  8231. model->numvoxtype = 0;
  8232. for(i = 0, data += sizeof(m3dchunk_t); data < chunk && i < k; i++) {
  8233. switch(model->ci_s) {
  8234. case 1: model->voxtype[i].color = model->cmap ? model->cmap[data[0]] : 0; data++; break;
  8235. case 2: model->voxtype[i].color = model->cmap ? model->cmap[*((uint16_t*)data)] : 0; data += 2; break;
  8236. case 4: model->voxtype[i].color = *((uint32_t*)data); data += 4; break;
  8237. }
  8238. M3D_GETSTR(name);
  8239. model->voxtype[i].materialid = M3D_UNDEF;
  8240. if(name) {
  8241. model->voxtype[i].name = name;
  8242. }
  8243. j = *data++;
  8244. model->voxtype[i].rotation = j & 0xBF;
  8245. model->voxtype[i].voxshape = ((j & 0x40) << 2) | *data++;
  8246. model->voxtype[i].numitem = *data++;
  8247. model->voxtype[i].skinid = M3D_UNDEF;
  8248. data = _m3d_getidx(data, model->sk_s, &model->voxtype[i].skinid);
  8249. if(model->voxtype[i].numitem) {
  8250. model->voxtype[i].item = (m3dvi_t*)M3D_MALLOC(model->voxtype[i].numitem * sizeof(m3dvi_t));
  8251. if(!model->voxtype[i].item) goto memerr;
  8252. memset(model->voxtype[i].item, 0, model->voxtype[i].numitem * sizeof(m3dvi_t));
  8253. for(j = 0; j < model->voxtype[i].numitem; j++) {
  8254. model->voxtype[i].item[j].count = *data++;
  8255. model->voxtype[i].item[j].count |= (*data++) << 8;
  8256. M3D_GETSTR(model->voxtype[i].item[j].name);
  8257. }
  8258. }
  8259. }
  8260. model->numvoxtype = i;
  8261. if(k != model->numvoxtype) {
  8262. model->voxtype = (m3dvt_t*)M3D_REALLOC(model->voxtype, model->numvoxtype * sizeof(m3dvt_t));
  8263. if(!model->voxtype) goto memerr;
  8264. }
  8265. } else
  8266. if(M3D_CHUNKMAGIC(data, 'V','O','X','D')) {
  8267. data += sizeof(m3dchunk_t);
  8268. M3D_GETSTR(name);
  8269. M3D_LOG("Voxel Data Layer");
  8270. M3D_LOG(name);
  8271. if(model->vd_s > 4 || model->vp_s > 2) { M3D_LOG("No voxel index size"); model->errcode = M3D_ERR_UNKVOX; continue; }
  8272. if(!model->voxtype) { M3D_LOG("No voxel type chunk before voxel data"); model->errcode = M3D_ERR_VOXT; }
  8273. i = model->numvoxel++;
  8274. model->voxel = (m3dvx_t*)M3D_REALLOC(model->voxel, model->numvoxel * sizeof(m3dvx_t));
  8275. if(!model->voxel) goto memerr;
  8276. memset(&model->voxel[i], 0, sizeof(m3dvx_t));
  8277. model->voxel[i].name = name;
  8278. switch(model->vd_s) {
  8279. case 1:
  8280. model->voxel[i].x = (int32_t)((int8_t)data[0]);
  8281. model->voxel[i].y = (int32_t)((int8_t)data[1]);
  8282. model->voxel[i].z = (int32_t)((int8_t)data[2]);
  8283. model->voxel[i].w = (uint32_t)(data[3]);
  8284. model->voxel[i].h = (uint32_t)(data[4]);
  8285. model->voxel[i].d = (uint32_t)(data[5]);
  8286. data += 6;
  8287. break;
  8288. case 2:
  8289. model->voxel[i].x = (int32_t)(*((int16_t*)(data+0)));
  8290. model->voxel[i].y = (int32_t)(*((int16_t*)(data+2)));
  8291. model->voxel[i].z = (int32_t)(*((int16_t*)(data+4)));
  8292. model->voxel[i].w = (uint32_t)(*((uint16_t*)(data+6)));
  8293. model->voxel[i].h = (uint32_t)(*((uint16_t*)(data+8)));
  8294. model->voxel[i].d = (uint32_t)(*((uint16_t*)(data+10)));
  8295. data += 12;
  8296. break;
  8297. case 4:
  8298. model->voxel[i].x = *((int32_t*)(data+0));
  8299. model->voxel[i].y = *((int32_t*)(data+4));
  8300. model->voxel[i].z = *((int32_t*)(data+8));
  8301. model->voxel[i].w = *((uint32_t*)(data+12));
  8302. model->voxel[i].h = *((uint32_t*)(data+16));
  8303. model->voxel[i].d = *((uint32_t*)(data+20));
  8304. data += 24;
  8305. break;
  8306. }
  8307. model->voxel[i].uncertain = *data++;
  8308. model->voxel[i].groupid = *data++;
  8309. k = model->voxel[i].w * model->voxel[i].h * model->voxel[i].d;
  8310. model->voxel[i].data = (M3D_VOXEL*)M3D_MALLOC(k * sizeof(M3D_VOXEL));
  8311. if(!model->voxel[i].data) goto memerr;
  8312. memset(model->voxel[i].data, 0xff, k * sizeof(M3D_VOXEL));
  8313. for(j = 0; data < chunk && j < k;) {
  8314. l = ((*data++) & 0x7F) + 1;
  8315. if(data[-1] & 0x80) {
  8316. data = _m3d_getidx(data, model->vp_s, &mi);
  8317. while(l-- && j < k) model->voxel[i].data[j++] = (M3D_VOXEL)mi;
  8318. } else
  8319. while(l-- && j < k) {
  8320. data = _m3d_getidx(data, model->vp_s, &mi);
  8321. model->voxel[i].data[j++] = (M3D_VOXEL)mi;
  8322. }
  8323. }
  8324. } else
  8325. if(M3D_CHUNKMAGIC(data, 'S','H','P','E')) {
  8326. data += sizeof(m3dchunk_t);
  8327. M3D_GETSTR(name);
  8328. M3D_LOG("Mathematical Shape");
  8329. M3D_LOG(name);
  8330. i = model->numshape++;
  8331. model->shape = (m3dh_t*)M3D_REALLOC(model->shape, model->numshape * sizeof(m3dh_t));
  8332. if(!model->shape) goto memerr;
  8333. h = &model->shape[i];
  8334. h->numcmd = 0;
  8335. h->cmd = NULL;
  8336. h->name = name;
  8337. h->group = M3D_UNDEF;
  8338. data = _m3d_getidx(data, model->bi_s, &h->group);
  8339. if(h->group != M3D_UNDEF && h->group >= model->numbone) {
  8340. M3D_LOG("Unknown bone id as shape group in shape");
  8341. M3D_LOG(name);
  8342. h->group = M3D_UNDEF;
  8343. model->errcode = M3D_ERR_SHPE;
  8344. }
  8345. while(data < chunk) {
  8346. i = h->numcmd++;
  8347. h->cmd = (m3dc_t*)M3D_REALLOC(h->cmd, h->numcmd * sizeof(m3dc_t));
  8348. if(!h->cmd) goto memerr;
  8349. h->cmd[i].type = *data++;
  8350. if(h->cmd[i].type & 0x80) {
  8351. h->cmd[i].type &= 0x7F;
  8352. h->cmd[i].type |= (*data++ << 7);
  8353. }
  8354. if(h->cmd[i].type >= (unsigned int)(sizeof(m3d_commandtypes)/sizeof(m3d_commandtypes[0]))) {
  8355. M3D_LOG("Unknown shape command in");
  8356. M3D_LOG(h->name);
  8357. model->errcode = M3D_ERR_UNKCMD;
  8358. break;
  8359. }
  8360. cd = &m3d_commandtypes[h->cmd[i].type];
  8361. h->cmd[i].arg = (uint32_t*)M3D_MALLOC(cd->p * sizeof(uint32_t));
  8362. if(!h->cmd[i].arg) goto memerr;
  8363. memset(h->cmd[i].arg, 0, cd->p * sizeof(uint32_t));
  8364. for(k = n = 0, l = cd->p; k < l; k++)
  8365. switch(cd->a[((k - n) % (cd->p - n)) + n]) {
  8366. case m3dcp_mi_t:
  8367. h->cmd[i].arg[k] = M3D_NOTDEFINED;
  8368. M3D_GETSTR(name);
  8369. if(name) {
  8370. for(n = 0; n < model->nummaterial; n++)
  8371. if(!strcmp(name, model->material[n].name)) {
  8372. h->cmd[i].arg[k] = n;
  8373. break;
  8374. }
  8375. if(h->cmd[i].arg[k] == M3D_NOTDEFINED) model->errcode = M3D_ERR_MTRL;
  8376. }
  8377. break;
  8378. case m3dcp_vc_t:
  8379. f = 0.0f;
  8380. switch(model->vc_s) {
  8381. case 1: f = (float)((int8_t)data[0]) / 127; break;
  8382. case 2: f = (float)(*((int16_t*)(data+0))) / 32767; break;
  8383. case 4: f = (float)(*((float*)(data+0))); break;
  8384. case 8: f = (float)(*((double*)(data+0))); break;
  8385. }
  8386. memcpy(&h->cmd[i].arg[k], &f, 4);
  8387. data += model->vc_s;
  8388. break;
  8389. case m3dcp_hi_t: data = _m3d_getidx(data, model->hi_s, &h->cmd[i].arg[k]); break;
  8390. case m3dcp_fi_t: data = _m3d_getidx(data, model->fi_s, &h->cmd[i].arg[k]); break;
  8391. case m3dcp_ti_t: data = _m3d_getidx(data, model->ti_s, &h->cmd[i].arg[k]); break;
  8392. case m3dcp_qi_t:
  8393. case m3dcp_vi_t: data = _m3d_getidx(data, model->vi_s, &h->cmd[i].arg[k]); break;
  8394. case m3dcp_i1_t: data = _m3d_getidx(data, 1, &h->cmd[i].arg[k]); break;
  8395. case m3dcp_i2_t: data = _m3d_getidx(data, 2, &h->cmd[i].arg[k]); break;
  8396. case m3dcp_i4_t: data = _m3d_getidx(data, 4, &h->cmd[i].arg[k]); break;
  8397. case m3dcp_va_t: data = _m3d_getidx(data, 4, &h->cmd[i].arg[k]);
  8398. n = k + 1; l += (h->cmd[i].arg[k] - 1) * (cd->p - k - 1);
  8399. h->cmd[i].arg = (uint32_t*)M3D_REALLOC(h->cmd[i].arg, l * sizeof(uint32_t));
  8400. if(!h->cmd[i].arg) goto memerr;
  8401. memset(&h->cmd[i].arg[k + 1], 0, (l - k - 1) * sizeof(uint32_t));
  8402. break;
  8403. }
  8404. }
  8405. } else
  8406. if(M3D_CHUNKMAGIC(data, 'L','B','L','S')) {
  8407. data += sizeof(m3dchunk_t);
  8408. M3D_GETSTR(name);
  8409. M3D_GETSTR(lang);
  8410. M3D_LOG("Label list");
  8411. if(name) { M3D_LOG(name); }
  8412. if(lang) { M3D_LOG(lang); }
  8413. if(model->ci_s && model->ci_s < 4 && !model->cmap) model->errcode = M3D_ERR_CMAP;
  8414. k = 0;
  8415. switch(model->ci_s) {
  8416. case 1: k = model->cmap ? model->cmap[data[0]] : 0; data++; break;
  8417. case 2: k = model->cmap ? model->cmap[*((uint16_t*)data)] : 0; data += 2; break;
  8418. case 4: k = *((uint32_t*)data); data += 4; break;
  8419. }
  8420. reclen = model->vi_s + model->si_s;
  8421. i = model->numlabel; model->numlabel += len / reclen;
  8422. model->label = (m3dl_t*)M3D_REALLOC(model->label, model->numlabel * sizeof(m3dl_t));
  8423. if(!model->label) goto memerr;
  8424. memset(&model->label[i], 0, (model->numlabel - i) * sizeof(m3dl_t));
  8425. for(; data < chunk && i < model->numlabel; i++) {
  8426. model->label[i].name = name;
  8427. model->label[i].lang = lang;
  8428. model->label[i].color = k;
  8429. data = _m3d_getidx(data, model->vi_s, &model->label[i].vertexid);
  8430. M3D_GETSTR(model->label[i].text);
  8431. }
  8432. } else
  8433. if(M3D_CHUNKMAGIC(data, 'A','C','T','N')) {
  8434. M3D_LOG("Action");
  8435. i = model->numaction++;
  8436. model->action = (m3da_t*)M3D_REALLOC(model->action, model->numaction * sizeof(m3da_t));
  8437. if(!model->action) goto memerr;
  8438. a = &model->action[i];
  8439. data += sizeof(m3dchunk_t);
  8440. M3D_GETSTR(a->name);
  8441. M3D_LOG(a->name);
  8442. a->numframe = *((uint16_t*)data); data += 2;
  8443. if(a->numframe < 1) {
  8444. model->numaction--;
  8445. } else {
  8446. a->durationmsec = *((uint32_t*)data); data += 4;
  8447. a->frame = (m3dfr_t*)M3D_MALLOC(a->numframe * sizeof(m3dfr_t));
  8448. if(!a->frame) goto memerr;
  8449. for(i = 0; data < chunk && i < a->numframe; i++) {
  8450. a->frame[i].msec = *((uint32_t*)data); data += 4;
  8451. a->frame[i].numtransform = 0; a->frame[i].transform = NULL;
  8452. data = _m3d_getidx(data, model->fc_s, &a->frame[i].numtransform);
  8453. if(a->frame[i].numtransform > 0) {
  8454. a->frame[i].transform = (m3dtr_t*)M3D_MALLOC(a->frame[i].numtransform * sizeof(m3dtr_t));
  8455. for(j = 0; j < a->frame[i].numtransform; j++) {
  8456. data = _m3d_getidx(data, model->bi_s, &a->frame[i].transform[j].boneid);
  8457. data = _m3d_getidx(data, model->vi_s, &a->frame[i].transform[j].pos);
  8458. data = _m3d_getidx(data, model->vi_s, &a->frame[i].transform[j].ori);
  8459. }
  8460. }
  8461. }
  8462. }
  8463. } else {
  8464. i = model->numextra++;
  8465. model->extra = (m3dchunk_t**)M3D_REALLOC(model->extra, model->numextra * sizeof(m3dchunk_t*));
  8466. if(!model->extra) goto memerr;
  8467. model->extra[i] = (m3dchunk_t*)data;
  8468. }
  8469. }
  8470. if(model) {
  8471. M3D_LOG("Post-process");
  8472. #ifndef M3D_NOVOXELS
  8473. if(model->numvoxel && model->voxel) {
  8474. M3D_LOG("Converting voxels into vertices and mesh");
  8475. enorm = model->numvertex; model->numvertex += 6;
  8476. model->vertex = (m3dv_t*)M3D_REALLOC(model->vertex, model->numvertex * sizeof(m3dv_t));
  8477. if(!model->vertex) goto memerr;
  8478. memset(&model->vertex[enorm], 0, 6 * sizeof(m3dv_t));
  8479. for(l = 0; l < 6; l++)
  8480. model->vertex[enorm+l].skinid = M3D_UNDEF;
  8481. model->vertex[enorm+0].y = (M3D_FLOAT)-1.0;
  8482. model->vertex[enorm+1].z = (M3D_FLOAT)-1.0;
  8483. model->vertex[enorm+2].x = (M3D_FLOAT)-1.0;
  8484. model->vertex[enorm+3].y = (M3D_FLOAT)1.0;
  8485. model->vertex[enorm+4].z = (M3D_FLOAT)1.0;
  8486. model->vertex[enorm+5].x = (M3D_FLOAT)1.0;
  8487. min_x = min_y = min_z = 2147483647L;
  8488. max_x = max_y = max_z = -2147483647L;
  8489. for(i = 0; i < model->numvoxel; i++) {
  8490. if(model->voxel[i].x + (int32_t)model->voxel[i].w > max_x) max_x = model->voxel[i].x + (int32_t)model->voxel[i].w;
  8491. if(model->voxel[i].x < min_x) min_x = model->voxel[i].x;
  8492. if(model->voxel[i].y + (int32_t)model->voxel[i].h > max_y) max_y = model->voxel[i].y + (int32_t)model->voxel[i].h;
  8493. if(model->voxel[i].y < min_y) min_y = model->voxel[i].y;
  8494. if(model->voxel[i].z + (int32_t)model->voxel[i].d > max_z) max_z = model->voxel[i].z + (int32_t)model->voxel[i].d;
  8495. if(model->voxel[i].z < min_z) min_z = model->voxel[i].z;
  8496. }
  8497. i = (-min_x > max_x ? -min_x : max_x);
  8498. j = (-min_y > max_y ? -min_y : max_y);
  8499. k = (-min_z > max_z ? -min_z : max_z);
  8500. if(j > i) i = j;
  8501. if(k > i) i = k;
  8502. if(i <= 1) i = 1;
  8503. w = (M3D_FLOAT)1.0 / (M3D_FLOAT)i;
  8504. if(i >= 254) model->vc_s = 2;
  8505. if(i >= 65534) model->vc_s = 4;
  8506. for(i = 0; i < model->numvoxel; i++) {
  8507. sx = model->voxel[i].w; sz = model->voxel[i].d; sy = model->voxel[i].h;
  8508. for(y = 0, j = 0; y < sy; y++)
  8509. for(z = 0; z < sz; z++)
  8510. for(x = 0; x < sx; x++, j++)
  8511. if(model->voxel[i].data[j] < model->numvoxtype) {
  8512. k = 0;
  8513. k = n = am = 0;
  8514. if(!y || model->voxel[i].data[j - sx*sz] >= model->numvoxtype) { n++; am |= 1; k |= 1|2|4|8; }
  8515. if(!z || model->voxel[i].data[j - sx] >= model->numvoxtype) { n++; am |= 2; k |= 1|2|16|32; }
  8516. if(!x || model->voxel[i].data[j - 1] >= model->numvoxtype) { n++; am |= 4; k |= 1|4|16|64; }
  8517. if(y == sy-1 || model->voxel[i].data[j + sx*sz] >= model->numvoxtype) { n++; am |= 8; k |= 16|32|64|128; }
  8518. if(z == sz-1 || model->voxel[i].data[j + sx] >= model->numvoxtype) { n++; am |= 16; k |= 4|8|64|128; }
  8519. if(x == sx-1 || model->voxel[i].data[j + 1] >= model->numvoxtype) { n++; am |= 32; k |= 2|8|32|128; }
  8520. if(k) {
  8521. memset(edge, 255, sizeof(edge));
  8522. for(l = 0, len = 1, reclen = model->numvertex; l < 8; l++, len <<= 1)
  8523. if(k & len) edge[l] = model->numvertex++;
  8524. model->vertex = (m3dv_t*)M3D_REALLOC(model->vertex, model->numvertex * sizeof(m3dv_t));
  8525. if(!model->vertex) goto memerr;
  8526. memset(&model->vertex[reclen], 0, (model->numvertex-reclen) * sizeof(m3dv_t));
  8527. for(l = reclen; l < model->numvertex; l++) {
  8528. model->vertex[l].skinid = model->voxtype[model->voxel[i].data[j]].skinid;
  8529. model->vertex[l].color = model->voxtype[model->voxel[i].data[j]].color;
  8530. }
  8531. l = reclen;
  8532. if(k & 1) {
  8533. model->vertex[l].x = (model->voxel[i].x + x) * w;
  8534. model->vertex[l].y = (model->voxel[i].y + y) * w;
  8535. model->vertex[l].z = (model->voxel[i].z + z) * w;
  8536. l++;
  8537. }
  8538. if(k & 2) {
  8539. model->vertex[l].x = (model->voxel[i].x + x + 1) * w;
  8540. model->vertex[l].y = (model->voxel[i].y + y) * w;
  8541. model->vertex[l].z = (model->voxel[i].z + z) * w;
  8542. l++;
  8543. }
  8544. if(k & 4) {
  8545. model->vertex[l].x = (model->voxel[i].x + x) * w;
  8546. model->vertex[l].y = (model->voxel[i].y + y) * w;
  8547. model->vertex[l].z = (model->voxel[i].z + z + 1) * w;
  8548. l++;
  8549. }
  8550. if(k & 8) {
  8551. model->vertex[l].x = (model->voxel[i].x + x + 1) * w;
  8552. model->vertex[l].y = (model->voxel[i].y + y) * w;
  8553. model->vertex[l].z = (model->voxel[i].z + z + 1) * w;
  8554. l++;
  8555. }
  8556. if(k & 16) {
  8557. model->vertex[l].x = (model->voxel[i].x + x) * w;
  8558. model->vertex[l].y = (model->voxel[i].y + y + 1) * w;
  8559. model->vertex[l].z = (model->voxel[i].z + z) * w;
  8560. l++;
  8561. }
  8562. if(k & 32) {
  8563. model->vertex[l].x = (model->voxel[i].x + x + 1) * w;
  8564. model->vertex[l].y = (model->voxel[i].y + y + 1) * w;
  8565. model->vertex[l].z = (model->voxel[i].z + z) * w;
  8566. l++;
  8567. }
  8568. if(k & 64) {
  8569. model->vertex[l].x = (model->voxel[i].x + x) * w;
  8570. model->vertex[l].y = (model->voxel[i].y + y + 1) * w;
  8571. model->vertex[l].z = (model->voxel[i].z + z + 1) * w;
  8572. l++;
  8573. }
  8574. if(k & 128) {
  8575. model->vertex[l].x = (model->voxel[i].x + x + 1) * w;
  8576. model->vertex[l].y = (model->voxel[i].y + y + 1) * w;
  8577. model->vertex[l].z = (model->voxel[i].z + z + 1) * w;
  8578. l++;
  8579. }
  8580. n <<= 1;
  8581. l = model->numface; model->numface += n;
  8582. model->face = (m3df_t*)M3D_REALLOC(model->face, model->numface * sizeof(m3df_t));
  8583. if(!model->face) goto memerr;
  8584. memset(&model->face[l], 255, n * sizeof(m3df_t));
  8585. for(reclen = l; reclen < model->numface; reclen++)
  8586. model->face[reclen].materialid = model->voxtype[model->voxel[i].data[j]].materialid;
  8587. if(am & 1) {
  8588. model->face[l].vertex[0] = edge[0]; model->face[l].vertex[1] = edge[1]; model->face[l].vertex[2] = edge[2];
  8589. model->face[l+1].vertex[0] = edge[2]; model->face[l+1].vertex[1] = edge[1]; model->face[l+1].vertex[2] = edge[3];
  8590. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8591. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm;
  8592. l += 2;
  8593. }
  8594. if(am & 2) {
  8595. model->face[l].vertex[0] = edge[0]; model->face[l].vertex[1] = edge[4]; model->face[l].vertex[2] = edge[1];
  8596. model->face[l+1].vertex[0] = edge[1]; model->face[l+1].vertex[1] = edge[4]; model->face[l+1].vertex[2] = edge[5];
  8597. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8598. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm+1;
  8599. l += 2;
  8600. }
  8601. if(am & 4) {
  8602. model->face[l].vertex[0] = edge[0]; model->face[l].vertex[1] = edge[2]; model->face[l].vertex[2] = edge[4];
  8603. model->face[l+1].vertex[0] = edge[2]; model->face[l+1].vertex[1] = edge[6]; model->face[l+1].vertex[2] = edge[4];
  8604. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8605. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm+2;
  8606. l += 2;
  8607. }
  8608. if(am & 8) {
  8609. model->face[l].vertex[0] = edge[4]; model->face[l].vertex[1] = edge[6]; model->face[l].vertex[2] = edge[5];
  8610. model->face[l+1].vertex[0] = edge[5]; model->face[l+1].vertex[1] = edge[6]; model->face[l+1].vertex[2] = edge[7];
  8611. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8612. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm+3;
  8613. l += 2;
  8614. }
  8615. if(am & 16) {
  8616. model->face[l].vertex[0] = edge[2]; model->face[l].vertex[1] = edge[7]; model->face[l].vertex[2] = edge[6];
  8617. model->face[l+1].vertex[0] = edge[7]; model->face[l+1].vertex[1] = edge[2]; model->face[l+1].vertex[2] = edge[3];
  8618. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8619. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm+4;
  8620. l += 2;
  8621. }
  8622. if(am & 32) {
  8623. model->face[l].vertex[0] = edge[1]; model->face[l].vertex[1] = edge[5]; model->face[l].vertex[2] = edge[7];
  8624. model->face[l+1].vertex[0] = edge[1]; model->face[l+1].vertex[1] = edge[7]; model->face[l+1].vertex[2] = edge[3];
  8625. model->face[l].normal[0] = model->face[l].normal[1] = model->face[l].normal[2] =
  8626. model->face[l+1].normal[0] = model->face[l+1].normal[1] = model->face[l+1].normal[2] = enorm+5;
  8627. l += 2;
  8628. }
  8629. }
  8630. }
  8631. }
  8632. }
  8633. #endif
  8634. #ifndef M3D_NONORMALS
  8635. if(model->numface && model->face && neednorm) {
  8636. norm = (m3dv_t*)M3D_MALLOC(model->numface * sizeof(m3dv_t));
  8637. if(!norm) goto memerr;
  8638. for(i = 0, n = model->numvertex; i < model->numface; i++)
  8639. if(model->face[i].normal[0] == M3D_UNDEF) {
  8640. v0 = &model->vertex[model->face[i].vertex[0]];
  8641. v1 = &model->vertex[model->face[i].vertex[1]];
  8642. v2 = &model->vertex[model->face[i].vertex[2]];
  8643. va.x = v1->x - v0->x; va.y = v1->y - v0->y; va.z = v1->z - v0->z;
  8644. vb.x = v2->x - v0->x; vb.y = v2->y - v0->y; vb.z = v2->z - v0->z;
  8645. v0 = &norm[i];
  8646. v0->x = (va.y * vb.z) - (va.z * vb.y);
  8647. v0->y = (va.z * vb.x) - (va.x * vb.z);
  8648. v0->z = (va.x * vb.y) - (va.y * vb.x);
  8649. w = _m3d_rsq((v0->x * v0->x) + (v0->y * v0->y) + (v0->z * v0->z));
  8650. v0->x *= w; v0->y *= w; v0->z *= w;
  8651. model->face[i].normal[0] = model->face[i].vertex[0] + n;
  8652. model->face[i].normal[1] = model->face[i].vertex[1] + n;
  8653. model->face[i].normal[2] = model->face[i].vertex[2] + n;
  8654. }
  8655. M3D_LOG("Generating normals");
  8656. model->flags |= M3D_FLG_GENNORM;
  8657. model->numvertex <<= 1;
  8658. model->vertex = (m3dv_t*)M3D_REALLOC(model->vertex, model->numvertex * sizeof(m3dv_t));
  8659. if(!model->vertex) goto memerr;
  8660. memset(&model->vertex[n], 0, n * sizeof(m3dv_t));
  8661. for(i = 0; i < model->numface; i++)
  8662. for(j = 0; j < 3; j++) {
  8663. v0 = &model->vertex[model->face[i].vertex[j] + n];
  8664. v0->x += norm[i].x;
  8665. v0->y += norm[i].y;
  8666. v0->z += norm[i].z;
  8667. }
  8668. for(i = 0, v0 = &model->vertex[n]; i < n; i++, v0++) {
  8669. w = _m3d_rsq((v0->x * v0->x) + (v0->y * v0->y) + (v0->z * v0->z));
  8670. v0->x *= w; v0->y *= w; v0->z *= w;
  8671. v0->skinid = M3D_UNDEF;
  8672. }
  8673. M3D_FREE(norm);
  8674. }
  8675. #endif
  8676. if(model->numbone && model->bone && model->numskin && model->skin && model->numvertex && model->vertex) {
  8677. #ifndef M3D_NOWEIGHTS
  8678. M3D_LOG("Generating weight cross-reference");
  8679. for(i = 0; i < model->numvertex; i++) {
  8680. if(model->vertex[i].skinid < model->numskin) {
  8681. sk = &model->skin[model->vertex[i].skinid];
  8682. w = (M3D_FLOAT)0.0;
  8683. for(j = 0; j < M3D_NUMBONE && sk->boneid[j] != M3D_UNDEF && sk->weight[j] > (M3D_FLOAT)0.0; j++)
  8684. w += sk->weight[j];
  8685. for(j = 0; j < M3D_NUMBONE && sk->boneid[j] != M3D_UNDEF && sk->weight[j] > (M3D_FLOAT)0.0; j++) {
  8686. sk->weight[j] /= w;
  8687. b = &model->bone[sk->boneid[j]];
  8688. k = b->numweight++;
  8689. b->weight = (m3dw_t*)M3D_REALLOC(b->weight, b->numweight * sizeof(m3da_t));
  8690. if(!b->weight) goto memerr;
  8691. b->weight[k].vertexid = i;
  8692. b->weight[k].weight = sk->weight[j];
  8693. }
  8694. }
  8695. }
  8696. #endif
  8697. #ifndef M3D_NOANIMATION
  8698. M3D_LOG("Calculating bone transformation matrices");
  8699. for(i = 0; i < model->numbone; i++) {
  8700. b = &model->bone[i];
  8701. if(model->bone[i].parent == M3D_UNDEF) {
  8702. _m3d_mat((M3D_FLOAT*)&b->mat4, &model->vertex[b->pos], &model->vertex[b->ori]);
  8703. } else {
  8704. _m3d_mat((M3D_FLOAT*)&r, &model->vertex[b->pos], &model->vertex[b->ori]);
  8705. _m3d_mul((M3D_FLOAT*)&b->mat4, (M3D_FLOAT*)&model->bone[b->parent].mat4, (M3D_FLOAT*)&r);
  8706. }
  8707. }
  8708. for(i = 0; i < model->numbone; i++)
  8709. _m3d_inv((M3D_FLOAT*)&model->bone[i].mat4);
  8710. #endif
  8711. }
  8712. }
  8713. return model;
  8714. }
  8715. m3dtr_t *m3d_frame(m3d_t *model, M3D_INDEX actionid, M3D_INDEX frameid, m3dtr_t *skeleton)
  8716. {
  8717. unsigned int i;
  8718. M3D_INDEX s = frameid;
  8719. m3dfr_t *fr;
  8720. if(!model || !model->numbone || !model->bone || (actionid != M3D_UNDEF && (!model->action ||
  8721. actionid >= model->numaction || frameid >= model->action[actionid].numframe))) {
  8722. model->errcode = M3D_ERR_UNKFRAME;
  8723. return skeleton;
  8724. }
  8725. model->errcode = M3D_SUCCESS;
  8726. if(!skeleton) {
  8727. skeleton = (m3dtr_t*)M3D_MALLOC(model->numbone * sizeof(m3dtr_t));
  8728. if(!skeleton) {
  8729. model->errcode = M3D_ERR_ALLOC;
  8730. return NULL;
  8731. }
  8732. goto gen;
  8733. }
  8734. if(actionid == M3D_UNDEF || !frameid) {
  8735. gen: s = 0;
  8736. for(i = 0; i < model->numbone; i++) {
  8737. skeleton[i].boneid = i;
  8738. skeleton[i].pos = model->bone[i].pos;
  8739. skeleton[i].ori = model->bone[i].ori;
  8740. }
  8741. }
  8742. if(actionid < model->numaction && (frameid || !model->action[actionid].frame[0].msec)) {
  8743. for(; s <= frameid; s++) {
  8744. fr = &model->action[actionid].frame[s];
  8745. for(i = 0; i < fr->numtransform; i++) {
  8746. skeleton[fr->transform[i].boneid].pos = fr->transform[i].pos;
  8747. skeleton[fr->transform[i].boneid].ori = fr->transform[i].ori;
  8748. }
  8749. }
  8750. }
  8751. return skeleton;
  8752. }
  8753. #ifndef M3D_NOANIMATION
  8754. m3db_t *m3d_pose(m3d_t *model, M3D_INDEX actionid, uint32_t msec)
  8755. {
  8756. unsigned int i, j, l;
  8757. M3D_FLOAT r[16], t, c, d, s;
  8758. m3db_t *ret;
  8759. m3dv_t *v, *p, *f;
  8760. m3dtr_t *tmp;
  8761. m3dfr_t *fr;
  8762. if(!model || !model->numbone || !model->bone) {
  8763. model->errcode = M3D_ERR_UNKFRAME;
  8764. return NULL;
  8765. }
  8766. ret = (m3db_t*)M3D_MALLOC(model->numbone * sizeof(m3db_t));
  8767. if(!ret) {
  8768. model->errcode = M3D_ERR_ALLOC;
  8769. return NULL;
  8770. }
  8771. memcpy(ret, model->bone, model->numbone * sizeof(m3db_t));
  8772. for(i = 0; i < model->numbone; i++)
  8773. _m3d_inv((M3D_FLOAT*)&ret[i].mat4);
  8774. if(!model->action || actionid >= model->numaction) {
  8775. model->errcode = M3D_ERR_UNKFRAME;
  8776. return ret;
  8777. }
  8778. msec %= model->action[actionid].durationmsec;
  8779. model->errcode = M3D_SUCCESS;
  8780. fr = &model->action[actionid].frame[0];
  8781. for(j = l = 0; j < model->action[actionid].numframe && model->action[actionid].frame[j].msec <= msec; j++) {
  8782. fr = &model->action[actionid].frame[j];
  8783. l = fr->msec;
  8784. for(i = 0; i < fr->numtransform; i++) {
  8785. ret[fr->transform[i].boneid].pos = fr->transform[i].pos;
  8786. ret[fr->transform[i].boneid].ori = fr->transform[i].ori;
  8787. }
  8788. }
  8789. if(l != msec) {
  8790. model->vertex = (m3dv_t*)M3D_REALLOC(model->vertex, (model->numvertex + 2 * model->numbone) * sizeof(m3dv_t));
  8791. if(!model->vertex) {
  8792. free(ret);
  8793. model->errcode = M3D_ERR_ALLOC;
  8794. return NULL;
  8795. }
  8796. tmp = (m3dtr_t*)M3D_MALLOC(model->numbone * sizeof(m3dtr_t));
  8797. if(tmp) {
  8798. for(i = 0; i < model->numbone; i++) {
  8799. tmp[i].pos = ret[i].pos;
  8800. tmp[i].ori = ret[i].ori;
  8801. }
  8802. fr = &model->action[actionid].frame[j % model->action[actionid].numframe];
  8803. t = l >= fr->msec ? (M3D_FLOAT)1.0 : (M3D_FLOAT)(msec - l) / (M3D_FLOAT)(fr->msec - l);
  8804. for(i = 0; i < fr->numtransform; i++) {
  8805. tmp[fr->transform[i].boneid].pos = fr->transform[i].pos;
  8806. tmp[fr->transform[i].boneid].ori = fr->transform[i].ori;
  8807. }
  8808. for(i = 0, j = model->numvertex; i < model->numbone; i++) {
  8809. if(ret[i].pos != tmp[i].pos) {
  8810. p = &model->vertex[ret[i].pos];
  8811. f = &model->vertex[tmp[i].pos];
  8812. v = &model->vertex[j];
  8813. v->x = p->x + t * (f->x - p->x);
  8814. v->y = p->y + t * (f->y - p->y);
  8815. v->z = p->z + t * (f->z - p->z);
  8816. ret[i].pos = j++;
  8817. }
  8818. if(ret[i].ori != tmp[i].ori) {
  8819. p = &model->vertex[ret[i].ori];
  8820. f = &model->vertex[tmp[i].ori];
  8821. v = &model->vertex[j];
  8822. d = p->w * f->w + p->x * f->x + p->y * f->y + p->z * f->z;
  8823. if(d < 0) { d = -d; s = (M3D_FLOAT)-1.0; } else s = (M3D_FLOAT)1.0;
  8824. #if 0
  8825. a = (M3D_FLOAT)1.0 - t; b = t;
  8826. if(d < (M3D_FLOAT)0.999999) { c = acosf(d); b = 1 / sinf(c); a = sinf(a * c) * b; b *= sinf(t * c) * s; }
  8827. v->x = p->x * a + f->x * b;
  8828. v->y = p->y * a + f->y * b;
  8829. v->z = p->z * a + f->z * b;
  8830. v->w = p->w * a + f->w * b;
  8831. #else
  8832. c = t - (M3D_FLOAT)0.5; t += t * c * (t - (M3D_FLOAT)1.0) * (((M3D_FLOAT)1.0904 + d * ((M3D_FLOAT)-3.2452 +
  8833. d * ((M3D_FLOAT)3.55645 - d * (M3D_FLOAT)1.43519))) * c * c + ((M3D_FLOAT)0.848013 + d *
  8834. ((M3D_FLOAT)-1.06021 + d * (M3D_FLOAT)0.215638)));
  8835. v->x = p->x + t * (s * f->x - p->x);
  8836. v->y = p->y + t * (s * f->y - p->y);
  8837. v->z = p->z + t * (s * f->z - p->z);
  8838. v->w = p->w + t * (s * f->w - p->w);
  8839. d = _m3d_rsq(v->w * v->w + v->x * v->x + v->y * v->y + v->z * v->z);
  8840. v->x *= d; v->y *= d; v->z *= d; v->w *= d;
  8841. #endif
  8842. ret[i].ori = j++;
  8843. }
  8844. }
  8845. M3D_FREE(tmp);
  8846. }
  8847. }
  8848. for(i = 0; i < model->numbone; i++) {
  8849. if(ret[i].parent == M3D_UNDEF) {
  8850. _m3d_mat((M3D_FLOAT*)&ret[i].mat4, &model->vertex[ret[i].pos], &model->vertex[ret[i].ori]);
  8851. } else {
  8852. _m3d_mat((M3D_FLOAT*)&r, &model->vertex[ret[i].pos], &model->vertex[ret[i].ori]);
  8853. _m3d_mul((M3D_FLOAT*)&ret[i].mat4, (M3D_FLOAT*)&ret[ret[i].parent].mat4, (M3D_FLOAT*)&r);
  8854. }
  8855. }
  8856. return ret;
  8857. }
  8858. #endif
  8859. #endif
  8860. #if !defined(M3D_NODUP) && (!defined(M3D_NOIMPORTER) || defined(M3D_EXPORTER))
  8861. void m3d_free(m3d_t *model)
  8862. {
  8863. unsigned int i, j;
  8864. if(!model) return;
  8865. if(model->flags & M3D_FLG_FREERAW) M3D_FREE(model->raw);
  8866. if(model->tmap) M3D_FREE(model->tmap);
  8867. if(model->bone) {
  8868. for(i = 0; i < model->numbone; i++)
  8869. if(model->bone[i].weight)
  8870. M3D_FREE(model->bone[i].weight);
  8871. M3D_FREE(model->bone);
  8872. }
  8873. if(model->skin) M3D_FREE(model->skin);
  8874. if(model->vertex) M3D_FREE(model->vertex);
  8875. if(model->face) M3D_FREE(model->face);
  8876. if(model->voxtype) {
  8877. for(i = 0; i < model->numvoxtype; i++)
  8878. if(model->voxtype[i].item)
  8879. M3D_FREE(model->voxtype[i].item);
  8880. M3D_FREE(model->voxtype);
  8881. }
  8882. if(model->voxel) {
  8883. for(i = 0; i < model->numvoxel; i++)
  8884. if(model->voxel[i].data)
  8885. M3D_FREE(model->voxel[i].data);
  8886. M3D_FREE(model->voxel);
  8887. }
  8888. if(model->shape) {
  8889. for(i = 0; i < model->numshape; i++) {
  8890. if(model->shape[i].cmd) {
  8891. for(j = 0; j < model->shape[i].numcmd; j++)
  8892. if(model->shape[i].cmd[j].arg) M3D_FREE(model->shape[i].cmd[j].arg);
  8893. M3D_FREE(model->shape[i].cmd);
  8894. }
  8895. }
  8896. M3D_FREE(model->shape);
  8897. }
  8898. if(model->material && !(model->flags & M3D_FLG_MTLLIB)) {
  8899. for(i = 0; i < model->nummaterial; i++)
  8900. if(model->material[i].prop) M3D_FREE(model->material[i].prop);
  8901. M3D_FREE(model->material);
  8902. }
  8903. if(model->texture) {
  8904. for(i = 0; i < model->numtexture; i++)
  8905. if(model->texture[i].d) M3D_FREE(model->texture[i].d);
  8906. M3D_FREE(model->texture);
  8907. }
  8908. if(model->action) {
  8909. for(i = 0; i < model->numaction; i++) {
  8910. if(model->action[i].frame) {
  8911. for(j = 0; j < model->action[i].numframe; j++)
  8912. if(model->action[i].frame[j].transform) M3D_FREE(model->action[i].frame[j].transform);
  8913. M3D_FREE(model->action[i].frame);
  8914. }
  8915. }
  8916. M3D_FREE(model->action);
  8917. }
  8918. if(model->label) M3D_FREE(model->label);
  8919. if(model->inlined) M3D_FREE(model->inlined);
  8920. if(model->extra) M3D_FREE(model->extra);
  8921. free(model);
  8922. }
  8923. #endif
  8924. #endif
  8925. #endif
  8926. m3d_t *apck_model(apck_t *ctx, char *name);
  8927. #ifdef APCK_IMPLEMENTATION
  8928. /**
  8929. * Read in an ULEB128 number
  8930. */
  8931. uint8_t *apck_uleb128(uint8_t *ptr, uint64_t *value)
  8932. {
  8933. uint32_t shift = 0, b;
  8934. *value = 0;
  8935. do {
  8936. b = *ptr++;
  8937. *value |= ((b & 0x7f) << shift);
  8938. shift += 7;
  8939. } while(shift < 64 && (b & 0x80));
  8940. return ptr;
  8941. }
  8942. /**
  8943. * Calculate checksum
  8944. */
  8945. uint32_t apck_crc32(uint8_t *buf, uint32_t size)
  8946. {
  8947. static uint32_t crc32_lookup[256] = { 0 };
  8948. uint32_t crc32_val = 0xffffffff, i, j, d;
  8949. if(!crc32_lookup[1])
  8950. for(i = 0; i < 256; i++)
  8951. for(d = i, j = 0; j < 8; j++)
  8952. crc32_lookup[i] = d = d & 1 ? (d >> 1) ^ 0xedb88320 : d >> 1;
  8953. while(size--) crc32_val = (crc32_val >> 8) ^ crc32_lookup[(crc32_val & 0xff) ^ *buf++];
  8954. return crc32_val ^ 0xffffffff;
  8955. }
  8956. /**
  8957. * Initialize unpacker context
  8958. */
  8959. int apck_init(apck_t *ctx, char *engine, uint32_t version, apck_initcb_t initcb, apck_readcb_t readcb)
  8960. {
  8961. if(!ctx) return APCK_ERR_BADINP;
  8962. memset(ctx, 0, sizeof(apck_t));
  8963. if(engine) strncpy((char*)ctx->engine, engine, 12);
  8964. ctx->version = version;
  8965. ctx->initcb = initcb;
  8966. ctx->readcb = readcb;
  8967. return APCK_OK;
  8968. }
  8969. /**
  8970. * Read asset from archive into a newly allocated buffer. Supported by all ciphers.
  8971. */
  8972. uint8_t *apck_readbuf(apck_t *ctx, uint32_t archive, uint64_t offs, uint64_t size)
  8973. {
  8974. uint8_t *buf;
  8975. uint64_t len;
  8976. if(!ctx || !size || archive >= ctx->numarchive || offs >= ctx->archives[archive].size) return NULL;
  8977. len = (size + 255) & ~255;
  8978. if(!(buf = (uint8_t*)malloc(len))) return NULL;
  8979. apck_fileseek(ctx->archives[archive].f, offs);
  8980. if((size = apck_fileread(ctx->archives[archive].f, buf, len)) && ctx->readcb)
  8981. (*ctx->readcb)(ctx->archives[archive].enc, offs, buf, size);
  8982. if(!size) { free(buf); buf = NULL; }
  8983. return buf;
  8984. }
  8985. /**
  8986. * Read part of archive into an existing buffer. Not all ciphers supports this.
  8987. */
  8988. uint64_t apck_read(apck_t *ctx, uint32_t archive, uint64_t offs, uint8_t *buf, uint64_t size)
  8989. {
  8990. if(!ctx || !buf || !size || archive >= ctx->numarchive || offs >= ctx->archives[archive].size) return APCK_ERR_BADINP;
  8991. if(offs + size > ctx->archives[archive].size) size = ctx->archives[archive].size - offs;
  8992. apck_fileseek(ctx->archives[archive].f, offs);
  8993. if((size = apck_fileread(ctx->archives[archive].f, buf, size)) && ctx->readcb)
  8994. (*ctx->readcb)(ctx->archives[archive].enc, offs, buf, size);
  8995. return size;
  8996. }
  8997. /**
  8998. * Merge an asset into the global Asset Directory
  8999. */
  9000. static int _apck_merge_asset(apck_t *ctx, char *name, uint32_t a, uint32_t j, uint32_t n, uint64_t o, uint64_t s, uint64_t c)
  9001. {
  9002. uint32_t k = 0;
  9003. if(j != APCK_ATLAS)
  9004. for(k = 0; k < ctx->numfiles[j] && strcmp(ctx->files[j][k].name, name); k++);
  9005. if(j == APCK_ATLAS || k >= ctx->numfiles[j]) {
  9006. k = ctx->numfiles[j]++;
  9007. if(!(ctx->files[j] = (apck_file_t*)realloc(ctx->files[j], ctx->numfiles[j] * sizeof(apck_file_t)))) {
  9008. DBG(("unable to allocate files[%u] for '%s' (%u entries)\n", j, name, ctx->numfiles[j]));
  9009. ctx->numfiles[j] = 0;
  9010. return 0;
  9011. }
  9012. memset(&ctx->files[j][k], 0, sizeof(apck_file_t));
  9013. }
  9014. if(ctx->files[j][k].buf) { free(ctx->files[j][k].buf); ctx->files[j][k].buf = NULL; }
  9015. ctx->files[j][k].archive = a;
  9016. ctx->files[j][k].w = ctx->files[j][k].h = 0;
  9017. ctx->files[j][k].name = name;
  9018. ctx->files[j][k].str = n;
  9019. ctx->files[j][k].offs = o;
  9020. ctx->files[j][k].size = s;
  9021. ctx->files[j][k].comp = c;
  9022. return 1;
  9023. }
  9024. /**
  9025. * Helper to sort assets
  9026. */
  9027. int _apck_filecmp(const void *a, const void *b)
  9028. {
  9029. return strcmp(((apck_file_t*)a)->name, ((apck_file_t*)b)->name);
  9030. }
  9031. /**
  9032. * Add an archive to the context
  9033. */
  9034. int apck_load(apck_t *ctx, char *fn)
  9035. {
  9036. uint64_t n, m, o, s, c;
  9037. uint32_t a, i, j, k = 0;
  9038. uint64_t size;
  9039. uint8_t *comp, *orig, *ptr, *end;
  9040. apck_hdr_t hdr;
  9041. void *f, *enc;
  9042. char *str, *name;
  9043. if(!ctx || !fn || !*fn) return APCK_ERR_BADINP;
  9044. /* get header */
  9045. if(!(f = apck_fileopen(fn, &size))) return APCK_ERR_BADPCK;
  9046. if(!apck_fileread(f, &hdr, sizeof(hdr)) || memcmp(hdr.magic, APCK_MAGIC, 4) ||
  9047. hdr.size < 9 || hdr.hdr_size - sizeof(apck_hdr_t) > hdr.size ||
  9048. (ctx->engine[0] && memcmp(ctx->engine, hdr.engine, 12)) || (ctx->version && ctx->version < hdr.version) ||
  9049. (*((uint64_t*)hdr.enckey) && (!ctx->initcb || !ctx->readcb))) {
  9050. apck_fileclose(f);
  9051. return APCK_ERR_BADPCK;
  9052. }
  9053. if(!(comp = (uint8_t*)malloc(hdr.hdr_size - sizeof(apck_hdr_t)))) {
  9054. apck_fileclose(f);
  9055. return APCK_ERR_NOMEM;
  9056. }
  9057. if(!(orig = (uint8_t*)malloc(hdr.size))) {
  9058. free(comp);
  9059. apck_fileclose(f);
  9060. return APCK_ERR_NOMEM;
  9061. }
  9062. /* we can't use apck_read yet, because the archive isn't registered yet */
  9063. enc = *((uint64_t*)hdr.enckey) ? (*ctx->initcb)(hdr.enckey) : NULL;
  9064. if(!apck_fileread(f, comp, hdr.hdr_size - sizeof(apck_hdr_t)) ||
  9065. (enc && (*ctx->readcb)(enc, sizeof(apck_hdr_t), comp, hdr.hdr_size - sizeof(apck_hdr_t))) ||
  9066. stbi_zlib_decode_buffer((char*)orig, (int)hdr.size, (char*)comp, (int)(hdr.hdr_size - sizeof(apck_hdr_t))) < 1 ||
  9067. apck_crc32(orig, hdr.size) != hdr.chksum || *((uint32_t*)orig) < 4 || *((uint32_t*)orig) >= hdr.size) {
  9068. if(enc) free(enc);
  9069. free(comp);
  9070. free(orig);
  9071. apck_fileclose(f);
  9072. return APCK_ERR_BADPCK;
  9073. }
  9074. free(comp);
  9075. /* add the archive to the list */
  9076. a = ctx->numarchive++;
  9077. if(!(ctx->archives = (apck_archive_t*)realloc(ctx->archives, ctx->numarchive * sizeof(apck_archive_t)))) {
  9078. ctx->numarchive = 0;
  9079. return APCK_ERR_NOMEM;
  9080. }
  9081. ctx->archives[a].f = f;
  9082. ctx->archives[a].size = size;
  9083. ctx->archives[a].str = orig;
  9084. ctx->archives[a].enc = enc;
  9085. ctx->archives[a].aidx = ctx->numfiles[APCK_ATLAS];
  9086. /* merge its asset directory with the existing one */
  9087. ptr = orig + *((uint32_t*)orig);
  9088. end = orig + hdr.size;
  9089. for(j = 0; j < APCK_NUMTYPES && ptr < end; j++) {
  9090. ptr = apck_uleb128(ptr, &m);
  9091. for(i = 0; i < m && ptr < end; i++) {
  9092. ptr = apck_uleb128(ptr, &n);
  9093. ptr = apck_uleb128(ptr, &o);
  9094. ptr = apck_uleb128(ptr, &s);
  9095. ptr = apck_uleb128(ptr, &c);
  9096. o += hdr.hdr_size;
  9097. name = (char*)orig + n;
  9098. if(j < APCK_FONT) {
  9099. /* locales need special treatment */
  9100. if(!i) {
  9101. for(k = 0; k < APCK_FONT && ctx->files[k] && strcmp(ctx->files[k][0].name, name); k++);
  9102. if(k < APCK_FONT) {
  9103. if(!ctx->files[k]) {
  9104. if(!_apck_merge_asset(ctx, name, a, k, n, 0, 0, 0) || !ctx->files[k]) k = APCK_FONT;
  9105. }
  9106. if(k < APCK_FONT && (comp = apck_readbuf(ctx, a, o, c))) {
  9107. if((str = (char*)malloc(s))) {
  9108. if(stbi_zlib_decode_buffer((char*)str, (int)s, (char*)comp, (int)c) < 1 ||
  9109. !_apck_merge_locale(ctx, k, str, s)) {
  9110. k = APCK_FONT; DBG(("unable to uncompress locale '%s' from '%s'\n", name, fn));
  9111. }
  9112. free(str);
  9113. } else { k = APCK_FONT; DBG(("unable to allocate locale '%s' from '%s' (%u bytes)\n", name, fn, (uint32_t)s)); }
  9114. free(comp);
  9115. } else { k = APCK_FONT; DBG(("unable to read locale '%s' from '%s'\n", name, fn)); }
  9116. }
  9117. } else
  9118. if(k < APCK_FONT) {
  9119. /* voices and images with text for this locale */
  9120. _apck_merge_asset(ctx, name, a, k, n, o, s, c);
  9121. }
  9122. } else {
  9123. /* every other asset */
  9124. _apck_merge_asset(ctx, name, a, j, n, o, s, c);
  9125. }
  9126. }
  9127. }
  9128. /* sort assets by name so that we can do an O(log2) search later */
  9129. for(j = 0; j < APCK_FONT; j++)
  9130. if(ctx->files[j] && ctx->numfiles[j] > 1)
  9131. qsort(&ctx->files[j][1], ctx->numfiles[j] - 1, sizeof(apck_file_t), _apck_filecmp);
  9132. for(; j < APCK_NUMTYPES; j++)
  9133. if(ctx->files[j] && ctx->numfiles[j] && j != APCK_ATLAS)
  9134. qsort(ctx->files[j], ctx->numfiles[j], sizeof(apck_file_t), _apck_filecmp);
  9135. return APCK_OK;
  9136. }
  9137. /**
  9138. * Free buffer for one particular asset
  9139. */
  9140. void _apck_asset_free(apck_file_t *file, int type)
  9141. {
  9142. if(file && file->buf) {
  9143. switch(type) {
  9144. case APCK_MODEL: m3d_free((m3d_t*)file->buf); break;
  9145. case APCK_SPRITE: apck_sprite_free((apck_sprite_t*)file->buf); break;
  9146. case APCK_MAP: apck_map_free((apck_map_t*)file->buf); break;
  9147. default: free(file->buf); break;
  9148. }
  9149. file->buf = NULL;
  9150. }
  9151. }
  9152. /**
  9153. * Free all resources
  9154. */
  9155. int apck_free(apck_t *ctx)
  9156. {
  9157. uint32_t i, j;
  9158. if(!ctx) return APCK_ERR_BADINP;
  9159. if(ctx->archives) {
  9160. for(i = 0; i < ctx->numarchive; i++) {
  9161. if(ctx->archives[i].f) apck_fileclose(ctx->archives[i].f);
  9162. if(ctx->archives[i].str) free(ctx->archives[i].str);
  9163. if(ctx->archives[i].enc) free(ctx->archives[i].enc);
  9164. }
  9165. free(ctx->archives);
  9166. }
  9167. for(j = 0; j < APCK_NUMTYPES; j++)
  9168. if(ctx->files[j]) {
  9169. for(i = 0; i < ctx->numfiles[j]; i++)
  9170. _apck_asset_free(&ctx->files[j][i], j);
  9171. free(ctx->files[j]);
  9172. }
  9173. for(i = 0; i < APCK_FONT; i++)
  9174. if(ctx->msgstr[i]) free(ctx->msgstr[i]);
  9175. if(ctx->font) {
  9176. ssfn_free(ctx->font);
  9177. free(ctx->font);
  9178. }
  9179. memset(ctx, 0, sizeof(apck_t));
  9180. return APCK_OK;
  9181. }
  9182. /**
  9183. * Look up an asset in the Global Asset Directory
  9184. */
  9185. apck_file_t *apck_lookup(apck_t *ctx, int type, char *name)
  9186. {
  9187. apck_file_t *dir;
  9188. int s, e, h, m;
  9189. if(!ctx || type < 0 || type >= APCK_NUMTYPES || !name || !*name || !ctx->files[type] || !ctx->numfiles[type])
  9190. return NULL;
  9191. /* use binary search */
  9192. dir = ctx->files[type];
  9193. s = !(type >= APCK_FONT);
  9194. e = ctx->numfiles[type] - 1;
  9195. while(s <= e) {
  9196. h = ((e + s) >> 1);
  9197. m = strcmp(dir[h].name, name);
  9198. if(!m) return &dir[h];
  9199. if(m > 0) e = h - 1; else s = h + 1;
  9200. }
  9201. return NULL;
  9202. }
  9203. /**
  9204. * Free internal cache of one particular asset
  9205. */
  9206. int apck_release(apck_t *ctx, int type, char *name)
  9207. {
  9208. if(!ctx || type < 0 || type >= APCK_NUMTYPES || !name || !*name)
  9209. return APCK_ERR_BADINP;
  9210. _apck_asset_free(apck_lookup(ctx, type, name), type);
  9211. return APCK_OK;
  9212. }
  9213. /**
  9214. * Look up and return any arbitrary asset
  9215. */
  9216. uint8_t *apck_asset(apck_t *ctx, int type, char *name, uint64_t *size)
  9217. {
  9218. apck_file_t *file = NULL;
  9219. uint8_t *buf, *comp;
  9220. if(size) *size = 0;
  9221. if(!ctx || type > APCK_MAP || type >= APCK_NUMTYPES || !name || !*name)
  9222. return NULL;
  9223. if((file = apck_lookup(ctx, type, name))) {
  9224. /* we have this asset, let's see if we have cached its contents already */
  9225. if(!file->buf) {
  9226. if(file->size && (comp = apck_readbuf(ctx, file->archive, file->offs, file->comp ? file->comp : file->size))) {
  9227. if(file->comp) {
  9228. /* we got the data from the archive, uncompress it */
  9229. if((buf = (uint8_t*)malloc(file->size))) {
  9230. if(stbi_zlib_decode_buffer((char*)buf, (int)file->size, (char*)comp, (int)file->comp) < 1) {
  9231. DBG(("unable to uncompress asset '%s'\n", name));
  9232. free(buf);
  9233. file->size = file->comp = 0;
  9234. } else
  9235. file->buf = buf;
  9236. } else { DBG(("unable to allocate asset '%s' (%u bytes)\n", name, (uint32_t)file->size)); }
  9237. free(comp);
  9238. } else file->buf = comp;
  9239. } else { DBG(("unable to read asset '%s'\n", name)); }
  9240. }
  9241. if(size) *size = file->size;
  9242. return (uint8_t*)file->buf;
  9243. }
  9244. return NULL;
  9245. }
  9246. /**
  9247. * Look up and set the font to be used by apck_text()
  9248. */
  9249. int apck_font(apck_t *ctx, char *name)
  9250. {
  9251. apck_file_t *file = NULL;
  9252. uint8_t *buf, *comp;
  9253. if(!ctx || !name || !*name)
  9254. return APCK_ERR_BADINP;
  9255. if(!ctx->font) {
  9256. if(!(ctx->font = (ssfn_t*)malloc(sizeof(ssfn_t))))
  9257. return APCK_ERR_NOMEM;
  9258. memset(ctx->font, 0, sizeof(ssfn_t));
  9259. } else
  9260. ssfn_free(ctx->font);
  9261. if((file = apck_lookup(ctx, APCK_FONT, name))) {
  9262. /* we have this asset, let's see if we have cached its contents already */
  9263. if(!file->buf) {
  9264. if(file->comp && (comp = apck_readbuf(ctx, file->archive, file->offs, file->comp))) {
  9265. /* we got the data from the archive, uncompress it */
  9266. if((buf = (uint8_t*)malloc(file->size))) {
  9267. if(stbi_zlib_decode_buffer((char*)buf, (int)file->size, (char*)comp, (int)file->comp) < 1 || memcmp(buf, "SFN2", 4)) {
  9268. DBG(("unable to uncompress font '%s'\n", name));
  9269. file->size = file->comp = 0;
  9270. free(buf);
  9271. } else
  9272. file->buf = buf;
  9273. } else { DBG(("unable to allocate font '%s' (%u bytes)\n", name, (uint32_t)file->size)); }
  9274. free(comp);
  9275. } else { DBG(("unable to read font '%s'\n", name)); }
  9276. }
  9277. if(ctx->font && file->buf)
  9278. ssfn_load(ctx->font, file->buf);
  9279. return APCK_OK;
  9280. }
  9281. return APCK_ERR_BADINP;
  9282. }
  9283. /**
  9284. * Render localized text and return a pixel buffer as if the were an asset stored in archive
  9285. */
  9286. uint32_t *apck_text(apck_t *ctx, char *msgid, uint32_t color, int fontstyle, int fontsize, int *w, int *h)
  9287. {
  9288. ssfn_buf_t buf = { 0 };
  9289. char *msgstr;
  9290. int ret;
  9291. if(w) *w = 0;
  9292. if(h) *h = 0;
  9293. if(!ctx || !ctx->font || !(color & 0xfc000000) || !(msgstr = apck_msgstr(ctx, msgid)) ||
  9294. ssfn_select(ctx->font, SSFN_FAMILY_ANY, NULL, fontstyle | SSFN_STYLE_NOCACHE, fontsize) != SSFN_OK ||
  9295. ssfn_bbox(ctx->font, msgstr, (int*)&buf.w, (int*)&buf.h, (int*)&buf.x, (int*)&buf.y) != SSFN_OK)
  9296. return NULL;
  9297. buf.fg = color;
  9298. buf.p = buf.w * sizeof(uint32_t);
  9299. if((buf.ptr = (uint8_t*)malloc(buf.p * buf.h))) {
  9300. memset(buf.ptr, 0, buf.p * buf.h);
  9301. while((ret = ssfn_render(ctx->font, &buf, msgstr)) > 0)
  9302. msgstr += ret;
  9303. if(w) *w = buf.w;
  9304. if(h) *h = buf.h;
  9305. }
  9306. return (uint32_t*)buf.ptr;
  9307. }
  9308. /**
  9309. * Look up and return a decoded 3D model
  9310. */
  9311. m3d_t *apck_model(apck_t *ctx, char *name)
  9312. {
  9313. apck_file_t *file = NULL;
  9314. uint8_t *buf, *comp;
  9315. if(!ctx || !name || !*name)
  9316. return NULL;
  9317. if((file = apck_lookup(ctx, APCK_MODEL, name))) {
  9318. /* we have this asset, let's see if we have cached its contents already */
  9319. if(!file->buf) {
  9320. if(file->comp && (comp = apck_readbuf(ctx, file->archive, file->offs, file->comp))) {
  9321. /* we got the data from the archive, uncompress it */
  9322. if((buf = (uint8_t*)malloc(file->size))) {
  9323. if(stbi_zlib_decode_buffer((char*)buf, (int)file->size, (char*)comp, (int)file->comp) < 1) {
  9324. DBG(("unable to uncompress model '%s'\n", name));
  9325. file->size = file->comp = 0;
  9326. } else
  9327. if(!(file->buf = (uint8_t*)m3d_load(buf, NULL, NULL, NULL))) {
  9328. DBG(("unable to decode model '%s'\n", name));
  9329. file->size = file->comp = 0;
  9330. }
  9331. free(buf);
  9332. } else { DBG(("unable to allocate model '%s' (%u bytes)\n", name, (uint32_t)file->size)); }
  9333. free(comp);
  9334. } else { DBG(("unable to read model '%s'\n", name)); }
  9335. }
  9336. return (m3d_t*)file->buf;
  9337. }
  9338. return NULL;
  9339. }
  9340. /**
  9341. * Look up and return a decoded image asset
  9342. */
  9343. uint32_t *apck_image(apck_t *ctx, int type, char *name, int *w, int *h)
  9344. {
  9345. apck_file_t *file = NULL;
  9346. uint8_t *buf;
  9347. int p, i;
  9348. if(w) *w = 0;
  9349. if(h) *h = 0;
  9350. if(!ctx || (type != APCK_IMAGE && type != APCK_ATLAS) || !name || !*name)
  9351. return NULL;
  9352. if(type == APCK_ATLAS) {
  9353. /* atlases are generated so they don't have a real name, they use index instead */
  9354. i = atoi(name) - 1;
  9355. if(ctx->files[APCK_ATLAS] && i >= 0 && (uint32_t)i < ctx->numfiles[APCK_ATLAS])
  9356. file = &ctx->files[APCK_ATLAS][i];
  9357. } else {
  9358. /* for images, try localized images first */
  9359. if(ctx->locale < APCK_FONT && ctx->files[ctx->locale])
  9360. file = apck_lookup(ctx, ctx->locale, name);
  9361. if(!file) file = apck_lookup(ctx, type, name);
  9362. }
  9363. if(file) {
  9364. /* we have this asset, let's see if we have cached its contents already */
  9365. if(!file->buf) {
  9366. if(file->size && (buf = apck_readbuf(ctx, file->archive, file->offs, file->size))) {
  9367. if(!(file->buf = (uint8_t*)stbi_load_from_memory(buf, file->size, &file->w, &file->h, &p, 4))) {
  9368. DBG(("unable to decode image asset '%s'\n", name));
  9369. file->size = file->comp = 0;
  9370. }
  9371. free(buf);
  9372. } else { DBG(("unable to read image asset '%s'\n", name)); }
  9373. }
  9374. /* extra check for images */
  9375. if(!file->buf || file->w < 1 || file->h < 1) return NULL;
  9376. /* return the decoded asset */
  9377. if(w) *w = file->w;
  9378. if(h) *h = file->h;
  9379. return (uint32_t*)file->buf;
  9380. }
  9381. return NULL;
  9382. }
  9383. /**
  9384. * Look up and return a decoded audio asset
  9385. */
  9386. int16_t *apck_audio(apck_t *ctx, int type, char *name, int *numsamples, int *channels)
  9387. {
  9388. apck_file_t *file = NULL;
  9389. uint8_t *buf;
  9390. int ch, hz;
  9391. if(numsamples) *numsamples = 0;
  9392. if(channels) *channels = 0;
  9393. if(!ctx || (type != APCK_BGM && type != APCK_SFX) || !name || !*name)
  9394. return NULL;
  9395. /* for sound effects, try localized voices first */
  9396. if(type == APCK_SFX && ctx->locale < APCK_FONT && ctx->files[ctx->locale])
  9397. file = apck_lookup(ctx, ctx->locale, name);
  9398. if(!file) file = apck_lookup(ctx, type, name);
  9399. if(file) {
  9400. /* we have this asset, let's see if we have cached its contents already */
  9401. if(!file->buf) {
  9402. if(file->size && (buf = apck_readbuf(ctx, file->archive, file->offs, file->size))) {
  9403. if(!(file->w = APCK_OGG(buf, file->size, &ch, &hz, (int16_t**)&file->buf))) {
  9404. DBG(("unable to decode audio asset '%s'\n", name));
  9405. file->size = file->comp = 0;
  9406. } else {
  9407. file->w *= ch;
  9408. file->h = -ch;
  9409. }
  9410. free(buf);
  9411. } else { DBG(("unable to read audio asset '%s'\n", name)); }
  9412. }
  9413. /* extra check for audio */
  9414. if(!file->buf || file->w < 1 || file->h > -1) return NULL;
  9415. /* return the decoded asset */
  9416. if(numsamples) *numsamples = file->w;
  9417. if(channels) *channels = -file->h;
  9418. return (int16_t*)file->buf;
  9419. }
  9420. return NULL;
  9421. }
  9422. /**
  9423. * Look up and return a decoded sprite asset
  9424. */
  9425. apck_sprite_t *apck_sprite(apck_t *ctx, char *name)
  9426. {
  9427. apck_file_t *file = NULL;
  9428. uint8_t *buf, *comp;
  9429. if(!ctx || !name || !*name)
  9430. return NULL;
  9431. if((file = apck_lookup(ctx, APCK_SPRITE, name))) {
  9432. /* we have this asset, let's see if we have cached its contents already */
  9433. if(!file->buf) {
  9434. if(file->comp && (comp = apck_readbuf(ctx, file->archive, file->offs, file->comp))) {
  9435. if((buf = (uint8_t*)malloc(file->size))) {
  9436. if(stbi_zlib_decode_buffer((char*)buf, (int)file->size, (char*)comp, (int)file->comp) < 1 ||
  9437. !(file->buf = (uint8_t*)apck_sprite_decode(ctx->archives[file->archive].aidx,
  9438. ctx->archives[file->archive].str, buf, file->size))) {
  9439. DBG(("unable to uncompress sprite '%s'\n", name));
  9440. file->size = file->comp = 0;
  9441. }
  9442. free(buf);
  9443. } else { DBG(("unable to allocate sprite '%s' (%u bytes)\n", name, (uint32_t)file->size)); }
  9444. free(comp);
  9445. } else { DBG(("unable to read sprite asset '%s'\n", name)); }
  9446. }
  9447. return (apck_sprite_t*)file->buf;
  9448. }
  9449. return NULL;
  9450. }
  9451. /**
  9452. * Look up and return a decoded map asset
  9453. */
  9454. apck_map_t *apck_map(apck_t *ctx, char *name)
  9455. {
  9456. apck_file_t *file = NULL;
  9457. uint8_t *buf, *comp;
  9458. if(!ctx || !name || !*name)
  9459. return NULL;
  9460. if((file = apck_lookup(ctx, APCK_MAP, name))) {
  9461. /* we have this asset, let's see if we have cached its contents already */
  9462. if(!file->buf) {
  9463. if(file->comp && (comp = apck_readbuf(ctx, file->archive, file->offs, file->comp))) {
  9464. if((buf = (uint8_t*)malloc(file->size))) {
  9465. if(stbi_zlib_decode_buffer((char*)buf, (int)file->size, (char*)comp, (int)file->comp) < 1 ||
  9466. !(file->buf = (uint8_t*)apck_map_decode(ctx->archives[file->archive].str, buf, file->size))) {
  9467. DBG(("unable to uncompress map '%s'\n", name));
  9468. file->size = file->comp = 0;
  9469. }
  9470. free(buf);
  9471. } else { DBG(("unable to allocate map '%s' (%u bytes)\n", name, (uint32_t)file->size)); }
  9472. free(comp);
  9473. } else { DBG(("unable to read map asset '%s'\n", name)); }
  9474. }
  9475. return (apck_map_t*)file->buf;
  9476. }
  9477. return NULL;
  9478. }
  9479. #endif /* APCK_IMPLEMENTATION */
  9480. #ifdef __cplusplus
  9481. }
  9482. #endif
  9483. #endif /* APIC_H */