tinyexr.h 456 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104
  1. /*
  2. Copyright (c) 2014 - 2018, Syoyo Fujita and many contributors.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of the Syoyo Fujita nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  18. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. // TinyEXR contains some OpenEXR code, which is licensed under ------------
  26. ///////////////////////////////////////////////////////////////////////////
  27. //
  28. // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
  29. // Digital Ltd. LLC
  30. //
  31. // All rights reserved.
  32. //
  33. // Redistribution and use in source and binary forms, with or without
  34. // modification, are permitted provided that the following conditions are
  35. // met:
  36. // * Redistributions of source code must retain the above copyright
  37. // notice, this list of conditions and the following disclaimer.
  38. // * Redistributions in binary form must reproduce the above
  39. // copyright notice, this list of conditions and the following disclaimer
  40. // in the documentation and/or other materials provided with the
  41. // distribution.
  42. // * Neither the name of Industrial Light & Magic nor the names of
  43. // its contributors may be used to endorse or promote products derived
  44. // from this software without specific prior written permission.
  45. //
  46. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  47. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  48. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  49. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  50. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  51. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  52. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  53. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  54. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  55. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  56. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  57. //
  58. ///////////////////////////////////////////////////////////////////////////
  59. // End of OpenEXR license -------------------------------------------------
  60. #ifndef TINYEXR_H_
  61. #define TINYEXR_H_
  62. //
  63. //
  64. // Do this:
  65. // #define TINYEXR_IMPLEMENTATION
  66. // before you include this file in *one* C or C++ file to create the
  67. // implementation.
  68. //
  69. // // i.e. it should look like this:
  70. // #include ...
  71. // #include ...
  72. // #include ...
  73. // #define TINYEXR_IMPLEMENTATION
  74. // #include "tinyexr.h"
  75. //
  76. //
  77. #include <stddef.h> // for size_t
  78. #include <stdint.h> // guess stdint.h is available(C99)
  79. #ifdef __cplusplus
  80. extern "C" {
  81. #endif
  82. // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib
  83. // required if this flas is 0.
  84. #ifndef TINYEXR_USE_MINIZ
  85. #define TINYEXR_USE_MINIZ (1)
  86. #endif
  87. // Disable PIZ comporession when applying cpplint.
  88. #ifndef TINYEXR_USE_PIZ
  89. #define TINYEXR_USE_PIZ (1)
  90. #endif
  91. #ifndef TINYEXR_USE_ZFP
  92. #define TINYEXR_USE_ZFP (0) // TinyEXR extension.
  93. // http://computation.llnl.gov/projects/floating-point-compression
  94. #endif
  95. #define TINYEXR_SUCCESS (0)
  96. #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)
  97. #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)
  98. #define TINYEXR_ERROR_INVALID_ARGUMENT (-3)
  99. #define TINYEXR_ERROR_INVALID_DATA (-4)
  100. #define TINYEXR_ERROR_INVALID_FILE (-5)
  101. #define TINYEXR_ERROR_INVALID_PARAMETER (-5)
  102. #define TINYEXR_ERROR_CANT_OPEN_FILE (-6)
  103. #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-7)
  104. #define TINYEXR_ERROR_INVALID_HEADER (-8)
  105. #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-9)
  106. #define TINYEXR_ERROR_CANT_WRITE_FILE (-10)
  107. #define TINYEXR_ERROR_SERIALZATION_FAILED (-11)
  108. // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }
  109. // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
  110. #define TINYEXR_PIXELTYPE_UINT (0)
  111. #define TINYEXR_PIXELTYPE_HALF (1)
  112. #define TINYEXR_PIXELTYPE_FLOAT (2)
  113. #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)
  114. #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)
  115. #define TINYEXR_COMPRESSIONTYPE_NONE (0)
  116. #define TINYEXR_COMPRESSIONTYPE_RLE (1)
  117. #define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
  118. #define TINYEXR_COMPRESSIONTYPE_ZIP (3)
  119. #define TINYEXR_COMPRESSIONTYPE_PIZ (4)
  120. #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension
  121. #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)
  122. #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)
  123. #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)
  124. #define TINYEXR_TILE_ONE_LEVEL (0)
  125. #define TINYEXR_TILE_MIPMAP_LEVELS (1)
  126. #define TINYEXR_TILE_RIPMAP_LEVELS (2)
  127. #define TINYEXR_TILE_ROUND_DOWN (0)
  128. #define TINYEXR_TILE_ROUND_UP (1)
  129. typedef struct _EXRVersion {
  130. int version; // this must be 2
  131. int tiled; // tile format image
  132. int long_name; // long name attribute
  133. int non_image; // deep image(EXR 2.0)
  134. int multipart; // multi-part(EXR 2.0)
  135. } EXRVersion;
  136. typedef struct _EXRAttribute {
  137. char name[256]; // name and type are up to 255 chars long.
  138. char type[256];
  139. unsigned char *value; // uint8_t*
  140. int size;
  141. int pad0;
  142. } EXRAttribute;
  143. typedef struct _EXRChannelInfo {
  144. char name[256]; // less than 255 bytes long
  145. int pixel_type;
  146. int x_sampling;
  147. int y_sampling;
  148. unsigned char p_linear;
  149. unsigned char pad[3];
  150. } EXRChannelInfo;
  151. typedef struct _EXRTile {
  152. int offset_x;
  153. int offset_y;
  154. int level_x;
  155. int level_y;
  156. int width; // actual width in a tile.
  157. int height; // actual height int a tile.
  158. unsigned char **images; // image[channels][pixels]
  159. } EXRTile;
  160. typedef struct _EXRHeader {
  161. float pixel_aspect_ratio;
  162. int line_order;
  163. int data_window[4];
  164. int display_window[4];
  165. float screen_window_center[2];
  166. float screen_window_width;
  167. int chunk_count;
  168. // Properties for tiled format(`tiledesc`).
  169. int tiled;
  170. int tile_size_x;
  171. int tile_size_y;
  172. int tile_level_mode;
  173. int tile_rounding_mode;
  174. int long_name;
  175. int non_image;
  176. int multipart;
  177. unsigned int header_len;
  178. // Custom attributes(exludes required attributes(e.g. `channels`,
  179. // `compression`, etc)
  180. int num_custom_attributes;
  181. EXRAttribute *custom_attributes; // array of EXRAttribute. size =
  182. // `num_custom_attributes`.
  183. EXRChannelInfo *channels; // [num_channels]
  184. int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
  185. // each channel. This is overwritten with `requested_pixel_types` when
  186. // loading.
  187. int num_channels;
  188. int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)
  189. int *requested_pixel_types; // Filled initially by
  190. // ParseEXRHeaderFrom(Meomory|File), then users
  191. // can edit it(only valid for HALF pixel type
  192. // channel)
  193. } EXRHeader;
  194. typedef struct _EXRMultiPartHeader {
  195. int num_headers;
  196. EXRHeader *headers;
  197. } EXRMultiPartHeader;
  198. typedef struct _EXRImage {
  199. EXRTile *tiles; // Tiled pixel data. The application must reconstruct image
  200. // from tiles manually. NULL if scanline format.
  201. unsigned char **images; // image[channels][pixels]. NULL if tiled format.
  202. int width;
  203. int height;
  204. int num_channels;
  205. // Properties for tile format.
  206. int num_tiles;
  207. } EXRImage;
  208. typedef struct _EXRMultiPartImage {
  209. int num_images;
  210. EXRImage *images;
  211. } EXRMultiPartImage;
  212. typedef struct _DeepImage {
  213. const char **channel_names;
  214. float ***image; // image[channels][scanlines][samples]
  215. int **offset_table; // offset_table[scanline][offsets]
  216. int num_channels;
  217. int width;
  218. int height;
  219. int pad0;
  220. } DeepImage;
  221. // @deprecated { to be removed. }
  222. // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel
  223. // alpha) or RGB(A) channels.
  224. // Application must free image data as returned by `out_rgba`
  225. // Result image format is: float x RGBA x width x hight
  226. // Returns negative value and may set error string in `err` when there's an
  227. // error
  228. extern int LoadEXR(float **out_rgba, int *width, int *height,
  229. const char *filename, const char **err);
  230. // @deprecated { to be removed. }
  231. // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
  232. // components must be 1(Grayscale), 3(RGB) or 4(RGBA).
  233. // Input image format is: `float x width x height`, or `float x RGB(A) x width x
  234. // hight`
  235. // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
  236. // value.
  237. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
  238. // Use ZIP compression by default.
  239. // Returns negative value and may set error string in `err` when there's an
  240. // error
  241. extern int SaveEXR(const float *data, const int width, const int height,
  242. const int components, const int save_as_fp16,
  243. const char *filename, const char **err);
  244. // Initialize EXRHeader struct
  245. extern void InitEXRHeader(EXRHeader *exr_header);
  246. // Initialize EXRImage struct
  247. extern void InitEXRImage(EXRImage *exr_image);
  248. // Free's internal data of EXRHeader struct
  249. extern int FreeEXRHeader(EXRHeader *exr_header);
  250. // Free's internal data of EXRImage struct
  251. extern int FreeEXRImage(EXRImage *exr_image);
  252. // Free's error message
  253. extern void FreeEXRErrorMessage(const char *msg);
  254. // Parse EXR version header of a file.
  255. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);
  256. // Parse EXR version header from memory-mapped EXR data.
  257. extern int ParseEXRVersionFromMemory(EXRVersion *version,
  258. const unsigned char *memory, size_t size);
  259. // Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
  260. // When there was an error message, Application must free `err` with
  261. // FreeEXRErrorMessage()
  262. extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,
  263. const char *filename, const char **err);
  264. // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
  265. // When there was an error message, Application must free `err` with
  266. // FreeEXRErrorMessage()
  267. extern int ParseEXRHeaderFromMemory(EXRHeader *header,
  268. const EXRVersion *version,
  269. const unsigned char *memory, size_t size,
  270. const char **err);
  271. // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
  272. // array.
  273. // When there was an error message, Application must free `err` with
  274. // FreeEXRErrorMessage()
  275. extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,
  276. int *num_headers,
  277. const EXRVersion *version,
  278. const char *filename,
  279. const char **err);
  280. // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
  281. // array
  282. // When there was an error message, Application must free `err` with
  283. // FreeEXRErrorMessage()
  284. extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,
  285. int *num_headers,
  286. const EXRVersion *version,
  287. const unsigned char *memory,
  288. size_t size, const char **err);
  289. // Loads single-part OpenEXR image from a file.
  290. // Application must setup `ParseEXRHeaderFromFile` before calling this function.
  291. // Application can free EXRImage using `FreeEXRImage`
  292. // Returns negative value and may set error string in `err` when there's an
  293. // error
  294. // When there was an error message, Application must free `err` with
  295. // FreeEXRErrorMessage()
  296. extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,
  297. const char *filename, const char **err);
  298. // Loads single-part OpenEXR image from a memory.
  299. // Application must setup `EXRHeader` with
  300. // `ParseEXRHeaderFromMemory` before calling this function.
  301. // Application can free EXRImage using `FreeEXRImage`
  302. // Returns negative value and may set error string in `err` when there's an
  303. // error
  304. // When there was an error message, Application must free `err` with
  305. // FreeEXRErrorMessage()
  306. extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,
  307. const unsigned char *memory,
  308. const size_t size, const char **err);
  309. // Loads multi-part OpenEXR image from a file.
  310. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
  311. // function.
  312. // Application can free EXRImage using `FreeEXRImage`
  313. // Returns negative value and may set error string in `err` when there's an
  314. // error
  315. // When there was an error message, Application must free `err` with
  316. // FreeEXRErrorMessage()
  317. extern int LoadEXRMultipartImageFromFile(EXRImage *images,
  318. const EXRHeader **headers,
  319. unsigned int num_parts,
  320. const char *filename,
  321. const char **err);
  322. // Loads multi-part OpenEXR image from a memory.
  323. // Application must setup `EXRHeader*` array with
  324. // `ParseEXRMultipartHeaderFromMemory` before calling this function.
  325. // Application can free EXRImage using `FreeEXRImage`
  326. // Returns negative value and may set error string in `err` when there's an
  327. // error
  328. // When there was an error message, Application must free `err` with
  329. // FreeEXRErrorMessage()
  330. extern int LoadEXRMultipartImageFromMemory(EXRImage *images,
  331. const EXRHeader **headers,
  332. unsigned int num_parts,
  333. const unsigned char *memory,
  334. const size_t size, const char **err);
  335. // Saves multi-channel, single-frame OpenEXR image to a file.
  336. // Returns negative value and may set error string in `err` when there's an
  337. // error
  338. // When there was an error message, Application must free `err` with
  339. // FreeEXRErrorMessage()
  340. extern int SaveEXRImageToFile(const EXRImage *image,
  341. const EXRHeader *exr_header, const char *filename,
  342. const char **err);
  343. // Saves multi-channel, single-frame OpenEXR image to a memory.
  344. // Image is compressed using EXRImage.compression value.
  345. // Return the number of bytes if success.
  346. // Return zero and will set error string in `err` when there's an
  347. // error.
  348. // When there was an error message, Application must free `err` with
  349. // FreeEXRErrorMessage()
  350. extern size_t SaveEXRImageToMemory(const EXRImage *image,
  351. const EXRHeader *exr_header,
  352. unsigned char **memory, const char **err);
  353. // Loads single-frame OpenEXR deep image.
  354. // Application must free memory of variables in DeepImage(image, offset_table)
  355. // Returns negative value and may set error string in `err` when there's an
  356. // error
  357. // When there was an error message, Application must free `err` with
  358. // FreeEXRErrorMessage()
  359. extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
  360. const char **err);
  361. // NOT YET IMPLEMENTED:
  362. // Saves single-frame OpenEXR deep image.
  363. // Returns negative value and may set error string in `err` when there's an
  364. // error
  365. // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
  366. // const char **err);
  367. // NOT YET IMPLEMENTED:
  368. // Loads multi-part OpenEXR deep image.
  369. // Application must free memory of variables in DeepImage(image, offset_table)
  370. // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
  371. // char *filename,
  372. // const char **err);
  373. // For emscripten.
  374. // Loads single-frame OpenEXR image from memory. Assume EXR image contains
  375. // RGB(A) channels.
  376. // Returns negative value and may set error string in `err` when there's an
  377. // error
  378. // When there was an error message, Application must free `err` with
  379. // FreeEXRErrorMessage()
  380. extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  381. const unsigned char *memory, size_t size,
  382. const char **err);
  383. #ifdef __cplusplus
  384. }
  385. #endif
  386. #endif // TINYEXR_H_
  387. #ifdef TINYEXR_IMPLEMENTATION
  388. #ifndef TINYEXR_IMPLEMENTATION_DEIFNED
  389. #define TINYEXR_IMPLEMENTATION_DEIFNED
  390. #include <algorithm>
  391. #include <cassert>
  392. #include <cstdio>
  393. #include <cstdlib>
  394. #include <cstring>
  395. #include <iostream>
  396. #include <sstream>
  397. #include <limits>
  398. #include <string>
  399. #include <vector>
  400. #if __cplusplus > 199711L
  401. // C++11
  402. #include <cstdint>
  403. #endif // __cplusplus > 199711L
  404. #ifdef _OPENMP
  405. #include <omp.h>
  406. #endif
  407. #if TINYEXR_USE_MINIZ
  408. #else
  409. // Issue #46. Please include your own zlib-compatible API header before
  410. // including `tinyexr.h`
  411. //#include "zlib.h"
  412. #endif
  413. #if TINYEXR_USE_ZFP
  414. #include "zfp.h"
  415. #endif
  416. namespace tinyexr {
  417. #if __cplusplus > 199711L
  418. // C++11
  419. typedef uint64_t tinyexr_uint64;
  420. typedef int64_t tinyexr_int64;
  421. #else
  422. // Although `long long` is not a standard type pre C++11, assume it is defined
  423. // as a compiler's extension.
  424. #ifdef __clang__
  425. #pragma clang diagnostic push
  426. #pragma clang diagnostic ignored "-Wc++11-long-long"
  427. #endif
  428. typedef unsigned long long tinyexr_uint64;
  429. typedef long long tinyexr_int64;
  430. #ifdef __clang__
  431. #pragma clang diagnostic pop
  432. #endif
  433. #endif
  434. #if TINYEXR_USE_MINIZ
  435. namespace miniz {
  436. #ifdef __clang__
  437. #pragma clang diagnostic push
  438. #pragma clang diagnostic ignored "-Wc++11-long-long"
  439. #pragma clang diagnostic ignored "-Wold-style-cast"
  440. #pragma clang diagnostic ignored "-Wpadded"
  441. #pragma clang diagnostic ignored "-Wsign-conversion"
  442. #pragma clang diagnostic ignored "-Wc++11-extensions"
  443. #pragma clang diagnostic ignored "-Wconversion"
  444. #pragma clang diagnostic ignored "-Wunused-function"
  445. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  446. #pragma clang diagnostic ignored "-Wundef"
  447. #if __has_warning("-Wcomma")
  448. #pragma clang diagnostic ignored "-Wcomma"
  449. #endif
  450. #if __has_warning("-Wmacro-redefined")
  451. #pragma clang diagnostic ignored "-Wmacro-redefined"
  452. #endif
  453. #if __has_warning("-Wcast-qual")
  454. #pragma clang diagnostic ignored "-Wcast-qual"
  455. #endif
  456. #if __has_warning("-Wzero-as-null-pointer-constant")
  457. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  458. #endif
  459. #if __has_warning("-Wtautological-constant-compare")
  460. #pragma clang diagnostic ignored "-Wtautological-constant-compare"
  461. #endif
  462. #endif
  463. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
  464. reading/writing/appending, PNG writing
  465. See "unlicense" statement at the end of this file.
  466. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
  467. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
  468. http://www.ietf.org/rfc/rfc1951.txt
  469. Most API's defined in miniz.c are optional. For example, to disable the
  470. archive related functions just define
  471. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
  472. (see the list below for more macros).
  473. * Change History
  474. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
  475. release with Zip64 support (almost there!):
  476. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
  477. (thanks kahmyong.moon@hp.com) which could cause locate files to not find
  478. files. This bug
  479. would only have occured in earlier versions if you explicitly used this
  480. flag, OR if you used mz_zip_extract_archive_file_to_heap() or
  481. mz_zip_add_mem_to_archive_file_in_place()
  482. (which used this flag). If you can't switch to v1.15 but want to fix
  483. this bug, just remove the uses of this flag from both helper funcs (and of
  484. course don't use the flag).
  485. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
  486. pUser_read_buf is not NULL and compressed size is > uncompressed size
  487. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
  488. compressed data from directory entries, to account for weird zipfiles which
  489. contain zero-size compressed data on dir entries.
  490. Hopefully this fix won't cause any issues on weird zip archives,
  491. because it assumes the low 16-bits of zip external attributes are DOS
  492. attributes (which I believe they always are in practice).
  493. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
  494. internal attributes, just the filename and external attributes
  495. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  496. - Added cmake support for Linux builds which builds all the examples,
  497. tested with clang v3.3 and gcc v4.6.
  498. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  499. - Merged MZ_FORCEINLINE fix from hdeanclark
  500. - Fix <time.h> include before config #ifdef, thanks emil.brink
  501. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
  502. (super useful for OpenGL apps), and explicit control over the compression
  503. level (so you can
  504. set it to 1 for real-time compression).
  505. - Merged in some compiler fixes from paulharris's github repro.
  506. - Retested this build under Windows (VS 2010, including static analysis),
  507. tcc 0.9.26, gcc v4.6 and clang v3.3.
  508. - Added example6.c, which dumps an image of the mandelbrot set to a PNG
  509. file.
  510. - Modified example2 to help test the
  511. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  512. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
  513. possible src file fclose() leak if alignment bytes+local header file write
  514. faiiled
  515. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
  516. Was pushing the wrong central dir header offset, appears harmless in this
  517. release, but it became a problem in the zip64 branch
  518. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
  519. #include <time.h> (thanks fermtect).
  520. 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
  521. mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  522. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
  523. re-ran a randomized regression test on ~500k files.
  524. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  525. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
  526. (static analysis) option and fixed all warnings (except for the silly
  527. "Use of the comma-operator in a tested expression.." analysis warning,
  528. which I purposely use to work around a MSVC compiler warning).
  529. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
  530. tested Linux executables. The codeblocks workspace is compatible with
  531. Linux+Win32/x64.
  532. - Added miniz_tester solution/project, which is a useful little app
  533. derived from LZHAM's tester app that I use as part of the regression test.
  534. - Ran miniz.c and tinfl.c through another series of regression testing on
  535. ~500,000 files and archives.
  536. - Modified example5.c so it purposely disables a bunch of high-level
  537. functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
  538. MINIZ_NO_STDIO bug report.)
  539. - Fix ftell() usage in examples so they exit with an error on files which
  540. are too large (a limitation of the examples, not miniz itself).
  541. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
  542. minor level_and_flags issues in the archive API's.
  543. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
  544. Dawson <bruced@valvesoftware.com> for the feedback/bug report.
  545. 5/28/11 v1.11 - Added statement from unlicense.org
  546. 5/27/11 v1.10 - Substantial compressor optimizations:
  547. - Level 1 is now ~4x faster than before. The L1 compressor's throughput
  548. now varies between 70-110MB/sec. on a
  549. - Core i7 (actual throughput varies depending on the type of data, and x64
  550. vs. x86).
  551. - Improved baseline L2-L9 compression perf. Also, greatly improved
  552. compression perf. issues on some file types.
  553. - Refactored the compression code for better readability and
  554. maintainability.
  555. - Added level 10 compression level (L10 has slightly better ratio than
  556. level 9, but could have a potentially large
  557. drop in throughput on some files).
  558. 5/15/11 v1.09 - Initial stable release.
  559. * Low-level Deflate/Inflate implementation notes:
  560. Compression: Use the "tdefl" API's. The compressor supports raw, static,
  561. and dynamic blocks, lazy or
  562. greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
  563. It performs and compresses
  564. approximately as well as zlib.
  565. Decompression: Use the "tinfl" API's. The entire decompressor is
  566. implemented as a single function
  567. coroutine: see tinfl_decompress(). It supports decompression into a 32KB
  568. (or larger power of 2) wrapping buffer, or into a memory
  569. block large enough to hold the entire file.
  570. The low-level tdefl/tinfl API's do not make any use of dynamic memory
  571. allocation.
  572. * zlib-style API notes:
  573. miniz.c implements a fairly large subset of zlib. There's enough
  574. functionality present for it to be a drop-in
  575. zlib replacement in many apps:
  576. The z_stream struct, optional memory allocation callbacks
  577. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  578. inflateInit/inflateInit2/inflate/inflateEnd
  579. compress, compress2, compressBound, uncompress
  580. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
  581. routines.
  582. Supports raw deflate streams or standard zlib streams with adler-32
  583. checking.
  584. Limitations:
  585. The callback API's are not implemented yet. No support for gzip headers or
  586. zlib static dictionaries.
  587. I've tried to closely emulate zlib's various flavors of stream flushing
  588. and return status codes, but
  589. there are no guarantees that miniz.c pulls this off perfectly.
  590. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
  591. originally written by
  592. Alex Evans. Supports 1-4 bytes/pixel images.
  593. * ZIP archive API notes:
  594. The ZIP archive API's where designed with simplicity and efficiency in
  595. mind, with just enough abstraction to
  596. get the job done with minimal fuss. There are simple API's to retrieve file
  597. information, read files from
  598. existing archives, create new archives, append new files to existing
  599. archives, or clone archive data from
  600. one archive to another. It supports archives located in memory or the heap,
  601. on disk (using stdio.h),
  602. or you can specify custom file read/write callbacks.
  603. - Archive reading: Just call this function to read a single file from a
  604. disk archive:
  605. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
  606. char *pArchive_name,
  607. size_t *pSize, mz_uint zip_flags);
  608. For more complex cases, use the "mz_zip_reader" functions. Upon opening an
  609. archive, the entire central
  610. directory is located and read as-is into memory, and subsequent file access
  611. only occurs when reading individual files.
  612. - Archives file scanning: The simple way is to use this function to scan a
  613. loaded archive for a specific file:
  614. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  615. const char *pComment, mz_uint flags);
  616. The locate operation can optionally check file comments too, which (as one
  617. example) can be used to identify
  618. multiple versions of the same file in an archive. This function uses a
  619. simple linear search through the central
  620. directory, so it's not very fast.
  621. Alternately, you can iterate through all the files in an archive (using
  622. mz_zip_reader_get_num_files()) and
  623. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  624. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
  625. immediately writes compressed file data
  626. to disk and builds an exact image of the central directory in memory. The
  627. central directory image is written
  628. all at once at the end of the archive file when the archive is finalized.
  629. The archive writer can optionally align each file's local header and file
  630. data to any power of 2 alignment,
  631. which can be useful when the archive will be read from optical media. Also,
  632. the writer supports placing
  633. arbitrary data blobs at the very beginning of ZIP archives. Archives
  634. written using either feature are still
  635. readable by any ZIP tool.
  636. - Archive appending: The simple way to add a single file to an archive is
  637. to call this function:
  638. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
  639. const char *pArchive_name,
  640. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
  641. comment_size, mz_uint level_and_flags);
  642. The archive will be created if it doesn't already exist, otherwise it'll be
  643. appended to.
  644. Note the appending is done in-place and is not an atomic operation, so if
  645. something goes wrong
  646. during the operation it's possible the archive could be left without a
  647. central directory (although the local
  648. file headers and file data will be fine, so the archive will be
  649. recoverable).
  650. For more complex archive modification scenarios:
  651. 1. The safest way is to use a mz_zip_reader to read the existing archive,
  652. cloning only those bits you want to
  653. preserve into a new archive using using the
  654. mz_zip_writer_add_from_zip_reader() function (which compiles the
  655. compressed file data as-is). When you're done, delete the old archive and
  656. rename the newly written archive, and
  657. you're done. This is safe but requires a bunch of temporary disk space or
  658. heap memory.
  659. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
  660. mz_zip_writer_init_from_reader(),
  661. append new files as needed, then finalize the archive which will write an
  662. updated central directory to the
  663. original archive. (This is basically what
  664. mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  665. possibility that the archive's central directory could be lost with this
  666. method if anything goes wrong, though.
  667. - ZIP archive support limitations:
  668. No zip64 or spanning support. Extraction functions can only handle
  669. unencrypted, stored or deflated files.
  670. Requires streams capable of seeking.
  671. * This is a header file library, like stb_image.c. To get only a header file,
  672. either cut and paste the
  673. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
  674. include miniz.c from it.
  675. * Important: For best perf. be sure to customize the below macros for your
  676. target platform:
  677. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  678. #define MINIZ_LITTLE_ENDIAN 1
  679. #define MINIZ_HAS_64BIT_REGISTERS 1
  680. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
  681. including miniz.c to ensure miniz
  682. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
  683. able to process large files
  684. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  685. */
  686. #ifndef MINIZ_HEADER_INCLUDED
  687. #define MINIZ_HEADER_INCLUDED
  688. //#include <stdlib.h>
  689. // Defines to completely disable specific portions of miniz.c:
  690. // If all macros here are defined the only functionality remaining will be
  691. // CRC-32, adler-32, tinfl, and tdefl.
  692. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
  693. // stdio for file I/O.
  694. //#define MINIZ_NO_STDIO
  695. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
  696. // to get the current time, or
  697. // get/set file times, and the C run-time funcs that get/set times won't be
  698. // called.
  699. // The current downside is the times written to your archives will be from 1979.
  700. #define MINIZ_NO_TIME
  701. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  702. #define MINIZ_NO_ARCHIVE_APIS
  703. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
  704. // API's.
  705. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  706. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
  707. // API's.
  708. //#define MINIZ_NO_ZLIB_APIS
  709. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
  710. // conflicts against stock zlib.
  711. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  712. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  713. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
  714. // user alloc/free/realloc
  715. // callbacks to the zlib and archive API's, and a few stand-alone helper API's
  716. // which don't provide custom user
  717. // functions (such as tdefl_compress_mem_to_heap() and
  718. // tinfl_decompress_mem_to_heap()) won't work.
  719. //#define MINIZ_NO_MALLOC
  720. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  721. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
  722. // on Linux
  723. #define MINIZ_NO_TIME
  724. #endif
  725. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  726. //#include <time.h>
  727. #endif
  728. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
  729. defined(__i386) || defined(__i486__) || defined(__i486) || \
  730. defined(i386) || defined(__ia64__) || defined(__x86_64__)
  731. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  732. #define MINIZ_X86_OR_X64_CPU 1
  733. #endif
  734. #if defined(__sparcv9)
  735. // Big endian
  736. #else
  737. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  738. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  739. #define MINIZ_LITTLE_ENDIAN 1
  740. #endif
  741. #endif
  742. #if MINIZ_X86_OR_X64_CPU
  743. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
  744. // integer loads and stores from unaligned addresses.
  745. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  746. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
  747. 0 // disable to suppress compiler warnings
  748. #endif
  749. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
  750. defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
  751. defined(__x86_64__)
  752. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
  753. // reasonably fast (and don't involve compiler generated calls to helper
  754. // functions).
  755. #define MINIZ_HAS_64BIT_REGISTERS 1
  756. #endif
  757. #ifdef __cplusplus
  758. extern "C" {
  759. #endif
  760. // ------------------- zlib-style API Definitions.
  761. // For more compatibility with zlib, miniz.c uses unsigned long for some
  762. // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  763. typedef unsigned long mz_ulong;
  764. // mz_free() internally uses the MZ_FREE() macro (which by default calls free()
  765. // unless you've modified the MZ_MALLOC macro) to release a block allocated from
  766. // the heap.
  767. void mz_free(void *p);
  768. #define MZ_ADLER32_INIT (1)
  769. // mz_adler32() returns the initial adler-32 value to use when called with
  770. // ptr==NULL.
  771. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  772. #define MZ_CRC32_INIT (0)
  773. // mz_crc32() returns the initial CRC-32 value to use when called with
  774. // ptr==NULL.
  775. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  776. // Compression strategies.
  777. enum {
  778. MZ_DEFAULT_STRATEGY = 0,
  779. MZ_FILTERED = 1,
  780. MZ_HUFFMAN_ONLY = 2,
  781. MZ_RLE = 3,
  782. MZ_FIXED = 4
  783. };
  784. // Method
  785. #define MZ_DEFLATED 8
  786. #ifndef MINIZ_NO_ZLIB_APIS
  787. // Heap allocation callbacks.
  788. // Note that mz_alloc_func parameter types purpsosely differ from zlib's:
  789. // items/size is size_t, not unsigned long.
  790. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  791. typedef void (*mz_free_func)(void *opaque, void *address);
  792. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
  793. size_t size);
  794. #define MZ_VERSION "9.1.15"
  795. #define MZ_VERNUM 0x91F0
  796. #define MZ_VER_MAJOR 9
  797. #define MZ_VER_MINOR 1
  798. #define MZ_VER_REVISION 15
  799. #define MZ_VER_SUBREVISION 0
  800. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
  801. // other values are for advanced use (refer to the zlib docs).
  802. enum {
  803. MZ_NO_FLUSH = 0,
  804. MZ_PARTIAL_FLUSH = 1,
  805. MZ_SYNC_FLUSH = 2,
  806. MZ_FULL_FLUSH = 3,
  807. MZ_FINISH = 4,
  808. MZ_BLOCK = 5
  809. };
  810. // Return status codes. MZ_PARAM_ERROR is non-standard.
  811. enum {
  812. MZ_OK = 0,
  813. MZ_STREAM_END = 1,
  814. MZ_NEED_DICT = 2,
  815. MZ_ERRNO = -1,
  816. MZ_STREAM_ERROR = -2,
  817. MZ_DATA_ERROR = -3,
  818. MZ_MEM_ERROR = -4,
  819. MZ_BUF_ERROR = -5,
  820. MZ_VERSION_ERROR = -6,
  821. MZ_PARAM_ERROR = -10000
  822. };
  823. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best
  824. // possible compression (not zlib compatible, and may be very slow),
  825. // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  826. enum {
  827. MZ_NO_COMPRESSION = 0,
  828. MZ_BEST_SPEED = 1,
  829. MZ_BEST_COMPRESSION = 9,
  830. MZ_UBER_COMPRESSION = 10,
  831. MZ_DEFAULT_LEVEL = 6,
  832. MZ_DEFAULT_COMPRESSION = -1
  833. };
  834. // Window bits
  835. #define MZ_DEFAULT_WINDOW_BITS 15
  836. struct mz_internal_state;
  837. // Compression/decompression stream struct.
  838. typedef struct mz_stream_s {
  839. const unsigned char *next_in; // pointer to next byte to read
  840. unsigned int avail_in; // number of bytes available at next_in
  841. mz_ulong total_in; // total number of bytes consumed so far
  842. unsigned char *next_out; // pointer to next byte to write
  843. unsigned int avail_out; // number of bytes that can be written to next_out
  844. mz_ulong total_out; // total number of bytes produced so far
  845. char *msg; // error msg (unused)
  846. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  847. mz_alloc_func
  848. zalloc; // optional heap allocation function (defaults to malloc)
  849. mz_free_func zfree; // optional heap free function (defaults to free)
  850. void *opaque; // heap alloc function user pointer
  851. int data_type; // data_type (unused)
  852. mz_ulong adler; // adler32 of the source or uncompressed data
  853. mz_ulong reserved; // not used
  854. } mz_stream;
  855. typedef mz_stream *mz_streamp;
  856. // Returns the version string of miniz.c.
  857. const char *mz_version(void);
  858. // mz_deflateInit() initializes a compressor with default options:
  859. // Parameters:
  860. // pStream must point to an initialized mz_stream struct.
  861. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  862. // level 1 enables a specially optimized compression function that's been
  863. // optimized purely for performance, not ratio.
  864. // (This special func. is currently only enabled when
  865. // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  866. // Return values:
  867. // MZ_OK on success.
  868. // MZ_STREAM_ERROR if the stream is bogus.
  869. // MZ_PARAM_ERROR if the input parameters are bogus.
  870. // MZ_MEM_ERROR on out of memory.
  871. int mz_deflateInit(mz_streamp pStream, int level);
  872. // mz_deflateInit2() is like mz_deflate(), except with more control:
  873. // Additional parameters:
  874. // method must be MZ_DEFLATED
  875. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
  876. // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
  877. // header or footer)
  878. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  879. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  880. int mem_level, int strategy);
  881. // Quickly resets a compressor without having to reallocate anything. Same as
  882. // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  883. int mz_deflateReset(mz_streamp pStream);
  884. // mz_deflate() compresses the input to output, consuming as much of the input
  885. // and producing as much output as possible.
  886. // Parameters:
  887. // pStream is the stream to read from and write to. You must initialize/update
  888. // the next_in, avail_in, next_out, and avail_out members.
  889. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
  890. // MZ_FINISH.
  891. // Return values:
  892. // MZ_OK on success (when flushing, or if more input is needed but not
  893. // available, and/or there's more output to be written but the output buffer
  894. // is full).
  895. // MZ_STREAM_END if all input has been consumed and all output bytes have been
  896. // written. Don't call mz_deflate() on the stream anymore.
  897. // MZ_STREAM_ERROR if the stream is bogus.
  898. // MZ_PARAM_ERROR if one of the parameters is invalid.
  899. // MZ_BUF_ERROR if no forward progress is possible because the input and/or
  900. // output buffers are empty. (Fill up the input buffer or free up some output
  901. // space and try again.)
  902. int mz_deflate(mz_streamp pStream, int flush);
  903. // mz_deflateEnd() deinitializes a compressor:
  904. // Return values:
  905. // MZ_OK on success.
  906. // MZ_STREAM_ERROR if the stream is bogus.
  907. int mz_deflateEnd(mz_streamp pStream);
  908. // mz_deflateBound() returns a (very) conservative upper bound on the amount of
  909. // data that could be generated by deflate(), assuming flush is set to only
  910. // MZ_NO_FLUSH or MZ_FINISH.
  911. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  912. // Single-call compression functions mz_compress() and mz_compress2():
  913. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on
  914. // failure.
  915. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  916. const unsigned char *pSource, mz_ulong source_len);
  917. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  918. const unsigned char *pSource, mz_ulong source_len, int level);
  919. // mz_compressBound() returns a (very) conservative upper bound on the amount of
  920. // data that could be generated by calling mz_compress().
  921. mz_ulong mz_compressBound(mz_ulong source_len);
  922. // Initializes a decompressor.
  923. int mz_inflateInit(mz_streamp pStream);
  924. // mz_inflateInit2() is like mz_inflateInit() with an additional option that
  925. // controls the window size and whether or not the stream has been wrapped with
  926. // a zlib header/footer:
  927. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
  928. // -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  929. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  930. // Decompresses the input stream to the output, consuming only as much of the
  931. // input as needed, and writing as much to the output as possible.
  932. // Parameters:
  933. // pStream is the stream to read from and write to. You must initialize/update
  934. // the next_in, avail_in, next_out, and avail_out members.
  935. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  936. // On the first call, if flush is MZ_FINISH it's assumed the input and output
  937. // buffers are both sized large enough to decompress the entire stream in a
  938. // single call (this is slightly faster).
  939. // MZ_FINISH implies that there are no more source bytes available beside
  940. // what's already in the input buffer, and that the output buffer is large
  941. // enough to hold the rest of the decompressed data.
  942. // Return values:
  943. // MZ_OK on success. Either more input is needed but not available, and/or
  944. // there's more output to be written but the output buffer is full.
  945. // MZ_STREAM_END if all needed input has been consumed and all output bytes
  946. // have been written. For zlib streams, the adler-32 of the decompressed data
  947. // has also been verified.
  948. // MZ_STREAM_ERROR if the stream is bogus.
  949. // MZ_DATA_ERROR if the deflate stream is invalid.
  950. // MZ_PARAM_ERROR if one of the parameters is invalid.
  951. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is
  952. // empty but the inflater needs more input to continue, or if the output
  953. // buffer is not large enough. Call mz_inflate() again
  954. // with more input data, or with more room in the output buffer (except when
  955. // using single call decompression, described above).
  956. int mz_inflate(mz_streamp pStream, int flush);
  957. // Deinitializes a decompressor.
  958. int mz_inflateEnd(mz_streamp pStream);
  959. // Single-call decompression.
  960. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on
  961. // failure.
  962. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  963. const unsigned char *pSource, mz_ulong source_len);
  964. // Returns a string description of the specified error code, or NULL if the
  965. // error code is invalid.
  966. const char *mz_error(int err);
  967. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
  968. // as a drop-in replacement for the subset of zlib that miniz.c supports.
  969. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
  970. // use zlib in the same project.
  971. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  972. typedef unsigned char Byte;
  973. typedef unsigned int uInt;
  974. typedef mz_ulong uLong;
  975. typedef Byte Bytef;
  976. typedef uInt uIntf;
  977. typedef char charf;
  978. typedef int intf;
  979. typedef void *voidpf;
  980. typedef uLong uLongf;
  981. typedef void *voidp;
  982. typedef void *const voidpc;
  983. #define Z_NULL 0
  984. #define Z_NO_FLUSH MZ_NO_FLUSH
  985. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  986. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  987. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  988. #define Z_FINISH MZ_FINISH
  989. #define Z_BLOCK MZ_BLOCK
  990. #define Z_OK MZ_OK
  991. #define Z_STREAM_END MZ_STREAM_END
  992. #define Z_NEED_DICT MZ_NEED_DICT
  993. #define Z_ERRNO MZ_ERRNO
  994. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  995. #define Z_DATA_ERROR MZ_DATA_ERROR
  996. #define Z_MEM_ERROR MZ_MEM_ERROR
  997. #define Z_BUF_ERROR MZ_BUF_ERROR
  998. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  999. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  1000. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  1001. #define Z_BEST_SPEED MZ_BEST_SPEED
  1002. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  1003. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  1004. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  1005. #define Z_FILTERED MZ_FILTERED
  1006. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  1007. #define Z_RLE MZ_RLE
  1008. #define Z_FIXED MZ_FIXED
  1009. #define Z_DEFLATED MZ_DEFLATED
  1010. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  1011. #define alloc_func mz_alloc_func
  1012. #define free_func mz_free_func
  1013. #define internal_state mz_internal_state
  1014. #define z_stream mz_stream
  1015. #define deflateInit mz_deflateInit
  1016. #define deflateInit2 mz_deflateInit2
  1017. #define deflateReset mz_deflateReset
  1018. #define deflate mz_deflate
  1019. #define deflateEnd mz_deflateEnd
  1020. #define deflateBound mz_deflateBound
  1021. #define compress mz_compress
  1022. #define compress2 mz_compress2
  1023. #define compressBound mz_compressBound
  1024. #define inflateInit mz_inflateInit
  1025. #define inflateInit2 mz_inflateInit2
  1026. #define inflate mz_inflate
  1027. #define inflateEnd mz_inflateEnd
  1028. #define uncompress mz_uncompress
  1029. #define crc32 mz_crc32
  1030. #define adler32 mz_adler32
  1031. #define MAX_WBITS 15
  1032. #define MAX_MEM_LEVEL 9
  1033. #define zError mz_error
  1034. #define ZLIB_VERSION MZ_VERSION
  1035. #define ZLIB_VERNUM MZ_VERNUM
  1036. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  1037. #define ZLIB_VER_MINOR MZ_VER_MINOR
  1038. #define ZLIB_VER_REVISION MZ_VER_REVISION
  1039. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  1040. #define zlibVersion mz_version
  1041. #define zlib_version mz_version()
  1042. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  1043. #endif // MINIZ_NO_ZLIB_APIS
  1044. // ------------------- Types and macros
  1045. typedef unsigned char mz_uint8;
  1046. typedef signed short mz_int16;
  1047. typedef unsigned short mz_uint16;
  1048. typedef unsigned int mz_uint32;
  1049. typedef unsigned int mz_uint;
  1050. typedef long long mz_int64;
  1051. typedef unsigned long long mz_uint64;
  1052. typedef int mz_bool;
  1053. #define MZ_FALSE (0)
  1054. #define MZ_TRUE (1)
  1055. // An attempt to work around MSVC's spammy "warning C4127: conditional
  1056. // expression is constant" message.
  1057. #ifdef _MSC_VER
  1058. #define MZ_MACRO_END while (0, 0)
  1059. #else
  1060. #define MZ_MACRO_END while (0)
  1061. #endif
  1062. // ------------------- ZIP archive reading/writing
  1063. #ifndef MINIZ_NO_ARCHIVE_APIS
  1064. enum {
  1065. MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
  1066. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  1067. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  1068. };
  1069. typedef struct {
  1070. mz_uint32 m_file_index;
  1071. mz_uint32 m_central_dir_ofs;
  1072. mz_uint16 m_version_made_by;
  1073. mz_uint16 m_version_needed;
  1074. mz_uint16 m_bit_flag;
  1075. mz_uint16 m_method;
  1076. #ifndef MINIZ_NO_TIME
  1077. time_t m_time;
  1078. #endif
  1079. mz_uint32 m_crc32;
  1080. mz_uint64 m_comp_size;
  1081. mz_uint64 m_uncomp_size;
  1082. mz_uint16 m_internal_attr;
  1083. mz_uint32 m_external_attr;
  1084. mz_uint64 m_local_header_ofs;
  1085. mz_uint32 m_comment_size;
  1086. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  1087. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  1088. } mz_zip_archive_file_stat;
  1089. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
  1090. void *pBuf, size_t n);
  1091. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
  1092. const void *pBuf, size_t n);
  1093. struct mz_zip_internal_state_tag;
  1094. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  1095. typedef enum {
  1096. MZ_ZIP_MODE_INVALID = 0,
  1097. MZ_ZIP_MODE_READING = 1,
  1098. MZ_ZIP_MODE_WRITING = 2,
  1099. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  1100. } mz_zip_mode;
  1101. typedef struct mz_zip_archive_tag {
  1102. mz_uint64 m_archive_size;
  1103. mz_uint64 m_central_directory_file_ofs;
  1104. mz_uint m_total_files;
  1105. mz_zip_mode m_zip_mode;
  1106. mz_uint m_file_offset_alignment;
  1107. mz_alloc_func m_pAlloc;
  1108. mz_free_func m_pFree;
  1109. mz_realloc_func m_pRealloc;
  1110. void *m_pAlloc_opaque;
  1111. mz_file_read_func m_pRead;
  1112. mz_file_write_func m_pWrite;
  1113. void *m_pIO_opaque;
  1114. mz_zip_internal_state *m_pState;
  1115. } mz_zip_archive;
  1116. typedef enum {
  1117. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  1118. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  1119. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  1120. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  1121. } mz_zip_flags;
  1122. // ZIP archive reading
  1123. // Inits a ZIP archive reader.
  1124. // These functions read and validate the archive's central directory.
  1125. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  1126. mz_uint32 flags);
  1127. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  1128. size_t size, mz_uint32 flags);
  1129. #ifndef MINIZ_NO_STDIO
  1130. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  1131. mz_uint32 flags);
  1132. #endif
  1133. // Returns the total number of files in the archive.
  1134. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  1135. // Returns detailed information about an archive file entry.
  1136. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  1137. mz_zip_archive_file_stat *pStat);
  1138. // Determines if an archive file entry is a directory entry.
  1139. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  1140. mz_uint file_index);
  1141. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  1142. mz_uint file_index);
  1143. // Retrieves the filename of an archive file entry.
  1144. // Returns the number of bytes written to pFilename, or if filename_buf_size is
  1145. // 0 this function returns the number of bytes needed to fully store the
  1146. // filename.
  1147. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  1148. char *pFilename, mz_uint filename_buf_size);
  1149. // Attempts to locates a file in the archive's central directory.
  1150. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  1151. // Returns -1 if the file cannot be found.
  1152. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  1153. const char *pComment, mz_uint flags);
  1154. // Extracts a archive file to a memory buffer using no memory allocation.
  1155. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  1156. mz_uint file_index, void *pBuf,
  1157. size_t buf_size, mz_uint flags,
  1158. void *pUser_read_buf,
  1159. size_t user_read_buf_size);
  1160. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  1161. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  1162. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  1163. // Extracts a archive file to a memory buffer.
  1164. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  1165. void *pBuf, size_t buf_size,
  1166. mz_uint flags);
  1167. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  1168. const char *pFilename, void *pBuf,
  1169. size_t buf_size, mz_uint flags);
  1170. // Extracts a archive file to a dynamically allocated heap buffer.
  1171. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  1172. size_t *pSize, mz_uint flags);
  1173. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  1174. const char *pFilename, size_t *pSize,
  1175. mz_uint flags);
  1176. // Extracts a archive file using a callback function to output the file's data.
  1177. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  1178. mz_uint file_index,
  1179. mz_file_write_func pCallback,
  1180. void *pOpaque, mz_uint flags);
  1181. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  1182. const char *pFilename,
  1183. mz_file_write_func pCallback,
  1184. void *pOpaque, mz_uint flags);
  1185. #ifndef MINIZ_NO_STDIO
  1186. // Extracts a archive file to a disk file and sets its last accessed and
  1187. // modified times.
  1188. // This function only extracts files, not archive directory records.
  1189. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  1190. const char *pDst_filename, mz_uint flags);
  1191. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  1192. const char *pArchive_filename,
  1193. const char *pDst_filename,
  1194. mz_uint flags);
  1195. #endif
  1196. // Ends archive reading, freeing all allocations, and closing the input archive
  1197. // file if mz_zip_reader_init_file() was used.
  1198. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  1199. // ZIP archive writing
  1200. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1201. // Inits a ZIP archive writer.
  1202. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  1203. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  1204. size_t size_to_reserve_at_beginning,
  1205. size_t initial_allocation_size);
  1206. #ifndef MINIZ_NO_STDIO
  1207. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  1208. mz_uint64 size_to_reserve_at_beginning);
  1209. #endif
  1210. // Converts a ZIP archive reader object into a writer object, to allow efficient
  1211. // in-place file appends to occur on an existing archive.
  1212. // For archives opened using mz_zip_reader_init_file, pFilename must be the
  1213. // archive's filename so it can be reopened for writing. If the file can't be
  1214. // reopened, mz_zip_reader_end() will be called.
  1215. // For archives opened using mz_zip_reader_init_mem, the memory block must be
  1216. // growable using the realloc callback (which defaults to realloc unless you've
  1217. // overridden it).
  1218. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
  1219. // user provided m_pWrite function cannot be NULL.
  1220. // Note: In-place archive modification is not recommended unless you know what
  1221. // you're doing, because if execution stops or something goes wrong before
  1222. // the archive is finalized the file's central directory will be hosed.
  1223. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  1224. const char *pFilename);
  1225. // Adds the contents of a memory buffer to an archive. These functions record
  1226. // the current local time into the archive.
  1227. // To add a directory entry, call this method with an archive name ending in a
  1228. // forwardslash with empty buffer.
  1229. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1230. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1231. // just set to MZ_DEFAULT_COMPRESSION.
  1232. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  1233. const void *pBuf, size_t buf_size,
  1234. mz_uint level_and_flags);
  1235. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  1236. const char *pArchive_name, const void *pBuf,
  1237. size_t buf_size, const void *pComment,
  1238. mz_uint16 comment_size,
  1239. mz_uint level_and_flags, mz_uint64 uncomp_size,
  1240. mz_uint32 uncomp_crc32);
  1241. #ifndef MINIZ_NO_STDIO
  1242. // Adds the contents of a disk file to an archive. This function also records
  1243. // the disk file's modified time into the archive.
  1244. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1245. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1246. // just set to MZ_DEFAULT_COMPRESSION.
  1247. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  1248. const char *pSrc_filename, const void *pComment,
  1249. mz_uint16 comment_size, mz_uint level_and_flags);
  1250. #endif
  1251. // Adds a file to an archive by fully cloning the data from another archive.
  1252. // This function fully clones the source file's compressed data (no
  1253. // recompression), along with its full filename, extra data, and comment fields.
  1254. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  1255. mz_zip_archive *pSource_zip,
  1256. mz_uint file_index);
  1257. // Finalizes the archive by writing the central directory records followed by
  1258. // the end of central directory record.
  1259. // After an archive is finalized, the only valid call on the mz_zip_archive
  1260. // struct is mz_zip_writer_end().
  1261. // An archive must be manually finalized by calling this function for it to be
  1262. // valid.
  1263. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  1264. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  1265. size_t *pSize);
  1266. // Ends archive writing, freeing all allocations, and closing the output file if
  1267. // mz_zip_writer_init_file() was used.
  1268. // Note for the archive to be valid, it must have been finalized before ending.
  1269. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  1270. // Misc. high-level helper functions:
  1271. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
  1272. // appends a memory blob to a ZIP archive.
  1273. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1274. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1275. // just set to MZ_DEFAULT_COMPRESSION.
  1276. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  1277. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  1278. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  1279. mz_uint level_and_flags);
  1280. // Reads a single file from an archive into a heap block.
  1281. // Returns NULL on failure.
  1282. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  1283. const char *pArchive_name,
  1284. size_t *pSize, mz_uint zip_flags);
  1285. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1286. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  1287. // ------------------- Low-level Decompression API Definitions
  1288. // Decompression flags used by tinfl_decompress().
  1289. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
  1290. // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
  1291. // input is a raw deflate stream.
  1292. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
  1293. // beyond the end of the supplied input buffer. If clear, the input buffer
  1294. // contains all remaining input.
  1295. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
  1296. // enough to hold the entire decompressed stream. If clear, the output buffer is
  1297. // at least the size of the dictionary (typically 32KB).
  1298. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
  1299. // decompressed bytes.
  1300. enum {
  1301. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  1302. TINFL_FLAG_HAS_MORE_INPUT = 2,
  1303. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  1304. TINFL_FLAG_COMPUTE_ADLER32 = 8
  1305. };
  1306. // High level decompression functions:
  1307. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
  1308. // allocated via malloc().
  1309. // On entry:
  1310. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
  1311. // to decompress.
  1312. // On return:
  1313. // Function returns a pointer to the decompressed data, or NULL on failure.
  1314. // *pOut_len will be set to the decompressed data's size, which could be larger
  1315. // than src_buf_len on uncompressible data.
  1316. // The caller must call mz_free() on the returned block when it's no longer
  1317. // needed.
  1318. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1319. size_t *pOut_len, int flags);
  1320. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
  1321. // in memory.
  1322. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
  1323. // written on success.
  1324. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  1325. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1326. const void *pSrc_buf, size_t src_buf_len,
  1327. int flags);
  1328. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an
  1329. // internal 32KB buffer, and a user provided callback function will be called to
  1330. // flush the buffer.
  1331. // Returns 1 on success or 0 on failure.
  1332. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
  1333. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  1334. tinfl_put_buf_func_ptr pPut_buf_func,
  1335. void *pPut_buf_user, int flags);
  1336. struct tinfl_decompressor_tag;
  1337. typedef struct tinfl_decompressor_tag tinfl_decompressor;
  1338. // Max size of LZ dictionary.
  1339. #define TINFL_LZ_DICT_SIZE 32768
  1340. // Return status.
  1341. typedef enum {
  1342. TINFL_STATUS_BAD_PARAM = -3,
  1343. TINFL_STATUS_ADLER32_MISMATCH = -2,
  1344. TINFL_STATUS_FAILED = -1,
  1345. TINFL_STATUS_DONE = 0,
  1346. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  1347. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  1348. } tinfl_status;
  1349. // Initializes the decompressor to its initial state.
  1350. #define tinfl_init(r) \
  1351. do { \
  1352. (r)->m_state = 0; \
  1353. } \
  1354. MZ_MACRO_END
  1355. #define tinfl_get_adler32(r) (r)->m_check_adler32
  1356. // Main low-level decompressor coroutine function. This is the only function
  1357. // actually needed for decompression. All the other functions are just
  1358. // high-level helpers for improved usability.
  1359. // This is a universal API, i.e. it can be used as a building block to build any
  1360. // desired higher level decompression API. In the limit case, it can be called
  1361. // once per every byte input or output.
  1362. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  1363. const mz_uint8 *pIn_buf_next,
  1364. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  1365. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  1366. const mz_uint32 decomp_flags);
  1367. // Internal/private bits follow.
  1368. enum {
  1369. TINFL_MAX_HUFF_TABLES = 3,
  1370. TINFL_MAX_HUFF_SYMBOLS_0 = 288,
  1371. TINFL_MAX_HUFF_SYMBOLS_1 = 32,
  1372. TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  1373. TINFL_FAST_LOOKUP_BITS = 10,
  1374. TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  1375. };
  1376. typedef struct {
  1377. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  1378. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
  1379. m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  1380. } tinfl_huff_table;
  1381. #if MINIZ_HAS_64BIT_REGISTERS
  1382. #define TINFL_USE_64BIT_BITBUF 1
  1383. #endif
  1384. #if TINFL_USE_64BIT_BITBUF
  1385. typedef mz_uint64 tinfl_bit_buf_t;
  1386. #define TINFL_BITBUF_SIZE (64)
  1387. #else
  1388. typedef mz_uint32 tinfl_bit_buf_t;
  1389. #define TINFL_BITBUF_SIZE (32)
  1390. #endif
  1391. struct tinfl_decompressor_tag {
  1392. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
  1393. m_check_adler32, m_dist, m_counter, m_num_extra,
  1394. m_table_sizes[TINFL_MAX_HUFF_TABLES];
  1395. tinfl_bit_buf_t m_bit_buf;
  1396. size_t m_dist_from_out_buf_start;
  1397. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  1398. mz_uint8 m_raw_header[4],
  1399. m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  1400. };
  1401. // ------------------- Low-level Compression API Definitions
  1402. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
  1403. // slower, and raw/dynamic blocks will be output more frequently).
  1404. #define TDEFL_LESS_MEMORY 0
  1405. // tdefl_init() compression flags logically OR'd together (low 12 bits contain
  1406. // the max. number of probes per dictionary search):
  1407. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
  1408. // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
  1409. // compression), 4095=Huffman+LZ (slowest/best compression).
  1410. enum {
  1411. TDEFL_HUFFMAN_ONLY = 0,
  1412. TDEFL_DEFAULT_MAX_PROBES = 128,
  1413. TDEFL_MAX_PROBES_MASK = 0xFFF
  1414. };
  1415. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
  1416. // the deflate data, and the Adler-32 of the source data at the end. Otherwise,
  1417. // you'll get raw deflate data.
  1418. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
  1419. // when not writing zlib headers).
  1420. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
  1421. // efficient lazy parsing.
  1422. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
  1423. // initialization time to the minimum, but the output may vary from run to run
  1424. // given the same input (depending on the contents of memory).
  1425. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  1426. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  1427. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  1428. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  1429. // The low 12 bits are reserved to control the max # of hash probes per
  1430. // dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  1431. enum {
  1432. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  1433. TDEFL_COMPUTE_ADLER32 = 0x02000,
  1434. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  1435. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  1436. TDEFL_RLE_MATCHES = 0x10000,
  1437. TDEFL_FILTER_MATCHES = 0x20000,
  1438. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  1439. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  1440. };
  1441. // High level compression functions:
  1442. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
  1443. // allocated via malloc().
  1444. // On entry:
  1445. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  1446. // flags: The max match finder probes (default is 128) logically OR'd against
  1447. // the above flags. Higher probes are slower but improve compression.
  1448. // On return:
  1449. // Function returns a pointer to the compressed data, or NULL on failure.
  1450. // *pOut_len will be set to the compressed data's size, which could be larger
  1451. // than src_buf_len on uncompressible data.
  1452. // The caller must free() the returned block when it's no longer needed.
  1453. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1454. size_t *pOut_len, int flags);
  1455. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in
  1456. // memory.
  1457. // Returns 0 on failure.
  1458. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1459. const void *pSrc_buf, size_t src_buf_len,
  1460. int flags);
  1461. // Compresses an image to a compressed PNG file in memory.
  1462. // On entry:
  1463. // pImage, w, h, and num_chans describe the image to compress. num_chans may be
  1464. // 1, 2, 3, or 4.
  1465. // The image pitch in bytes per scanline will be w*num_chans. The leftmost
  1466. // pixel on the top scanline is stored first in memory.
  1467. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
  1468. // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  1469. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL
  1470. // apps).
  1471. // On return:
  1472. // Function returns a pointer to the compressed data, or NULL on failure.
  1473. // *pLen_out will be set to the size of the PNG image file.
  1474. // The caller must mz_free() the returned heap block (which will typically be
  1475. // larger than *pLen_out) when it's no longer needed.
  1476. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  1477. int h, int num_chans,
  1478. size_t *pLen_out,
  1479. mz_uint level, mz_bool flip);
  1480. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  1481. int num_chans, size_t *pLen_out);
  1482. // Output stream interface. The compressor uses this interface to write
  1483. // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  1484. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
  1485. void *pUser);
  1486. // tdefl_compress_mem_to_output() compresses a block to an output stream. The
  1487. // above helpers use this function internally.
  1488. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  1489. tdefl_put_buf_func_ptr pPut_buf_func,
  1490. void *pPut_buf_user, int flags);
  1491. enum {
  1492. TDEFL_MAX_HUFF_TABLES = 3,
  1493. TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
  1494. TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
  1495. TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
  1496. TDEFL_LZ_DICT_SIZE = 32768,
  1497. TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
  1498. TDEFL_MIN_MATCH_LEN = 3,
  1499. TDEFL_MAX_MATCH_LEN = 258
  1500. };
  1501. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
  1502. // output block (using static/fixed Huffman codes).
  1503. #if TDEFL_LESS_MEMORY
  1504. enum {
  1505. TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
  1506. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1507. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1508. TDEFL_LZ_HASH_BITS = 12,
  1509. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1510. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1511. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1512. };
  1513. #else
  1514. enum {
  1515. TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
  1516. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1517. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1518. TDEFL_LZ_HASH_BITS = 15,
  1519. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1520. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1521. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1522. };
  1523. #endif
  1524. // The low-level tdefl functions below may be used directly if the above helper
  1525. // functions aren't flexible enough. The low-level functions don't make any heap
  1526. // allocations, unlike the above helper functions.
  1527. typedef enum {
  1528. TDEFL_STATUS_BAD_PARAM = -2,
  1529. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  1530. TDEFL_STATUS_OKAY = 0,
  1531. TDEFL_STATUS_DONE = 1
  1532. } tdefl_status;
  1533. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  1534. typedef enum {
  1535. TDEFL_NO_FLUSH = 0,
  1536. TDEFL_SYNC_FLUSH = 2,
  1537. TDEFL_FULL_FLUSH = 3,
  1538. TDEFL_FINISH = 4
  1539. } tdefl_flush;
  1540. // tdefl's compression state structure.
  1541. typedef struct {
  1542. tdefl_put_buf_func_ptr m_pPut_buf_func;
  1543. void *m_pPut_buf_user;
  1544. mz_uint m_flags, m_max_probes[2];
  1545. int m_greedy_parsing;
  1546. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  1547. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  1548. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
  1549. m_bit_buffer;
  1550. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
  1551. m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
  1552. m_wants_to_finish;
  1553. tdefl_status m_prev_return_status;
  1554. const void *m_pIn_buf;
  1555. void *m_pOut_buf;
  1556. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  1557. tdefl_flush m_flush;
  1558. const mz_uint8 *m_pSrc;
  1559. size_t m_src_buf_left, m_out_buf_ofs;
  1560. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  1561. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1562. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1563. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1564. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  1565. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  1566. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  1567. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  1568. } tdefl_compressor;
  1569. // Initializes the compressor.
  1570. // There is no corresponding deinit() function because the tdefl API's do not
  1571. // dynamically allocate memory.
  1572. // pBut_buf_func: If NULL, output data will be supplied to the specified
  1573. // callback. In this case, the user should call the tdefl_compress_buffer() API
  1574. // for compression.
  1575. // If pBut_buf_func is NULL the user should always call the tdefl_compress()
  1576. // API.
  1577. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
  1578. // etc.)
  1579. tdefl_status tdefl_init(tdefl_compressor *d,
  1580. tdefl_put_buf_func_ptr pPut_buf_func,
  1581. void *pPut_buf_user, int flags);
  1582. // Compresses a block of data, consuming as much of the specified input buffer
  1583. // as possible, and writing as much compressed data to the specified output
  1584. // buffer as possible.
  1585. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  1586. size_t *pIn_buf_size, void *pOut_buf,
  1587. size_t *pOut_buf_size, tdefl_flush flush);
  1588. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
  1589. // non-NULL tdefl_put_buf_func_ptr.
  1590. // tdefl_compress_buffer() always consumes the entire input buffer.
  1591. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  1592. size_t in_buf_size, tdefl_flush flush);
  1593. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  1594. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  1595. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
  1596. // defined, because it uses some of its macros.
  1597. #ifndef MINIZ_NO_ZLIB_APIS
  1598. // Create tdefl_compress() flags given zlib-style compression parameters.
  1599. // level may range from [0,10] (where 10 is absolute max compression, but may be
  1600. // much slower on some files)
  1601. // window_bits may be -15 (raw deflate) or 15 (zlib)
  1602. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
  1603. // MZ_RLE, or MZ_FIXED
  1604. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  1605. int strategy);
  1606. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  1607. #ifdef __cplusplus
  1608. }
  1609. #endif
  1610. #endif // MINIZ_HEADER_INCLUDED
  1611. // ------------------- End of Header: Implementation follows. (If you only want
  1612. // the header, define MINIZ_HEADER_FILE_ONLY.)
  1613. #ifndef MINIZ_HEADER_FILE_ONLY
  1614. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
  1615. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
  1616. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
  1617. //#include <assert.h>
  1618. //#include <string.h>
  1619. #define MZ_ASSERT(x) assert(x)
  1620. #ifdef MINIZ_NO_MALLOC
  1621. #define MZ_MALLOC(x) NULL
  1622. #define MZ_FREE(x) (void)x, ((void)0)
  1623. #define MZ_REALLOC(p, x) NULL
  1624. #else
  1625. #define MZ_MALLOC(x) malloc(x)
  1626. #define MZ_FREE(x) free(x)
  1627. #define MZ_REALLOC(p, x) realloc(p, x)
  1628. #endif
  1629. #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
  1630. #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
  1631. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  1632. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1633. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  1634. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  1635. #else
  1636. #define MZ_READ_LE16(p) \
  1637. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1638. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  1639. #define MZ_READ_LE32(p) \
  1640. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1641. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
  1642. ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
  1643. ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  1644. #endif
  1645. #ifdef _MSC_VER
  1646. #define MZ_FORCEINLINE __forceinline
  1647. #elif defined(__GNUC__)
  1648. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  1649. #else
  1650. #define MZ_FORCEINLINE inline
  1651. #endif
  1652. #ifdef __cplusplus
  1653. extern "C" {
  1654. #endif
  1655. // ------------------- zlib-style API's
  1656. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
  1657. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
  1658. size_t block_len = buf_len % 5552;
  1659. if (!ptr) return MZ_ADLER32_INIT;
  1660. while (buf_len) {
  1661. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  1662. s1 += ptr[0], s2 += s1;
  1663. s1 += ptr[1], s2 += s1;
  1664. s1 += ptr[2], s2 += s1;
  1665. s1 += ptr[3], s2 += s1;
  1666. s1 += ptr[4], s2 += s1;
  1667. s1 += ptr[5], s2 += s1;
  1668. s1 += ptr[6], s2 += s1;
  1669. s1 += ptr[7], s2 += s1;
  1670. }
  1671. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1672. s1 %= 65521U, s2 %= 65521U;
  1673. buf_len -= block_len;
  1674. block_len = 5552;
  1675. }
  1676. return (s2 << 16) + s1;
  1677. }
  1678. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
  1679. // implementation that balances processor cache usage against speed":
  1680. // http://www.geocities.com/malbrain/
  1681. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
  1682. static const mz_uint32 s_crc32[16] = {
  1683. 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
  1684. 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
  1685. 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
  1686. mz_uint32 crcu32 = (mz_uint32)crc;
  1687. if (!ptr) return MZ_CRC32_INIT;
  1688. crcu32 = ~crcu32;
  1689. while (buf_len--) {
  1690. mz_uint8 b = *ptr++;
  1691. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
  1692. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
  1693. }
  1694. return ~crcu32;
  1695. }
  1696. void mz_free(void *p) { MZ_FREE(p); }
  1697. #ifndef MINIZ_NO_ZLIB_APIS
  1698. static void *def_alloc_func(void *opaque, size_t items, size_t size) {
  1699. (void)opaque, (void)items, (void)size;
  1700. return MZ_MALLOC(items * size);
  1701. }
  1702. static void def_free_func(void *opaque, void *address) {
  1703. (void)opaque, (void)address;
  1704. MZ_FREE(address);
  1705. }
  1706. // static void *def_realloc_func(void *opaque, void *address, size_t items,
  1707. // size_t size) {
  1708. // (void)opaque, (void)address, (void)items, (void)size;
  1709. // return MZ_REALLOC(address, items * size);
  1710. //}
  1711. const char *mz_version(void) { return MZ_VERSION; }
  1712. int mz_deflateInit(mz_streamp pStream, int level) {
  1713. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
  1714. MZ_DEFAULT_STRATEGY);
  1715. }
  1716. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  1717. int mem_level, int strategy) {
  1718. tdefl_compressor *pComp;
  1719. mz_uint comp_flags =
  1720. TDEFL_COMPUTE_ADLER32 |
  1721. tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  1722. if (!pStream) return MZ_STREAM_ERROR;
  1723. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
  1724. ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1725. (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
  1726. return MZ_PARAM_ERROR;
  1727. pStream->data_type = 0;
  1728. pStream->adler = MZ_ADLER32_INIT;
  1729. pStream->msg = NULL;
  1730. pStream->reserved = 0;
  1731. pStream->total_in = 0;
  1732. pStream->total_out = 0;
  1733. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1734. if (!pStream->zfree) pStream->zfree = def_free_func;
  1735. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
  1736. sizeof(tdefl_compressor));
  1737. if (!pComp) return MZ_MEM_ERROR;
  1738. pStream->state = (struct mz_internal_state *)pComp;
  1739. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
  1740. mz_deflateEnd(pStream);
  1741. return MZ_PARAM_ERROR;
  1742. }
  1743. return MZ_OK;
  1744. }
  1745. int mz_deflateReset(mz_streamp pStream) {
  1746. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
  1747. (!pStream->zfree))
  1748. return MZ_STREAM_ERROR;
  1749. pStream->total_in = pStream->total_out = 0;
  1750. tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
  1751. ((tdefl_compressor *)pStream->state)->m_flags);
  1752. return MZ_OK;
  1753. }
  1754. int mz_deflate(mz_streamp pStream, int flush) {
  1755. size_t in_bytes, out_bytes;
  1756. mz_ulong orig_total_in, orig_total_out;
  1757. int mz_status = MZ_OK;
  1758. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
  1759. (!pStream->next_out))
  1760. return MZ_STREAM_ERROR;
  1761. if (!pStream->avail_out) return MZ_BUF_ERROR;
  1762. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1763. if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
  1764. TDEFL_STATUS_DONE)
  1765. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  1766. orig_total_in = pStream->total_in;
  1767. orig_total_out = pStream->total_out;
  1768. for (;;) {
  1769. tdefl_status defl_status;
  1770. in_bytes = pStream->avail_in;
  1771. out_bytes = pStream->avail_out;
  1772. defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
  1773. pStream->next_in, &in_bytes, pStream->next_out,
  1774. &out_bytes, (tdefl_flush)flush);
  1775. pStream->next_in += (mz_uint)in_bytes;
  1776. pStream->avail_in -= (mz_uint)in_bytes;
  1777. pStream->total_in += (mz_uint)in_bytes;
  1778. pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
  1779. pStream->next_out += (mz_uint)out_bytes;
  1780. pStream->avail_out -= (mz_uint)out_bytes;
  1781. pStream->total_out += (mz_uint)out_bytes;
  1782. if (defl_status < 0) {
  1783. mz_status = MZ_STREAM_ERROR;
  1784. break;
  1785. } else if (defl_status == TDEFL_STATUS_DONE) {
  1786. mz_status = MZ_STREAM_END;
  1787. break;
  1788. } else if (!pStream->avail_out)
  1789. break;
  1790. else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
  1791. if ((flush) || (pStream->total_in != orig_total_in) ||
  1792. (pStream->total_out != orig_total_out))
  1793. break;
  1794. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  1795. }
  1796. }
  1797. return mz_status;
  1798. }
  1799. int mz_deflateEnd(mz_streamp pStream) {
  1800. if (!pStream) return MZ_STREAM_ERROR;
  1801. if (pStream->state) {
  1802. pStream->zfree(pStream->opaque, pStream->state);
  1803. pStream->state = NULL;
  1804. }
  1805. return MZ_OK;
  1806. }
  1807. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
  1808. (void)pStream;
  1809. // This is really over conservative. (And lame, but it's actually pretty
  1810. // tricky to compute a true upper bound given the way tdefl's blocking works.)
  1811. return MZ_MAX(128 + (source_len * 110) / 100,
  1812. 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  1813. }
  1814. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  1815. const unsigned char *pSource, mz_ulong source_len, int level) {
  1816. int status;
  1817. mz_stream stream;
  1818. memset(&stream, 0, sizeof(stream));
  1819. // In case mz_ulong is 64-bits (argh I hate longs).
  1820. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1821. stream.next_in = pSource;
  1822. stream.avail_in = (mz_uint32)source_len;
  1823. stream.next_out = pDest;
  1824. stream.avail_out = (mz_uint32)*pDest_len;
  1825. status = mz_deflateInit(&stream, level);
  1826. if (status != MZ_OK) return status;
  1827. status = mz_deflate(&stream, MZ_FINISH);
  1828. if (status != MZ_STREAM_END) {
  1829. mz_deflateEnd(&stream);
  1830. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1831. }
  1832. *pDest_len = stream.total_out;
  1833. return mz_deflateEnd(&stream);
  1834. }
  1835. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  1836. const unsigned char *pSource, mz_ulong source_len) {
  1837. return mz_compress2(pDest, pDest_len, pSource, source_len,
  1838. MZ_DEFAULT_COMPRESSION);
  1839. }
  1840. mz_ulong mz_compressBound(mz_ulong source_len) {
  1841. return mz_deflateBound(NULL, source_len);
  1842. }
  1843. typedef struct {
  1844. tinfl_decompressor m_decomp;
  1845. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
  1846. int m_window_bits;
  1847. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1848. tinfl_status m_last_status;
  1849. } inflate_state;
  1850. int mz_inflateInit2(mz_streamp pStream, int window_bits) {
  1851. inflate_state *pDecomp;
  1852. if (!pStream) return MZ_STREAM_ERROR;
  1853. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1854. (-window_bits != MZ_DEFAULT_WINDOW_BITS))
  1855. return MZ_PARAM_ERROR;
  1856. pStream->data_type = 0;
  1857. pStream->adler = 0;
  1858. pStream->msg = NULL;
  1859. pStream->total_in = 0;
  1860. pStream->total_out = 0;
  1861. pStream->reserved = 0;
  1862. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1863. if (!pStream->zfree) pStream->zfree = def_free_func;
  1864. pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
  1865. sizeof(inflate_state));
  1866. if (!pDecomp) return MZ_MEM_ERROR;
  1867. pStream->state = (struct mz_internal_state *)pDecomp;
  1868. tinfl_init(&pDecomp->m_decomp);
  1869. pDecomp->m_dict_ofs = 0;
  1870. pDecomp->m_dict_avail = 0;
  1871. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1872. pDecomp->m_first_call = 1;
  1873. pDecomp->m_has_flushed = 0;
  1874. pDecomp->m_window_bits = window_bits;
  1875. return MZ_OK;
  1876. }
  1877. int mz_inflateInit(mz_streamp pStream) {
  1878. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1879. }
  1880. int mz_inflate(mz_streamp pStream, int flush) {
  1881. inflate_state *pState;
  1882. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1883. size_t in_bytes, out_bytes, orig_avail_in;
  1884. tinfl_status status;
  1885. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  1886. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1887. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
  1888. return MZ_STREAM_ERROR;
  1889. pState = (inflate_state *)pStream->state;
  1890. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1891. orig_avail_in = pStream->avail_in;
  1892. first_call = pState->m_first_call;
  1893. pState->m_first_call = 0;
  1894. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1895. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1896. pState->m_has_flushed |= (flush == MZ_FINISH);
  1897. if ((flush == MZ_FINISH) && (first_call)) {
  1898. // MZ_FINISH on the first call implies that the input and output buffers are
  1899. // large enough to hold the entire compressed/decompressed file.
  1900. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1901. in_bytes = pStream->avail_in;
  1902. out_bytes = pStream->avail_out;
  1903. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
  1904. pStream->next_out, pStream->next_out, &out_bytes,
  1905. decomp_flags);
  1906. pState->m_last_status = status;
  1907. pStream->next_in += (mz_uint)in_bytes;
  1908. pStream->avail_in -= (mz_uint)in_bytes;
  1909. pStream->total_in += (mz_uint)in_bytes;
  1910. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1911. pStream->next_out += (mz_uint)out_bytes;
  1912. pStream->avail_out -= (mz_uint)out_bytes;
  1913. pStream->total_out += (mz_uint)out_bytes;
  1914. if (status < 0)
  1915. return MZ_DATA_ERROR;
  1916. else if (status != TINFL_STATUS_DONE) {
  1917. pState->m_last_status = TINFL_STATUS_FAILED;
  1918. return MZ_BUF_ERROR;
  1919. }
  1920. return MZ_STREAM_END;
  1921. }
  1922. // flush != MZ_FINISH then we must assume there's more input.
  1923. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1924. if (pState->m_dict_avail) {
  1925. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1926. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1927. pStream->next_out += n;
  1928. pStream->avail_out -= n;
  1929. pStream->total_out += n;
  1930. pState->m_dict_avail -= n;
  1931. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1932. return ((pState->m_last_status == TINFL_STATUS_DONE) &&
  1933. (!pState->m_dict_avail))
  1934. ? MZ_STREAM_END
  1935. : MZ_OK;
  1936. }
  1937. for (;;) {
  1938. in_bytes = pStream->avail_in;
  1939. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1940. status = tinfl_decompress(
  1941. &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
  1942. pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1943. pState->m_last_status = status;
  1944. pStream->next_in += (mz_uint)in_bytes;
  1945. pStream->avail_in -= (mz_uint)in_bytes;
  1946. pStream->total_in += (mz_uint)in_bytes;
  1947. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1948. pState->m_dict_avail = (mz_uint)out_bytes;
  1949. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1950. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1951. pStream->next_out += n;
  1952. pStream->avail_out -= n;
  1953. pStream->total_out += n;
  1954. pState->m_dict_avail -= n;
  1955. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1956. if (status < 0)
  1957. return MZ_DATA_ERROR; // Stream is corrupted (there could be some
  1958. // uncompressed data left in the output dictionary -
  1959. // oh well).
  1960. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1961. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
  1962. // without supplying more input or by setting flush
  1963. // to MZ_FINISH.
  1964. else if (flush == MZ_FINISH) {
  1965. // The output buffer MUST be large to hold the remaining uncompressed data
  1966. // when flush==MZ_FINISH.
  1967. if (status == TINFL_STATUS_DONE)
  1968. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1969. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
  1970. // at least 1 more byte on the way. If there's no more room left in the
  1971. // output buffer then something is wrong.
  1972. else if (!pStream->avail_out)
  1973. return MZ_BUF_ERROR;
  1974. } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
  1975. (!pStream->avail_out) || (pState->m_dict_avail))
  1976. break;
  1977. }
  1978. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
  1979. ? MZ_STREAM_END
  1980. : MZ_OK;
  1981. }
  1982. int mz_inflateEnd(mz_streamp pStream) {
  1983. if (!pStream) return MZ_STREAM_ERROR;
  1984. if (pStream->state) {
  1985. pStream->zfree(pStream->opaque, pStream->state);
  1986. pStream->state = NULL;
  1987. }
  1988. return MZ_OK;
  1989. }
  1990. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  1991. const unsigned char *pSource, mz_ulong source_len) {
  1992. mz_stream stream;
  1993. int status;
  1994. memset(&stream, 0, sizeof(stream));
  1995. // In case mz_ulong is 64-bits (argh I hate longs).
  1996. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1997. stream.next_in = pSource;
  1998. stream.avail_in = (mz_uint32)source_len;
  1999. stream.next_out = pDest;
  2000. stream.avail_out = (mz_uint32)*pDest_len;
  2001. status = mz_inflateInit(&stream);
  2002. if (status != MZ_OK) return status;
  2003. status = mz_inflate(&stream, MZ_FINISH);
  2004. if (status != MZ_STREAM_END) {
  2005. mz_inflateEnd(&stream);
  2006. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
  2007. : status;
  2008. }
  2009. *pDest_len = stream.total_out;
  2010. return mz_inflateEnd(&stream);
  2011. }
  2012. const char *mz_error(int err) {
  2013. static struct {
  2014. int m_err;
  2015. const char *m_pDesc;
  2016. } s_error_descs[] = {{MZ_OK, ""},
  2017. {MZ_STREAM_END, "stream end"},
  2018. {MZ_NEED_DICT, "need dictionary"},
  2019. {MZ_ERRNO, "file error"},
  2020. {MZ_STREAM_ERROR, "stream error"},
  2021. {MZ_DATA_ERROR, "data error"},
  2022. {MZ_MEM_ERROR, "out of memory"},
  2023. {MZ_BUF_ERROR, "buf error"},
  2024. {MZ_VERSION_ERROR, "version error"},
  2025. {MZ_PARAM_ERROR, "parameter error"}};
  2026. mz_uint i;
  2027. for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
  2028. if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  2029. return NULL;
  2030. }
  2031. #endif // MINIZ_NO_ZLIB_APIS
  2032. // ------------------- Low-level Decompression (completely independent from all
  2033. // compression API's)
  2034. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  2035. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  2036. #define TINFL_CR_BEGIN \
  2037. switch (r->m_state) { \
  2038. case 0:
  2039. #define TINFL_CR_RETURN(state_index, result) \
  2040. do { \
  2041. status = result; \
  2042. r->m_state = state_index; \
  2043. goto common_exit; \
  2044. case state_index:; \
  2045. } \
  2046. MZ_MACRO_END
  2047. #define TINFL_CR_RETURN_FOREVER(state_index, result) \
  2048. do { \
  2049. for (;;) { \
  2050. TINFL_CR_RETURN(state_index, result); \
  2051. } \
  2052. } \
  2053. MZ_MACRO_END
  2054. #define TINFL_CR_FINISH }
  2055. // TODO: If the caller has indicated that there's no more input, and we attempt
  2056. // to read beyond the input buf, then something is wrong with the input because
  2057. // the inflator never
  2058. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
  2059. // the stream with 0's in this scenario.
  2060. #define TINFL_GET_BYTE(state_index, c) \
  2061. do { \
  2062. if (pIn_buf_cur >= pIn_buf_end) { \
  2063. for (;;) { \
  2064. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  2065. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  2066. if (pIn_buf_cur < pIn_buf_end) { \
  2067. c = *pIn_buf_cur++; \
  2068. break; \
  2069. } \
  2070. } else { \
  2071. c = 0; \
  2072. break; \
  2073. } \
  2074. } \
  2075. } else \
  2076. c = *pIn_buf_cur++; \
  2077. } \
  2078. MZ_MACRO_END
  2079. #define TINFL_NEED_BITS(state_index, n) \
  2080. do { \
  2081. mz_uint c; \
  2082. TINFL_GET_BYTE(state_index, c); \
  2083. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2084. num_bits += 8; \
  2085. } while (num_bits < (mz_uint)(n))
  2086. #define TINFL_SKIP_BITS(state_index, n) \
  2087. do { \
  2088. if (num_bits < (mz_uint)(n)) { \
  2089. TINFL_NEED_BITS(state_index, n); \
  2090. } \
  2091. bit_buf >>= (n); \
  2092. num_bits -= (n); \
  2093. } \
  2094. MZ_MACRO_END
  2095. #define TINFL_GET_BITS(state_index, b, n) \
  2096. do { \
  2097. if (num_bits < (mz_uint)(n)) { \
  2098. TINFL_NEED_BITS(state_index, n); \
  2099. } \
  2100. b = bit_buf & ((1 << (n)) - 1); \
  2101. bit_buf >>= (n); \
  2102. num_bits -= (n); \
  2103. } \
  2104. MZ_MACRO_END
  2105. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
  2106. // remaining in the input buffer falls below 2.
  2107. // It reads just enough bytes from the input stream that are needed to decode
  2108. // the next Huffman code (and absolutely no more). It works by trying to fully
  2109. // decode a
  2110. // Huffman code by using whatever bits are currently present in the bit buffer.
  2111. // If this fails, it reads another byte, and tries again until it succeeds or
  2112. // until the
  2113. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  2114. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  2115. do { \
  2116. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  2117. if (temp >= 0) { \
  2118. code_len = temp >> 9; \
  2119. if ((code_len) && (num_bits >= code_len)) break; \
  2120. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  2121. code_len = TINFL_FAST_LOOKUP_BITS; \
  2122. do { \
  2123. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2124. } while ((temp < 0) && (num_bits >= (code_len + 1))); \
  2125. if (temp >= 0) break; \
  2126. } \
  2127. TINFL_GET_BYTE(state_index, c); \
  2128. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2129. num_bits += 8; \
  2130. } while (num_bits < 15);
  2131. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
  2132. // than you would initially expect because the zlib API expects the decompressor
  2133. // to never read
  2134. // beyond the final byte of the deflate stream. (In other words, when this macro
  2135. // wants to read another byte from the input, it REALLY needs another byte in
  2136. // order to fully
  2137. // decode the next Huffman code.) Handling this properly is particularly
  2138. // important on raw deflate (non-zlib) streams, which aren't followed by a byte
  2139. // aligned adler-32.
  2140. // The slow path is only executed at the very end of the input buffer.
  2141. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
  2142. do { \
  2143. int temp; \
  2144. mz_uint code_len, c; \
  2145. if (num_bits < 15) { \
  2146. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  2147. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  2148. } else { \
  2149. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
  2150. (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
  2151. pIn_buf_cur += 2; \
  2152. num_bits += 16; \
  2153. } \
  2154. } \
  2155. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
  2156. 0) \
  2157. code_len = temp >> 9, temp &= 511; \
  2158. else { \
  2159. code_len = TINFL_FAST_LOOKUP_BITS; \
  2160. do { \
  2161. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2162. } while (temp < 0); \
  2163. } \
  2164. sym = temp; \
  2165. bit_buf >>= code_len; \
  2166. num_bits -= code_len; \
  2167. } \
  2168. MZ_MACRO_END
  2169. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  2170. const mz_uint8 *pIn_buf_next,
  2171. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  2172. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  2173. const mz_uint32 decomp_flags) {
  2174. static const int s_length_base[31] = {
  2175. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  2176. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  2177. static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
  2178. 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  2179. 4, 4, 5, 5, 5, 5, 0, 0, 0};
  2180. static const int s_dist_base[32] = {
  2181. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
  2182. 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
  2183. 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
  2184. static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  2185. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  2186. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
  2187. static const mz_uint8 s_length_dezigzag[19] = {
  2188. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2189. static const int s_min_table_sizes[3] = {257, 1, 4};
  2190. tinfl_status status = TINFL_STATUS_FAILED;
  2191. mz_uint32 num_bits, dist, counter, num_extra;
  2192. tinfl_bit_buf_t bit_buf;
  2193. const mz_uint8 *pIn_buf_cur = pIn_buf_next,
  2194. *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  2195. mz_uint8 *pOut_buf_cur = pOut_buf_next,
  2196. *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  2197. size_t out_buf_size_mask =
  2198. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
  2199. ? (size_t)-1
  2200. : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
  2201. dist_from_out_buf_start;
  2202. // Ensure the output buffer's size is a power of 2, unless the output buffer
  2203. // is large enough to hold the entire output file (in which case it doesn't
  2204. // matter).
  2205. if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
  2206. (pOut_buf_next < pOut_buf_start)) {
  2207. *pIn_buf_size = *pOut_buf_size = 0;
  2208. return TINFL_STATUS_BAD_PARAM;
  2209. }
  2210. num_bits = r->m_num_bits;
  2211. bit_buf = r->m_bit_buf;
  2212. dist = r->m_dist;
  2213. counter = r->m_counter;
  2214. num_extra = r->m_num_extra;
  2215. dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  2216. TINFL_CR_BEGIN
  2217. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
  2218. r->m_z_adler32 = r->m_check_adler32 = 1;
  2219. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2220. TINFL_GET_BYTE(1, r->m_zhdr0);
  2221. TINFL_GET_BYTE(2, r->m_zhdr1);
  2222. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
  2223. (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  2224. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  2225. counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
  2226. ((out_buf_size_mask + 1) <
  2227. (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4)))));
  2228. if (counter) {
  2229. TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
  2230. }
  2231. }
  2232. do {
  2233. TINFL_GET_BITS(3, r->m_final, 3);
  2234. r->m_type = r->m_final >> 1;
  2235. if (r->m_type == 0) {
  2236. TINFL_SKIP_BITS(5, num_bits & 7);
  2237. for (counter = 0; counter < 4; ++counter) {
  2238. if (num_bits)
  2239. TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
  2240. else
  2241. TINFL_GET_BYTE(7, r->m_raw_header[counter]);
  2242. }
  2243. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
  2244. (mz_uint)(0xFFFF ^
  2245. (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
  2246. TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
  2247. }
  2248. while ((counter) && (num_bits)) {
  2249. TINFL_GET_BITS(51, dist, 8);
  2250. while (pOut_buf_cur >= pOut_buf_end) {
  2251. TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
  2252. }
  2253. *pOut_buf_cur++ = (mz_uint8)dist;
  2254. counter--;
  2255. }
  2256. while (counter) {
  2257. size_t n;
  2258. while (pOut_buf_cur >= pOut_buf_end) {
  2259. TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
  2260. }
  2261. while (pIn_buf_cur >= pIn_buf_end) {
  2262. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
  2263. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  2264. } else {
  2265. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  2266. }
  2267. }
  2268. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
  2269. (size_t)(pIn_buf_end - pIn_buf_cur)),
  2270. counter);
  2271. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
  2272. pIn_buf_cur += n;
  2273. pOut_buf_cur += n;
  2274. counter -= (mz_uint)n;
  2275. }
  2276. } else if (r->m_type == 3) {
  2277. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  2278. } else {
  2279. if (r->m_type == 1) {
  2280. mz_uint8 *p = r->m_tables[0].m_code_size;
  2281. mz_uint i;
  2282. r->m_table_sizes[0] = 288;
  2283. r->m_table_sizes[1] = 32;
  2284. TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  2285. for (i = 0; i <= 143; ++i) *p++ = 8;
  2286. for (; i <= 255; ++i) *p++ = 9;
  2287. for (; i <= 279; ++i) *p++ = 7;
  2288. for (; i <= 287; ++i) *p++ = 8;
  2289. } else {
  2290. for (counter = 0; counter < 3; counter++) {
  2291. TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
  2292. r->m_table_sizes[counter] += s_min_table_sizes[counter];
  2293. }
  2294. MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
  2295. for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
  2296. mz_uint s;
  2297. TINFL_GET_BITS(14, s, 3);
  2298. r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
  2299. }
  2300. r->m_table_sizes[2] = 19;
  2301. }
  2302. for (; (int)r->m_type >= 0; r->m_type--) {
  2303. int tree_next, tree_cur;
  2304. tinfl_huff_table *pTable;
  2305. mz_uint i, j, used_syms, total, sym_index, next_code[17],
  2306. total_syms[16];
  2307. pTable = &r->m_tables[r->m_type];
  2308. MZ_CLEAR_OBJ(total_syms);
  2309. MZ_CLEAR_OBJ(pTable->m_look_up);
  2310. MZ_CLEAR_OBJ(pTable->m_tree);
  2311. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
  2312. total_syms[pTable->m_code_size[i]]++;
  2313. used_syms = 0, total = 0;
  2314. next_code[0] = next_code[1] = 0;
  2315. for (i = 1; i <= 15; ++i) {
  2316. used_syms += total_syms[i];
  2317. next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
  2318. }
  2319. if ((65536 != total) && (used_syms > 1)) {
  2320. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  2321. }
  2322. for (tree_next = -1, sym_index = 0;
  2323. sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
  2324. mz_uint rev_code = 0, l, cur_code,
  2325. code_size = pTable->m_code_size[sym_index];
  2326. if (!code_size) continue;
  2327. cur_code = next_code[code_size]++;
  2328. for (l = code_size; l > 0; l--, cur_code >>= 1)
  2329. rev_code = (rev_code << 1) | (cur_code & 1);
  2330. if (code_size <= TINFL_FAST_LOOKUP_BITS) {
  2331. mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
  2332. while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
  2333. pTable->m_look_up[rev_code] = k;
  2334. rev_code += (1 << code_size);
  2335. }
  2336. continue;
  2337. }
  2338. if (0 ==
  2339. (tree_cur = pTable->m_look_up[rev_code &
  2340. (TINFL_FAST_LOOKUP_SIZE - 1)])) {
  2341. pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
  2342. (mz_int16)tree_next;
  2343. tree_cur = tree_next;
  2344. tree_next -= 2;
  2345. }
  2346. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  2347. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
  2348. tree_cur -= ((rev_code >>= 1) & 1);
  2349. if (!pTable->m_tree[-tree_cur - 1]) {
  2350. pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
  2351. tree_cur = tree_next;
  2352. tree_next -= 2;
  2353. } else
  2354. tree_cur = pTable->m_tree[-tree_cur - 1];
  2355. }
  2356. tree_cur -= ((rev_code >>= 1) & 1);
  2357. pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  2358. }
  2359. if (r->m_type == 2) {
  2360. for (counter = 0;
  2361. counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
  2362. mz_uint s;
  2363. TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
  2364. if (dist < 16) {
  2365. r->m_len_codes[counter++] = (mz_uint8)dist;
  2366. continue;
  2367. }
  2368. if ((dist == 16) && (!counter)) {
  2369. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  2370. }
  2371. num_extra = "\02\03\07"[dist - 16];
  2372. TINFL_GET_BITS(18, s, num_extra);
  2373. s += "\03\03\013"[dist - 16];
  2374. TINFL_MEMSET(r->m_len_codes + counter,
  2375. (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
  2376. counter += s;
  2377. }
  2378. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
  2379. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  2380. }
  2381. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
  2382. r->m_table_sizes[0]);
  2383. TINFL_MEMCPY(r->m_tables[1].m_code_size,
  2384. r->m_len_codes + r->m_table_sizes[0],
  2385. r->m_table_sizes[1]);
  2386. }
  2387. }
  2388. for (;;) {
  2389. mz_uint8 *pSrc;
  2390. for (;;) {
  2391. if (((pIn_buf_end - pIn_buf_cur) < 4) ||
  2392. ((pOut_buf_end - pOut_buf_cur) < 2)) {
  2393. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  2394. if (counter >= 256) break;
  2395. while (pOut_buf_cur >= pOut_buf_end) {
  2396. TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
  2397. }
  2398. *pOut_buf_cur++ = (mz_uint8)counter;
  2399. } else {
  2400. int sym2;
  2401. mz_uint code_len;
  2402. #if TINFL_USE_64BIT_BITBUF
  2403. if (num_bits < 30) {
  2404. bit_buf |=
  2405. (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
  2406. pIn_buf_cur += 4;
  2407. num_bits += 32;
  2408. }
  2409. #else
  2410. if (num_bits < 15) {
  2411. bit_buf |=
  2412. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2413. pIn_buf_cur += 2;
  2414. num_bits += 16;
  2415. }
  2416. #endif
  2417. if ((sym2 =
  2418. r->m_tables[0]
  2419. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2420. 0)
  2421. code_len = sym2 >> 9;
  2422. else {
  2423. code_len = TINFL_FAST_LOOKUP_BITS;
  2424. do {
  2425. sym2 = r->m_tables[0]
  2426. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2427. } while (sym2 < 0);
  2428. }
  2429. counter = sym2;
  2430. bit_buf >>= code_len;
  2431. num_bits -= code_len;
  2432. if (counter & 256) break;
  2433. #if !TINFL_USE_64BIT_BITBUF
  2434. if (num_bits < 15) {
  2435. bit_buf |=
  2436. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2437. pIn_buf_cur += 2;
  2438. num_bits += 16;
  2439. }
  2440. #endif
  2441. if ((sym2 =
  2442. r->m_tables[0]
  2443. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2444. 0)
  2445. code_len = sym2 >> 9;
  2446. else {
  2447. code_len = TINFL_FAST_LOOKUP_BITS;
  2448. do {
  2449. sym2 = r->m_tables[0]
  2450. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2451. } while (sym2 < 0);
  2452. }
  2453. bit_buf >>= code_len;
  2454. num_bits -= code_len;
  2455. pOut_buf_cur[0] = (mz_uint8)counter;
  2456. if (sym2 & 256) {
  2457. pOut_buf_cur++;
  2458. counter = sym2;
  2459. break;
  2460. }
  2461. pOut_buf_cur[1] = (mz_uint8)sym2;
  2462. pOut_buf_cur += 2;
  2463. }
  2464. }
  2465. if ((counter &= 511) == 256) break;
  2466. num_extra = s_length_extra[counter - 257];
  2467. counter = s_length_base[counter - 257];
  2468. if (num_extra) {
  2469. mz_uint extra_bits;
  2470. TINFL_GET_BITS(25, extra_bits, num_extra);
  2471. counter += extra_bits;
  2472. }
  2473. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  2474. num_extra = s_dist_extra[dist];
  2475. dist = s_dist_base[dist];
  2476. if (num_extra) {
  2477. mz_uint extra_bits;
  2478. TINFL_GET_BITS(27, extra_bits, num_extra);
  2479. dist += extra_bits;
  2480. }
  2481. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  2482. if ((dist > dist_from_out_buf_start) &&
  2483. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
  2484. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  2485. }
  2486. pSrc = pOut_buf_start +
  2487. ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  2488. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
  2489. while (counter--) {
  2490. while (pOut_buf_cur >= pOut_buf_end) {
  2491. TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
  2492. }
  2493. *pOut_buf_cur++ =
  2494. pOut_buf_start[(dist_from_out_buf_start++ - dist) &
  2495. out_buf_size_mask];
  2496. }
  2497. continue;
  2498. }
  2499. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2500. else if ((counter >= 9) && (counter <= dist)) {
  2501. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  2502. do {
  2503. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  2504. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  2505. pOut_buf_cur += 8;
  2506. } while ((pSrc += 8) < pSrc_end);
  2507. if ((counter &= 7) < 3) {
  2508. if (counter) {
  2509. pOut_buf_cur[0] = pSrc[0];
  2510. if (counter > 1) pOut_buf_cur[1] = pSrc[1];
  2511. pOut_buf_cur += counter;
  2512. }
  2513. continue;
  2514. }
  2515. }
  2516. #endif
  2517. do {
  2518. pOut_buf_cur[0] = pSrc[0];
  2519. pOut_buf_cur[1] = pSrc[1];
  2520. pOut_buf_cur[2] = pSrc[2];
  2521. pOut_buf_cur += 3;
  2522. pSrc += 3;
  2523. } while ((int)(counter -= 3) > 2);
  2524. if ((int)counter > 0) {
  2525. pOut_buf_cur[0] = pSrc[0];
  2526. if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1];
  2527. pOut_buf_cur += counter;
  2528. }
  2529. }
  2530. }
  2531. } while (!(r->m_final & 1));
  2532. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2533. TINFL_SKIP_BITS(32, num_bits & 7);
  2534. for (counter = 0; counter < 4; ++counter) {
  2535. mz_uint s;
  2536. if (num_bits)
  2537. TINFL_GET_BITS(41, s, 8);
  2538. else
  2539. TINFL_GET_BYTE(42, s);
  2540. r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
  2541. }
  2542. }
  2543. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  2544. TINFL_CR_FINISH
  2545. common_exit:
  2546. r->m_num_bits = num_bits;
  2547. r->m_bit_buf = bit_buf;
  2548. r->m_dist = dist;
  2549. r->m_counter = counter;
  2550. r->m_num_extra = num_extra;
  2551. r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  2552. *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
  2553. *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  2554. if ((decomp_flags &
  2555. (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
  2556. (status >= 0)) {
  2557. const mz_uint8 *ptr = pOut_buf_next;
  2558. size_t buf_len = *pOut_buf_size;
  2559. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
  2560. s2 = r->m_check_adler32 >> 16;
  2561. size_t block_len = buf_len % 5552;
  2562. while (buf_len) {
  2563. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  2564. s1 += ptr[0], s2 += s1;
  2565. s1 += ptr[1], s2 += s1;
  2566. s1 += ptr[2], s2 += s1;
  2567. s1 += ptr[3], s2 += s1;
  2568. s1 += ptr[4], s2 += s1;
  2569. s1 += ptr[5], s2 += s1;
  2570. s1 += ptr[6], s2 += s1;
  2571. s1 += ptr[7], s2 += s1;
  2572. }
  2573. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  2574. s1 %= 65521U, s2 %= 65521U;
  2575. buf_len -= block_len;
  2576. block_len = 5552;
  2577. }
  2578. r->m_check_adler32 = (s2 << 16) + s1;
  2579. if ((status == TINFL_STATUS_DONE) &&
  2580. (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
  2581. (r->m_check_adler32 != r->m_z_adler32))
  2582. status = TINFL_STATUS_ADLER32_MISMATCH;
  2583. }
  2584. return status;
  2585. }
  2586. // Higher level helper functions.
  2587. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  2588. size_t *pOut_len, int flags) {
  2589. tinfl_decompressor decomp;
  2590. void *pBuf = NULL, *pNew_buf;
  2591. size_t src_buf_ofs = 0, out_buf_capacity = 0;
  2592. *pOut_len = 0;
  2593. tinfl_init(&decomp);
  2594. for (;;) {
  2595. size_t src_buf_size = src_buf_len - src_buf_ofs,
  2596. dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  2597. tinfl_status status = tinfl_decompress(
  2598. &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
  2599. (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
  2600. &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2601. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2602. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
  2603. MZ_FREE(pBuf);
  2604. *pOut_len = 0;
  2605. return NULL;
  2606. }
  2607. src_buf_ofs += src_buf_size;
  2608. *pOut_len += dst_buf_size;
  2609. if (status == TINFL_STATUS_DONE) break;
  2610. new_out_buf_capacity = out_buf_capacity * 2;
  2611. if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  2612. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  2613. if (!pNew_buf) {
  2614. MZ_FREE(pBuf);
  2615. *pOut_len = 0;
  2616. return NULL;
  2617. }
  2618. pBuf = pNew_buf;
  2619. out_buf_capacity = new_out_buf_capacity;
  2620. }
  2621. return pBuf;
  2622. }
  2623. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  2624. const void *pSrc_buf, size_t src_buf_len,
  2625. int flags) {
  2626. tinfl_decompressor decomp;
  2627. tinfl_status status;
  2628. tinfl_init(&decomp);
  2629. status =
  2630. tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
  2631. (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
  2632. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2633. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2634. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
  2635. : out_buf_len;
  2636. }
  2637. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  2638. tinfl_put_buf_func_ptr pPut_buf_func,
  2639. void *pPut_buf_user, int flags) {
  2640. int result = 0;
  2641. tinfl_decompressor decomp;
  2642. mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
  2643. size_t in_buf_ofs = 0, dict_ofs = 0;
  2644. if (!pDict) return TINFL_STATUS_FAILED;
  2645. tinfl_init(&decomp);
  2646. for (;;) {
  2647. size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
  2648. dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  2649. tinfl_status status =
  2650. tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
  2651. &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  2652. (flags &
  2653. ~(TINFL_FLAG_HAS_MORE_INPUT |
  2654. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  2655. in_buf_ofs += in_buf_size;
  2656. if ((dst_buf_size) &&
  2657. (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  2658. break;
  2659. if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
  2660. result = (status == TINFL_STATUS_DONE);
  2661. break;
  2662. }
  2663. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  2664. }
  2665. MZ_FREE(pDict);
  2666. *pIn_buf_size = in_buf_ofs;
  2667. return result;
  2668. }
  2669. // ------------------- Low-level Compression (independent from all decompression
  2670. // API's)
  2671. // Purposely making these tables static for faster init and thread safety.
  2672. static const mz_uint16 s_tdefl_len_sym[256] = {
  2673. 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
  2674. 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
  2675. 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
  2676. 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
  2677. 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  2678. 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
  2679. 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
  2680. 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
  2681. 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
  2682. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
  2683. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
  2684. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
  2685. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
  2686. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  2687. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
  2688. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2689. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2690. 285};
  2691. static const mz_uint8 s_tdefl_len_extra[256] = {
  2692. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
  2693. 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  2694. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  2695. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2696. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2697. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2698. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2699. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2700. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2701. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2702. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
  2703. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  2704. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  2705. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
  2706. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2707. 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2708. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2709. 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2710. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
  2711. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2712. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2713. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2714. 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2715. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2716. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2717. 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2718. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2719. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2720. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2721. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2722. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2723. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2724. 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2725. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2726. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2727. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2728. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2729. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2730. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
  2731. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  2732. 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  2733. 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2734. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2735. 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,
  2736. 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,
  2737. 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  2738. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  2739. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  2740. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  2741. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  2742. 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2743. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2744. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2745. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2746. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2747. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2748. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2749. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2750. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2751. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2752. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
  2753. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  2754. 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
  2755. 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
  2756. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  2757. 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2758. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2759. 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  2760. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
  2761. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  2762. 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
  2763. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
  2764. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2765. 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2766. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2767. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2768. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
  2769. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
  2770. // values.
  2771. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  2772. static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
  2773. tdefl_sym_freq *pSyms0,
  2774. tdefl_sym_freq *pSyms1) {
  2775. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  2776. tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  2777. MZ_CLEAR_OBJ(hist);
  2778. for (i = 0; i < num_syms; i++) {
  2779. mz_uint freq = pSyms0[i].m_key;
  2780. hist[freq & 0xFF]++;
  2781. hist[256 + ((freq >> 8) & 0xFF)]++;
  2782. }
  2783. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  2784. total_passes--;
  2785. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
  2786. const mz_uint32 *pHist = &hist[pass << 8];
  2787. mz_uint offsets[256], cur_ofs = 0;
  2788. for (i = 0; i < 256; i++) {
  2789. offsets[i] = cur_ofs;
  2790. cur_ofs += pHist[i];
  2791. }
  2792. for (i = 0; i < num_syms; i++)
  2793. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
  2794. pCur_syms[i];
  2795. {
  2796. tdefl_sym_freq *t = pCur_syms;
  2797. pCur_syms = pNew_syms;
  2798. pNew_syms = t;
  2799. }
  2800. }
  2801. return pCur_syms;
  2802. }
  2803. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
  2804. // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
  2805. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
  2806. int root, leaf, next, avbl, used, dpth;
  2807. if (n == 0)
  2808. return;
  2809. else if (n == 1) {
  2810. A[0].m_key = 1;
  2811. return;
  2812. }
  2813. A[0].m_key += A[1].m_key;
  2814. root = 0;
  2815. leaf = 2;
  2816. for (next = 1; next < n - 1; next++) {
  2817. if (leaf >= n || A[root].m_key < A[leaf].m_key) {
  2818. A[next].m_key = A[root].m_key;
  2819. A[root++].m_key = (mz_uint16)next;
  2820. } else
  2821. A[next].m_key = A[leaf++].m_key;
  2822. if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
  2823. A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
  2824. A[root++].m_key = (mz_uint16)next;
  2825. } else
  2826. A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  2827. }
  2828. A[n - 2].m_key = 0;
  2829. for (next = n - 3; next >= 0; next--)
  2830. A[next].m_key = A[A[next].m_key].m_key + 1;
  2831. avbl = 1;
  2832. used = dpth = 0;
  2833. root = n - 2;
  2834. next = n - 1;
  2835. while (avbl > 0) {
  2836. while (root >= 0 && (int)A[root].m_key == dpth) {
  2837. used++;
  2838. root--;
  2839. }
  2840. while (avbl > used) {
  2841. A[next--].m_key = (mz_uint16)(dpth);
  2842. avbl--;
  2843. }
  2844. avbl = 2 * used;
  2845. dpth++;
  2846. used = 0;
  2847. }
  2848. }
  2849. // Limits canonical Huffman code table's max code size.
  2850. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  2851. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
  2852. int code_list_len,
  2853. int max_code_size) {
  2854. int i;
  2855. mz_uint32 total = 0;
  2856. if (code_list_len <= 1) return;
  2857. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
  2858. pNum_codes[max_code_size] += pNum_codes[i];
  2859. for (i = max_code_size; i > 0; i--)
  2860. total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  2861. while (total != (1UL << max_code_size)) {
  2862. pNum_codes[max_code_size]--;
  2863. for (i = max_code_size - 1; i > 0; i--)
  2864. if (pNum_codes[i]) {
  2865. pNum_codes[i]--;
  2866. pNum_codes[i + 1] += 2;
  2867. break;
  2868. }
  2869. total--;
  2870. }
  2871. }
  2872. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
  2873. int table_len, int code_size_limit,
  2874. int static_table) {
  2875. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
  2876. mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
  2877. MZ_CLEAR_OBJ(num_codes);
  2878. if (static_table) {
  2879. for (i = 0; i < table_len; i++)
  2880. num_codes[d->m_huff_code_sizes[table_num][i]]++;
  2881. } else {
  2882. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
  2883. *pSyms;
  2884. int num_used_syms = 0;
  2885. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  2886. for (i = 0; i < table_len; i++)
  2887. if (pSym_count[i]) {
  2888. syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
  2889. syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
  2890. }
  2891. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
  2892. tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  2893. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  2894. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
  2895. code_size_limit);
  2896. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
  2897. MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  2898. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  2899. for (l = num_codes[i]; l > 0; l--)
  2900. d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  2901. }
  2902. next_code[1] = 0;
  2903. for (j = 0, i = 2; i <= code_size_limit; i++)
  2904. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  2905. for (i = 0; i < table_len; i++) {
  2906. mz_uint rev_code = 0, code, code_size;
  2907. if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  2908. code = next_code[code_size]++;
  2909. for (l = code_size; l > 0; l--, code >>= 1)
  2910. rev_code = (rev_code << 1) | (code & 1);
  2911. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  2912. }
  2913. }
  2914. #define TDEFL_PUT_BITS(b, l) \
  2915. do { \
  2916. mz_uint bits = b; \
  2917. mz_uint len = l; \
  2918. MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  2919. d->m_bit_buffer |= (bits << d->m_bits_in); \
  2920. d->m_bits_in += len; \
  2921. while (d->m_bits_in >= 8) { \
  2922. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  2923. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  2924. d->m_bit_buffer >>= 8; \
  2925. d->m_bits_in -= 8; \
  2926. } \
  2927. } \
  2928. MZ_MACRO_END
  2929. #define TDEFL_RLE_PREV_CODE_SIZE() \
  2930. { \
  2931. if (rle_repeat_count) { \
  2932. if (rle_repeat_count < 3) { \
  2933. d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
  2934. d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  2935. while (rle_repeat_count--) \
  2936. packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  2937. } else { \
  2938. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
  2939. packed_code_sizes[num_packed_code_sizes++] = 16; \
  2940. packed_code_sizes[num_packed_code_sizes++] = \
  2941. (mz_uint8)(rle_repeat_count - 3); \
  2942. } \
  2943. rle_repeat_count = 0; \
  2944. } \
  2945. }
  2946. #define TDEFL_RLE_ZERO_CODE_SIZE() \
  2947. { \
  2948. if (rle_z_count) { \
  2949. if (rle_z_count < 3) { \
  2950. d->m_huff_count[2][0] = \
  2951. (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
  2952. while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  2953. } else if (rle_z_count <= 10) { \
  2954. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
  2955. packed_code_sizes[num_packed_code_sizes++] = 17; \
  2956. packed_code_sizes[num_packed_code_sizes++] = \
  2957. (mz_uint8)(rle_z_count - 3); \
  2958. } else { \
  2959. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
  2960. packed_code_sizes[num_packed_code_sizes++] = 18; \
  2961. packed_code_sizes[num_packed_code_sizes++] = \
  2962. (mz_uint8)(rle_z_count - 11); \
  2963. } \
  2964. rle_z_count = 0; \
  2965. } \
  2966. }
  2967. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
  2968. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2969. static void tdefl_start_dynamic_block(tdefl_compressor *d) {
  2970. int num_lit_codes, num_dist_codes, num_bit_lengths;
  2971. mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
  2972. rle_repeat_count, packed_code_sizes_index;
  2973. mz_uint8
  2974. code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2975. packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2976. prev_code_size = 0xFF;
  2977. d->m_huff_count[0][256] = 1;
  2978. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  2979. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  2980. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
  2981. if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  2982. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
  2983. if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  2984. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  2985. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
  2986. num_dist_codes);
  2987. total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
  2988. num_packed_code_sizes = 0;
  2989. rle_z_count = 0;
  2990. rle_repeat_count = 0;
  2991. memset(&d->m_huff_count[2][0], 0,
  2992. sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  2993. for (i = 0; i < total_code_sizes_to_pack; i++) {
  2994. mz_uint8 code_size = code_sizes_to_pack[i];
  2995. if (!code_size) {
  2996. TDEFL_RLE_PREV_CODE_SIZE();
  2997. if (++rle_z_count == 138) {
  2998. TDEFL_RLE_ZERO_CODE_SIZE();
  2999. }
  3000. } else {
  3001. TDEFL_RLE_ZERO_CODE_SIZE();
  3002. if (code_size != prev_code_size) {
  3003. TDEFL_RLE_PREV_CODE_SIZE();
  3004. d->m_huff_count[2][code_size] =
  3005. (mz_uint16)(d->m_huff_count[2][code_size] + 1);
  3006. packed_code_sizes[num_packed_code_sizes++] = code_size;
  3007. } else if (++rle_repeat_count == 6) {
  3008. TDEFL_RLE_PREV_CODE_SIZE();
  3009. }
  3010. }
  3011. prev_code_size = code_size;
  3012. }
  3013. if (rle_repeat_count) {
  3014. TDEFL_RLE_PREV_CODE_SIZE();
  3015. } else {
  3016. TDEFL_RLE_ZERO_CODE_SIZE();
  3017. }
  3018. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  3019. TDEFL_PUT_BITS(2, 2);
  3020. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  3021. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  3022. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
  3023. if (d->m_huff_code_sizes
  3024. [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
  3025. break;
  3026. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
  3027. TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  3028. for (i = 0; (int)i < num_bit_lengths; i++)
  3029. TDEFL_PUT_BITS(
  3030. d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  3031. for (packed_code_sizes_index = 0;
  3032. packed_code_sizes_index < num_packed_code_sizes;) {
  3033. mz_uint code = packed_code_sizes[packed_code_sizes_index++];
  3034. MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  3035. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  3036. if (code >= 16)
  3037. TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
  3038. "\02\03\07"[code - 16]);
  3039. }
  3040. }
  3041. static void tdefl_start_static_block(tdefl_compressor *d) {
  3042. mz_uint i;
  3043. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  3044. for (i = 0; i <= 143; ++i) *p++ = 8;
  3045. for (; i <= 255; ++i) *p++ = 9;
  3046. for (; i <= 279; ++i) *p++ = 7;
  3047. for (; i <= 287; ++i) *p++ = 8;
  3048. memset(d->m_huff_code_sizes[1], 5, 32);
  3049. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  3050. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  3051. TDEFL_PUT_BITS(1, 2);
  3052. }
  3053. static const mz_uint mz_bitmasks[17] = {
  3054. 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  3055. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
  3056. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
  3057. MINIZ_HAS_64BIT_REGISTERS
  3058. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3059. mz_uint flags;
  3060. mz_uint8 *pLZ_codes;
  3061. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  3062. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  3063. mz_uint64 bit_buffer = d->m_bit_buffer;
  3064. mz_uint bits_in = d->m_bits_in;
  3065. #define TDEFL_PUT_BITS_FAST(b, l) \
  3066. { \
  3067. bit_buffer |= (((mz_uint64)(b)) << bits_in); \
  3068. bits_in += (l); \
  3069. }
  3070. flags = 1;
  3071. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
  3072. flags >>= 1) {
  3073. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3074. if (flags & 1) {
  3075. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  3076. mz_uint match_len = pLZ_codes[0],
  3077. match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
  3078. pLZ_codes += 3;
  3079. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3080. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3081. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3082. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3083. s_tdefl_len_extra[match_len]);
  3084. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  3085. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3086. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  3087. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  3088. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  3089. sym = (match_dist < 512) ? s0 : s1;
  3090. num_extra_bits = (match_dist < 512) ? n0 : n1;
  3091. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3092. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
  3093. d->m_huff_code_sizes[1][sym]);
  3094. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
  3095. num_extra_bits);
  3096. } else {
  3097. mz_uint lit = *pLZ_codes++;
  3098. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3099. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3100. d->m_huff_code_sizes[0][lit]);
  3101. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  3102. flags >>= 1;
  3103. lit = *pLZ_codes++;
  3104. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3105. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3106. d->m_huff_code_sizes[0][lit]);
  3107. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  3108. flags >>= 1;
  3109. lit = *pLZ_codes++;
  3110. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3111. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3112. d->m_huff_code_sizes[0][lit]);
  3113. }
  3114. }
  3115. }
  3116. if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE;
  3117. *(mz_uint64 *)pOutput_buf = bit_buffer;
  3118. pOutput_buf += (bits_in >> 3);
  3119. bit_buffer >>= (bits_in & ~7);
  3120. bits_in &= 7;
  3121. }
  3122. #undef TDEFL_PUT_BITS_FAST
  3123. d->m_pOutput_buf = pOutput_buf;
  3124. d->m_bits_in = 0;
  3125. d->m_bit_buffer = 0;
  3126. while (bits_in) {
  3127. mz_uint32 n = MZ_MIN(bits_in, 16);
  3128. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  3129. bit_buffer >>= n;
  3130. bits_in -= n;
  3131. }
  3132. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3133. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3134. }
  3135. #else
  3136. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3137. mz_uint flags;
  3138. mz_uint8 *pLZ_codes;
  3139. flags = 1;
  3140. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
  3141. flags >>= 1) {
  3142. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3143. if (flags & 1) {
  3144. mz_uint sym, num_extra_bits;
  3145. mz_uint match_len = pLZ_codes[0],
  3146. match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
  3147. pLZ_codes += 3;
  3148. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3149. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3150. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3151. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3152. s_tdefl_len_extra[match_len]);
  3153. if (match_dist < 512) {
  3154. sym = s_tdefl_small_dist_sym[match_dist];
  3155. num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  3156. } else {
  3157. sym = s_tdefl_large_dist_sym[match_dist >> 8];
  3158. num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  3159. }
  3160. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3161. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  3162. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  3163. } else {
  3164. mz_uint lit = *pLZ_codes++;
  3165. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3166. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  3167. }
  3168. }
  3169. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3170. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3171. }
  3172. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
  3173. // MINIZ_HAS_64BIT_REGISTERS
  3174. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
  3175. if (static_block)
  3176. tdefl_start_static_block(d);
  3177. else
  3178. tdefl_start_dynamic_block(d);
  3179. return tdefl_compress_lz_codes(d);
  3180. }
  3181. static int tdefl_flush_block(tdefl_compressor *d, int flush) {
  3182. mz_uint saved_bit_buf, saved_bits_in;
  3183. mz_uint8 *pSaved_output_buf;
  3184. mz_bool comp_block_succeeded = MZ_FALSE;
  3185. int n, use_raw_block =
  3186. ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
  3187. (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  3188. mz_uint8 *pOutput_buf_start =
  3189. ((d->m_pPut_buf_func == NULL) &&
  3190. ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
  3191. ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
  3192. : d->m_output_buf;
  3193. d->m_pOutput_buf = pOutput_buf_start;
  3194. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  3195. MZ_ASSERT(!d->m_output_flush_remaining);
  3196. d->m_output_flush_ofs = 0;
  3197. d->m_output_flush_remaining = 0;
  3198. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  3199. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  3200. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
  3201. TDEFL_PUT_BITS(0x78, 8);
  3202. TDEFL_PUT_BITS(0x01, 8);
  3203. }
  3204. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  3205. pSaved_output_buf = d->m_pOutput_buf;
  3206. saved_bit_buf = d->m_bit_buffer;
  3207. saved_bits_in = d->m_bits_in;
  3208. if (!use_raw_block)
  3209. comp_block_succeeded =
  3210. tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
  3211. (d->m_total_lz_bytes < 48));
  3212. // If the block gets expanded, forget the current contents of the output
  3213. // buffer and send a raw block instead.
  3214. if (((use_raw_block) ||
  3215. ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
  3216. d->m_total_lz_bytes))) &&
  3217. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
  3218. mz_uint i;
  3219. d->m_pOutput_buf = pSaved_output_buf;
  3220. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3221. TDEFL_PUT_BITS(0, 2);
  3222. if (d->m_bits_in) {
  3223. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3224. }
  3225. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
  3226. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  3227. }
  3228. for (i = 0; i < d->m_total_lz_bytes; ++i) {
  3229. TDEFL_PUT_BITS(
  3230. d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
  3231. 8);
  3232. }
  3233. }
  3234. // Check for the extremely unlikely (if not impossible) case of the compressed
  3235. // block not fitting into the output buffer when using dynamic codes.
  3236. else if (!comp_block_succeeded) {
  3237. d->m_pOutput_buf = pSaved_output_buf;
  3238. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3239. tdefl_compress_block(d, MZ_TRUE);
  3240. }
  3241. if (flush) {
  3242. if (flush == TDEFL_FINISH) {
  3243. if (d->m_bits_in) {
  3244. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3245. }
  3246. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
  3247. mz_uint i, a = d->m_adler32;
  3248. for (i = 0; i < 4; i++) {
  3249. TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
  3250. a <<= 8;
  3251. }
  3252. }
  3253. } else {
  3254. mz_uint i, z = 0;
  3255. TDEFL_PUT_BITS(0, 3);
  3256. if (d->m_bits_in) {
  3257. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3258. }
  3259. for (i = 2; i; --i, z ^= 0xFFFF) {
  3260. TDEFL_PUT_BITS(z & 0xFFFF, 16);
  3261. }
  3262. }
  3263. }
  3264. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  3265. memset(&d->m_huff_count[0][0], 0,
  3266. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3267. memset(&d->m_huff_count[1][0], 0,
  3268. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3269. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3270. d->m_pLZ_flags = d->m_lz_code_buf;
  3271. d->m_num_flags_left = 8;
  3272. d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
  3273. d->m_total_lz_bytes = 0;
  3274. d->m_block_index++;
  3275. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
  3276. if (d->m_pPut_buf_func) {
  3277. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3278. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  3279. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  3280. } else if (pOutput_buf_start == d->m_output_buf) {
  3281. int bytes_to_copy = (int)MZ_MIN(
  3282. (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  3283. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
  3284. bytes_to_copy);
  3285. d->m_out_buf_ofs += bytes_to_copy;
  3286. if ((n -= bytes_to_copy) != 0) {
  3287. d->m_output_flush_ofs = bytes_to_copy;
  3288. d->m_output_flush_remaining = n;
  3289. }
  3290. } else {
  3291. d->m_out_buf_ofs += n;
  3292. }
  3293. }
  3294. return d->m_output_flush_remaining;
  3295. }
  3296. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3297. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
  3298. static MZ_FORCEINLINE void tdefl_find_match(
  3299. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3300. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3301. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3302. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3303. probe_len;
  3304. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3305. const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
  3306. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
  3307. s01 = TDEFL_READ_UNALIGNED_WORD(s);
  3308. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3309. if (max_match_len <= match_len) return;
  3310. for (;;) {
  3311. for (;;) {
  3312. if (--num_probes_left == 0) return;
  3313. #define TDEFL_PROBE \
  3314. next_probe_pos = d->m_next[probe_pos]; \
  3315. if ((!next_probe_pos) || \
  3316. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3317. return; \
  3318. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3319. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
  3320. break;
  3321. TDEFL_PROBE;
  3322. TDEFL_PROBE;
  3323. TDEFL_PROBE;
  3324. }
  3325. if (!dist) break;
  3326. q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3327. if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue;
  3328. p = s;
  3329. probe_len = 32;
  3330. do {
  3331. } while (
  3332. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3333. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3334. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3335. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3336. (--probe_len > 0));
  3337. if (!probe_len) {
  3338. *pMatch_dist = dist;
  3339. *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
  3340. break;
  3341. } else if ((probe_len = ((mz_uint)(p - s) * 2) +
  3342. (mz_uint)(*(const mz_uint8 *)p ==
  3343. *(const mz_uint8 *)q)) > match_len) {
  3344. *pMatch_dist = dist;
  3345. if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
  3346. max_match_len)
  3347. break;
  3348. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  3349. }
  3350. }
  3351. }
  3352. #else
  3353. static MZ_FORCEINLINE void tdefl_find_match(
  3354. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3355. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3356. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3357. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3358. probe_len;
  3359. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3360. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  3361. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  3362. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3363. if (max_match_len <= match_len) return;
  3364. for (;;) {
  3365. for (;;) {
  3366. if (--num_probes_left == 0) return;
  3367. #define TDEFL_PROBE \
  3368. next_probe_pos = d->m_next[probe_pos]; \
  3369. if ((!next_probe_pos) || \
  3370. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3371. return; \
  3372. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3373. if ((d->m_dict[probe_pos + match_len] == c0) && \
  3374. (d->m_dict[probe_pos + match_len - 1] == c1)) \
  3375. break;
  3376. TDEFL_PROBE;
  3377. TDEFL_PROBE;
  3378. TDEFL_PROBE;
  3379. }
  3380. if (!dist) break;
  3381. p = s;
  3382. q = d->m_dict + probe_pos;
  3383. for (probe_len = 0; probe_len < max_match_len; probe_len++)
  3384. if (*p++ != *q++) break;
  3385. if (probe_len > match_len) {
  3386. *pMatch_dist = dist;
  3387. if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  3388. c0 = d->m_dict[pos + match_len];
  3389. c1 = d->m_dict[pos + match_len - 1];
  3390. }
  3391. }
  3392. }
  3393. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3394. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3395. static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
  3396. // Faster, minimally featured LZRW1-style match+parse loop with better
  3397. // register utilization. Intended for applications where raw throughput is
  3398. // valued more highly than ratio.
  3399. mz_uint lookahead_pos = d->m_lookahead_pos,
  3400. lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
  3401. total_lz_bytes = d->m_total_lz_bytes,
  3402. num_flags_left = d->m_num_flags_left;
  3403. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  3404. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3405. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
  3406. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  3407. mz_uint dst_pos =
  3408. (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  3409. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3410. d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  3411. d->m_src_buf_left -= num_bytes_to_process;
  3412. lookahead_size += num_bytes_to_process;
  3413. while (num_bytes_to_process) {
  3414. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  3415. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  3416. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3417. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
  3418. MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  3419. d->m_pSrc += n;
  3420. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  3421. num_bytes_to_process -= n;
  3422. }
  3423. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  3424. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
  3425. break;
  3426. while (lookahead_size >= 4) {
  3427. mz_uint cur_match_dist, cur_match_len = 1;
  3428. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  3429. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  3430. mz_uint hash =
  3431. (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
  3432. TDEFL_LEVEL1_HASH_SIZE_MASK;
  3433. mz_uint probe_pos = d->m_hash[hash];
  3434. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  3435. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
  3436. dict_size) &&
  3437. ((*(const mz_uint32 *)(d->m_dict +
  3438. (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
  3439. 0xFFFFFF) == first_trigram)) {
  3440. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  3441. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3442. mz_uint32 probe_len = 32;
  3443. do {
  3444. } while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
  3445. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3446. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3447. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3448. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3449. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3450. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3451. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3452. (--probe_len > 0));
  3453. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
  3454. (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  3455. if (!probe_len)
  3456. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  3457. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
  3458. ((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3459. (cur_match_dist >= 8U * 1024U))) {
  3460. cur_match_len = 1;
  3461. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3462. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3463. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3464. } else {
  3465. mz_uint32 s0, s1;
  3466. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  3467. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
  3468. (cur_match_dist >= 1) &&
  3469. (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  3470. cur_match_dist--;
  3471. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  3472. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  3473. pLZ_code_buf += 3;
  3474. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  3475. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  3476. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  3477. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  3478. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
  3479. TDEFL_MIN_MATCH_LEN]]++;
  3480. }
  3481. } else {
  3482. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3483. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3484. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3485. }
  3486. if (--num_flags_left == 0) {
  3487. num_flags_left = 8;
  3488. pLZ_flags = pLZ_code_buf++;
  3489. }
  3490. total_lz_bytes += cur_match_len;
  3491. lookahead_pos += cur_match_len;
  3492. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  3493. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  3494. MZ_ASSERT(lookahead_size >= cur_match_len);
  3495. lookahead_size -= cur_match_len;
  3496. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3497. int n;
  3498. d->m_lookahead_pos = lookahead_pos;
  3499. d->m_lookahead_size = lookahead_size;
  3500. d->m_dict_size = dict_size;
  3501. d->m_total_lz_bytes = total_lz_bytes;
  3502. d->m_pLZ_code_buf = pLZ_code_buf;
  3503. d->m_pLZ_flags = pLZ_flags;
  3504. d->m_num_flags_left = num_flags_left;
  3505. if ((n = tdefl_flush_block(d, 0)) != 0)
  3506. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3507. total_lz_bytes = d->m_total_lz_bytes;
  3508. pLZ_code_buf = d->m_pLZ_code_buf;
  3509. pLZ_flags = d->m_pLZ_flags;
  3510. num_flags_left = d->m_num_flags_left;
  3511. }
  3512. }
  3513. while (lookahead_size) {
  3514. mz_uint8 lit = d->m_dict[cur_pos];
  3515. total_lz_bytes++;
  3516. *pLZ_code_buf++ = lit;
  3517. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3518. if (--num_flags_left == 0) {
  3519. num_flags_left = 8;
  3520. pLZ_flags = pLZ_code_buf++;
  3521. }
  3522. d->m_huff_count[0][lit]++;
  3523. lookahead_pos++;
  3524. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  3525. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3526. lookahead_size--;
  3527. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3528. int n;
  3529. d->m_lookahead_pos = lookahead_pos;
  3530. d->m_lookahead_size = lookahead_size;
  3531. d->m_dict_size = dict_size;
  3532. d->m_total_lz_bytes = total_lz_bytes;
  3533. d->m_pLZ_code_buf = pLZ_code_buf;
  3534. d->m_pLZ_flags = pLZ_flags;
  3535. d->m_num_flags_left = num_flags_left;
  3536. if ((n = tdefl_flush_block(d, 0)) != 0)
  3537. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3538. total_lz_bytes = d->m_total_lz_bytes;
  3539. pLZ_code_buf = d->m_pLZ_code_buf;
  3540. pLZ_flags = d->m_pLZ_flags;
  3541. num_flags_left = d->m_num_flags_left;
  3542. }
  3543. }
  3544. }
  3545. d->m_lookahead_pos = lookahead_pos;
  3546. d->m_lookahead_size = lookahead_size;
  3547. d->m_dict_size = dict_size;
  3548. d->m_total_lz_bytes = total_lz_bytes;
  3549. d->m_pLZ_code_buf = pLZ_code_buf;
  3550. d->m_pLZ_flags = pLZ_flags;
  3551. d->m_num_flags_left = num_flags_left;
  3552. return MZ_TRUE;
  3553. }
  3554. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3555. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
  3556. mz_uint8 lit) {
  3557. d->m_total_lz_bytes++;
  3558. *d->m_pLZ_code_buf++ = lit;
  3559. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
  3560. if (--d->m_num_flags_left == 0) {
  3561. d->m_num_flags_left = 8;
  3562. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3563. }
  3564. d->m_huff_count[0][lit]++;
  3565. }
  3566. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d,
  3567. mz_uint match_len,
  3568. mz_uint match_dist) {
  3569. mz_uint32 s0, s1;
  3570. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
  3571. (match_dist <= TDEFL_LZ_DICT_SIZE));
  3572. d->m_total_lz_bytes += match_len;
  3573. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  3574. match_dist -= 1;
  3575. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  3576. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
  3577. d->m_pLZ_code_buf += 3;
  3578. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
  3579. if (--d->m_num_flags_left == 0) {
  3580. d->m_num_flags_left = 8;
  3581. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3582. }
  3583. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3584. s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  3585. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  3586. if (match_len >= TDEFL_MIN_MATCH_LEN)
  3587. d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  3588. }
  3589. static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
  3590. const mz_uint8 *pSrc = d->m_pSrc;
  3591. size_t src_buf_left = d->m_src_buf_left;
  3592. tdefl_flush flush = d->m_flush;
  3593. while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
  3594. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  3595. // Update dictionary and hash chains. Keeps the lookahead size equal to
  3596. // TDEFL_MAX_MATCH_LEN.
  3597. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
  3598. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3599. TDEFL_LZ_DICT_SIZE_MASK,
  3600. ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  3601. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3602. << TDEFL_LZ_HASH_SHIFT) ^
  3603. d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3604. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3605. src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  3606. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  3607. src_buf_left -= num_bytes_to_process;
  3608. d->m_lookahead_size += num_bytes_to_process;
  3609. while (pSrc != pSrc_end) {
  3610. mz_uint8 c = *pSrc++;
  3611. d->m_dict[dst_pos] = c;
  3612. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3613. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3614. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  3615. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3616. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3617. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3618. ins_pos++;
  3619. }
  3620. } else {
  3621. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
  3622. mz_uint8 c = *pSrc++;
  3623. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3624. TDEFL_LZ_DICT_SIZE_MASK;
  3625. src_buf_left--;
  3626. d->m_dict[dst_pos] = c;
  3627. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3628. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3629. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
  3630. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  3631. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3632. << (TDEFL_LZ_HASH_SHIFT * 2)) ^
  3633. (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
  3634. << TDEFL_LZ_HASH_SHIFT) ^
  3635. c) &
  3636. (TDEFL_LZ_HASH_SIZE - 1);
  3637. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3638. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3639. }
  3640. }
  3641. }
  3642. d->m_dict_size =
  3643. MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  3644. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break;
  3645. // Simple lazy/greedy parsing state machine.
  3646. len_to_move = 1;
  3647. cur_match_dist = 0;
  3648. cur_match_len =
  3649. d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
  3650. cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3651. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
  3652. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
  3653. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3654. cur_match_len = 0;
  3655. while (cur_match_len < d->m_lookahead_size) {
  3656. if (d->m_dict[cur_pos + cur_match_len] != c) break;
  3657. cur_match_len++;
  3658. }
  3659. if (cur_match_len < TDEFL_MIN_MATCH_LEN)
  3660. cur_match_len = 0;
  3661. else
  3662. cur_match_dist = 1;
  3663. }
  3664. } else {
  3665. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
  3666. d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  3667. }
  3668. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3669. (cur_match_dist >= 8U * 1024U)) ||
  3670. (cur_pos == cur_match_dist) ||
  3671. ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
  3672. cur_match_dist = cur_match_len = 0;
  3673. }
  3674. if (d->m_saved_match_len) {
  3675. if (cur_match_len > d->m_saved_match_len) {
  3676. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  3677. if (cur_match_len >= 128) {
  3678. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3679. d->m_saved_match_len = 0;
  3680. len_to_move = cur_match_len;
  3681. } else {
  3682. d->m_saved_lit = d->m_dict[cur_pos];
  3683. d->m_saved_match_dist = cur_match_dist;
  3684. d->m_saved_match_len = cur_match_len;
  3685. }
  3686. } else {
  3687. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  3688. len_to_move = d->m_saved_match_len - 1;
  3689. d->m_saved_match_len = 0;
  3690. }
  3691. } else if (!cur_match_dist)
  3692. tdefl_record_literal(d,
  3693. d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  3694. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
  3695. (cur_match_len >= 128)) {
  3696. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3697. len_to_move = cur_match_len;
  3698. } else {
  3699. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
  3700. d->m_saved_match_dist = cur_match_dist;
  3701. d->m_saved_match_len = cur_match_len;
  3702. }
  3703. // Move the lookahead forward by len_to_move bytes.
  3704. d->m_lookahead_pos += len_to_move;
  3705. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  3706. d->m_lookahead_size -= len_to_move;
  3707. d->m_dict_size =
  3708. MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
  3709. // Check if it's time to flush the current LZ codes to the internal output
  3710. // buffer.
  3711. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  3712. ((d->m_total_lz_bytes > 31 * 1024) &&
  3713. (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
  3714. d->m_total_lz_bytes) ||
  3715. (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
  3716. int n;
  3717. d->m_pSrc = pSrc;
  3718. d->m_src_buf_left = src_buf_left;
  3719. if ((n = tdefl_flush_block(d, 0)) != 0)
  3720. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3721. }
  3722. }
  3723. d->m_pSrc = pSrc;
  3724. d->m_src_buf_left = src_buf_left;
  3725. return MZ_TRUE;
  3726. }
  3727. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
  3728. if (d->m_pIn_buf_size) {
  3729. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3730. }
  3731. if (d->m_pOut_buf_size) {
  3732. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
  3733. d->m_output_flush_remaining);
  3734. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
  3735. d->m_output_buf + d->m_output_flush_ofs, n);
  3736. d->m_output_flush_ofs += (mz_uint)n;
  3737. d->m_output_flush_remaining -= (mz_uint)n;
  3738. d->m_out_buf_ofs += n;
  3739. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  3740. }
  3741. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
  3742. : TDEFL_STATUS_OKAY;
  3743. }
  3744. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  3745. size_t *pIn_buf_size, void *pOut_buf,
  3746. size_t *pOut_buf_size, tdefl_flush flush) {
  3747. if (!d) {
  3748. if (pIn_buf_size) *pIn_buf_size = 0;
  3749. if (pOut_buf_size) *pOut_buf_size = 0;
  3750. return TDEFL_STATUS_BAD_PARAM;
  3751. }
  3752. d->m_pIn_buf = pIn_buf;
  3753. d->m_pIn_buf_size = pIn_buf_size;
  3754. d->m_pOut_buf = pOut_buf;
  3755. d->m_pOut_buf_size = pOut_buf_size;
  3756. d->m_pSrc = (const mz_uint8 *)(pIn_buf);
  3757. d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  3758. d->m_out_buf_ofs = 0;
  3759. d->m_flush = flush;
  3760. if (((d->m_pPut_buf_func != NULL) ==
  3761. ((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
  3762. (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  3763. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
  3764. (pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
  3765. (pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
  3766. if (pIn_buf_size) *pIn_buf_size = 0;
  3767. if (pOut_buf_size) *pOut_buf_size = 0;
  3768. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  3769. }
  3770. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  3771. if ((d->m_output_flush_remaining) || (d->m_finished))
  3772. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3773. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3774. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  3775. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  3776. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
  3777. TDEFL_RLE_MATCHES)) == 0)) {
  3778. if (!tdefl_compress_fast(d)) return d->m_prev_return_status;
  3779. } else
  3780. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3781. {
  3782. if (!tdefl_compress_normal(d)) return d->m_prev_return_status;
  3783. }
  3784. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
  3785. (pIn_buf))
  3786. d->m_adler32 =
  3787. (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
  3788. d->m_pSrc - (const mz_uint8 *)pIn_buf);
  3789. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
  3790. (!d->m_output_flush_remaining)) {
  3791. if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status;
  3792. d->m_finished = (flush == TDEFL_FINISH);
  3793. if (flush == TDEFL_FULL_FLUSH) {
  3794. MZ_CLEAR_OBJ(d->m_hash);
  3795. MZ_CLEAR_OBJ(d->m_next);
  3796. d->m_dict_size = 0;
  3797. }
  3798. }
  3799. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3800. }
  3801. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  3802. size_t in_buf_size, tdefl_flush flush) {
  3803. MZ_ASSERT(d->m_pPut_buf_func);
  3804. return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  3805. }
  3806. tdefl_status tdefl_init(tdefl_compressor *d,
  3807. tdefl_put_buf_func_ptr pPut_buf_func,
  3808. void *pPut_buf_user, int flags) {
  3809. d->m_pPut_buf_func = pPut_buf_func;
  3810. d->m_pPut_buf_user = pPut_buf_user;
  3811. d->m_flags = (mz_uint)(flags);
  3812. d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
  3813. d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  3814. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  3815. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  3816. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
  3817. d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  3818. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
  3819. d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  3820. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3821. d->m_pLZ_flags = d->m_lz_code_buf;
  3822. d->m_num_flags_left = 8;
  3823. d->m_pOutput_buf = d->m_output_buf;
  3824. d->m_pOutput_buf_end = d->m_output_buf;
  3825. d->m_prev_return_status = TDEFL_STATUS_OKAY;
  3826. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
  3827. d->m_adler32 = 1;
  3828. d->m_pIn_buf = NULL;
  3829. d->m_pOut_buf = NULL;
  3830. d->m_pIn_buf_size = NULL;
  3831. d->m_pOut_buf_size = NULL;
  3832. d->m_flush = TDEFL_NO_FLUSH;
  3833. d->m_pSrc = NULL;
  3834. d->m_src_buf_left = 0;
  3835. d->m_out_buf_ofs = 0;
  3836. memset(&d->m_huff_count[0][0], 0,
  3837. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3838. memset(&d->m_huff_count[1][0], 0,
  3839. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3840. return TDEFL_STATUS_OKAY;
  3841. }
  3842. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
  3843. return d->m_prev_return_status;
  3844. }
  3845. mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
  3846. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  3847. tdefl_put_buf_func_ptr pPut_buf_func,
  3848. void *pPut_buf_user, int flags) {
  3849. tdefl_compressor *pComp;
  3850. mz_bool succeeded;
  3851. if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  3852. pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3853. if (!pComp) return MZ_FALSE;
  3854. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
  3855. TDEFL_STATUS_OKAY);
  3856. succeeded =
  3857. succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
  3858. TDEFL_STATUS_DONE);
  3859. MZ_FREE(pComp);
  3860. return succeeded;
  3861. }
  3862. typedef struct {
  3863. size_t m_size, m_capacity;
  3864. mz_uint8 *m_pBuf;
  3865. mz_bool m_expandable;
  3866. } tdefl_output_buffer;
  3867. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
  3868. void *pUser) {
  3869. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  3870. size_t new_size = p->m_size + len;
  3871. if (new_size > p->m_capacity) {
  3872. size_t new_capacity = p->m_capacity;
  3873. mz_uint8 *pNew_buf;
  3874. if (!p->m_expandable) return MZ_FALSE;
  3875. do {
  3876. new_capacity = MZ_MAX(128U, new_capacity << 1U);
  3877. } while (new_size > new_capacity);
  3878. pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
  3879. if (!pNew_buf) return MZ_FALSE;
  3880. p->m_pBuf = pNew_buf;
  3881. p->m_capacity = new_capacity;
  3882. }
  3883. memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
  3884. p->m_size = new_size;
  3885. return MZ_TRUE;
  3886. }
  3887. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  3888. size_t *pOut_len, int flags) {
  3889. tdefl_output_buffer out_buf;
  3890. MZ_CLEAR_OBJ(out_buf);
  3891. if (!pOut_len)
  3892. return MZ_FALSE;
  3893. else
  3894. *pOut_len = 0;
  3895. out_buf.m_expandable = MZ_TRUE;
  3896. if (!tdefl_compress_mem_to_output(
  3897. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3898. return NULL;
  3899. *pOut_len = out_buf.m_size;
  3900. return out_buf.m_pBuf;
  3901. }
  3902. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  3903. const void *pSrc_buf, size_t src_buf_len,
  3904. int flags) {
  3905. tdefl_output_buffer out_buf;
  3906. MZ_CLEAR_OBJ(out_buf);
  3907. if (!pOut_buf) return 0;
  3908. out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
  3909. out_buf.m_capacity = out_buf_len;
  3910. if (!tdefl_compress_mem_to_output(
  3911. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3912. return 0;
  3913. return out_buf.m_size;
  3914. }
  3915. #ifndef MINIZ_NO_ZLIB_APIS
  3916. static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
  3917. 128, 256, 512, 768, 1500};
  3918. // level may actually range from [0,10] (10 is a "hidden" max level, where we
  3919. // want a bit more compression and it's fine if throughput to fall off a cliff
  3920. // on some files).
  3921. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  3922. int strategy) {
  3923. mz_uint comp_flags =
  3924. s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
  3925. ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  3926. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  3927. if (!level)
  3928. comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  3929. else if (strategy == MZ_FILTERED)
  3930. comp_flags |= TDEFL_FILTER_MATCHES;
  3931. else if (strategy == MZ_HUFFMAN_ONLY)
  3932. comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  3933. else if (strategy == MZ_FIXED)
  3934. comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  3935. else if (strategy == MZ_RLE)
  3936. comp_flags |= TDEFL_RLE_MATCHES;
  3937. return comp_flags;
  3938. }
  3939. #endif // MINIZ_NO_ZLIB_APIS
  3940. #ifdef _MSC_VER
  3941. #pragma warning(push)
  3942. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  3943. // aggregate initializer (also supported by GNU
  3944. // C and C99, so no big deal)
  3945. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  3946. // 'int', possible loss of data
  3947. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  3948. // 'int', possible loss of data
  3949. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  3950. // deprecated. Instead, use the ISO C and C++
  3951. // conformant name: _strdup.
  3952. #endif
  3953. // Simple PNG writer function by Alex Evans, 2011. Released into the public
  3954. // domain: https://gist.github.com/908299, more context at
  3955. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  3956. // This is actually a modification of Alex's original code so PNG files
  3957. // generated by this function pass pngcheck.
  3958. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  3959. int h, int num_chans,
  3960. size_t *pLen_out,
  3961. mz_uint level, mz_bool flip) {
  3962. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
  3963. // defined.
  3964. static const mz_uint s_tdefl_png_num_probes[11] = {
  3965. 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
  3966. tdefl_compressor *pComp =
  3967. (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3968. tdefl_output_buffer out_buf;
  3969. int i, bpl = w * num_chans, y, z;
  3970. mz_uint32 c;
  3971. *pLen_out = 0;
  3972. if (!pComp) return NULL;
  3973. MZ_CLEAR_OBJ(out_buf);
  3974. out_buf.m_expandable = MZ_TRUE;
  3975. out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
  3976. if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
  3977. MZ_FREE(pComp);
  3978. return NULL;
  3979. }
  3980. // write dummy header
  3981. for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  3982. // compress image data
  3983. tdefl_init(
  3984. pComp, tdefl_output_buffer_putter, &out_buf,
  3985. s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  3986. for (y = 0; y < h; ++y) {
  3987. tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
  3988. tdefl_compress_buffer(pComp,
  3989. (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
  3990. bpl, TDEFL_NO_FLUSH);
  3991. }
  3992. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
  3993. TDEFL_STATUS_DONE) {
  3994. MZ_FREE(pComp);
  3995. MZ_FREE(out_buf.m_pBuf);
  3996. return NULL;
  3997. }
  3998. // write real header
  3999. *pLen_out = out_buf.m_size - 41;
  4000. {
  4001. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  4002. mz_uint8 pnghdr[41] = {0x89,
  4003. 0x50,
  4004. 0x4e,
  4005. 0x47,
  4006. 0x0d,
  4007. 0x0a,
  4008. 0x1a,
  4009. 0x0a,
  4010. 0x00,
  4011. 0x00,
  4012. 0x00,
  4013. 0x0d,
  4014. 0x49,
  4015. 0x48,
  4016. 0x44,
  4017. 0x52,
  4018. 0,
  4019. 0,
  4020. (mz_uint8)(w >> 8),
  4021. (mz_uint8)w,
  4022. 0,
  4023. 0,
  4024. (mz_uint8)(h >> 8),
  4025. (mz_uint8)h,
  4026. 8,
  4027. chans[num_chans],
  4028. 0,
  4029. 0,
  4030. 0,
  4031. 0,
  4032. 0,
  4033. 0,
  4034. 0,
  4035. (mz_uint8)(*pLen_out >> 24),
  4036. (mz_uint8)(*pLen_out >> 16),
  4037. (mz_uint8)(*pLen_out >> 8),
  4038. (mz_uint8)*pLen_out,
  4039. 0x49,
  4040. 0x44,
  4041. 0x41,
  4042. 0x54};
  4043. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
  4044. for (i = 0; i < 4; ++i, c <<= 8)
  4045. ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
  4046. memcpy(out_buf.m_pBuf, pnghdr, 41);
  4047. }
  4048. // write footer (IDAT CRC-32, followed by IEND chunk)
  4049. if (!tdefl_output_buffer_putter(
  4050. "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
  4051. *pLen_out = 0;
  4052. MZ_FREE(pComp);
  4053. MZ_FREE(out_buf.m_pBuf);
  4054. return NULL;
  4055. }
  4056. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
  4057. *pLen_out + 4);
  4058. for (i = 0; i < 4; ++i, c <<= 8)
  4059. (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
  4060. // compute final size of file, grab compressed data buffer and return
  4061. *pLen_out += 57;
  4062. MZ_FREE(pComp);
  4063. return out_buf.m_pBuf;
  4064. }
  4065. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  4066. int num_chans, size_t *pLen_out) {
  4067. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
  4068. // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
  4069. // where #defined out)
  4070. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
  4071. pLen_out, 6, MZ_FALSE);
  4072. }
  4073. // ------------------- .ZIP archive reading
  4074. #ifndef MINIZ_NO_ARCHIVE_APIS
  4075. #error "No arvhive APIs"
  4076. #ifdef MINIZ_NO_STDIO
  4077. #define MZ_FILE void *
  4078. #else
  4079. #include <stdio.h>
  4080. #include <sys/stat.h>
  4081. #if defined(_MSC_VER) || defined(__MINGW64__)
  4082. static FILE *mz_fopen(const char *pFilename, const char *pMode) {
  4083. FILE *pFile = NULL;
  4084. fopen_s(&pFile, pFilename, pMode);
  4085. return pFile;
  4086. }
  4087. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
  4088. FILE *pFile = NULL;
  4089. if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL;
  4090. return pFile;
  4091. }
  4092. #ifndef MINIZ_NO_TIME
  4093. #include <sys/utime.h>
  4094. #endif
  4095. #define MZ_FILE FILE
  4096. #define MZ_FOPEN mz_fopen
  4097. #define MZ_FCLOSE fclose
  4098. #define MZ_FREAD fread
  4099. #define MZ_FWRITE fwrite
  4100. #define MZ_FTELL64 _ftelli64
  4101. #define MZ_FSEEK64 _fseeki64
  4102. #define MZ_FILE_STAT_STRUCT _stat
  4103. #define MZ_FILE_STAT _stat
  4104. #define MZ_FFLUSH fflush
  4105. #define MZ_FREOPEN mz_freopen
  4106. #define MZ_DELETE_FILE remove
  4107. #elif defined(__MINGW32__)
  4108. #ifndef MINIZ_NO_TIME
  4109. #include <sys/utime.h>
  4110. #endif
  4111. #define MZ_FILE FILE
  4112. #define MZ_FOPEN(f, m) fopen(f, m)
  4113. #define MZ_FCLOSE fclose
  4114. #define MZ_FREAD fread
  4115. #define MZ_FWRITE fwrite
  4116. #define MZ_FTELL64 ftello64
  4117. #define MZ_FSEEK64 fseeko64
  4118. #define MZ_FILE_STAT_STRUCT _stat
  4119. #define MZ_FILE_STAT _stat
  4120. #define MZ_FFLUSH fflush
  4121. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4122. #define MZ_DELETE_FILE remove
  4123. #elif defined(__TINYC__)
  4124. #ifndef MINIZ_NO_TIME
  4125. #include <sys/utime.h>
  4126. #endif
  4127. #define MZ_FILE FILE
  4128. #define MZ_FOPEN(f, m) fopen(f, m)
  4129. #define MZ_FCLOSE fclose
  4130. #define MZ_FREAD fread
  4131. #define MZ_FWRITE fwrite
  4132. #define MZ_FTELL64 ftell
  4133. #define MZ_FSEEK64 fseek
  4134. #define MZ_FILE_STAT_STRUCT stat
  4135. #define MZ_FILE_STAT stat
  4136. #define MZ_FFLUSH fflush
  4137. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4138. #define MZ_DELETE_FILE remove
  4139. #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
  4140. #ifndef MINIZ_NO_TIME
  4141. #include <utime.h>
  4142. #endif
  4143. #define MZ_FILE FILE
  4144. #define MZ_FOPEN(f, m) fopen64(f, m)
  4145. #define MZ_FCLOSE fclose
  4146. #define MZ_FREAD fread
  4147. #define MZ_FWRITE fwrite
  4148. #define MZ_FTELL64 ftello64
  4149. #define MZ_FSEEK64 fseeko64
  4150. #define MZ_FILE_STAT_STRUCT stat64
  4151. #define MZ_FILE_STAT stat64
  4152. #define MZ_FFLUSH fflush
  4153. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  4154. #define MZ_DELETE_FILE remove
  4155. #else
  4156. #ifndef MINIZ_NO_TIME
  4157. #include <utime.h>
  4158. #endif
  4159. #define MZ_FILE FILE
  4160. #define MZ_FOPEN(f, m) fopen(f, m)
  4161. #define MZ_FCLOSE fclose
  4162. #define MZ_FREAD fread
  4163. #define MZ_FWRITE fwrite
  4164. #define MZ_FTELL64 ftello
  4165. #define MZ_FSEEK64 fseeko
  4166. #define MZ_FILE_STAT_STRUCT stat
  4167. #define MZ_FILE_STAT stat
  4168. #define MZ_FFLUSH fflush
  4169. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4170. #define MZ_DELETE_FILE remove
  4171. #endif // #ifdef _MSC_VER
  4172. #endif // #ifdef MINIZ_NO_STDIO
  4173. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  4174. // Various ZIP archive enums. To completely avoid cross platform compiler
  4175. // alignment and platform endian issues, miniz.c doesn't use structs for any of
  4176. // this stuff.
  4177. enum {
  4178. // ZIP archive identifiers and record sizes
  4179. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
  4180. MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
  4181. MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  4182. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
  4183. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
  4184. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  4185. // Central directory header record offsets
  4186. MZ_ZIP_CDH_SIG_OFS = 0,
  4187. MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
  4188. MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
  4189. MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  4190. MZ_ZIP_CDH_METHOD_OFS = 10,
  4191. MZ_ZIP_CDH_FILE_TIME_OFS = 12,
  4192. MZ_ZIP_CDH_FILE_DATE_OFS = 14,
  4193. MZ_ZIP_CDH_CRC32_OFS = 16,
  4194. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
  4195. MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
  4196. MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
  4197. MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  4198. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
  4199. MZ_ZIP_CDH_DISK_START_OFS = 34,
  4200. MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
  4201. MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
  4202. MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  4203. // Local directory header offsets
  4204. MZ_ZIP_LDH_SIG_OFS = 0,
  4205. MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
  4206. MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
  4207. MZ_ZIP_LDH_METHOD_OFS = 8,
  4208. MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  4209. MZ_ZIP_LDH_FILE_DATE_OFS = 12,
  4210. MZ_ZIP_LDH_CRC32_OFS = 14,
  4211. MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
  4212. MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  4213. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
  4214. MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  4215. // End of central directory offsets
  4216. MZ_ZIP_ECDH_SIG_OFS = 0,
  4217. MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
  4218. MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
  4219. MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  4220. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
  4221. MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
  4222. MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
  4223. MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  4224. };
  4225. typedef struct {
  4226. void *m_p;
  4227. size_t m_size, m_capacity;
  4228. mz_uint m_element_size;
  4229. } mz_zip_array;
  4230. struct mz_zip_internal_state_tag {
  4231. mz_zip_array m_central_dir;
  4232. mz_zip_array m_central_dir_offsets;
  4233. mz_zip_array m_sorted_central_dir_offsets;
  4234. MZ_FILE *m_pFile;
  4235. void *m_pMem;
  4236. size_t m_mem_size;
  4237. size_t m_mem_capacity;
  4238. };
  4239. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
  4240. (array_ptr)->m_element_size = element_size
  4241. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
  4242. ((element_type *)((array_ptr)->m_p))[index]
  4243. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
  4244. mz_zip_array *pArray) {
  4245. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  4246. memset(pArray, 0, sizeof(mz_zip_array));
  4247. }
  4248. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
  4249. mz_zip_array *pArray,
  4250. size_t min_new_capacity,
  4251. mz_uint growing) {
  4252. void *pNew_p;
  4253. size_t new_capacity = min_new_capacity;
  4254. MZ_ASSERT(pArray->m_element_size);
  4255. if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  4256. if (growing) {
  4257. new_capacity = MZ_MAX(1, pArray->m_capacity);
  4258. while (new_capacity < min_new_capacity) new_capacity *= 2;
  4259. }
  4260. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
  4261. pArray->m_element_size, new_capacity)))
  4262. return MZ_FALSE;
  4263. pArray->m_p = pNew_p;
  4264. pArray->m_capacity = new_capacity;
  4265. return MZ_TRUE;
  4266. }
  4267. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip,
  4268. mz_zip_array *pArray,
  4269. size_t new_capacity,
  4270. mz_uint growing) {
  4271. if (new_capacity > pArray->m_capacity) {
  4272. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
  4273. return MZ_FALSE;
  4274. }
  4275. return MZ_TRUE;
  4276. }
  4277. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip,
  4278. mz_zip_array *pArray,
  4279. size_t new_size,
  4280. mz_uint growing) {
  4281. if (new_size > pArray->m_capacity) {
  4282. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
  4283. return MZ_FALSE;
  4284. }
  4285. pArray->m_size = new_size;
  4286. return MZ_TRUE;
  4287. }
  4288. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip,
  4289. mz_zip_array *pArray,
  4290. size_t n) {
  4291. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  4292. }
  4293. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip,
  4294. mz_zip_array *pArray,
  4295. const void *pElements,
  4296. size_t n) {
  4297. size_t orig_size = pArray->m_size;
  4298. if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
  4299. return MZ_FALSE;
  4300. memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
  4301. pElements, n * pArray->m_element_size);
  4302. return MZ_TRUE;
  4303. }
  4304. #ifndef MINIZ_NO_TIME
  4305. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
  4306. struct tm tm;
  4307. memset(&tm, 0, sizeof(tm));
  4308. tm.tm_isdst = -1;
  4309. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
  4310. tm.tm_mon = ((dos_date >> 5) & 15) - 1;
  4311. tm.tm_mday = dos_date & 31;
  4312. tm.tm_hour = (dos_time >> 11) & 31;
  4313. tm.tm_min = (dos_time >> 5) & 63;
  4314. tm.tm_sec = (dos_time << 1) & 62;
  4315. return mktime(&tm);
  4316. }
  4317. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
  4318. mz_uint16 *pDOS_date) {
  4319. #ifdef _MSC_VER
  4320. struct tm tm_struct;
  4321. struct tm *tm = &tm_struct;
  4322. errno_t err = localtime_s(tm, &time);
  4323. if (err) {
  4324. *pDOS_date = 0;
  4325. *pDOS_time = 0;
  4326. return;
  4327. }
  4328. #else
  4329. struct tm *tm = localtime(&time);
  4330. #endif
  4331. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
  4332. ((tm->tm_sec) >> 1));
  4333. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
  4334. ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  4335. }
  4336. #endif
  4337. #ifndef MINIZ_NO_STDIO
  4338. static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
  4339. mz_uint16 *pDOS_time,
  4340. mz_uint16 *pDOS_date) {
  4341. #ifdef MINIZ_NO_TIME
  4342. (void)pFilename;
  4343. *pDOS_date = *pDOS_time = 0;
  4344. #else
  4345. struct MZ_FILE_STAT_STRUCT file_stat;
  4346. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
  4347. // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  4348. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE;
  4349. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  4350. #endif // #ifdef MINIZ_NO_TIME
  4351. return MZ_TRUE;
  4352. }
  4353. #ifndef MINIZ_NO_TIME
  4354. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
  4355. time_t modified_time) {
  4356. struct utimbuf t;
  4357. t.actime = access_time;
  4358. t.modtime = modified_time;
  4359. return !utime(pFilename, &t);
  4360. }
  4361. #endif // #ifndef MINIZ_NO_TIME
  4362. #endif // #ifndef MINIZ_NO_STDIO
  4363. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
  4364. mz_uint32 flags) {
  4365. (void)flags;
  4366. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  4367. return MZ_FALSE;
  4368. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  4369. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  4370. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  4371. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  4372. pZip->m_archive_size = 0;
  4373. pZip->m_central_directory_file_ofs = 0;
  4374. pZip->m_total_files = 0;
  4375. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  4376. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  4377. return MZ_FALSE;
  4378. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  4379. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  4380. sizeof(mz_uint8));
  4381. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  4382. sizeof(mz_uint32));
  4383. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  4384. sizeof(mz_uint32));
  4385. return MZ_TRUE;
  4386. }
  4387. static MZ_FORCEINLINE mz_bool
  4388. mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
  4389. const mz_zip_array *pCentral_dir_offsets,
  4390. mz_uint l_index, mz_uint r_index) {
  4391. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4392. pCentral_dir_array, mz_uint8,
  4393. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4394. l_index)),
  4395. *pE;
  4396. const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(
  4397. pCentral_dir_array, mz_uint8,
  4398. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  4399. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
  4400. r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4401. mz_uint8 l = 0, r = 0;
  4402. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4403. pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4404. pE = pL + MZ_MIN(l_len, r_len);
  4405. while (pL < pE) {
  4406. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4407. pL++;
  4408. pR++;
  4409. }
  4410. return (pL == pE) ? (l_len < r_len) : (l < r);
  4411. }
  4412. #define MZ_SWAP_UINT32(a, b) \
  4413. do { \
  4414. mz_uint32 t = a; \
  4415. a = b; \
  4416. b = t; \
  4417. } \
  4418. MZ_MACRO_END
  4419. // Heap sort of lowercased filenames, used to help accelerate plain central
  4420. // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
  4421. // but it could allocate memory.)
  4422. static void mz_zip_reader_sort_central_dir_offsets_by_filename(
  4423. mz_zip_archive *pZip) {
  4424. mz_zip_internal_state *pState = pZip->m_pState;
  4425. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4426. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4427. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4428. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4429. const int size = pZip->m_total_files;
  4430. int start = (size - 2) >> 1, end;
  4431. while (start >= 0) {
  4432. int child, root = start;
  4433. for (;;) {
  4434. if ((child = (root << 1) + 1) >= size) break;
  4435. child +=
  4436. (((child + 1) < size) &&
  4437. (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4438. pIndices[child], pIndices[child + 1])));
  4439. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4440. pIndices[root], pIndices[child]))
  4441. break;
  4442. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4443. root = child;
  4444. }
  4445. start--;
  4446. }
  4447. end = size - 1;
  4448. while (end > 0) {
  4449. int child, root = 0;
  4450. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  4451. for (;;) {
  4452. if ((child = (root << 1) + 1) >= end) break;
  4453. child +=
  4454. (((child + 1) < end) &&
  4455. mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4456. pIndices[child], pIndices[child + 1]));
  4457. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4458. pIndices[root], pIndices[child]))
  4459. break;
  4460. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4461. root = child;
  4462. }
  4463. end--;
  4464. }
  4465. }
  4466. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
  4467. mz_uint32 flags) {
  4468. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  4469. mz_uint64 cdir_ofs;
  4470. mz_int64 cur_file_ofs;
  4471. const mz_uint8 *p;
  4472. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
  4473. mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  4474. mz_bool sort_central_dir =
  4475. ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  4476. // Basic sanity checks - reject files which are too small, and check the first
  4477. // 4 bytes of the file to make sure a local header is there.
  4478. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4479. return MZ_FALSE;
  4480. // Find the end of central directory record by scanning the file from the end
  4481. // towards the beginning.
  4482. cur_file_ofs =
  4483. MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  4484. for (;;) {
  4485. int i,
  4486. n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  4487. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  4488. return MZ_FALSE;
  4489. for (i = n - 4; i >= 0; --i)
  4490. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break;
  4491. if (i >= 0) {
  4492. cur_file_ofs += i;
  4493. break;
  4494. }
  4495. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
  4496. (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  4497. return MZ_FALSE;
  4498. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  4499. }
  4500. // Read and verify the end of central directory record.
  4501. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4502. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
  4503. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4504. return MZ_FALSE;
  4505. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
  4506. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  4507. ((pZip->m_total_files =
  4508. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
  4509. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  4510. return MZ_FALSE;
  4511. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  4512. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  4513. if (((num_this_disk | cdir_disk_index) != 0) &&
  4514. ((num_this_disk != 1) || (cdir_disk_index != 1)))
  4515. return MZ_FALSE;
  4516. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
  4517. pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  4518. return MZ_FALSE;
  4519. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  4520. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE;
  4521. pZip->m_central_directory_file_ofs = cdir_ofs;
  4522. if (pZip->m_total_files) {
  4523. mz_uint i, n;
  4524. // Read the entire central directory into a heap block, and allocate another
  4525. // heap block to hold the unsorted central dir file record offsets, and
  4526. // another to hold the sorted indices.
  4527. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
  4528. MZ_FALSE)) ||
  4529. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
  4530. pZip->m_total_files, MZ_FALSE)))
  4531. return MZ_FALSE;
  4532. if (sort_central_dir) {
  4533. if (!mz_zip_array_resize(pZip,
  4534. &pZip->m_pState->m_sorted_central_dir_offsets,
  4535. pZip->m_total_files, MZ_FALSE))
  4536. return MZ_FALSE;
  4537. }
  4538. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
  4539. pZip->m_pState->m_central_dir.m_p,
  4540. cdir_size) != cdir_size)
  4541. return MZ_FALSE;
  4542. // Now create an index into the central directory file records, do some
  4543. // basic sanity checking on each record, and check for zip64 entries (which
  4544. // are not yet supported).
  4545. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  4546. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
  4547. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  4548. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
  4549. (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  4550. return MZ_FALSE;
  4551. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4552. i) =
  4553. (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  4554. if (sort_central_dir)
  4555. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
  4556. mz_uint32, i) = i;
  4557. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4558. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4559. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
  4560. (decomp_size != comp_size)) ||
  4561. (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
  4562. (comp_size == 0xFFFFFFFF))
  4563. return MZ_FALSE;
  4564. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  4565. if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE;
  4566. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
  4567. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  4568. return MZ_FALSE;
  4569. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4570. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4571. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  4572. MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
  4573. n)
  4574. return MZ_FALSE;
  4575. n -= total_header_size;
  4576. p += total_header_size;
  4577. }
  4578. }
  4579. if (sort_central_dir)
  4580. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  4581. return MZ_TRUE;
  4582. }
  4583. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  4584. mz_uint32 flags) {
  4585. if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE;
  4586. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4587. pZip->m_archive_size = size;
  4588. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4589. mz_zip_reader_end(pZip);
  4590. return MZ_FALSE;
  4591. }
  4592. return MZ_TRUE;
  4593. }
  4594. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
  4595. void *pBuf, size_t n) {
  4596. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4597. size_t s = (file_ofs >= pZip->m_archive_size)
  4598. ? 0
  4599. : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  4600. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  4601. return s;
  4602. }
  4603. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  4604. size_t size, mz_uint32 flags) {
  4605. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4606. pZip->m_archive_size = size;
  4607. pZip->m_pRead = mz_zip_mem_read_func;
  4608. pZip->m_pIO_opaque = pZip;
  4609. #ifdef __cplusplus
  4610. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  4611. #else
  4612. pZip->m_pState->m_pMem = (void *)pMem;
  4613. #endif
  4614. pZip->m_pState->m_mem_size = size;
  4615. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4616. mz_zip_reader_end(pZip);
  4617. return MZ_FALSE;
  4618. }
  4619. return MZ_TRUE;
  4620. }
  4621. #ifndef MINIZ_NO_STDIO
  4622. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
  4623. void *pBuf, size_t n) {
  4624. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4625. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  4626. if (((mz_int64)file_ofs < 0) ||
  4627. (((cur_ofs != (mz_int64)file_ofs)) &&
  4628. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  4629. return 0;
  4630. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  4631. }
  4632. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  4633. mz_uint32 flags) {
  4634. mz_uint64 file_size;
  4635. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  4636. if (!pFile) return MZ_FALSE;
  4637. if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
  4638. MZ_FCLOSE(pFile);
  4639. return MZ_FALSE;
  4640. }
  4641. file_size = MZ_FTELL64(pFile);
  4642. if (!mz_zip_reader_init_internal(pZip, flags)) {
  4643. MZ_FCLOSE(pFile);
  4644. return MZ_FALSE;
  4645. }
  4646. pZip->m_pRead = mz_zip_file_read_func;
  4647. pZip->m_pIO_opaque = pZip;
  4648. pZip->m_pState->m_pFile = pFile;
  4649. pZip->m_archive_size = file_size;
  4650. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4651. mz_zip_reader_end(pZip);
  4652. return MZ_FALSE;
  4653. }
  4654. return MZ_TRUE;
  4655. }
  4656. #endif // #ifndef MINIZ_NO_STDIO
  4657. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
  4658. return pZip ? pZip->m_total_files : 0;
  4659. }
  4660. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(
  4661. mz_zip_archive *pZip, mz_uint file_index) {
  4662. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
  4663. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4664. return NULL;
  4665. return &MZ_ZIP_ARRAY_ELEMENT(
  4666. &pZip->m_pState->m_central_dir, mz_uint8,
  4667. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4668. file_index));
  4669. }
  4670. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  4671. mz_uint file_index) {
  4672. mz_uint m_bit_flag;
  4673. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4674. if (!p) return MZ_FALSE;
  4675. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4676. return (m_bit_flag & 1);
  4677. }
  4678. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  4679. mz_uint file_index) {
  4680. mz_uint filename_len, external_attr;
  4681. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4682. if (!p) return MZ_FALSE;
  4683. // First see if the filename ends with a '/' character.
  4684. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4685. if (filename_len) {
  4686. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  4687. return MZ_TRUE;
  4688. }
  4689. // Bugfix: This code was also checking if the internal attribute was non-zero,
  4690. // which wasn't correct.
  4691. // Most/all zip writers (hopefully) set DOS file/directory attributes in the
  4692. // low 16-bits, so check for the DOS directory flag and ignore the source OS
  4693. // ID in the created by field.
  4694. // FIXME: Remove this check? Is it necessary - we already check the filename.
  4695. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4696. if ((external_attr & 0x10) != 0) return MZ_TRUE;
  4697. return MZ_FALSE;
  4698. }
  4699. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  4700. mz_zip_archive_file_stat *pStat) {
  4701. mz_uint n;
  4702. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4703. if ((!p) || (!pStat)) return MZ_FALSE;
  4704. // Unpack the central directory record.
  4705. pStat->m_file_index = file_index;
  4706. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
  4707. &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  4708. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  4709. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  4710. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4711. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  4712. #ifndef MINIZ_NO_TIME
  4713. pStat->m_time =
  4714. mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
  4715. MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  4716. #endif
  4717. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  4718. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4719. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4720. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  4721. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4722. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4723. // Copy as much of the filename and comment as possible.
  4724. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4725. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  4726. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4727. pStat->m_filename[n] = '\0';
  4728. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4729. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  4730. pStat->m_comment_size = n;
  4731. memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4732. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4733. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4734. n);
  4735. pStat->m_comment[n] = '\0';
  4736. return MZ_TRUE;
  4737. }
  4738. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  4739. char *pFilename, mz_uint filename_buf_size) {
  4740. mz_uint n;
  4741. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4742. if (!p) {
  4743. if (filename_buf_size) pFilename[0] = '\0';
  4744. return 0;
  4745. }
  4746. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4747. if (filename_buf_size) {
  4748. n = MZ_MIN(n, filename_buf_size - 1);
  4749. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4750. pFilename[n] = '\0';
  4751. }
  4752. return n + 1;
  4753. }
  4754. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA,
  4755. const char *pB,
  4756. mz_uint len,
  4757. mz_uint flags) {
  4758. mz_uint i;
  4759. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len);
  4760. for (i = 0; i < len; ++i)
  4761. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE;
  4762. return MZ_TRUE;
  4763. }
  4764. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(
  4765. const mz_zip_array *pCentral_dir_array,
  4766. const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR,
  4767. mz_uint r_len) {
  4768. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4769. pCentral_dir_array, mz_uint8,
  4770. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4771. l_index)),
  4772. *pE;
  4773. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4774. mz_uint8 l = 0, r = 0;
  4775. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4776. pE = pL + MZ_MIN(l_len, r_len);
  4777. while (pL < pE) {
  4778. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4779. pL++;
  4780. pR++;
  4781. }
  4782. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  4783. }
  4784. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
  4785. const char *pFilename) {
  4786. mz_zip_internal_state *pState = pZip->m_pState;
  4787. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4788. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4789. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4790. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4791. const int size = pZip->m_total_files;
  4792. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  4793. int l = 0, h = size - 1;
  4794. while (l <= h) {
  4795. int m = (l + h) >> 1, file_index = pIndices[m],
  4796. comp =
  4797. mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
  4798. file_index, pFilename, filename_len);
  4799. if (!comp)
  4800. return file_index;
  4801. else if (comp < 0)
  4802. l = m + 1;
  4803. else
  4804. h = m - 1;
  4805. }
  4806. return -1;
  4807. }
  4808. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  4809. const char *pComment, mz_uint flags) {
  4810. mz_uint file_index;
  4811. size_t name_len, comment_len;
  4812. if ((!pZip) || (!pZip->m_pState) || (!pName) ||
  4813. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4814. return -1;
  4815. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
  4816. (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  4817. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  4818. name_len = strlen(pName);
  4819. if (name_len > 0xFFFF) return -1;
  4820. comment_len = pComment ? strlen(pComment) : 0;
  4821. if (comment_len > 0xFFFF) return -1;
  4822. for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
  4823. const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(
  4824. &pZip->m_pState->m_central_dir, mz_uint8,
  4825. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4826. file_index));
  4827. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4828. const char *pFilename =
  4829. (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4830. if (filename_len < name_len) continue;
  4831. if (comment_len) {
  4832. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4833. file_comment_len =
  4834. MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4835. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  4836. if ((file_comment_len != comment_len) ||
  4837. (!mz_zip_reader_string_equal(pComment, pFile_comment,
  4838. file_comment_len, flags)))
  4839. continue;
  4840. }
  4841. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
  4842. int ofs = filename_len - 1;
  4843. do {
  4844. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
  4845. (pFilename[ofs] == ':'))
  4846. break;
  4847. } while (--ofs >= 0);
  4848. ofs++;
  4849. pFilename += ofs;
  4850. filename_len -= ofs;
  4851. }
  4852. if ((filename_len == name_len) &&
  4853. (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  4854. return file_index;
  4855. }
  4856. return -1;
  4857. }
  4858. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  4859. mz_uint file_index, void *pBuf,
  4860. size_t buf_size, mz_uint flags,
  4861. void *pUser_read_buf,
  4862. size_t user_read_buf_size) {
  4863. int status = TINFL_STATUS_DONE;
  4864. mz_uint64 needed_size, cur_file_ofs, comp_remaining,
  4865. out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  4866. mz_zip_archive_file_stat file_stat;
  4867. void *pRead_buf;
  4868. mz_uint32
  4869. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  4870. sizeof(mz_uint32)];
  4871. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4872. tinfl_decompressor inflator;
  4873. if ((buf_size) && (!pBuf)) return MZ_FALSE;
  4874. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  4875. // Empty file, or a directory (but not always a directory - I've seen odd zips
  4876. // with directories that have compressed data which inflates to 0 bytes)
  4877. if (!file_stat.m_comp_size) return MZ_TRUE;
  4878. // Entry is a subdirectory (I've seen old zips with dir entries which have
  4879. // compressed deflate data which inflates to 0 bytes, but these entries claim
  4880. // to uncompress to 512 bytes in the headers).
  4881. // I'm torn how to handle this case - should it fail instead?
  4882. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  4883. // Encryption and patch files are not supported.
  4884. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  4885. // This function only supports stored and deflate.
  4886. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  4887. (file_stat.m_method != MZ_DEFLATED))
  4888. return MZ_FALSE;
  4889. // Ensure supplied output buffer is large enough.
  4890. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
  4891. : file_stat.m_uncomp_size;
  4892. if (buf_size < needed_size) return MZ_FALSE;
  4893. // Read and parse the local directory entry.
  4894. cur_file_ofs = file_stat.m_local_header_ofs;
  4895. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  4896. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  4897. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4898. return MZ_FALSE;
  4899. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4900. return MZ_FALSE;
  4901. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  4902. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  4903. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4904. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  4905. return MZ_FALSE;
  4906. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  4907. // The file is stored or the caller has requested the compressed data.
  4908. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4909. (size_t)needed_size) != needed_size)
  4910. return MZ_FALSE;
  4911. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
  4912. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4913. (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  4914. }
  4915. // Decompress the file either directly from memory or from a file input
  4916. // buffer.
  4917. tinfl_init(&inflator);
  4918. if (pZip->m_pState->m_pMem) {
  4919. // Read directly from the archive in memory.
  4920. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  4921. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  4922. comp_remaining = 0;
  4923. } else if (pUser_read_buf) {
  4924. // Use a user provided read buffer.
  4925. if (!user_read_buf_size) return MZ_FALSE;
  4926. pRead_buf = (mz_uint8 *)pUser_read_buf;
  4927. read_buf_size = user_read_buf_size;
  4928. read_buf_avail = 0;
  4929. comp_remaining = file_stat.m_comp_size;
  4930. } else {
  4931. // Temporarily allocate a read buffer.
  4932. read_buf_size =
  4933. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  4934. #ifdef _MSC_VER
  4935. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  4936. (read_buf_size > 0x7FFFFFFF))
  4937. #else
  4938. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  4939. #endif
  4940. return MZ_FALSE;
  4941. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4942. (size_t)read_buf_size)))
  4943. return MZ_FALSE;
  4944. read_buf_avail = 0;
  4945. comp_remaining = file_stat.m_comp_size;
  4946. }
  4947. do {
  4948. size_t in_buf_size,
  4949. out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  4950. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  4951. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4952. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4953. (size_t)read_buf_avail) != read_buf_avail) {
  4954. status = TINFL_STATUS_FAILED;
  4955. break;
  4956. }
  4957. cur_file_ofs += read_buf_avail;
  4958. comp_remaining -= read_buf_avail;
  4959. read_buf_ofs = 0;
  4960. }
  4961. in_buf_size = (size_t)read_buf_avail;
  4962. status = tinfl_decompress(
  4963. &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  4964. (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
  4965. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
  4966. (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  4967. read_buf_avail -= in_buf_size;
  4968. read_buf_ofs += in_buf_size;
  4969. out_buf_ofs += out_buf_size;
  4970. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  4971. if (status == TINFL_STATUS_DONE) {
  4972. // Make sure the entire file was decompressed, and check its CRC.
  4973. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  4974. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4975. (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  4976. status = TINFL_STATUS_FAILED;
  4977. }
  4978. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  4979. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4980. return status == TINFL_STATUS_DONE;
  4981. }
  4982. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  4983. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  4984. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
  4985. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  4986. if (file_index < 0) return MZ_FALSE;
  4987. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  4988. flags, pUser_read_buf,
  4989. user_read_buf_size);
  4990. }
  4991. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  4992. void *pBuf, size_t buf_size,
  4993. mz_uint flags) {
  4994. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  4995. flags, NULL, 0);
  4996. }
  4997. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  4998. const char *pFilename, void *pBuf,
  4999. size_t buf_size, mz_uint flags) {
  5000. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
  5001. buf_size, flags, NULL, 0);
  5002. }
  5003. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  5004. size_t *pSize, mz_uint flags) {
  5005. mz_uint64 comp_size, uncomp_size, alloc_size;
  5006. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  5007. void *pBuf;
  5008. if (pSize) *pSize = 0;
  5009. if (!p) return NULL;
  5010. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5011. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  5012. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  5013. #ifdef _MSC_VER
  5014. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5015. #else
  5016. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5017. #endif
  5018. return NULL;
  5019. if (NULL ==
  5020. (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  5021. return NULL;
  5022. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
  5023. flags)) {
  5024. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5025. return NULL;
  5026. }
  5027. if (pSize) *pSize = (size_t)alloc_size;
  5028. return pBuf;
  5029. }
  5030. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  5031. const char *pFilename, size_t *pSize,
  5032. mz_uint flags) {
  5033. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5034. if (file_index < 0) {
  5035. if (pSize) *pSize = 0;
  5036. return MZ_FALSE;
  5037. }
  5038. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  5039. }
  5040. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  5041. mz_uint file_index,
  5042. mz_file_write_func pCallback,
  5043. void *pOpaque, mz_uint flags) {
  5044. int status = TINFL_STATUS_DONE;
  5045. mz_uint file_crc32 = MZ_CRC32_INIT;
  5046. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
  5047. out_buf_ofs = 0, cur_file_ofs;
  5048. mz_zip_archive_file_stat file_stat;
  5049. void *pRead_buf = NULL;
  5050. void *pWrite_buf = NULL;
  5051. mz_uint32
  5052. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5053. sizeof(mz_uint32)];
  5054. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5055. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5056. // Empty file, or a directory (but not always a directory - I've seen odd zips
  5057. // with directories that have compressed data which inflates to 0 bytes)
  5058. if (!file_stat.m_comp_size) return MZ_TRUE;
  5059. // Entry is a subdirectory (I've seen old zips with dir entries which have
  5060. // compressed deflate data which inflates to 0 bytes, but these entries claim
  5061. // to uncompress to 512 bytes in the headers).
  5062. // I'm torn how to handle this case - should it fail instead?
  5063. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  5064. // Encryption and patch files are not supported.
  5065. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  5066. // This function only supports stored and deflate.
  5067. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  5068. (file_stat.m_method != MZ_DEFLATED))
  5069. return MZ_FALSE;
  5070. // Read and parse the local directory entry.
  5071. cur_file_ofs = file_stat.m_local_header_ofs;
  5072. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  5073. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5074. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5075. return MZ_FALSE;
  5076. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5077. return MZ_FALSE;
  5078. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  5079. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5080. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5081. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  5082. return MZ_FALSE;
  5083. // Decompress the file either directly from memory or from a file input
  5084. // buffer.
  5085. if (pZip->m_pState->m_pMem) {
  5086. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  5087. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  5088. comp_remaining = 0;
  5089. } else {
  5090. read_buf_size =
  5091. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5092. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5093. (size_t)read_buf_size)))
  5094. return MZ_FALSE;
  5095. read_buf_avail = 0;
  5096. comp_remaining = file_stat.m_comp_size;
  5097. }
  5098. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  5099. // The file is stored or the caller has requested the compressed data.
  5100. if (pZip->m_pState->m_pMem) {
  5101. #ifdef _MSC_VER
  5102. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  5103. (file_stat.m_comp_size > 0xFFFFFFFF))
  5104. #else
  5105. if (((sizeof(size_t) == sizeof(mz_uint32))) &&
  5106. (file_stat.m_comp_size > 0xFFFFFFFF))
  5107. #endif
  5108. return MZ_FALSE;
  5109. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5110. (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  5111. status = TINFL_STATUS_FAILED;
  5112. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5113. file_crc32 =
  5114. (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
  5115. (size_t)file_stat.m_comp_size);
  5116. cur_file_ofs += file_stat.m_comp_size;
  5117. out_buf_ofs += file_stat.m_comp_size;
  5118. comp_remaining = 0;
  5119. } else {
  5120. while (comp_remaining) {
  5121. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5122. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5123. (size_t)read_buf_avail) != read_buf_avail) {
  5124. status = TINFL_STATUS_FAILED;
  5125. break;
  5126. }
  5127. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5128. file_crc32 = (mz_uint32)mz_crc32(
  5129. file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  5130. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5131. (size_t)read_buf_avail) != read_buf_avail) {
  5132. status = TINFL_STATUS_FAILED;
  5133. break;
  5134. }
  5135. cur_file_ofs += read_buf_avail;
  5136. out_buf_ofs += read_buf_avail;
  5137. comp_remaining -= read_buf_avail;
  5138. }
  5139. }
  5140. } else {
  5141. tinfl_decompressor inflator;
  5142. tinfl_init(&inflator);
  5143. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5144. TINFL_LZ_DICT_SIZE)))
  5145. status = TINFL_STATUS_FAILED;
  5146. else {
  5147. do {
  5148. mz_uint8 *pWrite_buf_cur =
  5149. (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5150. size_t in_buf_size,
  5151. out_buf_size =
  5152. TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5153. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  5154. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5155. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5156. (size_t)read_buf_avail) != read_buf_avail) {
  5157. status = TINFL_STATUS_FAILED;
  5158. break;
  5159. }
  5160. cur_file_ofs += read_buf_avail;
  5161. comp_remaining -= read_buf_avail;
  5162. read_buf_ofs = 0;
  5163. }
  5164. in_buf_size = (size_t)read_buf_avail;
  5165. status = tinfl_decompress(
  5166. &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  5167. (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
  5168. comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  5169. read_buf_avail -= in_buf_size;
  5170. read_buf_ofs += in_buf_size;
  5171. if (out_buf_size) {
  5172. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
  5173. out_buf_size) {
  5174. status = TINFL_STATUS_FAILED;
  5175. break;
  5176. }
  5177. file_crc32 =
  5178. (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  5179. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
  5180. status = TINFL_STATUS_FAILED;
  5181. break;
  5182. }
  5183. }
  5184. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
  5185. (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  5186. }
  5187. }
  5188. if ((status == TINFL_STATUS_DONE) &&
  5189. (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
  5190. // Make sure the entire file was decompressed, and check its CRC.
  5191. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  5192. (file_crc32 != file_stat.m_crc32))
  5193. status = TINFL_STATUS_FAILED;
  5194. }
  5195. if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5196. if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  5197. return status == TINFL_STATUS_DONE;
  5198. }
  5199. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  5200. const char *pFilename,
  5201. mz_file_write_func pCallback,
  5202. void *pOpaque, mz_uint flags) {
  5203. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5204. if (file_index < 0) return MZ_FALSE;
  5205. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
  5206. flags);
  5207. }
  5208. #ifndef MINIZ_NO_STDIO
  5209. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
  5210. const void *pBuf, size_t n) {
  5211. (void)ofs;
  5212. return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
  5213. }
  5214. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  5215. const char *pDst_filename,
  5216. mz_uint flags) {
  5217. mz_bool status;
  5218. mz_zip_archive_file_stat file_stat;
  5219. MZ_FILE *pFile;
  5220. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5221. pFile = MZ_FOPEN(pDst_filename, "wb");
  5222. if (!pFile) return MZ_FALSE;
  5223. status = mz_zip_reader_extract_to_callback(
  5224. pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  5225. if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE;
  5226. #ifndef MINIZ_NO_TIME
  5227. if (status)
  5228. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  5229. #endif
  5230. return status;
  5231. }
  5232. #endif // #ifndef MINIZ_NO_STDIO
  5233. mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
  5234. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  5235. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5236. return MZ_FALSE;
  5237. if (pZip->m_pState) {
  5238. mz_zip_internal_state *pState = pZip->m_pState;
  5239. pZip->m_pState = NULL;
  5240. mz_zip_array_clear(pZip, &pState->m_central_dir);
  5241. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  5242. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  5243. #ifndef MINIZ_NO_STDIO
  5244. if (pState->m_pFile) {
  5245. MZ_FCLOSE(pState->m_pFile);
  5246. pState->m_pFile = NULL;
  5247. }
  5248. #endif // #ifndef MINIZ_NO_STDIO
  5249. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  5250. }
  5251. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  5252. return MZ_TRUE;
  5253. }
  5254. #ifndef MINIZ_NO_STDIO
  5255. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  5256. const char *pArchive_filename,
  5257. const char *pDst_filename,
  5258. mz_uint flags) {
  5259. int file_index =
  5260. mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  5261. if (file_index < 0) return MZ_FALSE;
  5262. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  5263. }
  5264. #endif
  5265. // ------------------- .ZIP archive writing
  5266. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  5267. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
  5268. p[0] = (mz_uint8)v;
  5269. p[1] = (mz_uint8)(v >> 8);
  5270. }
  5271. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
  5272. p[0] = (mz_uint8)v;
  5273. p[1] = (mz_uint8)(v >> 8);
  5274. p[2] = (mz_uint8)(v >> 16);
  5275. p[3] = (mz_uint8)(v >> 24);
  5276. }
  5277. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  5278. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  5279. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
  5280. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
  5281. (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  5282. return MZ_FALSE;
  5283. if (pZip->m_file_offset_alignment) {
  5284. // Ensure user specified file offset alignment is a power of 2.
  5285. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  5286. return MZ_FALSE;
  5287. }
  5288. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  5289. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  5290. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  5291. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5292. pZip->m_archive_size = existing_size;
  5293. pZip->m_central_directory_file_ofs = 0;
  5294. pZip->m_total_files = 0;
  5295. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  5296. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  5297. return MZ_FALSE;
  5298. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  5299. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  5300. sizeof(mz_uint8));
  5301. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  5302. sizeof(mz_uint32));
  5303. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  5304. sizeof(mz_uint32));
  5305. return MZ_TRUE;
  5306. }
  5307. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
  5308. const void *pBuf, size_t n) {
  5309. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5310. mz_zip_internal_state *pState = pZip->m_pState;
  5311. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  5312. #ifdef _MSC_VER
  5313. if ((!n) ||
  5314. ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5315. #else
  5316. if ((!n) ||
  5317. ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5318. #endif
  5319. return 0;
  5320. if (new_size > pState->m_mem_capacity) {
  5321. void *pNew_block;
  5322. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
  5323. while (new_capacity < new_size) new_capacity *= 2;
  5324. if (NULL == (pNew_block = pZip->m_pRealloc(
  5325. pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  5326. return 0;
  5327. pState->m_pMem = pNew_block;
  5328. pState->m_mem_capacity = new_capacity;
  5329. }
  5330. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  5331. pState->m_mem_size = (size_t)new_size;
  5332. return n;
  5333. }
  5334. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  5335. size_t size_to_reserve_at_beginning,
  5336. size_t initial_allocation_size) {
  5337. pZip->m_pWrite = mz_zip_heap_write_func;
  5338. pZip->m_pIO_opaque = pZip;
  5339. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5340. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
  5341. size_to_reserve_at_beginning))) {
  5342. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
  5343. pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
  5344. mz_zip_writer_end(pZip);
  5345. return MZ_FALSE;
  5346. }
  5347. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  5348. }
  5349. return MZ_TRUE;
  5350. }
  5351. #ifndef MINIZ_NO_STDIO
  5352. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
  5353. const void *pBuf, size_t n) {
  5354. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5355. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  5356. if (((mz_int64)file_ofs < 0) ||
  5357. (((cur_ofs != (mz_int64)file_ofs)) &&
  5358. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  5359. return 0;
  5360. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  5361. }
  5362. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  5363. mz_uint64 size_to_reserve_at_beginning) {
  5364. MZ_FILE *pFile;
  5365. pZip->m_pWrite = mz_zip_file_write_func;
  5366. pZip->m_pIO_opaque = pZip;
  5367. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5368. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
  5369. mz_zip_writer_end(pZip);
  5370. return MZ_FALSE;
  5371. }
  5372. pZip->m_pState->m_pFile = pFile;
  5373. if (size_to_reserve_at_beginning) {
  5374. mz_uint64 cur_ofs = 0;
  5375. char buf[4096];
  5376. MZ_CLEAR_OBJ(buf);
  5377. do {
  5378. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  5379. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
  5380. mz_zip_writer_end(pZip);
  5381. return MZ_FALSE;
  5382. }
  5383. cur_ofs += n;
  5384. size_to_reserve_at_beginning -= n;
  5385. } while (size_to_reserve_at_beginning);
  5386. }
  5387. return MZ_TRUE;
  5388. }
  5389. #endif // #ifndef MINIZ_NO_STDIO
  5390. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  5391. const char *pFilename) {
  5392. mz_zip_internal_state *pState;
  5393. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5394. return MZ_FALSE;
  5395. // No sense in trying to write to an archive that's already at the support max
  5396. // size
  5397. if ((pZip->m_total_files == 0xFFFF) ||
  5398. ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5399. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  5400. return MZ_FALSE;
  5401. pState = pZip->m_pState;
  5402. if (pState->m_pFile) {
  5403. #ifdef MINIZ_NO_STDIO
  5404. pFilename;
  5405. return MZ_FALSE;
  5406. #else
  5407. // Archive is being read from stdio - try to reopen as writable.
  5408. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5409. if (!pFilename) return MZ_FALSE;
  5410. pZip->m_pWrite = mz_zip_file_write_func;
  5411. if (NULL ==
  5412. (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
  5413. // The mz_zip_archive is now in a bogus state because pState->m_pFile is
  5414. // NULL, so just close it.
  5415. mz_zip_reader_end(pZip);
  5416. return MZ_FALSE;
  5417. }
  5418. #endif // #ifdef MINIZ_NO_STDIO
  5419. } else if (pState->m_pMem) {
  5420. // Archive lives in a memory block. Assume it's from the heap that we can
  5421. // resize using the realloc callback.
  5422. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5423. pState->m_mem_capacity = pState->m_mem_size;
  5424. pZip->m_pWrite = mz_zip_heap_write_func;
  5425. }
  5426. // Archive is being read via a user provided read function - make sure the
  5427. // user has specified a write function too.
  5428. else if (!pZip->m_pWrite)
  5429. return MZ_FALSE;
  5430. // Start writing new files at the archive's current central directory
  5431. // location.
  5432. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  5433. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5434. pZip->m_central_directory_file_ofs = 0;
  5435. return MZ_TRUE;
  5436. }
  5437. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  5438. const void *pBuf, size_t buf_size,
  5439. mz_uint level_and_flags) {
  5440. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
  5441. level_and_flags, 0, 0);
  5442. }
  5443. typedef struct {
  5444. mz_zip_archive *m_pZip;
  5445. mz_uint64 m_cur_archive_file_ofs;
  5446. mz_uint64 m_comp_size;
  5447. } mz_zip_writer_add_state;
  5448. static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
  5449. void *pUser) {
  5450. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  5451. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
  5452. pState->m_cur_archive_file_ofs, pBuf,
  5453. len) != len)
  5454. return MZ_FALSE;
  5455. pState->m_cur_archive_file_ofs += len;
  5456. pState->m_comp_size += len;
  5457. return MZ_TRUE;
  5458. }
  5459. static mz_bool mz_zip_writer_create_local_dir_header(
  5460. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5461. mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5462. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5463. mz_uint16 dos_time, mz_uint16 dos_date) {
  5464. (void)pZip;
  5465. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  5466. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  5467. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5468. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  5469. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  5470. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  5471. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  5472. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  5473. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  5474. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5475. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  5476. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  5477. return MZ_TRUE;
  5478. }
  5479. static mz_bool mz_zip_writer_create_central_dir_header(
  5480. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5481. mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
  5482. mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
  5483. mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
  5484. mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
  5485. (void)pZip;
  5486. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5487. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  5488. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5489. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  5490. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  5491. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  5492. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  5493. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  5494. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  5495. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5496. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  5497. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  5498. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  5499. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  5500. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  5501. return MZ_TRUE;
  5502. }
  5503. static mz_bool mz_zip_writer_add_to_central_dir(
  5504. mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
  5505. const void *pExtra, mz_uint16 extra_size, const void *pComment,
  5506. mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5507. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5508. mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
  5509. mz_uint32 ext_attributes) {
  5510. mz_zip_internal_state *pState = pZip->m_pState;
  5511. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  5512. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  5513. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5514. // No zip64 support yet
  5515. if ((local_header_ofs > 0xFFFFFFFF) ||
  5516. (((mz_uint64)pState->m_central_dir.m_size +
  5517. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
  5518. comment_size) > 0xFFFFFFFF))
  5519. return MZ_FALSE;
  5520. if (!mz_zip_writer_create_central_dir_header(
  5521. pZip, central_dir_header, filename_size, extra_size, comment_size,
  5522. uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
  5523. dos_date, local_header_ofs, ext_attributes))
  5524. return MZ_FALSE;
  5525. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
  5526. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  5527. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
  5528. filename_size)) ||
  5529. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
  5530. extra_size)) ||
  5531. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
  5532. comment_size)) ||
  5533. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
  5534. &central_dir_ofs, 1))) {
  5535. // Try to push the central directory array back into its original state.
  5536. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5537. MZ_FALSE);
  5538. return MZ_FALSE;
  5539. }
  5540. return MZ_TRUE;
  5541. }
  5542. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
  5543. // Basic ZIP archive filename validity checks: Valid filenames cannot start
  5544. // with a forward slash, cannot contain a drive letter, and cannot use
  5545. // DOS-style backward slashes.
  5546. if (*pArchive_name == '/') return MZ_FALSE;
  5547. while (*pArchive_name) {
  5548. if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE;
  5549. pArchive_name++;
  5550. }
  5551. return MZ_TRUE;
  5552. }
  5553. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(
  5554. mz_zip_archive *pZip) {
  5555. mz_uint32 n;
  5556. if (!pZip->m_file_offset_alignment) return 0;
  5557. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  5558. return (pZip->m_file_offset_alignment - n) &
  5559. (pZip->m_file_offset_alignment - 1);
  5560. }
  5561. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
  5562. mz_uint64 cur_file_ofs, mz_uint32 n) {
  5563. char buf[4096];
  5564. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  5565. while (n) {
  5566. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  5567. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  5568. return MZ_FALSE;
  5569. cur_file_ofs += s;
  5570. n -= s;
  5571. }
  5572. return MZ_TRUE;
  5573. }
  5574. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  5575. const char *pArchive_name, const void *pBuf,
  5576. size_t buf_size, const void *pComment,
  5577. mz_uint16 comment_size,
  5578. mz_uint level_and_flags, mz_uint64 uncomp_size,
  5579. mz_uint32 uncomp_crc32) {
  5580. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  5581. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  5582. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5583. cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  5584. size_t archive_name_size;
  5585. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5586. tdefl_compressor *pComp = NULL;
  5587. mz_bool store_data_uncompressed;
  5588. mz_zip_internal_state *pState;
  5589. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5590. level = level_and_flags & 0xF;
  5591. store_data_uncompressed =
  5592. ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  5593. if ((!pZip) || (!pZip->m_pState) ||
  5594. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
  5595. (!pArchive_name) || ((comment_size) && (!pComment)) ||
  5596. (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  5597. return MZ_FALSE;
  5598. pState = pZip->m_pState;
  5599. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  5600. return MZ_FALSE;
  5601. // No zip64 support yet
  5602. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE;
  5603. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5604. #ifndef MINIZ_NO_TIME
  5605. {
  5606. time_t cur_time;
  5607. time(&cur_time);
  5608. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  5609. }
  5610. #endif // #ifndef MINIZ_NO_TIME
  5611. archive_name_size = strlen(pArchive_name);
  5612. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5613. num_alignment_padding_bytes =
  5614. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5615. // no zip64 support yet
  5616. if ((pZip->m_total_files == 0xFFFF) ||
  5617. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5618. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5619. comment_size + archive_name_size) > 0xFFFFFFFF))
  5620. return MZ_FALSE;
  5621. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
  5622. // Set DOS Subdirectory attribute bit.
  5623. ext_attributes |= 0x10;
  5624. // Subdirectories cannot contain data.
  5625. if ((buf_size) || (uncomp_size)) return MZ_FALSE;
  5626. }
  5627. // Try to do any allocations before writing to the archive, so if an
  5628. // allocation fails the file remains unmodified. (A good idea if we're doing
  5629. // an in-place modification.)
  5630. if ((!mz_zip_array_ensure_room(
  5631. pZip, &pState->m_central_dir,
  5632. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) ||
  5633. (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  5634. return MZ_FALSE;
  5635. if ((!store_data_uncompressed) && (buf_size)) {
  5636. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5637. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  5638. return MZ_FALSE;
  5639. }
  5640. if (!mz_zip_writer_write_zeros(
  5641. pZip, cur_archive_file_ofs,
  5642. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5643. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5644. return MZ_FALSE;
  5645. }
  5646. local_dir_header_ofs += num_alignment_padding_bytes;
  5647. if (pZip->m_file_offset_alignment) {
  5648. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5649. 0);
  5650. }
  5651. cur_archive_file_ofs +=
  5652. num_alignment_padding_bytes + sizeof(local_dir_header);
  5653. MZ_CLEAR_OBJ(local_dir_header);
  5654. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5655. archive_name_size) != archive_name_size) {
  5656. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5657. return MZ_FALSE;
  5658. }
  5659. cur_archive_file_ofs += archive_name_size;
  5660. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
  5661. uncomp_crc32 =
  5662. (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
  5663. uncomp_size = buf_size;
  5664. if (uncomp_size <= 3) {
  5665. level = 0;
  5666. store_data_uncompressed = MZ_TRUE;
  5667. }
  5668. }
  5669. if (store_data_uncompressed) {
  5670. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
  5671. buf_size) != buf_size) {
  5672. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5673. return MZ_FALSE;
  5674. }
  5675. cur_archive_file_ofs += buf_size;
  5676. comp_size = buf_size;
  5677. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED;
  5678. } else if (buf_size) {
  5679. mz_zip_writer_add_state state;
  5680. state.m_pZip = pZip;
  5681. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5682. state.m_comp_size = 0;
  5683. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5684. tdefl_create_comp_flags_from_zip_params(
  5685. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5686. TDEFL_STATUS_OKAY) ||
  5687. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
  5688. TDEFL_STATUS_DONE)) {
  5689. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5690. return MZ_FALSE;
  5691. }
  5692. comp_size = state.m_comp_size;
  5693. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5694. method = MZ_DEFLATED;
  5695. }
  5696. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5697. pComp = NULL;
  5698. // no zip64 support yet
  5699. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5700. return MZ_FALSE;
  5701. if (!mz_zip_writer_create_local_dir_header(
  5702. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5703. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5704. return MZ_FALSE;
  5705. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5706. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5707. return MZ_FALSE;
  5708. if (!mz_zip_writer_add_to_central_dir(
  5709. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5710. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5711. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5712. return MZ_FALSE;
  5713. pZip->m_total_files++;
  5714. pZip->m_archive_size = cur_archive_file_ofs;
  5715. return MZ_TRUE;
  5716. }
  5717. #ifndef MINIZ_NO_STDIO
  5718. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  5719. const char *pSrc_filename, const void *pComment,
  5720. mz_uint16 comment_size,
  5721. mz_uint level_and_flags) {
  5722. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  5723. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  5724. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5725. cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
  5726. comp_size = 0;
  5727. size_t archive_name_size;
  5728. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5729. MZ_FILE *pSrc_file = NULL;
  5730. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5731. level = level_and_flags & 0xF;
  5732. if ((!pZip) || (!pZip->m_pState) ||
  5733. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
  5734. ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  5735. return MZ_FALSE;
  5736. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE;
  5737. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5738. archive_name_size = strlen(pArchive_name);
  5739. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5740. num_alignment_padding_bytes =
  5741. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5742. // no zip64 support yet
  5743. if ((pZip->m_total_files == 0xFFFF) ||
  5744. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5745. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5746. comment_size + archive_name_size) > 0xFFFFFFFF))
  5747. return MZ_FALSE;
  5748. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  5749. return MZ_FALSE;
  5750. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  5751. if (!pSrc_file) return MZ_FALSE;
  5752. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  5753. uncomp_size = MZ_FTELL64(pSrc_file);
  5754. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  5755. if (uncomp_size > 0xFFFFFFFF) {
  5756. // No zip64 support yet
  5757. MZ_FCLOSE(pSrc_file);
  5758. return MZ_FALSE;
  5759. }
  5760. if (uncomp_size <= 3) level = 0;
  5761. if (!mz_zip_writer_write_zeros(
  5762. pZip, cur_archive_file_ofs,
  5763. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5764. MZ_FCLOSE(pSrc_file);
  5765. return MZ_FALSE;
  5766. }
  5767. local_dir_header_ofs += num_alignment_padding_bytes;
  5768. if (pZip->m_file_offset_alignment) {
  5769. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5770. 0);
  5771. }
  5772. cur_archive_file_ofs +=
  5773. num_alignment_padding_bytes + sizeof(local_dir_header);
  5774. MZ_CLEAR_OBJ(local_dir_header);
  5775. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5776. archive_name_size) != archive_name_size) {
  5777. MZ_FCLOSE(pSrc_file);
  5778. return MZ_FALSE;
  5779. }
  5780. cur_archive_file_ofs += archive_name_size;
  5781. if (uncomp_size) {
  5782. mz_uint64 uncomp_remaining = uncomp_size;
  5783. void *pRead_buf =
  5784. pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  5785. if (!pRead_buf) {
  5786. MZ_FCLOSE(pSrc_file);
  5787. return MZ_FALSE;
  5788. }
  5789. if (!level) {
  5790. while (uncomp_remaining) {
  5791. mz_uint n =
  5792. (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  5793. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
  5794. (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
  5795. n) != n)) {
  5796. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5797. MZ_FCLOSE(pSrc_file);
  5798. return MZ_FALSE;
  5799. }
  5800. uncomp_crc32 =
  5801. (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  5802. uncomp_remaining -= n;
  5803. cur_archive_file_ofs += n;
  5804. }
  5805. comp_size = uncomp_size;
  5806. } else {
  5807. mz_bool result = MZ_FALSE;
  5808. mz_zip_writer_add_state state;
  5809. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5810. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  5811. if (!pComp) {
  5812. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5813. MZ_FCLOSE(pSrc_file);
  5814. return MZ_FALSE;
  5815. }
  5816. state.m_pZip = pZip;
  5817. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5818. state.m_comp_size = 0;
  5819. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5820. tdefl_create_comp_flags_from_zip_params(
  5821. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5822. TDEFL_STATUS_OKAY) {
  5823. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5824. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5825. MZ_FCLOSE(pSrc_file);
  5826. return MZ_FALSE;
  5827. }
  5828. for (;;) {
  5829. size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining,
  5830. (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5831. tdefl_status status;
  5832. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  5833. break;
  5834. uncomp_crc32 = (mz_uint32)mz_crc32(
  5835. uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  5836. uncomp_remaining -= in_buf_size;
  5837. status = tdefl_compress_buffer(
  5838. pComp, pRead_buf, in_buf_size,
  5839. uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  5840. if (status == TDEFL_STATUS_DONE) {
  5841. result = MZ_TRUE;
  5842. break;
  5843. } else if (status != TDEFL_STATUS_OKAY)
  5844. break;
  5845. }
  5846. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5847. if (!result) {
  5848. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5849. MZ_FCLOSE(pSrc_file);
  5850. return MZ_FALSE;
  5851. }
  5852. comp_size = state.m_comp_size;
  5853. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5854. method = MZ_DEFLATED;
  5855. }
  5856. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5857. }
  5858. MZ_FCLOSE(pSrc_file);
  5859. pSrc_file = NULL;
  5860. // no zip64 support yet
  5861. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5862. return MZ_FALSE;
  5863. if (!mz_zip_writer_create_local_dir_header(
  5864. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5865. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5866. return MZ_FALSE;
  5867. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5868. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5869. return MZ_FALSE;
  5870. if (!mz_zip_writer_add_to_central_dir(
  5871. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5872. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5873. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5874. return MZ_FALSE;
  5875. pZip->m_total_files++;
  5876. pZip->m_archive_size = cur_archive_file_ofs;
  5877. return MZ_TRUE;
  5878. }
  5879. #endif // #ifndef MINIZ_NO_STDIO
  5880. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  5881. mz_zip_archive *pSource_zip,
  5882. mz_uint file_index) {
  5883. mz_uint n, bit_flags, num_alignment_padding_bytes;
  5884. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  5885. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  5886. mz_uint32
  5887. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5888. sizeof(mz_uint32)];
  5889. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5890. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5891. size_t orig_central_dir_size;
  5892. mz_zip_internal_state *pState;
  5893. void *pBuf;
  5894. const mz_uint8 *pSrc_central_header;
  5895. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  5896. return MZ_FALSE;
  5897. if (NULL ==
  5898. (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  5899. return MZ_FALSE;
  5900. pState = pZip->m_pState;
  5901. num_alignment_padding_bytes =
  5902. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5903. // no zip64 support yet
  5904. if ((pZip->m_total_files == 0xFFFF) ||
  5905. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5906. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
  5907. 0xFFFFFFFF))
  5908. return MZ_FALSE;
  5909. cur_src_file_ofs =
  5910. MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  5911. cur_dst_file_ofs = pZip->m_archive_size;
  5912. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
  5913. pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5914. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5915. return MZ_FALSE;
  5916. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5917. return MZ_FALSE;
  5918. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5919. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
  5920. num_alignment_padding_bytes))
  5921. return MZ_FALSE;
  5922. cur_dst_file_ofs += num_alignment_padding_bytes;
  5923. local_dir_header_ofs = cur_dst_file_ofs;
  5924. if (pZip->m_file_offset_alignment) {
  5925. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5926. 0);
  5927. }
  5928. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
  5929. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5930. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5931. return MZ_FALSE;
  5932. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5933. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5934. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5935. comp_bytes_remaining =
  5936. n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5937. if (NULL == (pBuf = pZip->m_pAlloc(
  5938. pZip->m_pAlloc_opaque, 1,
  5939. (size_t)MZ_MAX(sizeof(mz_uint32) * 4,
  5940. MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
  5941. comp_bytes_remaining)))))
  5942. return MZ_FALSE;
  5943. while (comp_bytes_remaining) {
  5944. n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  5945. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5946. n) != n) {
  5947. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5948. return MZ_FALSE;
  5949. }
  5950. cur_src_file_ofs += n;
  5951. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5952. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5953. return MZ_FALSE;
  5954. }
  5955. cur_dst_file_ofs += n;
  5956. comp_bytes_remaining -= n;
  5957. }
  5958. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  5959. if (bit_flags & 8) {
  5960. // Copy data descriptor
  5961. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5962. sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
  5963. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5964. return MZ_FALSE;
  5965. }
  5966. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  5967. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5968. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5969. return MZ_FALSE;
  5970. }
  5971. cur_src_file_ofs += n;
  5972. cur_dst_file_ofs += n;
  5973. }
  5974. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5975. // no zip64 support yet
  5976. if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE;
  5977. orig_central_dir_size = pState->m_central_dir.m_size;
  5978. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5979. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
  5980. local_dir_header_ofs);
  5981. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
  5982. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  5983. return MZ_FALSE;
  5984. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  5985. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  5986. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  5987. if (!mz_zip_array_push_back(
  5988. pZip, &pState->m_central_dir,
  5989. pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
  5990. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5991. MZ_FALSE);
  5992. return MZ_FALSE;
  5993. }
  5994. if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE;
  5995. n = (mz_uint32)orig_central_dir_size;
  5996. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
  5997. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5998. MZ_FALSE);
  5999. return MZ_FALSE;
  6000. }
  6001. pZip->m_total_files++;
  6002. pZip->m_archive_size = cur_dst_file_ofs;
  6003. return MZ_TRUE;
  6004. }
  6005. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
  6006. mz_zip_internal_state *pState;
  6007. mz_uint64 central_dir_ofs, central_dir_size;
  6008. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  6009. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  6010. return MZ_FALSE;
  6011. pState = pZip->m_pState;
  6012. // no zip64 support yet
  6013. if ((pZip->m_total_files > 0xFFFF) ||
  6014. ((pZip->m_archive_size + pState->m_central_dir.m_size +
  6015. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  6016. return MZ_FALSE;
  6017. central_dir_ofs = 0;
  6018. central_dir_size = 0;
  6019. if (pZip->m_total_files) {
  6020. // Write central directory
  6021. central_dir_ofs = pZip->m_archive_size;
  6022. central_dir_size = pState->m_central_dir.m_size;
  6023. pZip->m_central_directory_file_ofs = central_dir_ofs;
  6024. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
  6025. pState->m_central_dir.m_p,
  6026. (size_t)central_dir_size) != central_dir_size)
  6027. return MZ_FALSE;
  6028. pZip->m_archive_size += central_dir_size;
  6029. }
  6030. // Write end of central directory record
  6031. MZ_CLEAR_OBJ(hdr);
  6032. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
  6033. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  6034. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
  6035. pZip->m_total_files);
  6036. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  6037. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  6038. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  6039. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
  6040. sizeof(hdr)) != sizeof(hdr))
  6041. return MZ_FALSE;
  6042. #ifndef MINIZ_NO_STDIO
  6043. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE;
  6044. #endif // #ifndef MINIZ_NO_STDIO
  6045. pZip->m_archive_size += sizeof(hdr);
  6046. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  6047. return MZ_TRUE;
  6048. }
  6049. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  6050. size_t *pSize) {
  6051. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE;
  6052. if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE;
  6053. if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE;
  6054. *pBuf = pZip->m_pState->m_pMem;
  6055. *pSize = pZip->m_pState->m_mem_size;
  6056. pZip->m_pState->m_pMem = NULL;
  6057. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  6058. return MZ_TRUE;
  6059. }
  6060. mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
  6061. mz_zip_internal_state *pState;
  6062. mz_bool status = MZ_TRUE;
  6063. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  6064. ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
  6065. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  6066. return MZ_FALSE;
  6067. pState = pZip->m_pState;
  6068. pZip->m_pState = NULL;
  6069. mz_zip_array_clear(pZip, &pState->m_central_dir);
  6070. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  6071. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  6072. #ifndef MINIZ_NO_STDIO
  6073. if (pState->m_pFile) {
  6074. MZ_FCLOSE(pState->m_pFile);
  6075. pState->m_pFile = NULL;
  6076. }
  6077. #endif // #ifndef MINIZ_NO_STDIO
  6078. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
  6079. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  6080. pState->m_pMem = NULL;
  6081. }
  6082. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  6083. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  6084. return status;
  6085. }
  6086. #ifndef MINIZ_NO_STDIO
  6087. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  6088. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  6089. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  6090. mz_uint level_and_flags) {
  6091. mz_bool status, created_new_archive = MZ_FALSE;
  6092. mz_zip_archive zip_archive;
  6093. struct MZ_FILE_STAT_STRUCT file_stat;
  6094. MZ_CLEAR_OBJ(zip_archive);
  6095. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  6096. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
  6097. ((comment_size) && (!pComment)) ||
  6098. ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  6099. return MZ_FALSE;
  6100. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  6101. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
  6102. // Create a new archive.
  6103. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  6104. return MZ_FALSE;
  6105. created_new_archive = MZ_TRUE;
  6106. } else {
  6107. // Append to an existing archive.
  6108. if (!mz_zip_reader_init_file(
  6109. &zip_archive, pZip_filename,
  6110. level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6111. return MZ_FALSE;
  6112. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
  6113. mz_zip_reader_end(&zip_archive);
  6114. return MZ_FALSE;
  6115. }
  6116. }
  6117. status =
  6118. mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
  6119. pComment, comment_size, level_and_flags, 0, 0);
  6120. // Always finalize, even if adding failed for some reason, so we have a valid
  6121. // central directory. (This may not always succeed, but we can try.)
  6122. if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE;
  6123. if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE;
  6124. if ((!status) && (created_new_archive)) {
  6125. // It's a new archive and something went wrong, so just delete it.
  6126. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  6127. (void)ignoredStatus;
  6128. }
  6129. return status;
  6130. }
  6131. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  6132. const char *pArchive_name,
  6133. size_t *pSize, mz_uint flags) {
  6134. int file_index;
  6135. mz_zip_archive zip_archive;
  6136. void *p = NULL;
  6137. if (pSize) *pSize = 0;
  6138. if ((!pZip_filename) || (!pArchive_name)) return NULL;
  6139. MZ_CLEAR_OBJ(zip_archive);
  6140. if (!mz_zip_reader_init_file(
  6141. &zip_archive, pZip_filename,
  6142. flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6143. return NULL;
  6144. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
  6145. flags)) >= 0)
  6146. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  6147. mz_zip_reader_end(&zip_archive);
  6148. return p;
  6149. }
  6150. #endif // #ifndef MINIZ_NO_STDIO
  6151. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  6152. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  6153. #ifdef __cplusplus
  6154. }
  6155. #endif
  6156. #endif // MINIZ_HEADER_FILE_ONLY
  6157. /*
  6158. This is free and unencumbered software released into the public domain.
  6159. Anyone is free to copy, modify, publish, use, compile, sell, or
  6160. distribute this software, either in source code form or as a compiled
  6161. binary, for any purpose, commercial or non-commercial, and by any
  6162. means.
  6163. In jurisdictions that recognize copyright laws, the author or authors
  6164. of this software dedicate any and all copyright interest in the
  6165. software to the public domain. We make this dedication for the benefit
  6166. of the public at large and to the detriment of our heirs and
  6167. successors. We intend this dedication to be an overt act of
  6168. relinquishment in perpetuity of all present and future rights to this
  6169. software under copyright law.
  6170. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6171. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6172. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  6173. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6174. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6175. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  6176. OTHER DEALINGS IN THE SOFTWARE.
  6177. For more information, please refer to <http://unlicense.org/>
  6178. */
  6179. // ---------------------- end of miniz ----------------------------------------
  6180. #ifdef __clang__
  6181. #pragma clang diagnostic pop
  6182. #endif
  6183. #ifdef _MSC_VER
  6184. #pragma warning(pop)
  6185. #endif
  6186. } // namespace miniz
  6187. #else
  6188. // Reuse MINIZ_LITTE_ENDIAN macro
  6189. #if defined(__sparcv9)
  6190. // Big endian
  6191. #else
  6192. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  6193. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  6194. #define MINIZ_LITTLE_ENDIAN 1
  6195. #endif
  6196. #endif
  6197. #endif // TINYEXR_USE_MINIZ
  6198. // static bool IsBigEndian(void) {
  6199. // union {
  6200. // unsigned int i;
  6201. // char c[4];
  6202. // } bint = {0x01020304};
  6203. //
  6204. // return bint.c[0] == 1;
  6205. //}
  6206. static void SetErrorMessage(const std::string &msg, const char **err) {
  6207. if (err) {
  6208. #ifdef _WIN32
  6209. (*err) = _strdup(msg.c_str());
  6210. #else
  6211. (*err) = strdup(msg.c_str());
  6212. #endif
  6213. }
  6214. }
  6215. static const int kEXRVersionSize = 8;
  6216. static void cpy2(unsigned short *dst_val, const unsigned short *src_val) {
  6217. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6218. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6219. dst[0] = src[0];
  6220. dst[1] = src[1];
  6221. }
  6222. static void swap2(unsigned short *val) {
  6223. #ifdef MINIZ_LITTLE_ENDIAN
  6224. (void)val;
  6225. #else
  6226. unsigned short tmp = *val;
  6227. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6228. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6229. dst[0] = src[1];
  6230. dst[1] = src[0];
  6231. #endif
  6232. }
  6233. static void cpy4(int *dst_val, const int *src_val) {
  6234. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6235. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6236. dst[0] = src[0];
  6237. dst[1] = src[1];
  6238. dst[2] = src[2];
  6239. dst[3] = src[3];
  6240. }
  6241. static void cpy4(unsigned int *dst_val, const unsigned int *src_val) {
  6242. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6243. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6244. dst[0] = src[0];
  6245. dst[1] = src[1];
  6246. dst[2] = src[2];
  6247. dst[3] = src[3];
  6248. }
  6249. static void cpy4(float *dst_val, const float *src_val) {
  6250. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6251. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6252. dst[0] = src[0];
  6253. dst[1] = src[1];
  6254. dst[2] = src[2];
  6255. dst[3] = src[3];
  6256. }
  6257. static void swap4(unsigned int *val) {
  6258. #ifdef MINIZ_LITTLE_ENDIAN
  6259. (void)val;
  6260. #else
  6261. unsigned int tmp = *val;
  6262. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6263. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6264. dst[0] = src[3];
  6265. dst[1] = src[2];
  6266. dst[2] = src[1];
  6267. dst[3] = src[0];
  6268. #endif
  6269. }
  6270. #if 0
  6271. static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
  6272. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6273. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6274. dst[0] = src[0];
  6275. dst[1] = src[1];
  6276. dst[2] = src[2];
  6277. dst[3] = src[3];
  6278. dst[4] = src[4];
  6279. dst[5] = src[5];
  6280. dst[6] = src[6];
  6281. dst[7] = src[7];
  6282. }
  6283. #endif
  6284. static void swap8(tinyexr::tinyexr_uint64 *val) {
  6285. #ifdef MINIZ_LITTLE_ENDIAN
  6286. (void)val;
  6287. #else
  6288. tinyexr::tinyexr_uint64 tmp = (*val);
  6289. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6290. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6291. dst[0] = src[7];
  6292. dst[1] = src[6];
  6293. dst[2] = src[5];
  6294. dst[3] = src[4];
  6295. dst[4] = src[3];
  6296. dst[5] = src[2];
  6297. dst[6] = src[1];
  6298. dst[7] = src[0];
  6299. #endif
  6300. }
  6301. // https://gist.github.com/rygorous/2156668
  6302. // Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
  6303. union FP32 {
  6304. unsigned int u;
  6305. float f;
  6306. struct {
  6307. #if MINIZ_LITTLE_ENDIAN
  6308. unsigned int Mantissa : 23;
  6309. unsigned int Exponent : 8;
  6310. unsigned int Sign : 1;
  6311. #else
  6312. unsigned int Sign : 1;
  6313. unsigned int Exponent : 8;
  6314. unsigned int Mantissa : 23;
  6315. #endif
  6316. } s;
  6317. };
  6318. #ifdef __clang__
  6319. #pragma clang diagnostic push
  6320. #pragma clang diagnostic ignored "-Wpadded"
  6321. #endif
  6322. union FP16 {
  6323. unsigned short u;
  6324. struct {
  6325. #if MINIZ_LITTLE_ENDIAN
  6326. unsigned int Mantissa : 10;
  6327. unsigned int Exponent : 5;
  6328. unsigned int Sign : 1;
  6329. #else
  6330. unsigned int Sign : 1;
  6331. unsigned int Exponent : 5;
  6332. unsigned int Mantissa : 10;
  6333. #endif
  6334. } s;
  6335. };
  6336. #ifdef __clang__
  6337. #pragma clang diagnostic pop
  6338. #endif
  6339. static FP32 half_to_float(FP16 h) {
  6340. static const FP32 magic = {113 << 23};
  6341. static const unsigned int shifted_exp = 0x7c00
  6342. << 13; // exponent mask after shift
  6343. FP32 o;
  6344. o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
  6345. unsigned int exp_ = shifted_exp & o.u; // just the exponent
  6346. o.u += (127 - 15) << 23; // exponent adjust
  6347. // handle exponent special cases
  6348. if (exp_ == shifted_exp) // Inf/NaN?
  6349. o.u += (128 - 16) << 23; // extra exp adjust
  6350. else if (exp_ == 0) // Zero/Denormal?
  6351. {
  6352. o.u += 1 << 23; // extra exp adjust
  6353. o.f -= magic.f; // renormalize
  6354. }
  6355. o.u |= (h.u & 0x8000U) << 16U; // sign bit
  6356. return o;
  6357. }
  6358. static FP16 float_to_half_full(FP32 f) {
  6359. FP16 o = {0};
  6360. // Based on ISPC reference code (with minor modifications)
  6361. if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
  6362. o.s.Exponent = 0;
  6363. else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
  6364. {
  6365. o.s.Exponent = 31;
  6366. o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
  6367. } else // Normalized number
  6368. {
  6369. // Exponent unbias the single, then bias the halfp
  6370. int newexp = f.s.Exponent - 127 + 15;
  6371. if (newexp >= 31) // Overflow, return signed infinity
  6372. o.s.Exponent = 31;
  6373. else if (newexp <= 0) // Underflow
  6374. {
  6375. if ((14 - newexp) <= 24) // Mantissa might be non-zero
  6376. {
  6377. unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
  6378. o.s.Mantissa = mant >> (14 - newexp);
  6379. if ((mant >> (13 - newexp)) & 1) // Check for rounding
  6380. o.u++; // Round, might overflow into exp bit, but this is OK
  6381. }
  6382. } else {
  6383. o.s.Exponent = static_cast<unsigned int>(newexp);
  6384. o.s.Mantissa = f.s.Mantissa >> 13;
  6385. if (f.s.Mantissa & 0x1000) // Check for rounding
  6386. o.u++; // Round, might overflow to inf, this is OK
  6387. }
  6388. }
  6389. o.s.Sign = f.s.Sign;
  6390. return o;
  6391. }
  6392. // NOTE: From OpenEXR code
  6393. // #define IMF_INCREASING_Y 0
  6394. // #define IMF_DECREASING_Y 1
  6395. // #define IMF_RAMDOM_Y 2
  6396. //
  6397. // #define IMF_NO_COMPRESSION 0
  6398. // #define IMF_RLE_COMPRESSION 1
  6399. // #define IMF_ZIPS_COMPRESSION 2
  6400. // #define IMF_ZIP_COMPRESSION 3
  6401. // #define IMF_PIZ_COMPRESSION 4
  6402. // #define IMF_PXR24_COMPRESSION 5
  6403. // #define IMF_B44_COMPRESSION 6
  6404. // #define IMF_B44A_COMPRESSION 7
  6405. #ifdef __clang__
  6406. #pragma clang diagnostic push
  6407. #if __has_warning("-Wzero-as-null-pointer-constant")
  6408. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  6409. #endif
  6410. #endif
  6411. static const char *ReadString(std::string *s, const char *ptr, size_t len) {
  6412. // Read untile NULL(\0).
  6413. const char *p = ptr;
  6414. const char *q = ptr;
  6415. while ((size_t(q - ptr) < len) && (*q) != 0) {
  6416. q++;
  6417. }
  6418. if (size_t(q - ptr) >= len) {
  6419. (*s) = std::string();
  6420. return NULL;
  6421. }
  6422. (*s) = std::string(p, q);
  6423. return q + 1; // skip '\0'
  6424. }
  6425. static bool ReadAttribute(std::string *name, std::string *type,
  6426. std::vector<unsigned char> *data, size_t *marker_size,
  6427. const char *marker, size_t size) {
  6428. size_t name_len = strnlen(marker, size);
  6429. if (name_len == size) {
  6430. // String does not have a terminating character.
  6431. return false;
  6432. }
  6433. *name = std::string(marker, name_len);
  6434. marker += name_len + 1;
  6435. size -= name_len + 1;
  6436. size_t type_len = strnlen(marker, size);
  6437. if (type_len == size) {
  6438. return false;
  6439. }
  6440. *type = std::string(marker, type_len);
  6441. marker += type_len + 1;
  6442. size -= type_len + 1;
  6443. if (size < sizeof(uint32_t)) {
  6444. return false;
  6445. }
  6446. uint32_t data_len;
  6447. memcpy(&data_len, marker, sizeof(uint32_t));
  6448. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  6449. if (data_len == 0) {
  6450. if ((*type).compare("string") == 0) {
  6451. // Accept empty string attribute.
  6452. marker += sizeof(uint32_t);
  6453. size -= sizeof(uint32_t);
  6454. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
  6455. data->resize(1);
  6456. (*data)[0] = '\0';
  6457. return true;
  6458. } else {
  6459. return false;
  6460. }
  6461. }
  6462. marker += sizeof(uint32_t);
  6463. size -= sizeof(uint32_t);
  6464. if (size < data_len) {
  6465. return false;
  6466. }
  6467. data->resize(static_cast<size_t>(data_len));
  6468. memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
  6469. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
  6470. return true;
  6471. }
  6472. static void WriteAttributeToMemory(std::vector<unsigned char> *out,
  6473. const char *name, const char *type,
  6474. const unsigned char *data, int len) {
  6475. out->insert(out->end(), name, name + strlen(name) + 1);
  6476. out->insert(out->end(), type, type + strlen(type) + 1);
  6477. int outLen = len;
  6478. tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen));
  6479. out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),
  6480. reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
  6481. out->insert(out->end(), data, data + len);
  6482. }
  6483. typedef struct {
  6484. std::string name; // less than 255 bytes long
  6485. int pixel_type;
  6486. int x_sampling;
  6487. int y_sampling;
  6488. unsigned char p_linear;
  6489. unsigned char pad[3];
  6490. } ChannelInfo;
  6491. typedef struct {
  6492. std::vector<tinyexr::ChannelInfo> channels;
  6493. std::vector<EXRAttribute> attributes;
  6494. int data_window[4];
  6495. int line_order;
  6496. int display_window[4];
  6497. float screen_window_center[2];
  6498. float screen_window_width;
  6499. float pixel_aspect_ratio;
  6500. int chunk_count;
  6501. // Tiled format
  6502. int tile_size_x;
  6503. int tile_size_y;
  6504. int tile_level_mode;
  6505. int tile_rounding_mode;
  6506. unsigned int header_len;
  6507. int compression_type;
  6508. void clear() {
  6509. channels.clear();
  6510. attributes.clear();
  6511. data_window[0] = 0;
  6512. data_window[1] = 0;
  6513. data_window[2] = 0;
  6514. data_window[3] = 0;
  6515. line_order = 0;
  6516. display_window[0] = 0;
  6517. display_window[1] = 0;
  6518. display_window[2] = 0;
  6519. display_window[3] = 0;
  6520. screen_window_center[0] = 0.0f;
  6521. screen_window_center[1] = 0.0f;
  6522. screen_window_width = 0.0f;
  6523. pixel_aspect_ratio = 0.0f;
  6524. chunk_count = 0;
  6525. // Tiled format
  6526. tile_size_x = 0;
  6527. tile_size_y = 0;
  6528. tile_level_mode = 0;
  6529. tile_rounding_mode = 0;
  6530. header_len = 0;
  6531. compression_type = 0;
  6532. }
  6533. } HeaderInfo;
  6534. static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,
  6535. const std::vector<unsigned char> &data) {
  6536. const char *p = reinterpret_cast<const char *>(&data.at(0));
  6537. for (;;) {
  6538. if ((*p) == 0) {
  6539. break;
  6540. }
  6541. ChannelInfo info;
  6542. tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -
  6543. (p - reinterpret_cast<const char *>(data.data()));
  6544. if (data_len < 0) {
  6545. return false;
  6546. }
  6547. p = ReadString(&info.name, p, size_t(data_len));
  6548. if ((p == NULL) && (info.name.empty())) {
  6549. // Buffer overrun. Issue #51.
  6550. return false;
  6551. }
  6552. const unsigned char *data_end =
  6553. reinterpret_cast<const unsigned char *>(p) + 16;
  6554. if (data_end >= (data.data() + data.size())) {
  6555. return false;
  6556. }
  6557. memcpy(&info.pixel_type, p, sizeof(int));
  6558. p += 4;
  6559. info.p_linear = static_cast<unsigned char>(p[0]); // uchar
  6560. p += 1 + 3; // reserved: uchar[3]
  6561. memcpy(&info.x_sampling, p, sizeof(int)); // int
  6562. p += 4;
  6563. memcpy(&info.y_sampling, p, sizeof(int)); // int
  6564. p += 4;
  6565. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type));
  6566. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling));
  6567. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling));
  6568. channels.push_back(info);
  6569. }
  6570. return true;
  6571. }
  6572. static void WriteChannelInfo(std::vector<unsigned char> &data,
  6573. const std::vector<ChannelInfo> &channels) {
  6574. size_t sz = 0;
  6575. // Calculate total size.
  6576. for (size_t c = 0; c < channels.size(); c++) {
  6577. sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
  6578. sz += 16; // 4 * int
  6579. }
  6580. data.resize(sz + 1);
  6581. unsigned char *p = &data.at(0);
  6582. for (size_t c = 0; c < channels.size(); c++) {
  6583. memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
  6584. p += strlen(channels[c].name.c_str());
  6585. (*p) = '\0';
  6586. p++;
  6587. int pixel_type = channels[c].pixel_type;
  6588. int x_sampling = channels[c].x_sampling;
  6589. int y_sampling = channels[c].y_sampling;
  6590. tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type));
  6591. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling));
  6592. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling));
  6593. memcpy(p, &pixel_type, sizeof(int));
  6594. p += sizeof(int);
  6595. (*p) = channels[c].p_linear;
  6596. p += 4;
  6597. memcpy(p, &x_sampling, sizeof(int));
  6598. p += sizeof(int);
  6599. memcpy(p, &y_sampling, sizeof(int));
  6600. p += sizeof(int);
  6601. }
  6602. (*p) = '\0';
  6603. }
  6604. static void CompressZip(unsigned char *dst,
  6605. tinyexr::tinyexr_uint64 &compressedSize,
  6606. const unsigned char *src, unsigned long src_size) {
  6607. std::vector<unsigned char> tmpBuf(src_size);
  6608. //
  6609. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6610. // ImfZipCompressor.cpp
  6611. //
  6612. //
  6613. // Reorder the pixel data.
  6614. //
  6615. const char *srcPtr = reinterpret_cast<const char *>(src);
  6616. {
  6617. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6618. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6619. const char *stop = srcPtr + src_size;
  6620. for (;;) {
  6621. if (srcPtr < stop)
  6622. *(t1++) = *(srcPtr++);
  6623. else
  6624. break;
  6625. if (srcPtr < stop)
  6626. *(t2++) = *(srcPtr++);
  6627. else
  6628. break;
  6629. }
  6630. }
  6631. //
  6632. // Predictor.
  6633. //
  6634. {
  6635. unsigned char *t = &tmpBuf.at(0) + 1;
  6636. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6637. int p = t[-1];
  6638. while (t < stop) {
  6639. int d = int(t[0]) - p + (128 + 256);
  6640. p = t[0];
  6641. t[0] = static_cast<unsigned char>(d);
  6642. ++t;
  6643. }
  6644. }
  6645. #if TINYEXR_USE_MINIZ
  6646. //
  6647. // Compress the data using miniz
  6648. //
  6649. miniz::mz_ulong outSize = miniz::mz_compressBound(src_size);
  6650. int ret = miniz::mz_compress(
  6651. dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),
  6652. src_size);
  6653. assert(ret == miniz::MZ_OK);
  6654. (void)ret;
  6655. compressedSize = outSize;
  6656. #else
  6657. uLong outSize = compressBound(static_cast<uLong>(src_size));
  6658. int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),
  6659. src_size);
  6660. assert(ret == Z_OK);
  6661. compressedSize = outSize;
  6662. #endif
  6663. // Use uncompressed data when compressed data is larger than uncompressed.
  6664. // (Issue 40)
  6665. if (compressedSize >= src_size) {
  6666. compressedSize = src_size;
  6667. memcpy(dst, src, src_size);
  6668. }
  6669. }
  6670. static bool DecompressZip(unsigned char *dst,
  6671. unsigned long *uncompressed_size /* inout */,
  6672. const unsigned char *src, unsigned long src_size) {
  6673. if ((*uncompressed_size) == src_size) {
  6674. // Data is not compressed(Issue 40).
  6675. memcpy(dst, src, src_size);
  6676. return true;
  6677. }
  6678. std::vector<unsigned char> tmpBuf(*uncompressed_size);
  6679. #if TINYEXR_USE_MINIZ
  6680. int ret =
  6681. miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6682. if (miniz::MZ_OK != ret) {
  6683. return false;
  6684. }
  6685. #else
  6686. int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6687. if (Z_OK != ret) {
  6688. return false;
  6689. }
  6690. #endif
  6691. //
  6692. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6693. // ImfZipCompressor.cpp
  6694. //
  6695. // Predictor.
  6696. {
  6697. unsigned char *t = &tmpBuf.at(0) + 1;
  6698. unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);
  6699. while (t < stop) {
  6700. int d = int(t[-1]) + int(t[0]) - 128;
  6701. t[0] = static_cast<unsigned char>(d);
  6702. ++t;
  6703. }
  6704. }
  6705. // Reorder the pixel data.
  6706. {
  6707. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6708. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6709. (*uncompressed_size + 1) / 2;
  6710. char *s = reinterpret_cast<char *>(dst);
  6711. char *stop = s + (*uncompressed_size);
  6712. for (;;) {
  6713. if (s < stop)
  6714. *(s++) = *(t1++);
  6715. else
  6716. break;
  6717. if (s < stop)
  6718. *(s++) = *(t2++);
  6719. else
  6720. break;
  6721. }
  6722. }
  6723. return true;
  6724. }
  6725. // RLE code from OpenEXR --------------------------------------
  6726. #ifdef __clang__
  6727. #pragma clang diagnostic push
  6728. #pragma clang diagnostic ignored "-Wsign-conversion"
  6729. #endif
  6730. #ifdef _MSC_VER
  6731. #pragma warning(push)
  6732. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  6733. // aggregate initializer (also supported by GNU
  6734. // C and C99, so no big deal)
  6735. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  6736. // 'int', possible loss of data
  6737. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  6738. // 'int', possible loss of data
  6739. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  6740. // deprecated. Instead, use the ISO C and C++
  6741. // conformant name: _strdup.
  6742. #endif
  6743. const int MIN_RUN_LENGTH = 3;
  6744. const int MAX_RUN_LENGTH = 127;
  6745. //
  6746. // Compress an array of bytes, using run-length encoding,
  6747. // and return the length of the compressed data.
  6748. //
  6749. static int rleCompress(int inLength, const char in[], signed char out[]) {
  6750. const char *inEnd = in + inLength;
  6751. const char *runStart = in;
  6752. const char *runEnd = in + 1;
  6753. signed char *outWrite = out;
  6754. while (runStart < inEnd) {
  6755. while (runEnd < inEnd && *runStart == *runEnd &&
  6756. runEnd - runStart - 1 < MAX_RUN_LENGTH) {
  6757. ++runEnd;
  6758. }
  6759. if (runEnd - runStart >= MIN_RUN_LENGTH) {
  6760. //
  6761. // Compressable run
  6762. //
  6763. *outWrite++ = static_cast<char>(runEnd - runStart) - 1;
  6764. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart));
  6765. runStart = runEnd;
  6766. } else {
  6767. //
  6768. // Uncompressable run
  6769. //
  6770. while (runEnd < inEnd &&
  6771. ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||
  6772. (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&
  6773. runEnd - runStart < MAX_RUN_LENGTH) {
  6774. ++runEnd;
  6775. }
  6776. *outWrite++ = static_cast<char>(runStart - runEnd);
  6777. while (runStart < runEnd) {
  6778. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));
  6779. }
  6780. }
  6781. ++runEnd;
  6782. }
  6783. return static_cast<int>(outWrite - out);
  6784. }
  6785. //
  6786. // Uncompress an array of bytes compressed with rleCompress().
  6787. // Returns the length of the oncompressed data, or 0 if the
  6788. // length of the uncompressed data would be more than maxLength.
  6789. //
  6790. static int rleUncompress(int inLength, int maxLength, const signed char in[],
  6791. char out[]) {
  6792. char *outStart = out;
  6793. while (inLength > 0) {
  6794. if (*in < 0) {
  6795. int count = -(static_cast<int>(*in++));
  6796. inLength -= count + 1;
  6797. if (0 > (maxLength -= count)) return 0;
  6798. memcpy(out, in, count);
  6799. out += count;
  6800. in += count;
  6801. } else {
  6802. int count = *in++;
  6803. inLength -= 2;
  6804. if (0 > (maxLength -= count + 1)) return 0;
  6805. memset(out, *reinterpret_cast<const char *>(in), count + 1);
  6806. out += count + 1;
  6807. in++;
  6808. }
  6809. }
  6810. return static_cast<int>(out - outStart);
  6811. }
  6812. #ifdef __clang__
  6813. #pragma clang diagnostic pop
  6814. #endif
  6815. // End of RLE code from OpenEXR -----------------------------------
  6816. static void CompressRle(unsigned char *dst,
  6817. tinyexr::tinyexr_uint64 &compressedSize,
  6818. const unsigned char *src, unsigned long src_size) {
  6819. std::vector<unsigned char> tmpBuf(src_size);
  6820. //
  6821. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6822. // ImfRleCompressor.cpp
  6823. //
  6824. //
  6825. // Reorder the pixel data.
  6826. //
  6827. const char *srcPtr = reinterpret_cast<const char *>(src);
  6828. {
  6829. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6830. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6831. const char *stop = srcPtr + src_size;
  6832. for (;;) {
  6833. if (srcPtr < stop)
  6834. *(t1++) = *(srcPtr++);
  6835. else
  6836. break;
  6837. if (srcPtr < stop)
  6838. *(t2++) = *(srcPtr++);
  6839. else
  6840. break;
  6841. }
  6842. }
  6843. //
  6844. // Predictor.
  6845. //
  6846. {
  6847. unsigned char *t = &tmpBuf.at(0) + 1;
  6848. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6849. int p = t[-1];
  6850. while (t < stop) {
  6851. int d = int(t[0]) - p + (128 + 256);
  6852. p = t[0];
  6853. t[0] = static_cast<unsigned char>(d);
  6854. ++t;
  6855. }
  6856. }
  6857. // outSize will be (srcSiz * 3) / 2 at max.
  6858. int outSize = rleCompress(static_cast<int>(src_size),
  6859. reinterpret_cast<const char *>(&tmpBuf.at(0)),
  6860. reinterpret_cast<signed char *>(dst));
  6861. assert(outSize > 0);
  6862. compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
  6863. // Use uncompressed data when compressed data is larger than uncompressed.
  6864. // (Issue 40)
  6865. if (compressedSize >= src_size) {
  6866. compressedSize = src_size;
  6867. memcpy(dst, src, src_size);
  6868. }
  6869. }
  6870. static void DecompressRle(unsigned char *dst,
  6871. const unsigned long uncompressed_size,
  6872. const unsigned char *src, unsigned long src_size) {
  6873. if (uncompressed_size == src_size) {
  6874. // Data is not compressed(Issue 40).
  6875. memcpy(dst, src, src_size);
  6876. return;
  6877. }
  6878. std::vector<unsigned char> tmpBuf(uncompressed_size);
  6879. int ret = rleUncompress(static_cast<int>(src_size),
  6880. static_cast<int>(uncompressed_size),
  6881. reinterpret_cast<const signed char *>(src),
  6882. reinterpret_cast<char *>(&tmpBuf.at(0)));
  6883. assert(ret == static_cast<int>(uncompressed_size));
  6884. (void)ret;
  6885. //
  6886. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6887. // ImfRleCompressor.cpp
  6888. //
  6889. // Predictor.
  6890. {
  6891. unsigned char *t = &tmpBuf.at(0) + 1;
  6892. unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;
  6893. while (t < stop) {
  6894. int d = int(t[-1]) + int(t[0]) - 128;
  6895. t[0] = static_cast<unsigned char>(d);
  6896. ++t;
  6897. }
  6898. }
  6899. // Reorder the pixel data.
  6900. {
  6901. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6902. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6903. (uncompressed_size + 1) / 2;
  6904. char *s = reinterpret_cast<char *>(dst);
  6905. char *stop = s + uncompressed_size;
  6906. for (;;) {
  6907. if (s < stop)
  6908. *(s++) = *(t1++);
  6909. else
  6910. break;
  6911. if (s < stop)
  6912. *(s++) = *(t2++);
  6913. else
  6914. break;
  6915. }
  6916. }
  6917. }
  6918. #if TINYEXR_USE_PIZ
  6919. #ifdef __clang__
  6920. #pragma clang diagnostic push
  6921. #pragma clang diagnostic ignored "-Wc++11-long-long"
  6922. #pragma clang diagnostic ignored "-Wold-style-cast"
  6923. #pragma clang diagnostic ignored "-Wpadded"
  6924. #pragma clang diagnostic ignored "-Wsign-conversion"
  6925. #pragma clang diagnostic ignored "-Wc++11-extensions"
  6926. #pragma clang diagnostic ignored "-Wconversion"
  6927. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  6928. #if __has_warning("-Wcast-qual")
  6929. #pragma clang diagnostic ignored "-Wcast-qual"
  6930. #endif
  6931. #endif
  6932. //
  6933. // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
  6934. //
  6935. // -----------------------------------------------------------------
  6936. // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
  6937. // Digital Ltd. LLC)
  6938. // (3 clause BSD license)
  6939. //
  6940. struct PIZChannelData {
  6941. unsigned short *start;
  6942. unsigned short *end;
  6943. int nx;
  6944. int ny;
  6945. int ys;
  6946. int size;
  6947. };
  6948. //-----------------------------------------------------------------------------
  6949. //
  6950. // 16-bit Haar Wavelet encoding and decoding
  6951. //
  6952. // The source code in this file is derived from the encoding
  6953. // and decoding routines written by Christian Rouet for his
  6954. // PIZ image file format.
  6955. //
  6956. //-----------------------------------------------------------------------------
  6957. //
  6958. // Wavelet basis functions without modulo arithmetic; they produce
  6959. // the best compression ratios when the wavelet-transformed data are
  6960. // Huffman-encoded, but the wavelet transform works only for 14-bit
  6961. // data (untransformed data values must be less than (1 << 14)).
  6962. //
  6963. inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
  6964. unsigned short &h) {
  6965. short as = static_cast<short>(a);
  6966. short bs = static_cast<short>(b);
  6967. short ms = (as + bs) >> 1;
  6968. short ds = as - bs;
  6969. l = static_cast<unsigned short>(ms);
  6970. h = static_cast<unsigned short>(ds);
  6971. }
  6972. inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
  6973. unsigned short &b) {
  6974. short ls = static_cast<short>(l);
  6975. short hs = static_cast<short>(h);
  6976. int hi = hs;
  6977. int ai = ls + (hi & 1) + (hi >> 1);
  6978. short as = static_cast<short>(ai);
  6979. short bs = static_cast<short>(ai - hi);
  6980. a = static_cast<unsigned short>(as);
  6981. b = static_cast<unsigned short>(bs);
  6982. }
  6983. //
  6984. // Wavelet basis functions with modulo arithmetic; they work with full
  6985. // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
  6986. // compress the data quite as well.
  6987. //
  6988. const int NBITS = 16;
  6989. const int A_OFFSET = 1 << (NBITS - 1);
  6990. const int M_OFFSET = 1 << (NBITS - 1);
  6991. const int MOD_MASK = (1 << NBITS) - 1;
  6992. inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
  6993. unsigned short &h) {
  6994. int ao = (a + A_OFFSET) & MOD_MASK;
  6995. int m = ((ao + b) >> 1);
  6996. int d = ao - b;
  6997. if (d < 0) m = (m + M_OFFSET) & MOD_MASK;
  6998. d &= MOD_MASK;
  6999. l = static_cast<unsigned short>(m);
  7000. h = static_cast<unsigned short>(d);
  7001. }
  7002. inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
  7003. unsigned short &b) {
  7004. int m = l;
  7005. int d = h;
  7006. int bb = (m - (d >> 1)) & MOD_MASK;
  7007. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  7008. b = static_cast<unsigned short>(bb);
  7009. a = static_cast<unsigned short>(aa);
  7010. }
  7011. //
  7012. // 2D Wavelet encoding:
  7013. //
  7014. static void wav2Encode(
  7015. unsigned short *in, // io: values are transformed in place
  7016. int nx, // i : x size
  7017. int ox, // i : x offset
  7018. int ny, // i : y size
  7019. int oy, // i : y offset
  7020. unsigned short mx) // i : maximum in[x][y] value
  7021. {
  7022. bool w14 = (mx < (1 << 14));
  7023. int n = (nx > ny) ? ny : nx;
  7024. int p = 1; // == 1 << level
  7025. int p2 = 2; // == 1 << (level+1)
  7026. //
  7027. // Hierachical loop on smaller dimension n
  7028. //
  7029. while (p2 <= n) {
  7030. unsigned short *py = in;
  7031. unsigned short *ey = in + oy * (ny - p2);
  7032. int oy1 = oy * p;
  7033. int oy2 = oy * p2;
  7034. int ox1 = ox * p;
  7035. int ox2 = ox * p2;
  7036. unsigned short i00, i01, i10, i11;
  7037. //
  7038. // Y loop
  7039. //
  7040. for (; py <= ey; py += oy2) {
  7041. unsigned short *px = py;
  7042. unsigned short *ex = py + ox * (nx - p2);
  7043. //
  7044. // X loop
  7045. //
  7046. for (; px <= ex; px += ox2) {
  7047. unsigned short *p01 = px + ox1;
  7048. unsigned short *p10 = px + oy1;
  7049. unsigned short *p11 = p10 + ox1;
  7050. //
  7051. // 2D wavelet encoding
  7052. //
  7053. if (w14) {
  7054. wenc14(*px, *p01, i00, i01);
  7055. wenc14(*p10, *p11, i10, i11);
  7056. wenc14(i00, i10, *px, *p10);
  7057. wenc14(i01, i11, *p01, *p11);
  7058. } else {
  7059. wenc16(*px, *p01, i00, i01);
  7060. wenc16(*p10, *p11, i10, i11);
  7061. wenc16(i00, i10, *px, *p10);
  7062. wenc16(i01, i11, *p01, *p11);
  7063. }
  7064. }
  7065. //
  7066. // Encode (1D) odd column (still in Y loop)
  7067. //
  7068. if (nx & p) {
  7069. unsigned short *p10 = px + oy1;
  7070. if (w14)
  7071. wenc14(*px, *p10, i00, *p10);
  7072. else
  7073. wenc16(*px, *p10, i00, *p10);
  7074. *px = i00;
  7075. }
  7076. }
  7077. //
  7078. // Encode (1D) odd line (must loop in X)
  7079. //
  7080. if (ny & p) {
  7081. unsigned short *px = py;
  7082. unsigned short *ex = py + ox * (nx - p2);
  7083. for (; px <= ex; px += ox2) {
  7084. unsigned short *p01 = px + ox1;
  7085. if (w14)
  7086. wenc14(*px, *p01, i00, *p01);
  7087. else
  7088. wenc16(*px, *p01, i00, *p01);
  7089. *px = i00;
  7090. }
  7091. }
  7092. //
  7093. // Next level
  7094. //
  7095. p = p2;
  7096. p2 <<= 1;
  7097. }
  7098. }
  7099. //
  7100. // 2D Wavelet decoding:
  7101. //
  7102. static void wav2Decode(
  7103. unsigned short *in, // io: values are transformed in place
  7104. int nx, // i : x size
  7105. int ox, // i : x offset
  7106. int ny, // i : y size
  7107. int oy, // i : y offset
  7108. unsigned short mx) // i : maximum in[x][y] value
  7109. {
  7110. bool w14 = (mx < (1 << 14));
  7111. int n = (nx > ny) ? ny : nx;
  7112. int p = 1;
  7113. int p2;
  7114. //
  7115. // Search max level
  7116. //
  7117. while (p <= n) p <<= 1;
  7118. p >>= 1;
  7119. p2 = p;
  7120. p >>= 1;
  7121. //
  7122. // Hierarchical loop on smaller dimension n
  7123. //
  7124. while (p >= 1) {
  7125. unsigned short *py = in;
  7126. unsigned short *ey = in + oy * (ny - p2);
  7127. int oy1 = oy * p;
  7128. int oy2 = oy * p2;
  7129. int ox1 = ox * p;
  7130. int ox2 = ox * p2;
  7131. unsigned short i00, i01, i10, i11;
  7132. //
  7133. // Y loop
  7134. //
  7135. for (; py <= ey; py += oy2) {
  7136. unsigned short *px = py;
  7137. unsigned short *ex = py + ox * (nx - p2);
  7138. //
  7139. // X loop
  7140. //
  7141. for (; px <= ex; px += ox2) {
  7142. unsigned short *p01 = px + ox1;
  7143. unsigned short *p10 = px + oy1;
  7144. unsigned short *p11 = p10 + ox1;
  7145. //
  7146. // 2D wavelet decoding
  7147. //
  7148. if (w14) {
  7149. wdec14(*px, *p10, i00, i10);
  7150. wdec14(*p01, *p11, i01, i11);
  7151. wdec14(i00, i01, *px, *p01);
  7152. wdec14(i10, i11, *p10, *p11);
  7153. } else {
  7154. wdec16(*px, *p10, i00, i10);
  7155. wdec16(*p01, *p11, i01, i11);
  7156. wdec16(i00, i01, *px, *p01);
  7157. wdec16(i10, i11, *p10, *p11);
  7158. }
  7159. }
  7160. //
  7161. // Decode (1D) odd column (still in Y loop)
  7162. //
  7163. if (nx & p) {
  7164. unsigned short *p10 = px + oy1;
  7165. if (w14)
  7166. wdec14(*px, *p10, i00, *p10);
  7167. else
  7168. wdec16(*px, *p10, i00, *p10);
  7169. *px = i00;
  7170. }
  7171. }
  7172. //
  7173. // Decode (1D) odd line (must loop in X)
  7174. //
  7175. if (ny & p) {
  7176. unsigned short *px = py;
  7177. unsigned short *ex = py + ox * (nx - p2);
  7178. for (; px <= ex; px += ox2) {
  7179. unsigned short *p01 = px + ox1;
  7180. if (w14)
  7181. wdec14(*px, *p01, i00, *p01);
  7182. else
  7183. wdec16(*px, *p01, i00, *p01);
  7184. *px = i00;
  7185. }
  7186. }
  7187. //
  7188. // Next level
  7189. //
  7190. p2 = p;
  7191. p >>= 1;
  7192. }
  7193. }
  7194. //-----------------------------------------------------------------------------
  7195. //
  7196. // 16-bit Huffman compression and decompression.
  7197. //
  7198. // The source code in this file is derived from the 8-bit
  7199. // Huffman compression and decompression routines written
  7200. // by Christian Rouet for his PIZ image file format.
  7201. //
  7202. //-----------------------------------------------------------------------------
  7203. // Adds some modification for tinyexr.
  7204. const int HUF_ENCBITS = 16; // literal (value) bit length
  7205. const int HUF_DECBITS = 14; // decoding bit size (>= 8)
  7206. const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
  7207. const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  7208. const int HUF_DECMASK = HUF_DECSIZE - 1;
  7209. struct HufDec { // short code long code
  7210. //-------------------------------
  7211. int len : 8; // code length 0
  7212. int lit : 24; // lit p size
  7213. int *p; // 0 lits
  7214. };
  7215. inline long long hufLength(long long code) { return code & 63; }
  7216. inline long long hufCode(long long code) { return code >> 6; }
  7217. inline void outputBits(int nBits, long long bits, long long &c, int &lc,
  7218. char *&out) {
  7219. c <<= nBits;
  7220. lc += nBits;
  7221. c |= bits;
  7222. while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));
  7223. }
  7224. inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
  7225. while (lc < nBits) {
  7226. c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));
  7227. lc += 8;
  7228. }
  7229. lc -= nBits;
  7230. return (c >> lc) & ((1 << nBits) - 1);
  7231. }
  7232. //
  7233. // ENCODING TABLE BUILDING & (UN)PACKING
  7234. //
  7235. //
  7236. // Build a "canonical" Huffman code table:
  7237. // - for each (uncompressed) symbol, hcode contains the length
  7238. // of the corresponding code (in the compressed data)
  7239. // - canonical codes are computed and stored in hcode
  7240. // - the rules for constructing canonical codes are as follows:
  7241. // * shorter codes (if filled with zeroes to the right)
  7242. // have a numerically higher value than longer codes
  7243. // * for codes with the same length, numerical values
  7244. // increase with numerical symbol values
  7245. // - because the canonical code table can be constructed from
  7246. // symbol lengths alone, the code table can be transmitted
  7247. // without sending the actual code values
  7248. // - see http://www.compressconsult.com/huffman/
  7249. //
  7250. static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
  7251. long long n[59];
  7252. //
  7253. // For each i from 0 through 58, count the
  7254. // number of different codes of length i, and
  7255. // store the count in n[i].
  7256. //
  7257. for (int i = 0; i <= 58; ++i) n[i] = 0;
  7258. for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;
  7259. //
  7260. // For each i from 58 through 1, compute the
  7261. // numerically lowest code with length i, and
  7262. // store that code in n[i].
  7263. //
  7264. long long c = 0;
  7265. for (int i = 58; i > 0; --i) {
  7266. long long nc = ((c + n[i]) >> 1);
  7267. n[i] = c;
  7268. c = nc;
  7269. }
  7270. //
  7271. // hcode[i] contains the length, l, of the
  7272. // code for symbol i. Assign the next available
  7273. // code of length l to the symbol and store both
  7274. // l and the code in hcode[i].
  7275. //
  7276. for (int i = 0; i < HUF_ENCSIZE; ++i) {
  7277. int l = static_cast<int>(hcode[i]);
  7278. if (l > 0) hcode[i] = l | (n[l]++ << 6);
  7279. }
  7280. }
  7281. //
  7282. // Compute Huffman codes (based on frq input) and store them in frq:
  7283. // - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
  7284. // - max code length is 58 bits;
  7285. // - codes outside the range [im-iM] have a null length (unused values);
  7286. // - original frequencies are destroyed;
  7287. // - encoding tables are used by hufEncode() and hufBuildDecTable();
  7288. //
  7289. struct FHeapCompare {
  7290. bool operator()(long long *a, long long *b) { return *a > *b; }
  7291. };
  7292. static void hufBuildEncTable(
  7293. long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
  7294. int *im, // o: min frq index
  7295. int *iM) // o: max frq index
  7296. {
  7297. //
  7298. // This function assumes that when it is called, array frq
  7299. // indicates the frequency of all possible symbols in the data
  7300. // that are to be Huffman-encoded. (frq[i] contains the number
  7301. // of occurrences of symbol i in the data.)
  7302. //
  7303. // The loop below does three things:
  7304. //
  7305. // 1) Finds the minimum and maximum indices that point
  7306. // to non-zero entries in frq:
  7307. //
  7308. // frq[im] != 0, and frq[i] == 0 for all i < im
  7309. // frq[iM] != 0, and frq[i] == 0 for all i > iM
  7310. //
  7311. // 2) Fills array fHeap with pointers to all non-zero
  7312. // entries in frq.
  7313. //
  7314. // 3) Initializes array hlink such that hlink[i] == i
  7315. // for all array entries.
  7316. //
  7317. std::vector<int> hlink(HUF_ENCSIZE);
  7318. std::vector<long long *> fHeap(HUF_ENCSIZE);
  7319. *im = 0;
  7320. while (!frq[*im]) (*im)++;
  7321. int nf = 0;
  7322. for (int i = *im; i < HUF_ENCSIZE; i++) {
  7323. hlink[i] = i;
  7324. if (frq[i]) {
  7325. fHeap[nf] = &frq[i];
  7326. nf++;
  7327. *iM = i;
  7328. }
  7329. }
  7330. //
  7331. // Add a pseudo-symbol, with a frequency count of 1, to frq;
  7332. // adjust the fHeap and hlink array accordingly. Function
  7333. // hufEncode() uses the pseudo-symbol for run-length encoding.
  7334. //
  7335. (*iM)++;
  7336. frq[*iM] = 1;
  7337. fHeap[nf] = &frq[*iM];
  7338. nf++;
  7339. //
  7340. // Build an array, scode, such that scode[i] contains the number
  7341. // of bits assigned to symbol i. Conceptually this is done by
  7342. // constructing a tree whose leaves are the symbols with non-zero
  7343. // frequency:
  7344. //
  7345. // Make a heap that contains all symbols with a non-zero frequency,
  7346. // with the least frequent symbol on top.
  7347. //
  7348. // Repeat until only one symbol is left on the heap:
  7349. //
  7350. // Take the two least frequent symbols off the top of the heap.
  7351. // Create a new node that has first two nodes as children, and
  7352. // whose frequency is the sum of the frequencies of the first
  7353. // two nodes. Put the new node back into the heap.
  7354. //
  7355. // The last node left on the heap is the root of the tree. For each
  7356. // leaf node, the distance between the root and the leaf is the length
  7357. // of the code for the corresponding symbol.
  7358. //
  7359. // The loop below doesn't actually build the tree; instead we compute
  7360. // the distances of the leaves from the root on the fly. When a new
  7361. // node is added to the heap, then that node's descendants are linked
  7362. // into a single linear list that starts at the new node, and the code
  7363. // lengths of the descendants (that is, their distance from the root
  7364. // of the tree) are incremented by one.
  7365. //
  7366. std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7367. std::vector<long long> scode(HUF_ENCSIZE);
  7368. memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
  7369. while (nf > 1) {
  7370. //
  7371. // Find the indices, mm and m, of the two smallest non-zero frq
  7372. // values in fHeap, add the smallest frq to the second-smallest
  7373. // frq, and remove the smallest frq value from fHeap.
  7374. //
  7375. int mm = fHeap[0] - frq;
  7376. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7377. --nf;
  7378. int m = fHeap[0] - frq;
  7379. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7380. frq[m] += frq[mm];
  7381. std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7382. //
  7383. // The entries in scode are linked into lists with the
  7384. // entries in hlink serving as "next" pointers and with
  7385. // the end of a list marked by hlink[j] == j.
  7386. //
  7387. // Traverse the lists that start at scode[m] and scode[mm].
  7388. // For each element visited, increment the length of the
  7389. // corresponding code by one bit. (If we visit scode[j]
  7390. // during the traversal, then the code for symbol j becomes
  7391. // one bit longer.)
  7392. //
  7393. // Merge the lists that start at scode[m] and scode[mm]
  7394. // into a single list that starts at scode[m].
  7395. //
  7396. //
  7397. // Add a bit to all codes in the first list.
  7398. //
  7399. for (int j = m;; j = hlink[j]) {
  7400. scode[j]++;
  7401. assert(scode[j] <= 58);
  7402. if (hlink[j] == j) {
  7403. //
  7404. // Merge the two lists.
  7405. //
  7406. hlink[j] = mm;
  7407. break;
  7408. }
  7409. }
  7410. //
  7411. // Add a bit to all codes in the second list
  7412. //
  7413. for (int j = mm;; j = hlink[j]) {
  7414. scode[j]++;
  7415. assert(scode[j] <= 58);
  7416. if (hlink[j] == j) break;
  7417. }
  7418. }
  7419. //
  7420. // Build a canonical Huffman code table, replacing the code
  7421. // lengths in scode with (code, code length) pairs. Copy the
  7422. // code table from scode into frq.
  7423. //
  7424. hufCanonicalCodeTable(scode.data());
  7425. memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
  7426. }
  7427. //
  7428. // Pack an encoding table:
  7429. // - only code lengths, not actual codes, are stored
  7430. // - runs of zeroes are compressed as follows:
  7431. //
  7432. // unpacked packed
  7433. // --------------------------------
  7434. // 1 zero 0 (6 bits)
  7435. // 2 zeroes 59
  7436. // 3 zeroes 60
  7437. // 4 zeroes 61
  7438. // 5 zeroes 62
  7439. // n zeroes (6 or more) 63 n-6 (6 + 8 bits)
  7440. //
  7441. const int SHORT_ZEROCODE_RUN = 59;
  7442. const int LONG_ZEROCODE_RUN = 63;
  7443. const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  7444. const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
  7445. static void hufPackEncTable(
  7446. const long long *hcode, // i : encoding table [HUF_ENCSIZE]
  7447. int im, // i : min hcode index
  7448. int iM, // i : max hcode index
  7449. char **pcode) // o: ptr to packed table (updated)
  7450. {
  7451. char *p = *pcode;
  7452. long long c = 0;
  7453. int lc = 0;
  7454. for (; im <= iM; im++) {
  7455. int l = hufLength(hcode[im]);
  7456. if (l == 0) {
  7457. int zerun = 1;
  7458. while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
  7459. if (hufLength(hcode[im + 1]) > 0) break;
  7460. im++;
  7461. zerun++;
  7462. }
  7463. if (zerun >= 2) {
  7464. if (zerun >= SHORTEST_LONG_RUN) {
  7465. outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
  7466. outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
  7467. } else {
  7468. outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
  7469. }
  7470. continue;
  7471. }
  7472. }
  7473. outputBits(6, l, c, lc, p);
  7474. }
  7475. if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));
  7476. *pcode = p;
  7477. }
  7478. //
  7479. // Unpack an encoding table packed by hufPackEncTable():
  7480. //
  7481. static bool hufUnpackEncTable(
  7482. const char **pcode, // io: ptr to packed table (updated)
  7483. int ni, // i : input size (in bytes)
  7484. int im, // i : min hcode index
  7485. int iM, // i : max hcode index
  7486. long long *hcode) // o: encoding table [HUF_ENCSIZE]
  7487. {
  7488. memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
  7489. const char *p = *pcode;
  7490. long long c = 0;
  7491. int lc = 0;
  7492. for (; im <= iM; im++) {
  7493. if (p - *pcode > ni) {
  7494. return false;
  7495. }
  7496. long long l = hcode[im] = getBits(6, c, lc, p); // code length
  7497. if (l == (long long)LONG_ZEROCODE_RUN) {
  7498. if (p - *pcode > ni) {
  7499. return false;
  7500. }
  7501. int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
  7502. if (im + zerun > iM + 1) {
  7503. return false;
  7504. }
  7505. while (zerun--) hcode[im++] = 0;
  7506. im--;
  7507. } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
  7508. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  7509. if (im + zerun > iM + 1) {
  7510. return false;
  7511. }
  7512. while (zerun--) hcode[im++] = 0;
  7513. im--;
  7514. }
  7515. }
  7516. *pcode = const_cast<char *>(p);
  7517. hufCanonicalCodeTable(hcode);
  7518. return true;
  7519. }
  7520. //
  7521. // DECODING TABLE BUILDING
  7522. //
  7523. //
  7524. // Clear a newly allocated decoding table so that it contains only zeroes.
  7525. //
  7526. static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
  7527. // decoding table [HUF_DECSIZE]
  7528. {
  7529. for (int i = 0; i < HUF_DECSIZE; i++) {
  7530. hdecod[i].len = 0;
  7531. hdecod[i].lit = 0;
  7532. hdecod[i].p = NULL;
  7533. }
  7534. // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
  7535. }
  7536. //
  7537. // Build a decoding hash table based on the encoding table hcode:
  7538. // - short codes (<= HUF_DECBITS) are resolved with a single table access;
  7539. // - long code entry allocations are not optimized, because long codes are
  7540. // unfrequent;
  7541. // - decoding tables are used by hufDecode();
  7542. //
  7543. static bool hufBuildDecTable(const long long *hcode, // i : encoding table
  7544. int im, // i : min index in hcode
  7545. int iM, // i : max index in hcode
  7546. HufDec *hdecod) // o: (allocated by caller)
  7547. // decoding table [HUF_DECSIZE]
  7548. {
  7549. //
  7550. // Init hashtable & loop on all codes.
  7551. // Assumes that hufClearDecTable(hdecod) has already been called.
  7552. //
  7553. for (; im <= iM; im++) {
  7554. long long c = hufCode(hcode[im]);
  7555. int l = hufLength(hcode[im]);
  7556. if (c >> l) {
  7557. //
  7558. // Error: c is supposed to be an l-bit code,
  7559. // but c contains a value that is greater
  7560. // than the largest l-bit number.
  7561. //
  7562. // invalidTableEntry();
  7563. return false;
  7564. }
  7565. if (l > HUF_DECBITS) {
  7566. //
  7567. // Long code: add a secondary entry
  7568. //
  7569. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  7570. if (pl->len) {
  7571. //
  7572. // Error: a short code has already
  7573. // been stored in table entry *pl.
  7574. //
  7575. // invalidTableEntry();
  7576. return false;
  7577. }
  7578. pl->lit++;
  7579. if (pl->p) {
  7580. int *p = pl->p;
  7581. pl->p = new int[pl->lit];
  7582. for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i];
  7583. delete[] p;
  7584. } else {
  7585. pl->p = new int[1];
  7586. }
  7587. pl->p[pl->lit - 1] = im;
  7588. } else if (l) {
  7589. //
  7590. // Short code: init all primary entries
  7591. //
  7592. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  7593. for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
  7594. if (pl->len || pl->p) {
  7595. //
  7596. // Error: a short code or a long code has
  7597. // already been stored in table entry *pl.
  7598. //
  7599. // invalidTableEntry();
  7600. return false;
  7601. }
  7602. pl->len = l;
  7603. pl->lit = im;
  7604. }
  7605. }
  7606. }
  7607. return true;
  7608. }
  7609. //
  7610. // Free the long code entries of a decoding table built by hufBuildDecTable()
  7611. //
  7612. static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
  7613. {
  7614. for (int i = 0; i < HUF_DECSIZE; i++) {
  7615. if (hdecod[i].p) {
  7616. delete[] hdecod[i].p;
  7617. hdecod[i].p = 0;
  7618. }
  7619. }
  7620. }
  7621. //
  7622. // ENCODING
  7623. //
  7624. inline void outputCode(long long code, long long &c, int &lc, char *&out) {
  7625. outputBits(hufLength(code), hufCode(code), c, lc, out);
  7626. }
  7627. inline void sendCode(long long sCode, int runCount, long long runCode,
  7628. long long &c, int &lc, char *&out) {
  7629. //
  7630. // Output a run of runCount instances of the symbol sCount.
  7631. // Output the symbols explicitly, or if that is shorter, output
  7632. // the sCode symbol once followed by a runCode symbol and runCount
  7633. // expressed as an 8-bit number.
  7634. //
  7635. if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
  7636. outputCode(sCode, c, lc, out);
  7637. outputCode(runCode, c, lc, out);
  7638. outputBits(8, runCount, c, lc, out);
  7639. } else {
  7640. while (runCount-- >= 0) outputCode(sCode, c, lc, out);
  7641. }
  7642. }
  7643. //
  7644. // Encode (compress) ni values based on the Huffman encoding table hcode:
  7645. //
  7646. static int hufEncode // return: output size (in bits)
  7647. (const long long *hcode, // i : encoding table
  7648. const unsigned short *in, // i : uncompressed input buffer
  7649. const int ni, // i : input buffer size (in bytes)
  7650. int rlc, // i : rl code
  7651. char *out) // o: compressed output buffer
  7652. {
  7653. char *outStart = out;
  7654. long long c = 0; // bits not yet written to out
  7655. int lc = 0; // number of valid bits in c (LSB)
  7656. int s = in[0];
  7657. int cs = 0;
  7658. //
  7659. // Loop on input values
  7660. //
  7661. for (int i = 1; i < ni; i++) {
  7662. //
  7663. // Count same values or send code
  7664. //
  7665. if (s == in[i] && cs < 255) {
  7666. cs++;
  7667. } else {
  7668. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7669. cs = 0;
  7670. }
  7671. s = in[i];
  7672. }
  7673. //
  7674. // Send remaining code
  7675. //
  7676. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7677. if (lc) *out = (c << (8 - lc)) & 0xff;
  7678. return (out - outStart) * 8 + lc;
  7679. }
  7680. //
  7681. // DECODING
  7682. //
  7683. //
  7684. // In order to force the compiler to inline them,
  7685. // getChar() and getCode() are implemented as macros
  7686. // instead of "inline" functions.
  7687. //
  7688. #define getChar(c, lc, in) \
  7689. { \
  7690. c = (c << 8) | *(unsigned char *)(in++); \
  7691. lc += 8; \
  7692. }
  7693. #if 0
  7694. #define getCode(po, rlc, c, lc, in, out, ob, oe) \
  7695. { \
  7696. if (po == rlc) { \
  7697. if (lc < 8) getChar(c, lc, in); \
  7698. \
  7699. lc -= 8; \
  7700. \
  7701. unsigned char cs = (c >> lc); \
  7702. \
  7703. if (out + cs > oe) return false; \
  7704. \
  7705. /* TinyEXR issue 78 */ \
  7706. unsigned short s = out[-1]; \
  7707. \
  7708. while (cs-- > 0) *out++ = s; \
  7709. } else if (out < oe) { \
  7710. *out++ = po; \
  7711. } else { \
  7712. return false; \
  7713. } \
  7714. }
  7715. #else
  7716. static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,
  7717. const char *in_end, unsigned short *&out,
  7718. const unsigned short *ob, const unsigned short *oe) {
  7719. (void)ob;
  7720. if (po == rlc) {
  7721. if (lc < 8) {
  7722. /* TinyEXR issue 78 */
  7723. if ((in + 1) >= in_end) {
  7724. return false;
  7725. }
  7726. getChar(c, lc, in);
  7727. }
  7728. lc -= 8;
  7729. unsigned char cs = (c >> lc);
  7730. if (out + cs > oe) return false;
  7731. // Bounds check for safety
  7732. if ((out - 1) <= ob) return false;
  7733. unsigned short s = out[-1];
  7734. while (cs-- > 0) *out++ = s;
  7735. } else if (out < oe) {
  7736. *out++ = po;
  7737. } else {
  7738. return false;
  7739. }
  7740. return true;
  7741. }
  7742. #endif
  7743. //
  7744. // Decode (uncompress) ni bits based on encoding & decoding tables:
  7745. //
  7746. static bool hufDecode(const long long *hcode, // i : encoding table
  7747. const HufDec *hdecod, // i : decoding table
  7748. const char *in, // i : compressed input buffer
  7749. int ni, // i : input size (in bits)
  7750. int rlc, // i : run-length code
  7751. int no, // i : expected output size (in bytes)
  7752. unsigned short *out) // o: uncompressed output buffer
  7753. {
  7754. long long c = 0;
  7755. int lc = 0;
  7756. unsigned short *outb = out; // begin
  7757. unsigned short *oe = out + no; // end
  7758. const char *ie = in + (ni + 7) / 8; // input byte size
  7759. //
  7760. // Loop on input bytes
  7761. //
  7762. while (in < ie) {
  7763. getChar(c, lc, in);
  7764. //
  7765. // Access decoding table
  7766. //
  7767. while (lc >= HUF_DECBITS) {
  7768. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  7769. if (pl.len) {
  7770. //
  7771. // Get short code
  7772. //
  7773. lc -= pl.len;
  7774. // std::cout << "lit = " << pl.lit << std::endl;
  7775. // std::cout << "rlc = " << rlc << std::endl;
  7776. // std::cout << "c = " << c << std::endl;
  7777. // std::cout << "lc = " << lc << std::endl;
  7778. // std::cout << "in = " << in << std::endl;
  7779. // std::cout << "out = " << out << std::endl;
  7780. // std::cout << "oe = " << oe << std::endl;
  7781. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7782. return false;
  7783. }
  7784. } else {
  7785. if (!pl.p) {
  7786. return false;
  7787. }
  7788. // invalidCode(); // wrong code
  7789. //
  7790. // Search long code
  7791. //
  7792. int j;
  7793. for (j = 0; j < pl.lit; j++) {
  7794. int l = hufLength(hcode[pl.p[j]]);
  7795. while (lc < l && in < ie) // get more bits
  7796. getChar(c, lc, in);
  7797. if (lc >= l) {
  7798. if (hufCode(hcode[pl.p[j]]) ==
  7799. ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
  7800. //
  7801. // Found : get long code
  7802. //
  7803. lc -= l;
  7804. if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
  7805. return false;
  7806. }
  7807. break;
  7808. }
  7809. }
  7810. }
  7811. if (j == pl.lit) {
  7812. return false;
  7813. // invalidCode(); // Not found
  7814. }
  7815. }
  7816. }
  7817. }
  7818. //
  7819. // Get remaining (short) codes
  7820. //
  7821. int i = (8 - ni) & 7;
  7822. c >>= i;
  7823. lc -= i;
  7824. while (lc > 0) {
  7825. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  7826. if (pl.len) {
  7827. lc -= pl.len;
  7828. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7829. return false;
  7830. }
  7831. } else {
  7832. return false;
  7833. // invalidCode(); // wrong (long) code
  7834. }
  7835. }
  7836. if (out - outb != no) {
  7837. return false;
  7838. }
  7839. // notEnoughData ();
  7840. return true;
  7841. }
  7842. static void countFrequencies(std::vector<long long> &freq,
  7843. const unsigned short data[/*n*/], int n) {
  7844. for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;
  7845. for (int i = 0; i < n; ++i) ++freq[data[i]];
  7846. }
  7847. static void writeUInt(char buf[4], unsigned int i) {
  7848. unsigned char *b = (unsigned char *)buf;
  7849. b[0] = i;
  7850. b[1] = i >> 8;
  7851. b[2] = i >> 16;
  7852. b[3] = i >> 24;
  7853. }
  7854. static unsigned int readUInt(const char buf[4]) {
  7855. const unsigned char *b = (const unsigned char *)buf;
  7856. return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
  7857. ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
  7858. }
  7859. //
  7860. // EXTERNAL INTERFACE
  7861. //
  7862. static int hufCompress(const unsigned short raw[], int nRaw,
  7863. char compressed[]) {
  7864. if (nRaw == 0) return 0;
  7865. std::vector<long long> freq(HUF_ENCSIZE);
  7866. countFrequencies(freq, raw, nRaw);
  7867. int im = 0;
  7868. int iM = 0;
  7869. hufBuildEncTable(freq.data(), &im, &iM);
  7870. char *tableStart = compressed + 20;
  7871. char *tableEnd = tableStart;
  7872. hufPackEncTable(freq.data(), im, iM, &tableEnd);
  7873. int tableLength = tableEnd - tableStart;
  7874. char *dataStart = tableEnd;
  7875. int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
  7876. int data_length = (nBits + 7) / 8;
  7877. writeUInt(compressed, im);
  7878. writeUInt(compressed + 4, iM);
  7879. writeUInt(compressed + 8, tableLength);
  7880. writeUInt(compressed + 12, nBits);
  7881. writeUInt(compressed + 16, 0); // room for future extensions
  7882. return dataStart + data_length - compressed;
  7883. }
  7884. static bool hufUncompress(const char compressed[], int nCompressed,
  7885. std::vector<unsigned short> *raw) {
  7886. if (nCompressed == 0) {
  7887. if (raw->size() != 0) return false;
  7888. return false;
  7889. }
  7890. int im = readUInt(compressed);
  7891. int iM = readUInt(compressed + 4);
  7892. // int tableLength = readUInt (compressed + 8);
  7893. int nBits = readUInt(compressed + 12);
  7894. if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;
  7895. const char *ptr = compressed + 20;
  7896. //
  7897. // Fast decoder needs at least 2x64-bits of compressed data, and
  7898. // needs to be run-able on this platform. Otherwise, fall back
  7899. // to the original decoder
  7900. //
  7901. // if (FastHufDecoder::enabled() && nBits > 128)
  7902. //{
  7903. // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
  7904. // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
  7905. //}
  7906. // else
  7907. {
  7908. std::vector<long long> freq(HUF_ENCSIZE);
  7909. std::vector<HufDec> hdec(HUF_DECSIZE);
  7910. hufClearDecTable(&hdec.at(0));
  7911. hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
  7912. &freq.at(0));
  7913. {
  7914. if (nBits > 8 * (nCompressed - (ptr - compressed))) {
  7915. return false;
  7916. }
  7917. hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
  7918. hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
  7919. raw->data());
  7920. }
  7921. // catch (...)
  7922. //{
  7923. // hufFreeDecTable (hdec);
  7924. // throw;
  7925. //}
  7926. hufFreeDecTable(&hdec.at(0));
  7927. }
  7928. return true;
  7929. }
  7930. //
  7931. // Functions to compress the range of values in the pixel data
  7932. //
  7933. const int USHORT_RANGE = (1 << 16);
  7934. const int BITMAP_SIZE = (USHORT_RANGE >> 3);
  7935. static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
  7936. unsigned char bitmap[BITMAP_SIZE],
  7937. unsigned short &minNonZero,
  7938. unsigned short &maxNonZero) {
  7939. for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;
  7940. for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
  7941. bitmap[0] &= ~1; // zero is not explicitly stored in
  7942. // the bitmap; we assume that the
  7943. // data always contain zeroes
  7944. minNonZero = BITMAP_SIZE - 1;
  7945. maxNonZero = 0;
  7946. for (int i = 0; i < BITMAP_SIZE; ++i) {
  7947. if (bitmap[i]) {
  7948. if (minNonZero > i) minNonZero = i;
  7949. if (maxNonZero < i) maxNonZero = i;
  7950. }
  7951. }
  7952. }
  7953. static unsigned short forwardLutFromBitmap(
  7954. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  7955. int k = 0;
  7956. for (int i = 0; i < USHORT_RANGE; ++i) {
  7957. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  7958. lut[i] = k++;
  7959. else
  7960. lut[i] = 0;
  7961. }
  7962. return k - 1; // maximum value stored in lut[],
  7963. } // i.e. number of ones in bitmap minus 1
  7964. static unsigned short reverseLutFromBitmap(
  7965. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  7966. int k = 0;
  7967. for (int i = 0; i < USHORT_RANGE; ++i) {
  7968. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;
  7969. }
  7970. int n = k - 1;
  7971. while (k < USHORT_RANGE) lut[k++] = 0;
  7972. return n; // maximum k where lut[k] is non-zero,
  7973. } // i.e. number of ones in bitmap minus 1
  7974. static void applyLut(const unsigned short lut[USHORT_RANGE],
  7975. unsigned short data[/*nData*/], int nData) {
  7976. for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];
  7977. }
  7978. #ifdef __clang__
  7979. #pragma clang diagnostic pop
  7980. #endif // __clang__
  7981. #ifdef _MSC_VER
  7982. #pragma warning(pop)
  7983. #endif
  7984. static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,
  7985. const unsigned char *inPtr, size_t inSize,
  7986. const std::vector<ChannelInfo> &channelInfo,
  7987. int data_width, int num_lines) {
  7988. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  7989. unsigned short minNonZero;
  7990. unsigned short maxNonZero;
  7991. #if !MINIZ_LITTLE_ENDIAN
  7992. // @todo { PIZ compression on BigEndian architecture. }
  7993. assert(0);
  7994. return false;
  7995. #endif
  7996. // Assume `inSize` is multiple of 2 or 4.
  7997. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
  7998. std::vector<PIZChannelData> channelData(channelInfo.size());
  7999. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8000. for (size_t c = 0; c < channelData.size(); c++) {
  8001. PIZChannelData &cd = channelData[c];
  8002. cd.start = tmpBufferEnd;
  8003. cd.end = cd.start;
  8004. cd.nx = data_width;
  8005. cd.ny = num_lines;
  8006. // cd.ys = c.channel().ySampling;
  8007. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8008. if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8009. pixelSize = sizeof(short);
  8010. }
  8011. cd.size = static_cast<int>(pixelSize / sizeof(short));
  8012. tmpBufferEnd += cd.nx * cd.ny * cd.size;
  8013. }
  8014. const unsigned char *ptr = inPtr;
  8015. for (int y = 0; y < num_lines; ++y) {
  8016. for (size_t i = 0; i < channelData.size(); ++i) {
  8017. PIZChannelData &cd = channelData[i];
  8018. // if (modp (y, cd.ys) != 0)
  8019. // continue;
  8020. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8021. memcpy(cd.end, ptr, n * sizeof(unsigned short));
  8022. ptr += n * sizeof(unsigned short);
  8023. cd.end += n;
  8024. }
  8025. }
  8026. bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
  8027. bitmap.data(), minNonZero, maxNonZero);
  8028. std::vector<unsigned short> lut(USHORT_RANGE);
  8029. unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
  8030. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
  8031. //
  8032. // Store range compression info in _outBuffer
  8033. //
  8034. char *buf = reinterpret_cast<char *>(outPtr);
  8035. memcpy(buf, &minNonZero, sizeof(unsigned short));
  8036. buf += sizeof(unsigned short);
  8037. memcpy(buf, &maxNonZero, sizeof(unsigned short));
  8038. buf += sizeof(unsigned short);
  8039. if (minNonZero <= maxNonZero) {
  8040. memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),
  8041. maxNonZero - minNonZero + 1);
  8042. buf += maxNonZero - minNonZero + 1;
  8043. }
  8044. //
  8045. // Apply wavelet encoding
  8046. //
  8047. for (size_t i = 0; i < channelData.size(); ++i) {
  8048. PIZChannelData &cd = channelData[i];
  8049. for (int j = 0; j < cd.size; ++j) {
  8050. wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8051. maxValue);
  8052. }
  8053. }
  8054. //
  8055. // Apply Huffman encoding; append the result to _outBuffer
  8056. //
  8057. // length header(4byte), then huff data. Initialize length header with zero,
  8058. // then later fill it by `length`.
  8059. char *lengthPtr = buf;
  8060. int zero = 0;
  8061. memcpy(buf, &zero, sizeof(int));
  8062. buf += sizeof(int);
  8063. int length =
  8064. hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
  8065. memcpy(lengthPtr, &length, sizeof(int));
  8066. (*outSize) = static_cast<unsigned int>(
  8067. (reinterpret_cast<unsigned char *>(buf) - outPtr) +
  8068. static_cast<unsigned int>(length));
  8069. // Use uncompressed data when compressed data is larger than uncompressed.
  8070. // (Issue 40)
  8071. if ((*outSize) >= inSize) {
  8072. (*outSize) = static_cast<unsigned int>(inSize);
  8073. memcpy(outPtr, inPtr, inSize);
  8074. }
  8075. return true;
  8076. }
  8077. static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,
  8078. size_t tmpBufSize, size_t inLen, int num_channels,
  8079. const EXRChannelInfo *channels, int data_width,
  8080. int num_lines) {
  8081. if (inLen == tmpBufSize) {
  8082. // Data is not compressed(Issue 40).
  8083. memcpy(outPtr, inPtr, inLen);
  8084. return true;
  8085. }
  8086. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  8087. unsigned short minNonZero;
  8088. unsigned short maxNonZero;
  8089. #if !MINIZ_LITTLE_ENDIAN
  8090. // @todo { PIZ compression on BigEndian architecture. }
  8091. assert(0);
  8092. return false;
  8093. #endif
  8094. memset(bitmap.data(), 0, BITMAP_SIZE);
  8095. const unsigned char *ptr = inPtr;
  8096. // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
  8097. tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));
  8098. // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
  8099. tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));
  8100. ptr += 4;
  8101. if (maxNonZero >= BITMAP_SIZE) {
  8102. return false;
  8103. }
  8104. if (minNonZero <= maxNonZero) {
  8105. memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,
  8106. maxNonZero - minNonZero + 1);
  8107. ptr += maxNonZero - minNonZero + 1;
  8108. }
  8109. std::vector<unsigned short> lut(USHORT_RANGE);
  8110. memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
  8111. unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
  8112. //
  8113. // Huffman decoding
  8114. //
  8115. int length;
  8116. // length = *(reinterpret_cast<const int *>(ptr));
  8117. tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));
  8118. ptr += sizeof(int);
  8119. std::vector<unsigned short> tmpBuffer(tmpBufSize);
  8120. hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);
  8121. //
  8122. // Wavelet decoding
  8123. //
  8124. std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
  8125. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8126. for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
  8127. const EXRChannelInfo &chan = channels[i];
  8128. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8129. if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8130. pixelSize = sizeof(short);
  8131. }
  8132. channelData[i].start = tmpBufferEnd;
  8133. channelData[i].end = channelData[i].start;
  8134. channelData[i].nx = data_width;
  8135. channelData[i].ny = num_lines;
  8136. // channelData[i].ys = 1;
  8137. channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
  8138. tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
  8139. }
  8140. for (size_t i = 0; i < channelData.size(); ++i) {
  8141. PIZChannelData &cd = channelData[i];
  8142. for (int j = 0; j < cd.size; ++j) {
  8143. wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8144. maxValue);
  8145. }
  8146. }
  8147. //
  8148. // Expand the pixel data to their original range
  8149. //
  8150. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize));
  8151. for (int y = 0; y < num_lines; y++) {
  8152. for (size_t i = 0; i < channelData.size(); ++i) {
  8153. PIZChannelData &cd = channelData[i];
  8154. // if (modp (y, cd.ys) != 0)
  8155. // continue;
  8156. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8157. memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
  8158. outPtr += n * sizeof(unsigned short);
  8159. cd.end += n;
  8160. }
  8161. }
  8162. return true;
  8163. }
  8164. #endif // TINYEXR_USE_PIZ
  8165. #if TINYEXR_USE_ZFP
  8166. struct ZFPCompressionParam {
  8167. double rate;
  8168. int precision;
  8169. double tolerance;
  8170. int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
  8171. ZFPCompressionParam() {
  8172. type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;
  8173. rate = 2.0;
  8174. precision = 0;
  8175. tolerance = 0.0f;
  8176. }
  8177. };
  8178. bool FindZFPCompressionParam(ZFPCompressionParam *param,
  8179. const EXRAttribute *attributes,
  8180. int num_attributes) {
  8181. bool foundType = false;
  8182. for (int i = 0; i < num_attributes; i++) {
  8183. if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) &&
  8184. (attributes[i].size == 1)) {
  8185. param->type = static_cast<int>(attributes[i].value[0]);
  8186. foundType = true;
  8187. }
  8188. }
  8189. if (!foundType) {
  8190. return false;
  8191. }
  8192. if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8193. for (int i = 0; i < num_attributes; i++) {
  8194. if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&
  8195. (attributes[i].size == 8)) {
  8196. param->rate = *(reinterpret_cast<double *>(attributes[i].value));
  8197. return true;
  8198. }
  8199. }
  8200. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8201. for (int i = 0; i < num_attributes; i++) {
  8202. if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&
  8203. (attributes[i].size == 4)) {
  8204. param->rate = *(reinterpret_cast<int *>(attributes[i].value));
  8205. return true;
  8206. }
  8207. }
  8208. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8209. for (int i = 0; i < num_attributes; i++) {
  8210. if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&
  8211. (attributes[i].size == 8)) {
  8212. param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));
  8213. return true;
  8214. }
  8215. }
  8216. } else {
  8217. assert(0);
  8218. }
  8219. return false;
  8220. }
  8221. // Assume pixel format is FLOAT for all channels.
  8222. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,
  8223. int num_channels, const unsigned char *src,
  8224. unsigned long src_size,
  8225. const ZFPCompressionParam &param) {
  8226. size_t uncompressed_size = dst_width * dst_num_lines * num_channels;
  8227. if (uncompressed_size == src_size) {
  8228. // Data is not compressed(Issue 40).
  8229. memcpy(dst, src, src_size);
  8230. }
  8231. zfp_stream *zfp = NULL;
  8232. zfp_field *field = NULL;
  8233. assert((dst_width % 4) == 0);
  8234. assert((dst_num_lines % 4) == 0);
  8235. if ((dst_width & 3U) || (dst_num_lines & 3U)) {
  8236. return false;
  8237. }
  8238. field =
  8239. zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),
  8240. zfp_type_float, dst_width, dst_num_lines * num_channels);
  8241. zfp = zfp_stream_open(NULL);
  8242. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8243. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2,
  8244. /* write random access */ 0);
  8245. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8246. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8247. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8248. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8249. } else {
  8250. assert(0);
  8251. }
  8252. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8253. std::vector<unsigned char> buf(buf_size);
  8254. memcpy(&buf.at(0), src, src_size);
  8255. bitstream *stream = stream_open(&buf.at(0), buf_size);
  8256. zfp_stream_set_bit_stream(zfp, stream);
  8257. zfp_stream_rewind(zfp);
  8258. size_t image_size = dst_width * dst_num_lines;
  8259. for (int c = 0; c < num_channels; c++) {
  8260. // decompress 4x4 pixel block.
  8261. for (int y = 0; y < dst_num_lines; y += 4) {
  8262. for (int x = 0; x < dst_width; x += 4) {
  8263. float fblock[16];
  8264. zfp_decode_block_float_2(zfp, fblock);
  8265. for (int j = 0; j < 4; j++) {
  8266. for (int i = 0; i < 4; i++) {
  8267. dst[c * image_size + ((y + j) * dst_width + (x + i))] =
  8268. fblock[j * 4 + i];
  8269. }
  8270. }
  8271. }
  8272. }
  8273. }
  8274. zfp_field_free(field);
  8275. zfp_stream_close(zfp);
  8276. stream_close(stream);
  8277. return true;
  8278. }
  8279. // Assume pixel format is FLOAT for all channels.
  8280. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize,
  8281. const float *inPtr, int width, int num_lines, int num_channels,
  8282. const ZFPCompressionParam &param) {
  8283. zfp_stream *zfp = NULL;
  8284. zfp_field *field = NULL;
  8285. assert((width % 4) == 0);
  8286. assert((num_lines % 4) == 0);
  8287. if ((width & 3U) || (num_lines & 3U)) {
  8288. return false;
  8289. }
  8290. // create input array.
  8291. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),
  8292. zfp_type_float, width, num_lines * num_channels);
  8293. zfp = zfp_stream_open(NULL);
  8294. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8295. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
  8296. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8297. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8298. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8299. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8300. } else {
  8301. assert(0);
  8302. }
  8303. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8304. outBuf->resize(buf_size);
  8305. bitstream *stream = stream_open(&outBuf->at(0), buf_size);
  8306. zfp_stream_set_bit_stream(zfp, stream);
  8307. zfp_field_free(field);
  8308. size_t image_size = width * num_lines;
  8309. for (int c = 0; c < num_channels; c++) {
  8310. // compress 4x4 pixel block.
  8311. for (int y = 0; y < num_lines; y += 4) {
  8312. for (int x = 0; x < width; x += 4) {
  8313. float fblock[16];
  8314. for (int j = 0; j < 4; j++) {
  8315. for (int i = 0; i < 4; i++) {
  8316. fblock[j * 4 + i] =
  8317. inPtr[c * image_size + ((y + j) * width + (x + i))];
  8318. }
  8319. }
  8320. zfp_encode_block_float_2(zfp, fblock);
  8321. }
  8322. }
  8323. }
  8324. zfp_stream_flush(zfp);
  8325. (*outSize) = zfp_stream_compressed_size(zfp);
  8326. zfp_stream_close(zfp);
  8327. return true;
  8328. }
  8329. #endif
  8330. //
  8331. // -----------------------------------------------------------------
  8332. //
  8333. // TODO(syoyo): Refactor function arguments.
  8334. static bool DecodePixelData(/* out */ unsigned char **out_images,
  8335. const int *requested_pixel_types,
  8336. const unsigned char *data_ptr, size_t data_len,
  8337. int compression_type, int line_order, int width,
  8338. int height, int x_stride, int y, int line_no,
  8339. int num_lines, size_t pixel_data_size,
  8340. size_t num_attributes,
  8341. const EXRAttribute *attributes, size_t num_channels,
  8342. const EXRChannelInfo *channels,
  8343. const std::vector<size_t> &channel_offset_list) {
  8344. if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
  8345. #if TINYEXR_USE_PIZ
  8346. if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
  8347. // Invalid input #90
  8348. return false;
  8349. }
  8350. // Allocate original data size.
  8351. std::vector<unsigned char> outBuf(static_cast<size_t>(
  8352. static_cast<size_t>(width * num_lines) * pixel_data_size));
  8353. size_t tmpBufLen = outBuf.size();
  8354. bool ret = tinyexr::DecompressPiz(
  8355. reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,
  8356. data_len, static_cast<int>(num_channels), channels, width, num_lines);
  8357. assert(ret);
  8358. (void)ret;
  8359. // For PIZ_COMPRESSION:
  8360. // pixel sample data for channel 0 for scanline 0
  8361. // pixel sample data for channel 1 for scanline 0
  8362. // pixel sample data for channel ... for scanline 0
  8363. // pixel sample data for channel n for scanline 0
  8364. // pixel sample data for channel 0 for scanline 1
  8365. // pixel sample data for channel 1 for scanline 1
  8366. // pixel sample data for channel ... for scanline 1
  8367. // pixel sample data for channel n for scanline 1
  8368. // ...
  8369. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8370. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8371. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8372. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8373. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8374. channel_offset_list[c] * static_cast<size_t>(width)));
  8375. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8376. FP16 hf;
  8377. // hf.u = line_ptr[u];
  8378. // use `cpy` to avoid unaligned memory access when compiler's
  8379. // optimization is on.
  8380. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8381. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8382. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8383. unsigned short *image =
  8384. reinterpret_cast<unsigned short **>(out_images)[c];
  8385. if (line_order == 0) {
  8386. image += (static_cast<size_t>(line_no) + v) *
  8387. static_cast<size_t>(x_stride) +
  8388. u;
  8389. } else {
  8390. image += static_cast<size_t>(
  8391. (height - 1 - (line_no + static_cast<int>(v)))) *
  8392. static_cast<size_t>(x_stride) +
  8393. u;
  8394. }
  8395. *image = hf.u;
  8396. } else { // HALF -> FLOAT
  8397. FP32 f32 = half_to_float(hf);
  8398. float *image = reinterpret_cast<float **>(out_images)[c];
  8399. if (line_order == 0) {
  8400. image += (static_cast<size_t>(line_no) + v) *
  8401. static_cast<size_t>(x_stride) +
  8402. u;
  8403. } else {
  8404. image += static_cast<size_t>(
  8405. (height - 1 - (line_no + static_cast<int>(v)))) *
  8406. static_cast<size_t>(x_stride) +
  8407. u;
  8408. }
  8409. *image = f32.f;
  8410. }
  8411. }
  8412. }
  8413. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8414. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8415. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8416. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8417. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8418. channel_offset_list[c] * static_cast<size_t>(width)));
  8419. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8420. unsigned int val;
  8421. // val = line_ptr[u];
  8422. tinyexr::cpy4(&val, line_ptr + u);
  8423. tinyexr::swap4(&val);
  8424. unsigned int *image =
  8425. reinterpret_cast<unsigned int **>(out_images)[c];
  8426. if (line_order == 0) {
  8427. image += (static_cast<size_t>(line_no) + v) *
  8428. static_cast<size_t>(x_stride) +
  8429. u;
  8430. } else {
  8431. image += static_cast<size_t>(
  8432. (height - 1 - (line_no + static_cast<int>(v)))) *
  8433. static_cast<size_t>(x_stride) +
  8434. u;
  8435. }
  8436. *image = val;
  8437. }
  8438. }
  8439. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8440. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8441. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8442. const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(
  8443. v * pixel_data_size * static_cast<size_t>(x_stride) +
  8444. channel_offset_list[c] * static_cast<size_t>(x_stride)));
  8445. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8446. float val;
  8447. // val = line_ptr[u];
  8448. tinyexr::cpy4(&val, line_ptr + u);
  8449. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8450. float *image = reinterpret_cast<float **>(out_images)[c];
  8451. if (line_order == 0) {
  8452. image += (static_cast<size_t>(line_no) + v) *
  8453. static_cast<size_t>(x_stride) +
  8454. u;
  8455. } else {
  8456. image += static_cast<size_t>(
  8457. (height - 1 - (line_no + static_cast<int>(v)))) *
  8458. static_cast<size_t>(x_stride) +
  8459. u;
  8460. }
  8461. *image = val;
  8462. }
  8463. }
  8464. } else {
  8465. assert(0);
  8466. }
  8467. }
  8468. #else
  8469. assert(0 && "PIZ is enabled in this build");
  8470. return false;
  8471. #endif
  8472. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||
  8473. compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  8474. // Allocate original data size.
  8475. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8476. static_cast<size_t>(num_lines) *
  8477. pixel_data_size);
  8478. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8479. assert(dstLen > 0);
  8480. if (!tinyexr::DecompressZip(
  8481. reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,
  8482. static_cast<unsigned long>(data_len))) {
  8483. return false;
  8484. }
  8485. // For ZIP_COMPRESSION:
  8486. // pixel sample data for channel 0 for scanline 0
  8487. // pixel sample data for channel 1 for scanline 0
  8488. // pixel sample data for channel ... for scanline 0
  8489. // pixel sample data for channel n for scanline 0
  8490. // pixel sample data for channel 0 for scanline 1
  8491. // pixel sample data for channel 1 for scanline 1
  8492. // pixel sample data for channel ... for scanline 1
  8493. // pixel sample data for channel n for scanline 1
  8494. // ...
  8495. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8496. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8497. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8498. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8499. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8500. static_cast<size_t>(width) +
  8501. channel_offset_list[c] * static_cast<size_t>(width)));
  8502. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8503. tinyexr::FP16 hf;
  8504. // hf.u = line_ptr[u];
  8505. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8506. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8507. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8508. unsigned short *image =
  8509. reinterpret_cast<unsigned short **>(out_images)[c];
  8510. if (line_order == 0) {
  8511. image += (static_cast<size_t>(line_no) + v) *
  8512. static_cast<size_t>(x_stride) +
  8513. u;
  8514. } else {
  8515. image += (static_cast<size_t>(height) - 1U -
  8516. (static_cast<size_t>(line_no) + v)) *
  8517. static_cast<size_t>(x_stride) +
  8518. u;
  8519. }
  8520. *image = hf.u;
  8521. } else { // HALF -> FLOAT
  8522. tinyexr::FP32 f32 = half_to_float(hf);
  8523. float *image = reinterpret_cast<float **>(out_images)[c];
  8524. if (line_order == 0) {
  8525. image += (static_cast<size_t>(line_no) + v) *
  8526. static_cast<size_t>(x_stride) +
  8527. u;
  8528. } else {
  8529. image += (static_cast<size_t>(height) - 1U -
  8530. (static_cast<size_t>(line_no) + v)) *
  8531. static_cast<size_t>(x_stride) +
  8532. u;
  8533. }
  8534. *image = f32.f;
  8535. }
  8536. }
  8537. }
  8538. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8539. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8540. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8541. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8542. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8543. channel_offset_list[c] * static_cast<size_t>(width)));
  8544. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8545. unsigned int val;
  8546. // val = line_ptr[u];
  8547. tinyexr::cpy4(&val, line_ptr + u);
  8548. tinyexr::swap4(&val);
  8549. unsigned int *image =
  8550. reinterpret_cast<unsigned int **>(out_images)[c];
  8551. if (line_order == 0) {
  8552. image += (static_cast<size_t>(line_no) + v) *
  8553. static_cast<size_t>(x_stride) +
  8554. u;
  8555. } else {
  8556. image += (static_cast<size_t>(height) - 1U -
  8557. (static_cast<size_t>(line_no) + v)) *
  8558. static_cast<size_t>(x_stride) +
  8559. u;
  8560. }
  8561. *image = val;
  8562. }
  8563. }
  8564. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8565. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8566. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8567. const float *line_ptr = reinterpret_cast<float *>(
  8568. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8569. channel_offset_list[c] * static_cast<size_t>(width)));
  8570. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8571. float val;
  8572. // val = line_ptr[u];
  8573. tinyexr::cpy4(&val, line_ptr + u);
  8574. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8575. float *image = reinterpret_cast<float **>(out_images)[c];
  8576. if (line_order == 0) {
  8577. image += (static_cast<size_t>(line_no) + v) *
  8578. static_cast<size_t>(x_stride) +
  8579. u;
  8580. } else {
  8581. image += (static_cast<size_t>(height) - 1U -
  8582. (static_cast<size_t>(line_no) + v)) *
  8583. static_cast<size_t>(x_stride) +
  8584. u;
  8585. }
  8586. *image = val;
  8587. }
  8588. }
  8589. } else {
  8590. assert(0);
  8591. return false;
  8592. }
  8593. }
  8594. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  8595. // Allocate original data size.
  8596. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8597. static_cast<size_t>(num_lines) *
  8598. pixel_data_size);
  8599. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8600. assert(dstLen > 0);
  8601. tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)),
  8602. dstLen, data_ptr,
  8603. static_cast<unsigned long>(data_len));
  8604. // For RLE_COMPRESSION:
  8605. // pixel sample data for channel 0 for scanline 0
  8606. // pixel sample data for channel 1 for scanline 0
  8607. // pixel sample data for channel ... for scanline 0
  8608. // pixel sample data for channel n for scanline 0
  8609. // pixel sample data for channel 0 for scanline 1
  8610. // pixel sample data for channel 1 for scanline 1
  8611. // pixel sample data for channel ... for scanline 1
  8612. // pixel sample data for channel n for scanline 1
  8613. // ...
  8614. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8615. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8616. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8617. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8618. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8619. static_cast<size_t>(width) +
  8620. channel_offset_list[c] * static_cast<size_t>(width)));
  8621. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8622. tinyexr::FP16 hf;
  8623. // hf.u = line_ptr[u];
  8624. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8625. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8626. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8627. unsigned short *image =
  8628. reinterpret_cast<unsigned short **>(out_images)[c];
  8629. if (line_order == 0) {
  8630. image += (static_cast<size_t>(line_no) + v) *
  8631. static_cast<size_t>(x_stride) +
  8632. u;
  8633. } else {
  8634. image += (static_cast<size_t>(height) - 1U -
  8635. (static_cast<size_t>(line_no) + v)) *
  8636. static_cast<size_t>(x_stride) +
  8637. u;
  8638. }
  8639. *image = hf.u;
  8640. } else { // HALF -> FLOAT
  8641. tinyexr::FP32 f32 = half_to_float(hf);
  8642. float *image = reinterpret_cast<float **>(out_images)[c];
  8643. if (line_order == 0) {
  8644. image += (static_cast<size_t>(line_no) + v) *
  8645. static_cast<size_t>(x_stride) +
  8646. u;
  8647. } else {
  8648. image += (static_cast<size_t>(height) - 1U -
  8649. (static_cast<size_t>(line_no) + v)) *
  8650. static_cast<size_t>(x_stride) +
  8651. u;
  8652. }
  8653. *image = f32.f;
  8654. }
  8655. }
  8656. }
  8657. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8658. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8659. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8660. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8661. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8662. channel_offset_list[c] * static_cast<size_t>(width)));
  8663. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8664. unsigned int val;
  8665. // val = line_ptr[u];
  8666. tinyexr::cpy4(&val, line_ptr + u);
  8667. tinyexr::swap4(&val);
  8668. unsigned int *image =
  8669. reinterpret_cast<unsigned int **>(out_images)[c];
  8670. if (line_order == 0) {
  8671. image += (static_cast<size_t>(line_no) + v) *
  8672. static_cast<size_t>(x_stride) +
  8673. u;
  8674. } else {
  8675. image += (static_cast<size_t>(height) - 1U -
  8676. (static_cast<size_t>(line_no) + v)) *
  8677. static_cast<size_t>(x_stride) +
  8678. u;
  8679. }
  8680. *image = val;
  8681. }
  8682. }
  8683. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8684. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8685. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8686. const float *line_ptr = reinterpret_cast<float *>(
  8687. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8688. channel_offset_list[c] * static_cast<size_t>(width)));
  8689. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8690. float val;
  8691. // val = line_ptr[u];
  8692. tinyexr::cpy4(&val, line_ptr + u);
  8693. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8694. float *image = reinterpret_cast<float **>(out_images)[c];
  8695. if (line_order == 0) {
  8696. image += (static_cast<size_t>(line_no) + v) *
  8697. static_cast<size_t>(x_stride) +
  8698. u;
  8699. } else {
  8700. image += (static_cast<size_t>(height) - 1U -
  8701. (static_cast<size_t>(line_no) + v)) *
  8702. static_cast<size_t>(x_stride) +
  8703. u;
  8704. }
  8705. *image = val;
  8706. }
  8707. }
  8708. } else {
  8709. assert(0);
  8710. return false;
  8711. }
  8712. }
  8713. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  8714. #if TINYEXR_USE_ZFP
  8715. tinyexr::ZFPCompressionParam zfp_compression_param;
  8716. if (!FindZFPCompressionParam(&zfp_compression_param, attributes,
  8717. num_attributes)) {
  8718. assert(0);
  8719. return false;
  8720. }
  8721. // Allocate original data size.
  8722. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8723. static_cast<size_t>(num_lines) *
  8724. pixel_data_size);
  8725. unsigned long dstLen = outBuf.size();
  8726. assert(dstLen > 0);
  8727. tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,
  8728. num_lines, num_channels, data_ptr,
  8729. static_cast<unsigned long>(data_len),
  8730. zfp_compression_param);
  8731. // For ZFP_COMPRESSION:
  8732. // pixel sample data for channel 0 for scanline 0
  8733. // pixel sample data for channel 1 for scanline 0
  8734. // pixel sample data for channel ... for scanline 0
  8735. // pixel sample data for channel n for scanline 0
  8736. // pixel sample data for channel 0 for scanline 1
  8737. // pixel sample data for channel 1 for scanline 1
  8738. // pixel sample data for channel ... for scanline 1
  8739. // pixel sample data for channel n for scanline 1
  8740. // ...
  8741. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8742. assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT);
  8743. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8744. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8745. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8746. const float *line_ptr = reinterpret_cast<float *>(
  8747. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8748. channel_offset_list[c] * static_cast<size_t>(width)));
  8749. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8750. float val;
  8751. tinyexr::cpy4(&val, line_ptr + u);
  8752. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8753. float *image = reinterpret_cast<float **>(out_images)[c];
  8754. if (line_order == 0) {
  8755. image += (static_cast<size_t>(line_no) + v) *
  8756. static_cast<size_t>(x_stride) +
  8757. u;
  8758. } else {
  8759. image += (static_cast<size_t>(height) - 1U -
  8760. (static_cast<size_t>(line_no) + v)) *
  8761. static_cast<size_t>(x_stride) +
  8762. u;
  8763. }
  8764. *image = val;
  8765. }
  8766. }
  8767. } else {
  8768. assert(0);
  8769. return false;
  8770. }
  8771. }
  8772. #else
  8773. (void)attributes;
  8774. (void)num_attributes;
  8775. (void)num_channels;
  8776. assert(0);
  8777. return false;
  8778. #endif
  8779. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  8780. for (size_t c = 0; c < num_channels; c++) {
  8781. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8782. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8783. const unsigned short *line_ptr =
  8784. reinterpret_cast<const unsigned short *>(
  8785. data_ptr + v * pixel_data_size * size_t(width) +
  8786. channel_offset_list[c] * static_cast<size_t>(width));
  8787. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8788. unsigned short *outLine =
  8789. reinterpret_cast<unsigned short *>(out_images[c]);
  8790. if (line_order == 0) {
  8791. outLine += (size_t(y) + v) * size_t(x_stride);
  8792. } else {
  8793. outLine +=
  8794. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8795. }
  8796. for (int u = 0; u < width; u++) {
  8797. tinyexr::FP16 hf;
  8798. // hf.u = line_ptr[u];
  8799. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8800. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8801. outLine[u] = hf.u;
  8802. }
  8803. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8804. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8805. if (line_order == 0) {
  8806. outLine += (size_t(y) + v) * size_t(x_stride);
  8807. } else {
  8808. outLine +=
  8809. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8810. }
  8811. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8812. (data_ptr + data_len)) {
  8813. // Insufficient data size
  8814. return false;
  8815. }
  8816. for (int u = 0; u < width; u++) {
  8817. tinyexr::FP16 hf;
  8818. // address may not be aliged. use byte-wise copy for safety.#76
  8819. // hf.u = line_ptr[u];
  8820. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8821. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8822. tinyexr::FP32 f32 = half_to_float(hf);
  8823. outLine[u] = f32.f;
  8824. }
  8825. } else {
  8826. assert(0);
  8827. return false;
  8828. }
  8829. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8830. const float *line_ptr = reinterpret_cast<const float *>(
  8831. data_ptr + v * pixel_data_size * size_t(width) +
  8832. channel_offset_list[c] * static_cast<size_t>(width));
  8833. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8834. if (line_order == 0) {
  8835. outLine += (size_t(y) + v) * size_t(x_stride);
  8836. } else {
  8837. outLine +=
  8838. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8839. }
  8840. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8841. (data_ptr + data_len)) {
  8842. // Insufficient data size
  8843. return false;
  8844. }
  8845. for (int u = 0; u < width; u++) {
  8846. float val;
  8847. tinyexr::cpy4(&val, line_ptr + u);
  8848. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8849. outLine[u] = val;
  8850. }
  8851. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8852. const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(
  8853. data_ptr + v * pixel_data_size * size_t(width) +
  8854. channel_offset_list[c] * static_cast<size_t>(width));
  8855. unsigned int *outLine =
  8856. reinterpret_cast<unsigned int *>(out_images[c]);
  8857. if (line_order == 0) {
  8858. outLine += (size_t(y) + v) * size_t(x_stride);
  8859. } else {
  8860. outLine +=
  8861. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8862. }
  8863. for (int u = 0; u < width; u++) {
  8864. if (reinterpret_cast<const unsigned char *>(line_ptr + u) >=
  8865. (data_ptr + data_len)) {
  8866. // Corrupsed data?
  8867. return false;
  8868. }
  8869. unsigned int val;
  8870. tinyexr::cpy4(&val, line_ptr + u);
  8871. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8872. outLine[u] = val;
  8873. }
  8874. }
  8875. }
  8876. }
  8877. }
  8878. return true;
  8879. }
  8880. static void DecodeTiledPixelData(
  8881. unsigned char **out_images, int *width, int *height,
  8882. const int *requested_pixel_types, const unsigned char *data_ptr,
  8883. size_t data_len, int compression_type, int line_order, int data_width,
  8884. int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
  8885. int tile_size_y, size_t pixel_data_size, size_t num_attributes,
  8886. const EXRAttribute *attributes, size_t num_channels,
  8887. const EXRChannelInfo *channels,
  8888. const std::vector<size_t> &channel_offset_list) {
  8889. assert(tile_offset_x * tile_size_x < data_width);
  8890. assert(tile_offset_y * tile_size_y < data_height);
  8891. // Compute actual image size in a tile.
  8892. if ((tile_offset_x + 1) * tile_size_x >= data_width) {
  8893. (*width) = data_width - (tile_offset_x * tile_size_x);
  8894. } else {
  8895. (*width) = tile_size_x;
  8896. }
  8897. if ((tile_offset_y + 1) * tile_size_y >= data_height) {
  8898. (*height) = data_height - (tile_offset_y * tile_size_y);
  8899. } else {
  8900. (*height) = tile_size_y;
  8901. }
  8902. // Image size = tile size.
  8903. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
  8904. compression_type, line_order, (*width), tile_size_y,
  8905. /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
  8906. (*height), pixel_data_size, num_attributes, attributes,
  8907. num_channels, channels, channel_offset_list);
  8908. }
  8909. static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,
  8910. int *pixel_data_size, size_t *channel_offset,
  8911. int num_channels,
  8912. const EXRChannelInfo *channels) {
  8913. channel_offset_list->resize(static_cast<size_t>(num_channels));
  8914. (*pixel_data_size) = 0;
  8915. (*channel_offset) = 0;
  8916. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8917. (*channel_offset_list)[c] = (*channel_offset);
  8918. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8919. (*pixel_data_size) += sizeof(unsigned short);
  8920. (*channel_offset) += sizeof(unsigned short);
  8921. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8922. (*pixel_data_size) += sizeof(float);
  8923. (*channel_offset) += sizeof(float);
  8924. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8925. (*pixel_data_size) += sizeof(unsigned int);
  8926. (*channel_offset) += sizeof(unsigned int);
  8927. } else {
  8928. // ???
  8929. return false;
  8930. }
  8931. }
  8932. return true;
  8933. }
  8934. static unsigned char **AllocateImage(int num_channels,
  8935. const EXRChannelInfo *channels,
  8936. const int *requested_pixel_types,
  8937. int data_width, int data_height) {
  8938. unsigned char **images =
  8939. reinterpret_cast<unsigned char **>(static_cast<float **>(
  8940. malloc(sizeof(float *) * static_cast<size_t>(num_channels))));
  8941. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8942. size_t data_len =
  8943. static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
  8944. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8945. // pixel_data_size += sizeof(unsigned short);
  8946. // channel_offset += sizeof(unsigned short);
  8947. // Alloc internal image for half type.
  8948. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8949. images[c] =
  8950. reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(
  8951. malloc(sizeof(unsigned short) * data_len)));
  8952. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8953. images[c] = reinterpret_cast<unsigned char *>(
  8954. static_cast<float *>(malloc(sizeof(float) * data_len)));
  8955. } else {
  8956. assert(0);
  8957. }
  8958. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8959. // pixel_data_size += sizeof(float);
  8960. // channel_offset += sizeof(float);
  8961. images[c] = reinterpret_cast<unsigned char *>(
  8962. static_cast<float *>(malloc(sizeof(float) * data_len)));
  8963. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8964. // pixel_data_size += sizeof(unsigned int);
  8965. // channel_offset += sizeof(unsigned int);
  8966. images[c] = reinterpret_cast<unsigned char *>(
  8967. static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));
  8968. } else {
  8969. assert(0);
  8970. }
  8971. }
  8972. return images;
  8973. }
  8974. static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,
  8975. const EXRVersion *version, std::string *err,
  8976. const unsigned char *buf, size_t size) {
  8977. const char *marker = reinterpret_cast<const char *>(&buf[0]);
  8978. if (empty_header) {
  8979. (*empty_header) = false;
  8980. }
  8981. if (version->multipart) {
  8982. if (size > 0 && marker[0] == '\0') {
  8983. // End of header list.
  8984. if (empty_header) {
  8985. (*empty_header) = true;
  8986. }
  8987. return TINYEXR_SUCCESS;
  8988. }
  8989. }
  8990. // According to the spec, the header of every OpenEXR file must contain at
  8991. // least the following attributes:
  8992. //
  8993. // channels chlist
  8994. // compression compression
  8995. // dataWindow box2i
  8996. // displayWindow box2i
  8997. // lineOrder lineOrder
  8998. // pixelAspectRatio float
  8999. // screenWindowCenter v2f
  9000. // screenWindowWidth float
  9001. bool has_channels = false;
  9002. bool has_compression = false;
  9003. bool has_data_window = false;
  9004. bool has_display_window = false;
  9005. bool has_line_order = false;
  9006. bool has_pixel_aspect_ratio = false;
  9007. bool has_screen_window_center = false;
  9008. bool has_screen_window_width = false;
  9009. info->data_window[0] = 0;
  9010. info->data_window[1] = 0;
  9011. info->data_window[2] = 0;
  9012. info->data_window[3] = 0;
  9013. info->line_order = 0; // @fixme
  9014. info->display_window[0] = 0;
  9015. info->display_window[1] = 0;
  9016. info->display_window[2] = 0;
  9017. info->display_window[3] = 0;
  9018. info->screen_window_center[0] = 0.0f;
  9019. info->screen_window_center[1] = 0.0f;
  9020. info->screen_window_width = -1.0f;
  9021. info->pixel_aspect_ratio = -1.0f;
  9022. info->tile_size_x = -1;
  9023. info->tile_size_y = -1;
  9024. info->tile_level_mode = -1;
  9025. info->tile_rounding_mode = -1;
  9026. info->attributes.clear();
  9027. // Read attributes
  9028. size_t orig_size = size;
  9029. for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
  9030. if (0 == size) {
  9031. if (err) {
  9032. (*err) += "Insufficient data size for attributes.\n";
  9033. }
  9034. return TINYEXR_ERROR_INVALID_DATA;
  9035. } else if (marker[0] == '\0') {
  9036. size--;
  9037. break;
  9038. }
  9039. std::string attr_name;
  9040. std::string attr_type;
  9041. std::vector<unsigned char> data;
  9042. size_t marker_size;
  9043. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  9044. marker, size)) {
  9045. if (err) {
  9046. (*err) += "Failed to read attribute.\n";
  9047. }
  9048. return TINYEXR_ERROR_INVALID_DATA;
  9049. }
  9050. marker += marker_size;
  9051. size -= marker_size;
  9052. if (version->tiled && attr_name.compare("tiles") == 0) {
  9053. unsigned int x_size, y_size;
  9054. unsigned char tile_mode;
  9055. assert(data.size() == 9);
  9056. memcpy(&x_size, &data.at(0), sizeof(int));
  9057. memcpy(&y_size, &data.at(4), sizeof(int));
  9058. tile_mode = data[8];
  9059. tinyexr::swap4(&x_size);
  9060. tinyexr::swap4(&y_size);
  9061. info->tile_size_x = static_cast<int>(x_size);
  9062. info->tile_size_y = static_cast<int>(y_size);
  9063. // mode = levelMode + roundingMode * 16
  9064. info->tile_level_mode = tile_mode & 0x3;
  9065. info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
  9066. } else if (attr_name.compare("compression") == 0) {
  9067. bool ok = false;
  9068. if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
  9069. ok = true;
  9070. }
  9071. if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9072. #if TINYEXR_USE_PIZ
  9073. ok = true;
  9074. #else
  9075. if (err) {
  9076. (*err) = "PIZ compression is not supported.";
  9077. }
  9078. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9079. #endif
  9080. }
  9081. if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9082. #if TINYEXR_USE_ZFP
  9083. ok = true;
  9084. #else
  9085. if (err) {
  9086. (*err) = "ZFP compression is not supported.";
  9087. }
  9088. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9089. #endif
  9090. }
  9091. if (!ok) {
  9092. if (err) {
  9093. (*err) = "Unknown compression type.";
  9094. }
  9095. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9096. }
  9097. info->compression_type = static_cast<int>(data[0]);
  9098. has_compression = true;
  9099. } else if (attr_name.compare("channels") == 0) {
  9100. // name: zero-terminated string, from 1 to 255 bytes long
  9101. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  9102. // pLinear: unsigned char, possible values are 0 and 1
  9103. // reserved: three chars, should be zero
  9104. // xSampling: int
  9105. // ySampling: int
  9106. if (!ReadChannelInfo(info->channels, data)) {
  9107. if (err) {
  9108. (*err) += "Failed to parse channel info.\n";
  9109. }
  9110. return TINYEXR_ERROR_INVALID_DATA;
  9111. }
  9112. if (info->channels.size() < 1) {
  9113. if (err) {
  9114. (*err) += "# of channels is zero.\n";
  9115. }
  9116. return TINYEXR_ERROR_INVALID_DATA;
  9117. }
  9118. has_channels = true;
  9119. } else if (attr_name.compare("dataWindow") == 0) {
  9120. if (data.size() >= 16) {
  9121. memcpy(&info->data_window[0], &data.at(0), sizeof(int));
  9122. memcpy(&info->data_window[1], &data.at(4), sizeof(int));
  9123. memcpy(&info->data_window[2], &data.at(8), sizeof(int));
  9124. memcpy(&info->data_window[3], &data.at(12), sizeof(int));
  9125. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0]));
  9126. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1]));
  9127. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2]));
  9128. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3]));
  9129. has_data_window = true;
  9130. }
  9131. } else if (attr_name.compare("displayWindow") == 0) {
  9132. if (data.size() >= 16) {
  9133. memcpy(&info->display_window[0], &data.at(0), sizeof(int));
  9134. memcpy(&info->display_window[1], &data.at(4), sizeof(int));
  9135. memcpy(&info->display_window[2], &data.at(8), sizeof(int));
  9136. memcpy(&info->display_window[3], &data.at(12), sizeof(int));
  9137. tinyexr::swap4(
  9138. reinterpret_cast<unsigned int *>(&info->display_window[0]));
  9139. tinyexr::swap4(
  9140. reinterpret_cast<unsigned int *>(&info->display_window[1]));
  9141. tinyexr::swap4(
  9142. reinterpret_cast<unsigned int *>(&info->display_window[2]));
  9143. tinyexr::swap4(
  9144. reinterpret_cast<unsigned int *>(&info->display_window[3]));
  9145. has_display_window = true;
  9146. }
  9147. } else if (attr_name.compare("lineOrder") == 0) {
  9148. if (data.size() >= 1) {
  9149. info->line_order = static_cast<int>(data[0]);
  9150. has_line_order = true;
  9151. }
  9152. } else if (attr_name.compare("pixelAspectRatio") == 0) {
  9153. if (data.size() >= sizeof(float)) {
  9154. memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
  9155. tinyexr::swap4(
  9156. reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio));
  9157. has_pixel_aspect_ratio = true;
  9158. }
  9159. } else if (attr_name.compare("screenWindowCenter") == 0) {
  9160. if (data.size() >= 8) {
  9161. memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
  9162. memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
  9163. tinyexr::swap4(
  9164. reinterpret_cast<unsigned int *>(&info->screen_window_center[0]));
  9165. tinyexr::swap4(
  9166. reinterpret_cast<unsigned int *>(&info->screen_window_center[1]));
  9167. has_screen_window_center = true;
  9168. }
  9169. } else if (attr_name.compare("screenWindowWidth") == 0) {
  9170. if (data.size() >= sizeof(float)) {
  9171. memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
  9172. tinyexr::swap4(
  9173. reinterpret_cast<unsigned int *>(&info->screen_window_width));
  9174. has_screen_window_width = true;
  9175. }
  9176. } else if (attr_name.compare("chunkCount") == 0) {
  9177. if (data.size() >= sizeof(int)) {
  9178. memcpy(&info->chunk_count, &data.at(0), sizeof(int));
  9179. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count));
  9180. }
  9181. } else {
  9182. // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
  9183. if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9184. EXRAttribute attrib;
  9185. #ifdef _MSC_VER
  9186. strncpy_s(attrib.name, attr_name.c_str(), 255);
  9187. strncpy_s(attrib.type, attr_type.c_str(), 255);
  9188. #else
  9189. strncpy(attrib.name, attr_name.c_str(), 255);
  9190. strncpy(attrib.type, attr_type.c_str(), 255);
  9191. #endif
  9192. attrib.name[255] = '\0';
  9193. attrib.type[255] = '\0';
  9194. attrib.size = static_cast<int>(data.size());
  9195. attrib.value = static_cast<unsigned char *>(malloc(data.size()));
  9196. memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),
  9197. data.size());
  9198. info->attributes.push_back(attrib);
  9199. }
  9200. }
  9201. }
  9202. // Check if required attributes exist
  9203. {
  9204. std::stringstream ss_err;
  9205. if (!has_compression) {
  9206. ss_err << "\"compression\" attribute not found in the header."
  9207. << std::endl;
  9208. }
  9209. if (!has_channels) {
  9210. ss_err << "\"channels\" attribute not found in the header." << std::endl;
  9211. }
  9212. if (!has_line_order) {
  9213. ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
  9214. }
  9215. if (!has_display_window) {
  9216. ss_err << "\"displayWindow\" attribute not found in the header."
  9217. << std::endl;
  9218. }
  9219. if (!has_data_window) {
  9220. ss_err << "\"dataWindow\" attribute not found in the header or invalid."
  9221. << std::endl;
  9222. }
  9223. if (!has_pixel_aspect_ratio) {
  9224. ss_err << "\"pixelAspectRatio\" attribute not found in the header."
  9225. << std::endl;
  9226. }
  9227. if (!has_screen_window_width) {
  9228. ss_err << "\"screenWindowWidth\" attribute not found in the header."
  9229. << std::endl;
  9230. }
  9231. if (!has_screen_window_center) {
  9232. ss_err << "\"screenWindowCenter\" attribute not found in the header."
  9233. << std::endl;
  9234. }
  9235. if (!(ss_err.str().empty())) {
  9236. if (err) {
  9237. (*err) += ss_err.str();
  9238. }
  9239. return TINYEXR_ERROR_INVALID_HEADER;
  9240. }
  9241. }
  9242. info->header_len = static_cast<unsigned int>(orig_size - size);
  9243. return TINYEXR_SUCCESS;
  9244. }
  9245. // C++ HeaderInfo to C EXRHeader conversion.
  9246. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) {
  9247. exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
  9248. exr_header->screen_window_center[0] = info.screen_window_center[0];
  9249. exr_header->screen_window_center[1] = info.screen_window_center[1];
  9250. exr_header->screen_window_width = info.screen_window_width;
  9251. exr_header->chunk_count = info.chunk_count;
  9252. exr_header->display_window[0] = info.display_window[0];
  9253. exr_header->display_window[1] = info.display_window[1];
  9254. exr_header->display_window[2] = info.display_window[2];
  9255. exr_header->display_window[3] = info.display_window[3];
  9256. exr_header->data_window[0] = info.data_window[0];
  9257. exr_header->data_window[1] = info.data_window[1];
  9258. exr_header->data_window[2] = info.data_window[2];
  9259. exr_header->data_window[3] = info.data_window[3];
  9260. exr_header->line_order = info.line_order;
  9261. exr_header->compression_type = info.compression_type;
  9262. exr_header->tile_size_x = info.tile_size_x;
  9263. exr_header->tile_size_y = info.tile_size_y;
  9264. exr_header->tile_level_mode = info.tile_level_mode;
  9265. exr_header->tile_rounding_mode = info.tile_rounding_mode;
  9266. exr_header->num_channels = static_cast<int>(info.channels.size());
  9267. exr_header->channels = static_cast<EXRChannelInfo *>(malloc(
  9268. sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
  9269. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9270. #ifdef _MSC_VER
  9271. strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9272. #else
  9273. strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9274. #endif
  9275. // manually add '\0' for safety.
  9276. exr_header->channels[c].name[255] = '\0';
  9277. exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
  9278. exr_header->channels[c].p_linear = info.channels[c].p_linear;
  9279. exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
  9280. exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
  9281. }
  9282. exr_header->pixel_types = static_cast<int *>(
  9283. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9284. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9285. exr_header->pixel_types[c] = info.channels[c].pixel_type;
  9286. }
  9287. // Initially fill with values of `pixel_types`
  9288. exr_header->requested_pixel_types = static_cast<int *>(
  9289. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9290. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9291. exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
  9292. }
  9293. exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
  9294. if (exr_header->num_custom_attributes > 0) {
  9295. // TODO(syoyo): Report warning when # of attributes exceeds
  9296. // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
  9297. if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9298. exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;
  9299. }
  9300. exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(
  9301. sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
  9302. for (size_t i = 0; i < info.attributes.size(); i++) {
  9303. memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
  9304. 256);
  9305. memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
  9306. 256);
  9307. exr_header->custom_attributes[i].size = info.attributes[i].size;
  9308. // Just copy poiner
  9309. exr_header->custom_attributes[i].value = info.attributes[i].value;
  9310. }
  9311. } else {
  9312. exr_header->custom_attributes = NULL;
  9313. }
  9314. exr_header->header_len = info.header_len;
  9315. }
  9316. static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
  9317. const std::vector<tinyexr::tinyexr_uint64> &offsets,
  9318. const unsigned char *head, const size_t size,
  9319. std::string *err) {
  9320. int num_channels = exr_header->num_channels;
  9321. int num_scanline_blocks = 1;
  9322. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9323. num_scanline_blocks = 16;
  9324. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9325. num_scanline_blocks = 32;
  9326. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9327. num_scanline_blocks = 16;
  9328. }
  9329. int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;
  9330. int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;
  9331. size_t num_blocks = offsets.size();
  9332. std::vector<size_t> channel_offset_list;
  9333. int pixel_data_size = 0;
  9334. size_t channel_offset = 0;
  9335. if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
  9336. &channel_offset, num_channels,
  9337. exr_header->channels)) {
  9338. if (err) {
  9339. (*err) += "Failed to compute channel layout.\n";
  9340. }
  9341. return TINYEXR_ERROR_INVALID_DATA;
  9342. }
  9343. bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety.
  9344. if (exr_header->tiled) {
  9345. size_t num_tiles = offsets.size(); // = # of blocks
  9346. exr_image->tiles = static_cast<EXRTile *>(
  9347. calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles)));
  9348. for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
  9349. // Allocate memory for each tile.
  9350. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
  9351. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9352. exr_header->tile_size_x, exr_header->tile_size_y);
  9353. // 16 byte: tile coordinates
  9354. // 4 byte : data size
  9355. // ~ : data(uncompressed or compressed)
  9356. if (offsets[tile_idx] + sizeof(int) * 5 > size) {
  9357. if (err) {
  9358. (*err) += "Insufficient data size.\n";
  9359. }
  9360. return TINYEXR_ERROR_INVALID_DATA;
  9361. }
  9362. size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));
  9363. const unsigned char *data_ptr =
  9364. reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]);
  9365. int tile_coordinates[4];
  9366. memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
  9367. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0]));
  9368. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1]));
  9369. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2]));
  9370. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3]));
  9371. // @todo{ LoD }
  9372. if (tile_coordinates[2] != 0) {
  9373. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9374. }
  9375. if (tile_coordinates[3] != 0) {
  9376. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9377. }
  9378. int data_len;
  9379. memcpy(&data_len, data_ptr + 16,
  9380. sizeof(int)); // 16 = sizeof(tile_coordinates)
  9381. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9382. if (data_len < 4 || size_t(data_len) > data_size) {
  9383. if (err) {
  9384. (*err) += "Insufficient data length.\n";
  9385. }
  9386. return TINYEXR_ERROR_INVALID_DATA;
  9387. }
  9388. // Move to data addr: 20 = 16 + 4;
  9389. data_ptr += 20;
  9390. tinyexr::DecodeTiledPixelData(
  9391. exr_image->tiles[tile_idx].images,
  9392. &(exr_image->tiles[tile_idx].width),
  9393. &(exr_image->tiles[tile_idx].height),
  9394. exr_header->requested_pixel_types, data_ptr,
  9395. static_cast<size_t>(data_len), exr_header->compression_type,
  9396. exr_header->line_order, data_width, data_height, tile_coordinates[0],
  9397. tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,
  9398. static_cast<size_t>(pixel_data_size),
  9399. static_cast<size_t>(exr_header->num_custom_attributes),
  9400. exr_header->custom_attributes,
  9401. static_cast<size_t>(exr_header->num_channels), exr_header->channels,
  9402. channel_offset_list);
  9403. exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
  9404. exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
  9405. exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
  9406. exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
  9407. exr_image->num_tiles = static_cast<int>(num_tiles);
  9408. }
  9409. } else { // scanline format
  9410. exr_image->images = tinyexr::AllocateImage(
  9411. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9412. data_width, data_height);
  9413. #ifdef _OPENMP
  9414. #pragma omp parallel for
  9415. #endif
  9416. for (int y = 0; y < static_cast<int>(num_blocks); y++) {
  9417. size_t y_idx = static_cast<size_t>(y);
  9418. if (offsets[y_idx] + sizeof(int) * 2 > size) {
  9419. invalid_data = true;
  9420. } else {
  9421. // 4 byte: scan line
  9422. // 4 byte: data size
  9423. // ~ : pixel data(uncompressed or compressed)
  9424. size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));
  9425. const unsigned char *data_ptr =
  9426. reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);
  9427. int line_no;
  9428. memcpy(&line_no, data_ptr, sizeof(int));
  9429. int data_len;
  9430. memcpy(&data_len, data_ptr + 4, sizeof(int));
  9431. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  9432. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9433. if (size_t(data_len) > data_size) {
  9434. invalid_data = true;
  9435. } else {
  9436. int end_line_no = (std::min)(line_no + num_scanline_blocks,
  9437. (exr_header->data_window[3] + 1));
  9438. int num_lines = end_line_no - line_no;
  9439. // assert(num_lines > 0);
  9440. if (num_lines <= 0) {
  9441. invalid_data = true;
  9442. } else {
  9443. // Move to data addr: 8 = 4 + 4;
  9444. data_ptr += 8;
  9445. // Adjust line_no with data_window.bmin.y
  9446. line_no -= exr_header->data_window[1];
  9447. if (line_no < 0) {
  9448. invalid_data = true;
  9449. } else {
  9450. if (!tinyexr::DecodePixelData(
  9451. exr_image->images, exr_header->requested_pixel_types,
  9452. data_ptr, static_cast<size_t>(data_len),
  9453. exr_header->compression_type, exr_header->line_order,
  9454. data_width, data_height, data_width, y, line_no,
  9455. num_lines, static_cast<size_t>(pixel_data_size),
  9456. static_cast<size_t>(exr_header->num_custom_attributes),
  9457. exr_header->custom_attributes,
  9458. static_cast<size_t>(exr_header->num_channels),
  9459. exr_header->channels, channel_offset_list)) {
  9460. invalid_data = true;
  9461. }
  9462. }
  9463. }
  9464. }
  9465. }
  9466. } // omp parallel
  9467. }
  9468. if (invalid_data) {
  9469. return TINYEXR_ERROR_INVALID_DATA;
  9470. }
  9471. // Overwrite `pixel_type` with `requested_pixel_type`.
  9472. {
  9473. for (int c = 0; c < exr_header->num_channels; c++) {
  9474. exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
  9475. }
  9476. }
  9477. {
  9478. exr_image->num_channels = num_channels;
  9479. exr_image->width = data_width;
  9480. exr_image->height = data_height;
  9481. }
  9482. return TINYEXR_SUCCESS;
  9483. }
  9484. static bool ReconstructLineOffsets(
  9485. std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,
  9486. const unsigned char *head, const unsigned char *marker, const size_t size) {
  9487. assert(head < marker);
  9488. assert(offsets->size() == n);
  9489. for (size_t i = 0; i < n; i++) {
  9490. size_t offset = static_cast<size_t>(marker - head);
  9491. // Offset should not exceed whole EXR file/data size.
  9492. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
  9493. return false;
  9494. }
  9495. int y;
  9496. unsigned int data_len;
  9497. memcpy(&y, marker, sizeof(int));
  9498. memcpy(&data_len, marker + 4, sizeof(unsigned int));
  9499. if (data_len >= size) {
  9500. return false;
  9501. }
  9502. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  9503. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9504. (*offsets)[i] = offset;
  9505. marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
  9506. }
  9507. return true;
  9508. }
  9509. static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,
  9510. const unsigned char *head,
  9511. const unsigned char *marker, const size_t size,
  9512. const char **err) {
  9513. if (exr_image == NULL || exr_header == NULL || head == NULL ||
  9514. marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
  9515. tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
  9516. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9517. }
  9518. int num_scanline_blocks = 1;
  9519. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9520. num_scanline_blocks = 16;
  9521. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9522. num_scanline_blocks = 32;
  9523. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9524. num_scanline_blocks = 16;
  9525. }
  9526. int data_width = exr_header->data_window[2] - exr_header->data_window[0];
  9527. if (data_width >= std::numeric_limits<int>::max()) {
  9528. // Issue 63
  9529. tinyexr::SetErrorMessage("Invalid data window value", err);
  9530. return TINYEXR_ERROR_INVALID_DATA;
  9531. }
  9532. data_width++;
  9533. int data_height = exr_header->data_window[3] - exr_header->data_window[1];
  9534. if (data_height >= std::numeric_limits<int>::max()) {
  9535. tinyexr::SetErrorMessage("Invalid data height value", err);
  9536. return TINYEXR_ERROR_INVALID_DATA;
  9537. }
  9538. data_height++;
  9539. if ((data_width < 0) || (data_height < 0)) {
  9540. tinyexr::SetErrorMessage("data window or data height is negative.", err);
  9541. return TINYEXR_ERROR_INVALID_DATA;
  9542. }
  9543. // Read offset tables.
  9544. size_t num_blocks = 0;
  9545. if (exr_header->chunk_count > 0) {
  9546. // Use `chunkCount` attribute.
  9547. num_blocks = static_cast<size_t>(exr_header->chunk_count);
  9548. } else if (exr_header->tiled) {
  9549. // @todo { LoD }
  9550. size_t num_x_tiles = static_cast<size_t>(data_width) /
  9551. static_cast<size_t>(exr_header->tile_size_x);
  9552. if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) <
  9553. static_cast<size_t>(data_width)) {
  9554. num_x_tiles++;
  9555. }
  9556. size_t num_y_tiles = static_cast<size_t>(data_height) /
  9557. static_cast<size_t>(exr_header->tile_size_y);
  9558. if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) <
  9559. static_cast<size_t>(data_height)) {
  9560. num_y_tiles++;
  9561. }
  9562. num_blocks = num_x_tiles * num_y_tiles;
  9563. } else {
  9564. num_blocks = static_cast<size_t>(data_height) /
  9565. static_cast<size_t>(num_scanline_blocks);
  9566. if (num_blocks * static_cast<size_t>(num_scanline_blocks) <
  9567. static_cast<size_t>(data_height)) {
  9568. num_blocks++;
  9569. }
  9570. }
  9571. std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks);
  9572. for (size_t y = 0; y < num_blocks; y++) {
  9573. tinyexr::tinyexr_uint64 offset;
  9574. // Issue #81
  9575. if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
  9576. tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
  9577. return TINYEXR_ERROR_INVALID_DATA;
  9578. }
  9579. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  9580. tinyexr::swap8(&offset);
  9581. if (offset >= size) {
  9582. tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
  9583. return TINYEXR_ERROR_INVALID_DATA;
  9584. }
  9585. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  9586. offsets[y] = offset;
  9587. }
  9588. // If line offsets are invalid, we try to reconstruct it.
  9589. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
  9590. for (size_t y = 0; y < num_blocks; y++) {
  9591. if (offsets[y] <= 0) {
  9592. // TODO(syoyo) Report as warning?
  9593. // if (err) {
  9594. // stringstream ss;
  9595. // ss << "Incomplete lineOffsets." << std::endl;
  9596. // (*err) += ss.str();
  9597. //}
  9598. bool ret =
  9599. ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
  9600. if (ret) {
  9601. // OK
  9602. break;
  9603. } else {
  9604. tinyexr::SetErrorMessage(
  9605. "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
  9606. return TINYEXR_ERROR_INVALID_DATA;
  9607. }
  9608. }
  9609. }
  9610. {
  9611. std::string e;
  9612. int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e);
  9613. if (ret != TINYEXR_SUCCESS) {
  9614. if (!e.empty()) {
  9615. tinyexr::SetErrorMessage(e, err);
  9616. }
  9617. // release memory(if exists)
  9618. if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
  9619. for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
  9620. if (exr_image->images[c]) {
  9621. free(exr_image->images[c]);
  9622. exr_image->images[c] = NULL;
  9623. }
  9624. }
  9625. free(exr_image->images);
  9626. exr_image->images = NULL;
  9627. }
  9628. }
  9629. return ret;
  9630. }
  9631. }
  9632. } // namespace tinyexr
  9633. int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
  9634. const char **err) {
  9635. if (out_rgba == NULL) {
  9636. tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
  9637. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9638. }
  9639. EXRVersion exr_version;
  9640. EXRImage exr_image;
  9641. EXRHeader exr_header;
  9642. InitEXRHeader(&exr_header);
  9643. InitEXRImage(&exr_image);
  9644. {
  9645. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  9646. if (ret != TINYEXR_SUCCESS) {
  9647. tinyexr::SetErrorMessage("Invalid EXR header.", err);
  9648. return ret;
  9649. }
  9650. if (exr_version.multipart || exr_version.non_image) {
  9651. tinyexr::SetErrorMessage(
  9652. "Loading multipart or DeepImage is not supported in LoadEXR() API",
  9653. err);
  9654. return TINYEXR_ERROR_INVALID_DATA; // @fixme.
  9655. }
  9656. }
  9657. {
  9658. int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
  9659. if (ret != TINYEXR_SUCCESS) {
  9660. FreeEXRHeader(&exr_header);
  9661. return ret;
  9662. }
  9663. }
  9664. // Read HALF channel as FLOAT.
  9665. for (int i = 0; i < exr_header.num_channels; i++) {
  9666. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  9667. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  9668. }
  9669. }
  9670. {
  9671. int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
  9672. if (ret != TINYEXR_SUCCESS) {
  9673. FreeEXRHeader(&exr_header);
  9674. return ret;
  9675. }
  9676. }
  9677. // RGBA
  9678. int idxR = -1;
  9679. int idxG = -1;
  9680. int idxB = -1;
  9681. int idxA = -1;
  9682. for (int c = 0; c < exr_header.num_channels; c++) {
  9683. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  9684. idxR = c;
  9685. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  9686. idxG = c;
  9687. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  9688. idxB = c;
  9689. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  9690. idxA = c;
  9691. }
  9692. }
  9693. if (exr_header.num_channels == 1) {
  9694. // Grayscale channel only.
  9695. (*out_rgba) = reinterpret_cast<float *>(
  9696. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9697. static_cast<size_t>(exr_image.height)));
  9698. if (exr_header.tiled) {
  9699. // todo.implement this
  9700. for (int it = 0; it < exr_image.num_tiles; it++) {
  9701. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9702. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9703. const int ii =
  9704. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9705. const int jj =
  9706. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9707. const int idx = ii + jj * exr_image.width;
  9708. // out of region check.
  9709. if (ii >= exr_image.width) {
  9710. continue;
  9711. }
  9712. if (jj >= exr_image.height) {
  9713. continue;
  9714. }
  9715. const int srcIdx = i + j * exr_header.tile_size_x;
  9716. unsigned char **src = exr_image.tiles[it].images;
  9717. (*out_rgba)[4 * idx + 0] =
  9718. reinterpret_cast<float **>(src)[0][srcIdx];
  9719. (*out_rgba)[4 * idx + 1] =
  9720. reinterpret_cast<float **>(src)[0][srcIdx];
  9721. (*out_rgba)[4 * idx + 2] =
  9722. reinterpret_cast<float **>(src)[0][srcIdx];
  9723. (*out_rgba)[4 * idx + 3] =
  9724. reinterpret_cast<float **>(src)[0][srcIdx];
  9725. }
  9726. }
  9727. }
  9728. } else {
  9729. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9730. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  9731. (*out_rgba)[4 * i + 0] = val;
  9732. (*out_rgba)[4 * i + 1] = val;
  9733. (*out_rgba)[4 * i + 2] = val;
  9734. (*out_rgba)[4 * i + 3] = val;
  9735. }
  9736. }
  9737. } else {
  9738. // Assume RGB(A)
  9739. if (idxR == -1) {
  9740. tinyexr::SetErrorMessage("R channel not found", err);
  9741. // @todo { free exr_image }
  9742. FreeEXRHeader(&exr_header);
  9743. return TINYEXR_ERROR_INVALID_DATA;
  9744. }
  9745. if (idxG == -1) {
  9746. tinyexr::SetErrorMessage("G channel not found", err);
  9747. // @todo { free exr_image }
  9748. FreeEXRHeader(&exr_header);
  9749. return TINYEXR_ERROR_INVALID_DATA;
  9750. }
  9751. if (idxB == -1) {
  9752. tinyexr::SetErrorMessage("B channel not found", err);
  9753. // @todo { free exr_image }
  9754. FreeEXRHeader(&exr_header);
  9755. return TINYEXR_ERROR_INVALID_DATA;
  9756. }
  9757. (*out_rgba) = reinterpret_cast<float *>(
  9758. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9759. static_cast<size_t>(exr_image.height)));
  9760. if (exr_header.tiled) {
  9761. for (int it = 0; it < exr_image.num_tiles; it++) {
  9762. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9763. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9764. const int ii =
  9765. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9766. const int jj =
  9767. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9768. const int idx = ii + jj * exr_image.width;
  9769. // out of region check.
  9770. if (ii >= exr_image.width) {
  9771. continue;
  9772. }
  9773. if (jj >= exr_image.height) {
  9774. continue;
  9775. }
  9776. const int srcIdx = i + j * exr_header.tile_size_x;
  9777. unsigned char **src = exr_image.tiles[it].images;
  9778. (*out_rgba)[4 * idx + 0] =
  9779. reinterpret_cast<float **>(src)[idxR][srcIdx];
  9780. (*out_rgba)[4 * idx + 1] =
  9781. reinterpret_cast<float **>(src)[idxG][srcIdx];
  9782. (*out_rgba)[4 * idx + 2] =
  9783. reinterpret_cast<float **>(src)[idxB][srcIdx];
  9784. if (idxA != -1) {
  9785. (*out_rgba)[4 * idx + 3] =
  9786. reinterpret_cast<float **>(src)[idxA][srcIdx];
  9787. } else {
  9788. (*out_rgba)[4 * idx + 3] = 1.0;
  9789. }
  9790. }
  9791. }
  9792. }
  9793. } else {
  9794. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9795. (*out_rgba)[4 * i + 0] =
  9796. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  9797. (*out_rgba)[4 * i + 1] =
  9798. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  9799. (*out_rgba)[4 * i + 2] =
  9800. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  9801. if (idxA != -1) {
  9802. (*out_rgba)[4 * i + 3] =
  9803. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  9804. } else {
  9805. (*out_rgba)[4 * i + 3] = 1.0;
  9806. }
  9807. }
  9808. }
  9809. }
  9810. (*width) = exr_image.width;
  9811. (*height) = exr_image.height;
  9812. FreeEXRHeader(&exr_header);
  9813. FreeEXRImage(&exr_image);
  9814. return TINYEXR_SUCCESS;
  9815. }
  9816. int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,
  9817. const unsigned char *memory, size_t size,
  9818. const char **err) {
  9819. if (memory == NULL || exr_header == NULL) {
  9820. tinyexr::SetErrorMessage(
  9821. "Invalid argument. `memory` or `exr_header` argument is null in "
  9822. "ParseEXRHeaderFromMemory()",
  9823. err);
  9824. // Invalid argument
  9825. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9826. }
  9827. if (size < tinyexr::kEXRVersionSize) {
  9828. tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
  9829. return TINYEXR_ERROR_INVALID_DATA;
  9830. }
  9831. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  9832. size_t marker_size = size - tinyexr::kEXRVersionSize;
  9833. tinyexr::HeaderInfo info;
  9834. info.clear();
  9835. std::string err_str;
  9836. int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
  9837. if (ret != TINYEXR_SUCCESS) {
  9838. if (err && !err_str.empty()) {
  9839. tinyexr::SetErrorMessage(err_str, err);
  9840. }
  9841. }
  9842. ConvertHeader(exr_header, info);
  9843. // transfoer `tiled` from version.
  9844. exr_header->tiled = version->tiled;
  9845. return ret;
  9846. }
  9847. int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  9848. const unsigned char *memory, size_t size,
  9849. const char **err) {
  9850. if (out_rgba == NULL || memory == NULL) {
  9851. tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
  9852. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9853. }
  9854. EXRVersion exr_version;
  9855. EXRImage exr_image;
  9856. EXRHeader exr_header;
  9857. InitEXRHeader(&exr_header);
  9858. int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
  9859. if (ret != TINYEXR_SUCCESS) {
  9860. tinyexr::SetErrorMessage("Failed to parse EXR version", err);
  9861. return ret;
  9862. }
  9863. ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
  9864. if (ret != TINYEXR_SUCCESS) {
  9865. return ret;
  9866. }
  9867. // Read HALF channel as FLOAT.
  9868. for (int i = 0; i < exr_header.num_channels; i++) {
  9869. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  9870. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  9871. }
  9872. }
  9873. InitEXRImage(&exr_image);
  9874. ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
  9875. if (ret != TINYEXR_SUCCESS) {
  9876. return ret;
  9877. }
  9878. // RGBA
  9879. int idxR = -1;
  9880. int idxG = -1;
  9881. int idxB = -1;
  9882. int idxA = -1;
  9883. for (int c = 0; c < exr_header.num_channels; c++) {
  9884. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  9885. idxR = c;
  9886. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  9887. idxG = c;
  9888. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  9889. idxB = c;
  9890. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  9891. idxA = c;
  9892. }
  9893. }
  9894. if (idxR == -1) {
  9895. tinyexr::SetErrorMessage("R channel not found", err);
  9896. // @todo { free exr_image }
  9897. return TINYEXR_ERROR_INVALID_DATA;
  9898. }
  9899. if (idxG == -1) {
  9900. tinyexr::SetErrorMessage("G channel not found", err);
  9901. // @todo { free exr_image }
  9902. return TINYEXR_ERROR_INVALID_DATA;
  9903. }
  9904. if (idxB == -1) {
  9905. tinyexr::SetErrorMessage("B channel not found", err);
  9906. // @todo { free exr_image }
  9907. return TINYEXR_ERROR_INVALID_DATA;
  9908. }
  9909. (*out_rgba) = reinterpret_cast<float *>(
  9910. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9911. static_cast<size_t>(exr_image.height)));
  9912. if (exr_header.tiled) {
  9913. for (int it = 0; it < exr_image.num_tiles; it++) {
  9914. for (int j = 0; j < exr_header.tile_size_y; j++)
  9915. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9916. const int ii =
  9917. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9918. const int jj =
  9919. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9920. const int idx = ii + jj * exr_image.width;
  9921. // out of region check.
  9922. if (ii >= exr_image.width) {
  9923. continue;
  9924. }
  9925. if (jj >= exr_image.height) {
  9926. continue;
  9927. }
  9928. const int srcIdx = i + j * exr_header.tile_size_x;
  9929. unsigned char **src = exr_image.tiles[it].images;
  9930. (*out_rgba)[4 * idx + 0] =
  9931. reinterpret_cast<float **>(src)[idxR][srcIdx];
  9932. (*out_rgba)[4 * idx + 1] =
  9933. reinterpret_cast<float **>(src)[idxG][srcIdx];
  9934. (*out_rgba)[4 * idx + 2] =
  9935. reinterpret_cast<float **>(src)[idxB][srcIdx];
  9936. if (idxA != -1) {
  9937. (*out_rgba)[4 * idx + 3] =
  9938. reinterpret_cast<float **>(src)[idxA][srcIdx];
  9939. } else {
  9940. (*out_rgba)[4 * idx + 3] = 1.0;
  9941. }
  9942. }
  9943. }
  9944. } else {
  9945. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9946. (*out_rgba)[4 * i + 0] =
  9947. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  9948. (*out_rgba)[4 * i + 1] =
  9949. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  9950. (*out_rgba)[4 * i + 2] =
  9951. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  9952. if (idxA != -1) {
  9953. (*out_rgba)[4 * i + 3] =
  9954. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  9955. } else {
  9956. (*out_rgba)[4 * i + 3] = 1.0;
  9957. }
  9958. }
  9959. }
  9960. (*width) = exr_image.width;
  9961. (*height) = exr_image.height;
  9962. FreeEXRHeader(&exr_header);
  9963. FreeEXRImage(&exr_image);
  9964. return TINYEXR_SUCCESS;
  9965. }
  9966. int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,
  9967. const char *filename, const char **err) {
  9968. if (exr_image == NULL) {
  9969. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
  9970. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9971. }
  9972. #ifdef _WIN32
  9973. FILE *fp = NULL;
  9974. fopen_s(&fp, filename, "rb");
  9975. #else
  9976. FILE *fp = fopen(filename, "rb");
  9977. #endif
  9978. if (!fp) {
  9979. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  9980. return TINYEXR_ERROR_CANT_OPEN_FILE;
  9981. }
  9982. size_t filesize;
  9983. // Compute size
  9984. fseek(fp, 0, SEEK_END);
  9985. filesize = static_cast<size_t>(ftell(fp));
  9986. fseek(fp, 0, SEEK_SET);
  9987. if (filesize < 16) {
  9988. tinyexr::SetErrorMessage("File size too short " + std::string(filename),
  9989. err);
  9990. return TINYEXR_ERROR_INVALID_FILE;
  9991. }
  9992. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  9993. {
  9994. size_t ret;
  9995. ret = fread(&buf[0], 1, filesize, fp);
  9996. assert(ret == filesize);
  9997. fclose(fp);
  9998. (void)ret;
  9999. }
  10000. return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize,
  10001. err);
  10002. }
  10003. int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,
  10004. const unsigned char *memory, const size_t size,
  10005. const char **err) {
  10006. if (exr_image == NULL || memory == NULL ||
  10007. (size < tinyexr::kEXRVersionSize)) {
  10008. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
  10009. err);
  10010. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10011. }
  10012. if (exr_header->header_len == 0) {
  10013. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  10014. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10015. }
  10016. const unsigned char *head = memory;
  10017. const unsigned char *marker = reinterpret_cast<const unsigned char *>(
  10018. memory + exr_header->header_len +
  10019. 8); // +8 for magic number + version header.
  10020. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
  10021. err);
  10022. }
  10023. size_t SaveEXRImageToMemory(const EXRImage *exr_image,
  10024. const EXRHeader *exr_header,
  10025. unsigned char **memory_out, const char **err) {
  10026. if (exr_image == NULL || memory_out == NULL ||
  10027. exr_header->compression_type < 0) {
  10028. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err);
  10029. return 0;
  10030. }
  10031. #if !TINYEXR_USE_PIZ
  10032. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10033. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10034. err);
  10035. return 0;
  10036. }
  10037. #endif
  10038. #if !TINYEXR_USE_ZFP
  10039. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10040. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10041. err);
  10042. return 0;
  10043. }
  10044. #endif
  10045. #if TINYEXR_USE_ZFP
  10046. for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) {
  10047. if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) {
  10048. tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
  10049. err);
  10050. return 0;
  10051. }
  10052. }
  10053. #endif
  10054. std::vector<unsigned char> memory;
  10055. // Header
  10056. {
  10057. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10058. memory.insert(memory.end(), header, header + 4);
  10059. }
  10060. // Version, scanline.
  10061. {
  10062. char marker[] = {2, 0, 0, 0};
  10063. /* @todo
  10064. if (exr_header->tiled) {
  10065. marker[1] |= 0x2;
  10066. }
  10067. if (exr_header->long_name) {
  10068. marker[1] |= 0x4;
  10069. }
  10070. if (exr_header->non_image) {
  10071. marker[1] |= 0x8;
  10072. }
  10073. if (exr_header->multipart) {
  10074. marker[1] |= 0x10;
  10075. }
  10076. */
  10077. memory.insert(memory.end(), marker, marker + 4);
  10078. }
  10079. int num_scanlines = 1;
  10080. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10081. num_scanlines = 16;
  10082. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10083. num_scanlines = 32;
  10084. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10085. num_scanlines = 16;
  10086. }
  10087. // Write attributes.
  10088. std::vector<tinyexr::ChannelInfo> channels;
  10089. {
  10090. std::vector<unsigned char> data;
  10091. for (int c = 0; c < exr_header->num_channels; c++) {
  10092. tinyexr::ChannelInfo info;
  10093. info.p_linear = 0;
  10094. info.pixel_type = exr_header->requested_pixel_types[c];
  10095. info.x_sampling = 1;
  10096. info.y_sampling = 1;
  10097. info.name = std::string(exr_header->channels[c].name);
  10098. channels.push_back(info);
  10099. }
  10100. tinyexr::WriteChannelInfo(data, channels);
  10101. tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
  10102. static_cast<int>(data.size()));
  10103. }
  10104. {
  10105. int comp = exr_header->compression_type;
  10106. tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp));
  10107. tinyexr::WriteAttributeToMemory(
  10108. &memory, "compression", "compression",
  10109. reinterpret_cast<const unsigned char *>(&comp), 1);
  10110. }
  10111. {
  10112. int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1};
  10113. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0]));
  10114. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1]));
  10115. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2]));
  10116. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3]));
  10117. tinyexr::WriteAttributeToMemory(
  10118. &memory, "dataWindow", "box2i",
  10119. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10120. tinyexr::WriteAttributeToMemory(
  10121. &memory, "displayWindow", "box2i",
  10122. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10123. }
  10124. {
  10125. unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
  10126. tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
  10127. &line_order, 1);
  10128. }
  10129. {
  10130. float aspectRatio = 1.0f;
  10131. tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
  10132. tinyexr::WriteAttributeToMemory(
  10133. &memory, "pixelAspectRatio", "float",
  10134. reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
  10135. }
  10136. {
  10137. float center[2] = {0.0f, 0.0f};
  10138. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0]));
  10139. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1]));
  10140. tinyexr::WriteAttributeToMemory(
  10141. &memory, "screenWindowCenter", "v2f",
  10142. reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float));
  10143. }
  10144. {
  10145. float w = static_cast<float>(exr_image->width);
  10146. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10147. tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
  10148. reinterpret_cast<const unsigned char *>(&w),
  10149. sizeof(float));
  10150. }
  10151. // Custom attributes
  10152. if (exr_header->num_custom_attributes > 0) {
  10153. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  10154. tinyexr::WriteAttributeToMemory(
  10155. &memory, exr_header->custom_attributes[i].name,
  10156. exr_header->custom_attributes[i].type,
  10157. reinterpret_cast<const unsigned char *>(
  10158. exr_header->custom_attributes[i].value),
  10159. exr_header->custom_attributes[i].size);
  10160. }
  10161. }
  10162. { // end of header
  10163. unsigned char e = 0;
  10164. memory.push_back(e);
  10165. }
  10166. int num_blocks = exr_image->height / num_scanlines;
  10167. if (num_blocks * num_scanlines < exr_image->height) {
  10168. num_blocks++;
  10169. }
  10170. std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks));
  10171. size_t headerSize = memory.size();
  10172. tinyexr::tinyexr_uint64 offset =
  10173. headerSize +
  10174. static_cast<size_t>(num_blocks) *
  10175. sizeof(
  10176. tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable)
  10177. std::vector<std::vector<unsigned char> > data_list(
  10178. static_cast<size_t>(num_blocks));
  10179. std::vector<size_t> channel_offset_list(
  10180. static_cast<size_t>(exr_header->num_channels));
  10181. int pixel_data_size = 0;
  10182. size_t channel_offset = 0;
  10183. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10184. channel_offset_list[c] = channel_offset;
  10185. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10186. pixel_data_size += sizeof(unsigned short);
  10187. channel_offset += sizeof(unsigned short);
  10188. } else if (exr_header->requested_pixel_types[c] ==
  10189. TINYEXR_PIXELTYPE_FLOAT) {
  10190. pixel_data_size += sizeof(float);
  10191. channel_offset += sizeof(float);
  10192. } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10193. pixel_data_size += sizeof(unsigned int);
  10194. channel_offset += sizeof(unsigned int);
  10195. } else {
  10196. assert(0);
  10197. }
  10198. }
  10199. #if TINYEXR_USE_ZFP
  10200. tinyexr::ZFPCompressionParam zfp_compression_param;
  10201. // Use ZFP compression parameter from custom attributes(if such a parameter
  10202. // exists)
  10203. {
  10204. bool ret = tinyexr::FindZFPCompressionParam(
  10205. &zfp_compression_param, exr_header->custom_attributes,
  10206. exr_header->num_custom_attributes);
  10207. if (!ret) {
  10208. // Use predefined compression parameter.
  10209. zfp_compression_param.type = 0;
  10210. zfp_compression_param.rate = 2;
  10211. }
  10212. }
  10213. #endif
  10214. // Use signed int since some OpenMP compiler doesn't allow unsigned type for
  10215. // `parallel for`
  10216. #ifdef _OPENMP
  10217. #pragma omp parallel for
  10218. #endif
  10219. for (int i = 0; i < num_blocks; i++) {
  10220. size_t ii = static_cast<size_t>(i);
  10221. int start_y = num_scanlines * i;
  10222. int endY = (std::min)(num_scanlines * (i + 1), exr_image->height);
  10223. int h = endY - start_y;
  10224. std::vector<unsigned char> buf(
  10225. static_cast<size_t>(exr_image->width * h * pixel_data_size));
  10226. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10227. if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10228. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10229. for (int y = 0; y < h; y++) {
  10230. // Assume increasing Y
  10231. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10232. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10233. channel_offset_list[c] *
  10234. static_cast<size_t>(exr_image->width)));
  10235. for (int x = 0; x < exr_image->width; x++) {
  10236. tinyexr::FP16 h16;
  10237. h16.u = reinterpret_cast<unsigned short **>(
  10238. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10239. tinyexr::FP32 f32 = half_to_float(h16);
  10240. tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f));
  10241. // line_ptr[x] = f32.f;
  10242. tinyexr::cpy4(line_ptr + x, &(f32.f));
  10243. }
  10244. }
  10245. } else if (exr_header->requested_pixel_types[c] ==
  10246. TINYEXR_PIXELTYPE_HALF) {
  10247. for (int y = 0; y < h; y++) {
  10248. // Assume increasing Y
  10249. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10250. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10251. exr_image->width) +
  10252. channel_offset_list[c] *
  10253. static_cast<size_t>(exr_image->width)));
  10254. for (int x = 0; x < exr_image->width; x++) {
  10255. unsigned short val = reinterpret_cast<unsigned short **>(
  10256. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10257. tinyexr::swap2(&val);
  10258. // line_ptr[x] = val;
  10259. tinyexr::cpy2(line_ptr + x, &val);
  10260. }
  10261. }
  10262. } else {
  10263. assert(0);
  10264. }
  10265. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10266. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10267. for (int y = 0; y < h; y++) {
  10268. // Assume increasing Y
  10269. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10270. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10271. exr_image->width) +
  10272. channel_offset_list[c] *
  10273. static_cast<size_t>(exr_image->width)));
  10274. for (int x = 0; x < exr_image->width; x++) {
  10275. tinyexr::FP32 f32;
  10276. f32.f = reinterpret_cast<float **>(
  10277. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10278. tinyexr::FP16 h16;
  10279. h16 = float_to_half_full(f32);
  10280. tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));
  10281. // line_ptr[x] = h16.u;
  10282. tinyexr::cpy2(line_ptr + x, &(h16.u));
  10283. }
  10284. }
  10285. } else if (exr_header->requested_pixel_types[c] ==
  10286. TINYEXR_PIXELTYPE_FLOAT) {
  10287. for (int y = 0; y < h; y++) {
  10288. // Assume increasing Y
  10289. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10290. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10291. channel_offset_list[c] *
  10292. static_cast<size_t>(exr_image->width)));
  10293. for (int x = 0; x < exr_image->width; x++) {
  10294. float val = reinterpret_cast<float **>(
  10295. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10296. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  10297. // line_ptr[x] = val;
  10298. tinyexr::cpy4(line_ptr + x, &val);
  10299. }
  10300. }
  10301. } else {
  10302. assert(0);
  10303. }
  10304. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10305. for (int y = 0; y < h; y++) {
  10306. // Assume increasing Y
  10307. unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(
  10308. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10309. channel_offset_list[c] * static_cast<size_t>(exr_image->width)));
  10310. for (int x = 0; x < exr_image->width; x++) {
  10311. unsigned int val = reinterpret_cast<unsigned int **>(
  10312. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10313. tinyexr::swap4(&val);
  10314. // line_ptr[x] = val;
  10315. tinyexr::cpy4(line_ptr + x, &val);
  10316. }
  10317. }
  10318. }
  10319. }
  10320. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  10321. // 4 byte: scan line
  10322. // 4 byte: data size
  10323. // ~ : pixel data(uncompressed)
  10324. std::vector<unsigned char> header(8);
  10325. unsigned int data_len = static_cast<unsigned int>(buf.size());
  10326. memcpy(&header.at(0), &start_y, sizeof(int));
  10327. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10328. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10329. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10330. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10331. data_list[ii].insert(data_list[ii].end(), buf.begin(),
  10332. buf.begin() + data_len);
  10333. } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10334. (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10335. #if TINYEXR_USE_MINIZ
  10336. std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound(
  10337. static_cast<unsigned long>(buf.size())));
  10338. #else
  10339. std::vector<unsigned char> block(
  10340. compressBound(static_cast<uLong>(buf.size())));
  10341. #endif
  10342. tinyexr::tinyexr_uint64 outSize = block.size();
  10343. tinyexr::CompressZip(&block.at(0), outSize,
  10344. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10345. static_cast<unsigned long>(buf.size()));
  10346. // 4 byte: scan line
  10347. // 4 byte: data size
  10348. // ~ : pixel data(compressed)
  10349. std::vector<unsigned char> header(8);
  10350. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10351. memcpy(&header.at(0), &start_y, sizeof(int));
  10352. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10353. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10354. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10355. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10356. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10357. block.begin() + data_len);
  10358. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  10359. // (buf.size() * 3) / 2 would be enough.
  10360. std::vector<unsigned char> block((buf.size() * 3) / 2);
  10361. tinyexr::tinyexr_uint64 outSize = block.size();
  10362. tinyexr::CompressRle(&block.at(0), outSize,
  10363. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10364. static_cast<unsigned long>(buf.size()));
  10365. // 4 byte: scan line
  10366. // 4 byte: data size
  10367. // ~ : pixel data(compressed)
  10368. std::vector<unsigned char> header(8);
  10369. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10370. memcpy(&header.at(0), &start_y, sizeof(int));
  10371. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10372. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10373. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10374. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10375. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10376. block.begin() + data_len);
  10377. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10378. #if TINYEXR_USE_PIZ
  10379. unsigned int bufLen =
  10380. 8192 + static_cast<unsigned int>(
  10381. 2 * static_cast<unsigned int>(
  10382. buf.size())); // @fixme { compute good bound. }
  10383. std::vector<unsigned char> block(bufLen);
  10384. unsigned int outSize = static_cast<unsigned int>(block.size());
  10385. CompressPiz(&block.at(0), &outSize,
  10386. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10387. buf.size(), channels, exr_image->width, h);
  10388. // 4 byte: scan line
  10389. // 4 byte: data size
  10390. // ~ : pixel data(compressed)
  10391. std::vector<unsigned char> header(8);
  10392. unsigned int data_len = outSize;
  10393. memcpy(&header.at(0), &start_y, sizeof(int));
  10394. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10395. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10396. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10397. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10398. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10399. block.begin() + data_len);
  10400. #else
  10401. assert(0);
  10402. #endif
  10403. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10404. #if TINYEXR_USE_ZFP
  10405. std::vector<unsigned char> block;
  10406. unsigned int outSize;
  10407. tinyexr::CompressZfp(
  10408. &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),
  10409. exr_image->width, h, exr_header->num_channels, zfp_compression_param);
  10410. // 4 byte: scan line
  10411. // 4 byte: data size
  10412. // ~ : pixel data(compressed)
  10413. std::vector<unsigned char> header(8);
  10414. unsigned int data_len = outSize;
  10415. memcpy(&header.at(0), &start_y, sizeof(int));
  10416. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10417. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10418. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10419. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10420. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10421. block.begin() + data_len);
  10422. #else
  10423. assert(0);
  10424. #endif
  10425. } else {
  10426. assert(0);
  10427. }
  10428. } // omp parallel
  10429. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10430. offsets[i] = offset;
  10431. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));
  10432. offset += data_list[i].size();
  10433. }
  10434. size_t totalSize = static_cast<size_t>(offset);
  10435. {
  10436. memory.insert(
  10437. memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)),
  10438. reinterpret_cast<unsigned char *>(&offsets.at(0)) +
  10439. sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks));
  10440. }
  10441. if ( memory.size() == 0 ) {
  10442. tinyexr::SetErrorMessage("Output memory size is zero", err);
  10443. return 0;
  10444. }
  10445. (*memory_out) = static_cast<unsigned char *>(malloc(totalSize));
  10446. memcpy((*memory_out), &memory.at(0), memory.size());
  10447. unsigned char *memory_ptr = *memory_out + memory.size();
  10448. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10449. memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size());
  10450. memory_ptr += data_list[i].size();
  10451. }
  10452. return totalSize; // OK
  10453. }
  10454. int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,
  10455. const char *filename, const char **err) {
  10456. if (exr_image == NULL || filename == NULL ||
  10457. exr_header->compression_type < 0) {
  10458. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
  10459. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10460. }
  10461. #if !TINYEXR_USE_PIZ
  10462. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10463. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10464. err);
  10465. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10466. }
  10467. #endif
  10468. #if !TINYEXR_USE_ZFP
  10469. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10470. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10471. err);
  10472. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10473. }
  10474. #endif
  10475. #ifdef _WIN32
  10476. FILE *fp = NULL;
  10477. fopen_s(&fp, filename, "wb");
  10478. #else
  10479. FILE *fp = fopen(filename, "wb");
  10480. #endif
  10481. if (!fp) {
  10482. tinyexr::SetErrorMessage("Cannot write a file", err);
  10483. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10484. }
  10485. unsigned char *mem = NULL;
  10486. size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
  10487. if (mem_size == 0) {
  10488. return TINYEXR_ERROR_SERIALZATION_FAILED;
  10489. }
  10490. size_t written_size = 0;
  10491. if ((mem_size > 0) && mem) {
  10492. written_size = fwrite(mem, 1, mem_size, fp);
  10493. }
  10494. free(mem);
  10495. fclose(fp);
  10496. if (written_size != mem_size) {
  10497. tinyexr::SetErrorMessage("Cannot write a file", err);
  10498. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10499. }
  10500. return TINYEXR_SUCCESS;
  10501. }
  10502. int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {
  10503. if (deep_image == NULL) {
  10504. tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
  10505. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10506. }
  10507. #ifdef _MSC_VER
  10508. FILE *fp = NULL;
  10509. errno_t errcode = fopen_s(&fp, filename, "rb");
  10510. if ((0 != errcode) || (!fp)) {
  10511. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10512. err);
  10513. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10514. }
  10515. #else
  10516. FILE *fp = fopen(filename, "rb");
  10517. if (!fp) {
  10518. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10519. err);
  10520. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10521. }
  10522. #endif
  10523. size_t filesize;
  10524. // Compute size
  10525. fseek(fp, 0, SEEK_END);
  10526. filesize = static_cast<size_t>(ftell(fp));
  10527. fseek(fp, 0, SEEK_SET);
  10528. if (filesize == 0) {
  10529. fclose(fp);
  10530. tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
  10531. err);
  10532. return TINYEXR_ERROR_INVALID_FILE;
  10533. }
  10534. std::vector<char> buf(filesize); // @todo { use mmap }
  10535. {
  10536. size_t ret;
  10537. ret = fread(&buf[0], 1, filesize, fp);
  10538. assert(ret == filesize);
  10539. (void)ret;
  10540. }
  10541. fclose(fp);
  10542. const char *head = &buf[0];
  10543. const char *marker = &buf[0];
  10544. // Header check.
  10545. {
  10546. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10547. if (memcmp(marker, header, 4) != 0) {
  10548. tinyexr::SetErrorMessage("Invalid magic number", err);
  10549. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  10550. }
  10551. marker += 4;
  10552. }
  10553. // Version, scanline.
  10554. {
  10555. // ver 2.0, scanline, deep bit on(0x800)
  10556. // must be [2, 0, 0, 0]
  10557. if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
  10558. tinyexr::SetErrorMessage("Unsupported version or scanline", err);
  10559. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10560. }
  10561. marker += 4;
  10562. }
  10563. int dx = -1;
  10564. int dy = -1;
  10565. int dw = -1;
  10566. int dh = -1;
  10567. int num_scanline_blocks = 1; // 16 for ZIP compression.
  10568. int compression_type = -1;
  10569. int num_channels = -1;
  10570. std::vector<tinyexr::ChannelInfo> channels;
  10571. // Read attributes
  10572. size_t size = filesize - tinyexr::kEXRVersionSize;
  10573. for (;;) {
  10574. if (0 == size) {
  10575. return TINYEXR_ERROR_INVALID_DATA;
  10576. } else if (marker[0] == '\0') {
  10577. marker++;
  10578. size--;
  10579. break;
  10580. }
  10581. std::string attr_name;
  10582. std::string attr_type;
  10583. std::vector<unsigned char> data;
  10584. size_t marker_size;
  10585. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  10586. marker, size)) {
  10587. return TINYEXR_ERROR_INVALID_DATA;
  10588. }
  10589. marker += marker_size;
  10590. size -= marker_size;
  10591. if (attr_name.compare("compression") == 0) {
  10592. compression_type = data[0];
  10593. if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
  10594. std::stringstream ss;
  10595. ss << "Unsupported compression type : " << compression_type;
  10596. tinyexr::SetErrorMessage(ss.str(), err);
  10597. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10598. }
  10599. if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10600. num_scanline_blocks = 16;
  10601. }
  10602. } else if (attr_name.compare("channels") == 0) {
  10603. // name: zero-terminated string, from 1 to 255 bytes long
  10604. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  10605. // pLinear: unsigned char, possible values are 0 and 1
  10606. // reserved: three chars, should be zero
  10607. // xSampling: int
  10608. // ySampling: int
  10609. if (!tinyexr::ReadChannelInfo(channels, data)) {
  10610. tinyexr::SetErrorMessage("Failed to parse channel info", err);
  10611. return TINYEXR_ERROR_INVALID_DATA;
  10612. }
  10613. num_channels = static_cast<int>(channels.size());
  10614. if (num_channels < 1) {
  10615. tinyexr::SetErrorMessage("Invalid channels format", err);
  10616. return TINYEXR_ERROR_INVALID_DATA;
  10617. }
  10618. } else if (attr_name.compare("dataWindow") == 0) {
  10619. memcpy(&dx, &data.at(0), sizeof(int));
  10620. memcpy(&dy, &data.at(4), sizeof(int));
  10621. memcpy(&dw, &data.at(8), sizeof(int));
  10622. memcpy(&dh, &data.at(12), sizeof(int));
  10623. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx));
  10624. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy));
  10625. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw));
  10626. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh));
  10627. } else if (attr_name.compare("displayWindow") == 0) {
  10628. int x;
  10629. int y;
  10630. int w;
  10631. int h;
  10632. memcpy(&x, &data.at(0), sizeof(int));
  10633. memcpy(&y, &data.at(4), sizeof(int));
  10634. memcpy(&w, &data.at(8), sizeof(int));
  10635. memcpy(&h, &data.at(12), sizeof(int));
  10636. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x));
  10637. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  10638. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10639. tinyexr::swap4(reinterpret_cast<unsigned int *>(&h));
  10640. }
  10641. }
  10642. assert(dx >= 0);
  10643. assert(dy >= 0);
  10644. assert(dw >= 0);
  10645. assert(dh >= 0);
  10646. assert(num_channels >= 1);
  10647. int data_width = dw - dx + 1;
  10648. int data_height = dh - dy + 1;
  10649. std::vector<float> image(
  10650. static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA
  10651. // Read offset tables.
  10652. int num_blocks = data_height / num_scanline_blocks;
  10653. if (num_blocks * num_scanline_blocks < data_height) {
  10654. num_blocks++;
  10655. }
  10656. std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
  10657. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10658. tinyexr::tinyexr_int64 offset;
  10659. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
  10660. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));
  10661. marker += sizeof(tinyexr::tinyexr_int64); // = 8
  10662. offsets[y] = offset;
  10663. }
  10664. #if TINYEXR_USE_PIZ
  10665. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10666. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10667. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10668. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||
  10669. (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
  10670. #else
  10671. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10672. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10673. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10674. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10675. #endif
  10676. // OK
  10677. } else {
  10678. tinyexr::SetErrorMessage("Unsupported compression format", err);
  10679. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10680. }
  10681. deep_image->image = static_cast<float ***>(
  10682. malloc(sizeof(float **) * static_cast<size_t>(num_channels)));
  10683. for (int c = 0; c < num_channels; c++) {
  10684. deep_image->image[c] = static_cast<float **>(
  10685. malloc(sizeof(float *) * static_cast<size_t>(data_height)));
  10686. for (int y = 0; y < data_height; y++) {
  10687. }
  10688. }
  10689. deep_image->offset_table = static_cast<int **>(
  10690. malloc(sizeof(int *) * static_cast<size_t>(data_height)));
  10691. for (int y = 0; y < data_height; y++) {
  10692. deep_image->offset_table[y] = static_cast<int *>(
  10693. malloc(sizeof(int) * static_cast<size_t>(data_width)));
  10694. }
  10695. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10696. const unsigned char *data_ptr =
  10697. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  10698. // int: y coordinate
  10699. // int64: packed size of pixel offset table
  10700. // int64: packed size of sample data
  10701. // int64: unpacked size of sample data
  10702. // compressed pixel offset table
  10703. // compressed sample data
  10704. int line_no;
  10705. tinyexr::tinyexr_int64 packedOffsetTableSize;
  10706. tinyexr::tinyexr_int64 packedSampleDataSize;
  10707. tinyexr::tinyexr_int64 unpackedSampleDataSize;
  10708. memcpy(&line_no, data_ptr, sizeof(int));
  10709. memcpy(&packedOffsetTableSize, data_ptr + 4,
  10710. sizeof(tinyexr::tinyexr_int64));
  10711. memcpy(&packedSampleDataSize, data_ptr + 12,
  10712. sizeof(tinyexr::tinyexr_int64));
  10713. memcpy(&unpackedSampleDataSize, data_ptr + 20,
  10714. sizeof(tinyexr::tinyexr_int64));
  10715. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  10716. tinyexr::swap8(
  10717. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));
  10718. tinyexr::swap8(
  10719. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));
  10720. tinyexr::swap8(
  10721. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));
  10722. std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
  10723. // decode pixel offset table.
  10724. {
  10725. unsigned long dstLen =
  10726. static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
  10727. if (!tinyexr::DecompressZip(
  10728. reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  10729. &dstLen, data_ptr + 28,
  10730. static_cast<unsigned long>(packedOffsetTableSize))) {
  10731. return false;
  10732. }
  10733. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  10734. for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
  10735. deep_image->offset_table[y][i] = pixelOffsetTable[i];
  10736. }
  10737. }
  10738. std::vector<unsigned char> sample_data(
  10739. static_cast<size_t>(unpackedSampleDataSize));
  10740. // decode sample data.
  10741. {
  10742. unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
  10743. if (dstLen) {
  10744. if (!tinyexr::DecompressZip(
  10745. reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,
  10746. data_ptr + 28 + packedOffsetTableSize,
  10747. static_cast<unsigned long>(packedSampleDataSize))) {
  10748. return false;
  10749. }
  10750. assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize));
  10751. }
  10752. }
  10753. // decode sample
  10754. int sampleSize = -1;
  10755. std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
  10756. {
  10757. int channel_offset = 0;
  10758. for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
  10759. channel_offset_list[i] = channel_offset;
  10760. if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
  10761. channel_offset += 4;
  10762. } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
  10763. channel_offset += 2;
  10764. } else if (channels[i].pixel_type ==
  10765. TINYEXR_PIXELTYPE_FLOAT) { // float
  10766. channel_offset += 4;
  10767. } else {
  10768. assert(0);
  10769. }
  10770. }
  10771. sampleSize = channel_offset;
  10772. }
  10773. assert(sampleSize >= 2);
  10774. assert(static_cast<size_t>(
  10775. pixelOffsetTable[static_cast<size_t>(data_width - 1)] *
  10776. sampleSize) == sample_data.size());
  10777. int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
  10778. //
  10779. // Alloc memory
  10780. //
  10781. //
  10782. // pixel data is stored as image[channels][pixel_samples]
  10783. //
  10784. {
  10785. tinyexr::tinyexr_uint64 data_offset = 0;
  10786. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  10787. deep_image->image[c][y] = static_cast<float *>(
  10788. malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
  10789. if (channels[c].pixel_type == 0) { // UINT
  10790. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10791. unsigned int ui;
  10792. unsigned int *src_ptr = reinterpret_cast<unsigned int *>(
  10793. &sample_data.at(size_t(data_offset) + x * sizeof(int)));
  10794. tinyexr::cpy4(&ui, src_ptr);
  10795. deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
  10796. }
  10797. data_offset +=
  10798. sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
  10799. } else if (channels[c].pixel_type == 1) { // half
  10800. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10801. tinyexr::FP16 f16;
  10802. const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(
  10803. &sample_data.at(size_t(data_offset) + x * sizeof(short)));
  10804. tinyexr::cpy2(&(f16.u), src_ptr);
  10805. tinyexr::FP32 f32 = half_to_float(f16);
  10806. deep_image->image[c][y][x] = f32.f;
  10807. }
  10808. data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
  10809. } else { // float
  10810. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10811. float f;
  10812. const float *src_ptr = reinterpret_cast<float *>(
  10813. &sample_data.at(size_t(data_offset) + x * sizeof(float)));
  10814. tinyexr::cpy4(&f, src_ptr);
  10815. deep_image->image[c][y][x] = f;
  10816. }
  10817. data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
  10818. }
  10819. }
  10820. }
  10821. } // y
  10822. deep_image->width = data_width;
  10823. deep_image->height = data_height;
  10824. deep_image->channel_names = static_cast<const char **>(
  10825. malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));
  10826. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  10827. #ifdef _WIN32
  10828. deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
  10829. #else
  10830. deep_image->channel_names[c] = strdup(channels[c].name.c_str());
  10831. #endif
  10832. }
  10833. deep_image->num_channels = num_channels;
  10834. return TINYEXR_SUCCESS;
  10835. }
  10836. void InitEXRImage(EXRImage *exr_image) {
  10837. if (exr_image == NULL) {
  10838. return;
  10839. }
  10840. exr_image->width = 0;
  10841. exr_image->height = 0;
  10842. exr_image->num_channels = 0;
  10843. exr_image->images = NULL;
  10844. exr_image->tiles = NULL;
  10845. exr_image->num_tiles = 0;
  10846. }
  10847. void FreeEXRErrorMessage(const char *msg) {
  10848. if (msg) {
  10849. free(reinterpret_cast<void *>(const_cast<char *>(msg)));
  10850. }
  10851. return;
  10852. }
  10853. void InitEXRHeader(EXRHeader *exr_header) {
  10854. if (exr_header == NULL) {
  10855. return;
  10856. }
  10857. memset(exr_header, 0, sizeof(EXRHeader));
  10858. }
  10859. int FreeEXRHeader(EXRHeader *exr_header) {
  10860. if (exr_header == NULL) {
  10861. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10862. }
  10863. if (exr_header->channels) {
  10864. free(exr_header->channels);
  10865. }
  10866. if (exr_header->pixel_types) {
  10867. free(exr_header->pixel_types);
  10868. }
  10869. if (exr_header->requested_pixel_types) {
  10870. free(exr_header->requested_pixel_types);
  10871. }
  10872. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  10873. if (exr_header->custom_attributes[i].value) {
  10874. free(exr_header->custom_attributes[i].value);
  10875. }
  10876. }
  10877. if (exr_header->custom_attributes) {
  10878. free(exr_header->custom_attributes);
  10879. }
  10880. return TINYEXR_SUCCESS;
  10881. }
  10882. int FreeEXRImage(EXRImage *exr_image) {
  10883. if (exr_image == NULL) {
  10884. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10885. }
  10886. for (int i = 0; i < exr_image->num_channels; i++) {
  10887. if (exr_image->images && exr_image->images[i]) {
  10888. free(exr_image->images[i]);
  10889. }
  10890. }
  10891. if (exr_image->images) {
  10892. free(exr_image->images);
  10893. }
  10894. if (exr_image->tiles) {
  10895. for (int tid = 0; tid < exr_image->num_tiles; tid++) {
  10896. for (int i = 0; i < exr_image->num_channels; i++) {
  10897. if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
  10898. free(exr_image->tiles[tid].images[i]);
  10899. }
  10900. }
  10901. if (exr_image->tiles[tid].images) {
  10902. free(exr_image->tiles[tid].images);
  10903. }
  10904. }
  10905. free(exr_image->tiles);
  10906. }
  10907. return TINYEXR_SUCCESS;
  10908. }
  10909. int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,
  10910. const char *filename, const char **err) {
  10911. if (exr_header == NULL || exr_version == NULL || filename == NULL) {
  10912. tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
  10913. err);
  10914. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10915. }
  10916. #ifdef _WIN32
  10917. FILE *fp = NULL;
  10918. fopen_s(&fp, filename, "rb");
  10919. #else
  10920. FILE *fp = fopen(filename, "rb");
  10921. #endif
  10922. if (!fp) {
  10923. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  10924. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10925. }
  10926. size_t filesize;
  10927. // Compute size
  10928. fseek(fp, 0, SEEK_END);
  10929. filesize = static_cast<size_t>(ftell(fp));
  10930. fseek(fp, 0, SEEK_SET);
  10931. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  10932. {
  10933. size_t ret;
  10934. ret = fread(&buf[0], 1, filesize, fp);
  10935. assert(ret == filesize);
  10936. fclose(fp);
  10937. if (ret != filesize) {
  10938. tinyexr::SetErrorMessage("fread() error on " + std::string(filename),
  10939. err);
  10940. return TINYEXR_ERROR_INVALID_FILE;
  10941. }
  10942. }
  10943. return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize,
  10944. err);
  10945. }
  10946. int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,
  10947. int *num_headers,
  10948. const EXRVersion *exr_version,
  10949. const unsigned char *memory, size_t size,
  10950. const char **err) {
  10951. if (memory == NULL || exr_headers == NULL || num_headers == NULL ||
  10952. exr_version == NULL) {
  10953. // Invalid argument
  10954. tinyexr::SetErrorMessage(
  10955. "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
  10956. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10957. }
  10958. if (size < tinyexr::kEXRVersionSize) {
  10959. tinyexr::SetErrorMessage("Data size too short", err);
  10960. return TINYEXR_ERROR_INVALID_DATA;
  10961. }
  10962. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  10963. size_t marker_size = size - tinyexr::kEXRVersionSize;
  10964. std::vector<tinyexr::HeaderInfo> infos;
  10965. for (;;) {
  10966. tinyexr::HeaderInfo info;
  10967. info.clear();
  10968. std::string err_str;
  10969. bool empty_header = false;
  10970. int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
  10971. marker, marker_size);
  10972. if (ret != TINYEXR_SUCCESS) {
  10973. tinyexr::SetErrorMessage(err_str, err);
  10974. return ret;
  10975. }
  10976. if (empty_header) {
  10977. marker += 1; // skip '\0'
  10978. break;
  10979. }
  10980. // `chunkCount` must exist in the header.
  10981. if (info.chunk_count == 0) {
  10982. tinyexr::SetErrorMessage(
  10983. "`chunkCount' attribute is not found in the header.", err);
  10984. return TINYEXR_ERROR_INVALID_DATA;
  10985. }
  10986. infos.push_back(info);
  10987. // move to next header.
  10988. marker += info.header_len;
  10989. size -= info.header_len;
  10990. }
  10991. // allocate memory for EXRHeader and create array of EXRHeader pointers.
  10992. (*exr_headers) =
  10993. static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));
  10994. for (size_t i = 0; i < infos.size(); i++) {
  10995. EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));
  10996. ConvertHeader(exr_header, infos[i]);
  10997. // transfoer `tiled` from version.
  10998. exr_header->tiled = exr_version->tiled;
  10999. (*exr_headers)[i] = exr_header;
  11000. }
  11001. (*num_headers) = static_cast<int>(infos.size());
  11002. return TINYEXR_SUCCESS;
  11003. }
  11004. int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,
  11005. const EXRVersion *exr_version,
  11006. const char *filename, const char **err) {
  11007. if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||
  11008. filename == NULL) {
  11009. tinyexr::SetErrorMessage(
  11010. "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
  11011. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11012. }
  11013. #ifdef _WIN32
  11014. FILE *fp = NULL;
  11015. fopen_s(&fp, filename, "rb");
  11016. #else
  11017. FILE *fp = fopen(filename, "rb");
  11018. #endif
  11019. if (!fp) {
  11020. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11021. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11022. }
  11023. size_t filesize;
  11024. // Compute size
  11025. fseek(fp, 0, SEEK_END);
  11026. filesize = static_cast<size_t>(ftell(fp));
  11027. fseek(fp, 0, SEEK_SET);
  11028. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11029. {
  11030. size_t ret;
  11031. ret = fread(&buf[0], 1, filesize, fp);
  11032. assert(ret == filesize);
  11033. fclose(fp);
  11034. if (ret != filesize) {
  11035. tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err);
  11036. return TINYEXR_ERROR_INVALID_FILE;
  11037. }
  11038. }
  11039. return ParseEXRMultipartHeaderFromMemory(
  11040. exr_headers, num_headers, exr_version, &buf.at(0), filesize, err);
  11041. }
  11042. int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,
  11043. size_t size) {
  11044. if (version == NULL || memory == NULL) {
  11045. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11046. }
  11047. if (size < tinyexr::kEXRVersionSize) {
  11048. return TINYEXR_ERROR_INVALID_DATA;
  11049. }
  11050. const unsigned char *marker = memory;
  11051. // Header check.
  11052. {
  11053. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  11054. if (memcmp(marker, header, 4) != 0) {
  11055. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  11056. }
  11057. marker += 4;
  11058. }
  11059. version->tiled = false;
  11060. version->long_name = false;
  11061. version->non_image = false;
  11062. version->multipart = false;
  11063. // Parse version header.
  11064. {
  11065. // must be 2
  11066. if (marker[0] != 2) {
  11067. return TINYEXR_ERROR_INVALID_EXR_VERSION;
  11068. }
  11069. if (version == NULL) {
  11070. return TINYEXR_SUCCESS; // May OK
  11071. }
  11072. version->version = 2;
  11073. if (marker[1] & 0x2) { // 9th bit
  11074. version->tiled = true;
  11075. }
  11076. if (marker[1] & 0x4) { // 10th bit
  11077. version->long_name = true;
  11078. }
  11079. if (marker[1] & 0x8) { // 11th bit
  11080. version->non_image = true; // (deep image)
  11081. }
  11082. if (marker[1] & 0x10) { // 12th bit
  11083. version->multipart = true;
  11084. }
  11085. }
  11086. return TINYEXR_SUCCESS;
  11087. }
  11088. int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {
  11089. if (filename == NULL) {
  11090. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11091. }
  11092. #ifdef _WIN32
  11093. FILE *fp = NULL;
  11094. fopen_s(&fp, filename, "rb");
  11095. #else
  11096. FILE *fp = fopen(filename, "rb");
  11097. #endif
  11098. if (!fp) {
  11099. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11100. }
  11101. size_t file_size;
  11102. // Compute size
  11103. fseek(fp, 0, SEEK_END);
  11104. file_size = static_cast<size_t>(ftell(fp));
  11105. fseek(fp, 0, SEEK_SET);
  11106. if (file_size < tinyexr::kEXRVersionSize) {
  11107. return TINYEXR_ERROR_INVALID_FILE;
  11108. }
  11109. unsigned char buf[tinyexr::kEXRVersionSize];
  11110. size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
  11111. fclose(fp);
  11112. if (ret != tinyexr::kEXRVersionSize) {
  11113. return TINYEXR_ERROR_INVALID_FILE;
  11114. }
  11115. return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
  11116. }
  11117. int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,
  11118. const EXRHeader **exr_headers,
  11119. unsigned int num_parts,
  11120. const unsigned char *memory,
  11121. const size_t size, const char **err) {
  11122. if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
  11123. memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
  11124. tinyexr::SetErrorMessage(
  11125. "Invalid argument for LoadEXRMultipartImageFromMemory()", err);
  11126. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11127. }
  11128. // compute total header size.
  11129. size_t total_header_size = 0;
  11130. for (unsigned int i = 0; i < num_parts; i++) {
  11131. if (exr_headers[i]->header_len == 0) {
  11132. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  11133. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11134. }
  11135. total_header_size += exr_headers[i]->header_len;
  11136. }
  11137. const char *marker = reinterpret_cast<const char *>(
  11138. memory + total_header_size + 4 +
  11139. 4); // +8 for magic number and version header.
  11140. marker += 1; // Skip empty header.
  11141. // NOTE 1:
  11142. // In multipart image, There is 'part number' before chunk data.
  11143. // 4 byte : part number
  11144. // 4+ : chunk
  11145. //
  11146. // NOTE 2:
  11147. // EXR spec says 'part number' is 'unsigned long' but actually this is
  11148. // 'unsigned int(4 bytes)' in OpenEXR implementation...
  11149. // http://www.openexr.com/openexrfilelayout.pdf
  11150. // Load chunk offset table.
  11151. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list;
  11152. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11153. std::vector<tinyexr::tinyexr_uint64> offset_table(
  11154. static_cast<size_t>(exr_headers[i]->chunk_count));
  11155. for (size_t c = 0; c < offset_table.size(); c++) {
  11156. tinyexr::tinyexr_uint64 offset;
  11157. memcpy(&offset, marker, 8);
  11158. tinyexr::swap8(&offset);
  11159. if (offset >= size) {
  11160. tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
  11161. err);
  11162. return TINYEXR_ERROR_INVALID_DATA;
  11163. }
  11164. offset_table[c] = offset + 4; // +4 to skip 'part number'
  11165. marker += 8;
  11166. }
  11167. chunk_offset_table_list.push_back(offset_table);
  11168. }
  11169. // Decode image.
  11170. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11171. std::vector<tinyexr::tinyexr_uint64> &offset_table =
  11172. chunk_offset_table_list[i];
  11173. // First check 'part number' is identitical to 'i'
  11174. for (size_t c = 0; c < offset_table.size(); c++) {
  11175. const unsigned char *part_number_addr =
  11176. memory + offset_table[c] - 4; // -4 to move to 'part number' field.
  11177. unsigned int part_no;
  11178. memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
  11179. tinyexr::swap4(&part_no);
  11180. if (part_no != i) {
  11181. tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
  11182. err);
  11183. return TINYEXR_ERROR_INVALID_DATA;
  11184. }
  11185. }
  11186. std::string e;
  11187. int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table,
  11188. memory, size, &e);
  11189. if (ret != TINYEXR_SUCCESS) {
  11190. if (!e.empty()) {
  11191. tinyexr::SetErrorMessage(e, err);
  11192. }
  11193. return ret;
  11194. }
  11195. }
  11196. return TINYEXR_SUCCESS;
  11197. }
  11198. int LoadEXRMultipartImageFromFile(EXRImage *exr_images,
  11199. const EXRHeader **exr_headers,
  11200. unsigned int num_parts, const char *filename,
  11201. const char **err) {
  11202. if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
  11203. tinyexr::SetErrorMessage(
  11204. "Invalid argument for LoadEXRMultipartImageFromFile", err);
  11205. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11206. }
  11207. #ifdef _WIN32
  11208. FILE *fp = NULL;
  11209. fopen_s(&fp, filename, "rb");
  11210. #else
  11211. FILE *fp = fopen(filename, "rb");
  11212. #endif
  11213. if (!fp) {
  11214. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11215. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11216. }
  11217. size_t filesize;
  11218. // Compute size
  11219. fseek(fp, 0, SEEK_END);
  11220. filesize = static_cast<size_t>(ftell(fp));
  11221. fseek(fp, 0, SEEK_SET);
  11222. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11223. {
  11224. size_t ret;
  11225. ret = fread(&buf[0], 1, filesize, fp);
  11226. assert(ret == filesize);
  11227. fclose(fp);
  11228. (void)ret;
  11229. }
  11230. return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
  11231. &buf.at(0), filesize, err);
  11232. }
  11233. int SaveEXR(const float *data, int width, int height, int components,
  11234. const int save_as_fp16, const char *outfilename, const char **err) {
  11235. if ((components == 1) || components == 3 || components == 4) {
  11236. // OK
  11237. } else {
  11238. std::stringstream ss;
  11239. ss << "Unsupported component value : " << components << std::endl;
  11240. tinyexr::SetErrorMessage(ss.str(), err);
  11241. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11242. }
  11243. EXRHeader header;
  11244. InitEXRHeader(&header);
  11245. if ((width < 16) && (height < 16)) {
  11246. // No compression for small image.
  11247. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;
  11248. } else {
  11249. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  11250. }
  11251. EXRImage image;
  11252. InitEXRImage(&image);
  11253. image.num_channels = components;
  11254. std::vector<float> images[4];
  11255. if (components == 1) {
  11256. images[0].resize(static_cast<size_t>(width * height));
  11257. memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
  11258. } else {
  11259. images[0].resize(static_cast<size_t>(width * height));
  11260. images[1].resize(static_cast<size_t>(width * height));
  11261. images[2].resize(static_cast<size_t>(width * height));
  11262. images[3].resize(static_cast<size_t>(width * height));
  11263. // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
  11264. for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
  11265. images[0][i] = data[static_cast<size_t>(components) * i + 0];
  11266. images[1][i] = data[static_cast<size_t>(components) * i + 1];
  11267. images[2][i] = data[static_cast<size_t>(components) * i + 2];
  11268. if (components == 4) {
  11269. images[3][i] = data[static_cast<size_t>(components) * i + 3];
  11270. }
  11271. }
  11272. }
  11273. float *image_ptr[4] = {0, 0, 0, 0};
  11274. if (components == 4) {
  11275. image_ptr[0] = &(images[3].at(0)); // A
  11276. image_ptr[1] = &(images[2].at(0)); // B
  11277. image_ptr[2] = &(images[1].at(0)); // G
  11278. image_ptr[3] = &(images[0].at(0)); // R
  11279. } else if (components == 3) {
  11280. image_ptr[0] = &(images[2].at(0)); // B
  11281. image_ptr[1] = &(images[1].at(0)); // G
  11282. image_ptr[2] = &(images[0].at(0)); // R
  11283. } else if (components == 1) {
  11284. image_ptr[0] = &(images[0].at(0)); // A
  11285. }
  11286. image.images = reinterpret_cast<unsigned char **>(image_ptr);
  11287. image.width = width;
  11288. image.height = height;
  11289. header.num_channels = components;
  11290. header.channels = static_cast<EXRChannelInfo *>(malloc(
  11291. sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
  11292. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  11293. if (components == 4) {
  11294. #ifdef _MSC_VER
  11295. strncpy_s(header.channels[0].name, "A", 255);
  11296. strncpy_s(header.channels[1].name, "B", 255);
  11297. strncpy_s(header.channels[2].name, "G", 255);
  11298. strncpy_s(header.channels[3].name, "R", 255);
  11299. #else
  11300. strncpy(header.channels[0].name, "A", 255);
  11301. strncpy(header.channels[1].name, "B", 255);
  11302. strncpy(header.channels[2].name, "G", 255);
  11303. strncpy(header.channels[3].name, "R", 255);
  11304. #endif
  11305. header.channels[0].name[strlen("A")] = '\0';
  11306. header.channels[1].name[strlen("B")] = '\0';
  11307. header.channels[2].name[strlen("G")] = '\0';
  11308. header.channels[3].name[strlen("R")] = '\0';
  11309. } else if (components == 3) {
  11310. #ifdef _MSC_VER
  11311. strncpy_s(header.channels[0].name, "B", 255);
  11312. strncpy_s(header.channels[1].name, "G", 255);
  11313. strncpy_s(header.channels[2].name, "R", 255);
  11314. #else
  11315. strncpy(header.channels[0].name, "B", 255);
  11316. strncpy(header.channels[1].name, "G", 255);
  11317. strncpy(header.channels[2].name, "R", 255);
  11318. #endif
  11319. header.channels[0].name[strlen("B")] = '\0';
  11320. header.channels[1].name[strlen("G")] = '\0';
  11321. header.channels[2].name[strlen("R")] = '\0';
  11322. } else {
  11323. #ifdef _MSC_VER
  11324. strncpy_s(header.channels[0].name, "A", 255);
  11325. #else
  11326. strncpy(header.channels[0].name, "A", 255);
  11327. #endif
  11328. header.channels[0].name[strlen("A")] = '\0';
  11329. }
  11330. header.pixel_types = static_cast<int *>(
  11331. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11332. header.requested_pixel_types = static_cast<int *>(
  11333. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11334. for (int i = 0; i < header.num_channels; i++) {
  11335. header.pixel_types[i] =
  11336. TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
  11337. if (save_as_fp16 > 0) {
  11338. header.requested_pixel_types[i] =
  11339. TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
  11340. } else {
  11341. header.requested_pixel_types[i] =
  11342. TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
  11343. // no precision reduction)
  11344. }
  11345. }
  11346. int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
  11347. if (ret != TINYEXR_SUCCESS) {
  11348. return ret;
  11349. }
  11350. free(header.channels);
  11351. free(header.pixel_types);
  11352. free(header.requested_pixel_types);
  11353. return ret;
  11354. }
  11355. #ifdef __clang__
  11356. // zero-as-null-ppinter-constant
  11357. #pragma clang diagnostic pop
  11358. #endif
  11359. #endif // TINYEXR_IMPLEMENTATION_DEIFNED
  11360. #endif // TINYEXR_IMPLEMENTATION