tinyexr.h 381 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140
  1. /*
  2. Copyright (c) 2014 - 2015, Syoyo Fujita
  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 <organization> 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. #ifndef __TINYEXR_H__
  26. #define __TINYEXR_H__
  27. //
  28. //
  29. // Do this:
  30. // #define TINYEXR_IMPLEMENTATION
  31. // before you include this file in *one* C or C++ file to create the
  32. // implementation.
  33. //
  34. // // i.e. it should look like this:
  35. // #include ...
  36. // #include ...
  37. // #include ...
  38. // #define TINYEXR_IMPLEMENTATION
  39. // #include "tinyexr.h"
  40. //
  41. //
  42. #include <stddef.h> // for size_t
  43. #ifdef __cplusplus
  44. extern "C" {
  45. #endif
  46. // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
  47. #define TINYEXR_PIXELTYPE_UINT (0)
  48. #define TINYEXR_PIXELTYPE_HALF (1)
  49. #define TINYEXR_PIXELTYPE_FLOAT (2)
  50. #define TINYEXR_MAX_ATTRIBUTES (128)
  51. #define TINYEXR_COMPRESSIONTYPE_NONE (0)
  52. //#define TINYEXR_COMPRESSIONTYPE_RLE (1) // not supported yet
  53. #define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
  54. #define TINYEXR_COMPRESSIONTYPE_ZIP (3)
  55. #define TINYEXR_COMPRESSIONTYPE_PIZ (4)
  56. typedef struct _EXRAttribute {
  57. char *name;
  58. char *type;
  59. int size;
  60. unsigned char *value; // uint8_t*
  61. } EXRAttribute;
  62. typedef struct _EXRImage {
  63. // Custom attributes(exludes required attributes(e.g. `channels`,
  64. // `compression`, etc)
  65. EXRAttribute custom_attributes[TINYEXR_MAX_ATTRIBUTES];
  66. int num_custom_attributes;
  67. int num_channels;
  68. const char **channel_names;
  69. unsigned char **images; // image[channels][pixels]
  70. int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
  71. // each channel
  72. int *requested_pixel_types; // Filled initially by
  73. // ParseEXRHeaderFrom(Meomory|File), then users
  74. // can edit it(only valid for HALF pixel type
  75. // channel)
  76. int width;
  77. int height;
  78. float pixel_aspect_ratio;
  79. int compression; // compression type(TINYEXR_COMPRESSIONTYPE_*)
  80. int line_order;
  81. int data_window[4];
  82. int display_window[4];
  83. float screen_window_center[2];
  84. float screen_window_width;
  85. } EXRImage;
  86. typedef struct _DeepImage {
  87. int num_channels;
  88. const char **channel_names;
  89. float ***image; // image[channels][scanlines][samples]
  90. int **offset_table; // offset_table[scanline][offsets]
  91. int width;
  92. int height;
  93. } DeepImage;
  94. // @deprecated { to be removed. }
  95. // Loads single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
  96. // Application must free image data as returned by `out_rgba`
  97. // Result image format is: float x RGBA x width x hight
  98. // Return 0 if success
  99. // Returns error string in `err` when there's an error
  100. extern int LoadEXR(float **out_rgba, int *width, int *height,
  101. const char *filename, const char **err);
  102. // Parse single-frame OpenEXR header from a file and initialize `EXRImage`
  103. // struct.
  104. // Users then call LoadMultiChannelEXRFromFile to actually load image data into
  105. // `EXRImage`
  106. extern int ParseMultiChannelEXRHeaderFromFile(EXRImage *image,
  107. const char *filename,
  108. const char **err);
  109. // Parse single-frame OpenEXR header from a memory and initialize `EXRImage`
  110. // struct.
  111. // Users then call LoadMultiChannelEXRFromMemory to actually load image data
  112. // into `EXRImage`
  113. extern int ParseMultiChannelEXRHeaderFromMemory(EXRImage *image,
  114. const unsigned char *memory,
  115. const char **err);
  116. // Loads multi-channel, single-frame OpenEXR image from a file.
  117. // Application must setup `ParseMultiChannelEXRHeaderFromFile` before calling
  118. // `LoadMultiChannelEXRFromFile`.
  119. // Application can free EXRImage using `FreeExrImage`
  120. // Return 0 if success
  121. // Returns error string in `err` when there's an error
  122. extern int LoadMultiChannelEXRFromFile(EXRImage *image, const char *filename,
  123. const char **err);
  124. // Loads multi-channel, single-frame OpenEXR image from a memory.
  125. // Application must setup `EXRImage` with `ParseMultiChannelEXRHeaderFromMemory`
  126. // before calling `LoadMultiChannelEXRFromMemory`.
  127. // Application can free EXRImage using `FreeExrImage`
  128. // Return 0 if success
  129. // Returns error string in `err` when there's an error
  130. extern int LoadMultiChannelEXRFromMemory(EXRImage *image,
  131. const unsigned char *memory,
  132. const char **err);
  133. // Saves floating point RGBA image as OpenEXR.
  134. // Image is compressed using EXRImage.compression value.
  135. // Return 0 if success
  136. // Returns error string in `err` when there's an error
  137. // extern int SaveEXR(const float *in_rgba, int width, int height,
  138. // const char *filename, const char **err);
  139. // Saves multi-channel, single-frame OpenEXR image to a file.
  140. // `compression_type` is one of TINYEXR_COMPRESSIONTYPE_*.
  141. // Returns 0 if success
  142. // Returns error string in `err` when there's an error
  143. extern int SaveMultiChannelEXRToFile(const EXRImage *image,
  144. const char *filename, const char **err);
  145. // Saves multi-channel, single-frame OpenEXR image to a memory.
  146. // Image is compressed using EXRImage.compression value.
  147. // Return the number of bytes if succes.
  148. // Retruns 0 if success, negative number when failed.
  149. // Returns error string in `err` when there's an error
  150. extern size_t SaveMultiChannelEXRToMemory(const EXRImage *image,
  151. unsigned char **memory,
  152. const char **err);
  153. // Loads single-frame OpenEXR deep image.
  154. // Application must free memory of variables in DeepImage(image, offset_table)
  155. // Returns 0 if success
  156. // Returns error string in `err` when there's an error
  157. extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
  158. const char **err);
  159. // NOT YET IMPLEMENTED:
  160. // Saves single-frame OpenEXR deep image.
  161. // Return 0 if success
  162. // Returns error string in `err` when there's an error
  163. // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
  164. // const char **err);
  165. // NOT YET IMPLEMENTED:
  166. // Loads multi-part OpenEXR deep image.
  167. // Application must free memory of variables in DeepImage(image, offset_table)
  168. // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
  169. // char *filename,
  170. // const char **err);
  171. // Initialize of EXRImage struct
  172. extern void InitEXRImage(EXRImage *exrImage);
  173. // Free's internal data of EXRImage struct
  174. // Returns 0 if success.
  175. extern int FreeEXRImage(EXRImage *exrImage);
  176. // For emscripten.
  177. // Parse single-frame OpenEXR header from memory.
  178. // Return 0 if success
  179. extern int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
  180. int *numCustomAttributes, int *width,
  181. int *height, const unsigned char *memory);
  182. // For emscripten.
  183. // Loads single-frame OpenEXR image from memory. Assume EXR image contains
  184. // RGB(A) channels.
  185. // `out_rgba` must have enough memory(at least sizeof(float) x 4(RGBA) x width x
  186. // hight)
  187. // Return 0 if success
  188. // Returns error string in `err` when there's an error
  189. extern int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
  190. const char **err);
  191. #ifdef __cplusplus
  192. }
  193. #endif
  194. #ifdef TINYEXR_IMPLEMENTATION
  195. #include <cstdio>
  196. #include <cstdlib>
  197. #include <cassert>
  198. #include <cstring>
  199. #include <algorithm>
  200. #include <string>
  201. #include <vector>
  202. #include "tinyexr.h"
  203. #ifdef _OPENMP
  204. #include <omp.h>
  205. #endif
  206. namespace {
  207. namespace miniz {
  208. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
  209. reading/writing/appending, PNG writing
  210. See "unlicense" statement at the end of this file.
  211. Rich Geldreich <[email protected]>, last updated Oct. 13, 2013
  212. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
  213. http://www.ietf.org/rfc/rfc1951.txt
  214. Most API's defined in miniz.c are optional. For example, to disable the
  215. archive related functions just define
  216. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
  217. (see the list below for more macros).
  218. * Change History
  219. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
  220. release with Zip64 support (almost there!):
  221. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
  222. (thanks [email protected]) which could cause locate files to not find
  223. files. This bug
  224. would only have occured in earlier versions if you explicitly used this
  225. flag, OR if you used mz_zip_extract_archive_file_to_heap() or
  226. mz_zip_add_mem_to_archive_file_in_place()
  227. (which used this flag). If you can't switch to v1.15 but want to fix
  228. this bug, just remove the uses of this flag from both helper funcs (and of
  229. course don't use the flag).
  230. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
  231. pUser_read_buf is not NULL and compressed size is > uncompressed size
  232. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
  233. compressed data from directory entries, to account for weird zipfiles which
  234. contain zero-size compressed data on dir entries.
  235. Hopefully this fix won't cause any issues on weird zip archives,
  236. because it assumes the low 16-bits of zip external attributes are DOS
  237. attributes (which I believe they always are in practice).
  238. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
  239. internal attributes, just the filename and external attributes
  240. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  241. - Added cmake support for Linux builds which builds all the examples,
  242. tested with clang v3.3 and gcc v4.6.
  243. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  244. - Merged MZ_FORCEINLINE fix from hdeanclark
  245. - Fix <time.h> include before config #ifdef, thanks emil.brink
  246. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
  247. (super useful for OpenGL apps), and explicit control over the compression
  248. level (so you can
  249. set it to 1 for real-time compression).
  250. - Merged in some compiler fixes from paulharris's github repro.
  251. - Retested this build under Windows (VS 2010, including static analysis),
  252. tcc 0.9.26, gcc v4.6 and clang v3.3.
  253. - Added example6.c, which dumps an image of the mandelbrot set to a PNG
  254. file.
  255. - Modified example2 to help test the
  256. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  257. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
  258. possible src file fclose() leak if alignment bytes+local header file write
  259. faiiled
  260. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
  261. Was pushing the wrong central dir header offset, appears harmless in this
  262. release, but it became a problem in the zip64 branch
  263. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
  264. #include <time.h> (thanks fermtect).
  265. 5/19/12 v1.13 - From [email protected] and [email protected] - Fix
  266. mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  267. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
  268. re-ran a randomized regression test on ~500k files.
  269. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  270. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
  271. (static analysis) option and fixed all warnings (except for the silly
  272. "Use of the comma-operator in a tested expression.." analysis warning,
  273. which I purposely use to work around a MSVC compiler warning).
  274. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
  275. tested Linux executables. The codeblocks workspace is compatible with
  276. Linux+Win32/x64.
  277. - Added miniz_tester solution/project, which is a useful little app
  278. derived from LZHAM's tester app that I use as part of the regression test.
  279. - Ran miniz.c and tinfl.c through another series of regression testing on
  280. ~500,000 files and archives.
  281. - Modified example5.c so it purposely disables a bunch of high-level
  282. functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
  283. MINIZ_NO_STDIO bug report.)
  284. - Fix ftell() usage in examples so they exit with an error on files which
  285. are too large (a limitation of the examples, not miniz itself).
  286. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
  287. minor level_and_flags issues in the archive API's.
  288. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
  289. Dawson <[email protected]> for the feedback/bug report.
  290. 5/28/11 v1.11 - Added statement from unlicense.org
  291. 5/27/11 v1.10 - Substantial compressor optimizations:
  292. - Level 1 is now ~4x faster than before. The L1 compressor's throughput
  293. now varies between 70-110MB/sec. on a
  294. - Core i7 (actual throughput varies depending on the type of data, and x64
  295. vs. x86).
  296. - Improved baseline L2-L9 compression perf. Also, greatly improved
  297. compression perf. issues on some file types.
  298. - Refactored the compression code for better readability and
  299. maintainability.
  300. - Added level 10 compression level (L10 has slightly better ratio than
  301. level 9, but could have a potentially large
  302. drop in throughput on some files).
  303. 5/15/11 v1.09 - Initial stable release.
  304. * Low-level Deflate/Inflate implementation notes:
  305. Compression: Use the "tdefl" API's. The compressor supports raw, static,
  306. and dynamic blocks, lazy or
  307. greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
  308. It performs and compresses
  309. approximately as well as zlib.
  310. Decompression: Use the "tinfl" API's. The entire decompressor is
  311. implemented as a single function
  312. coroutine: see tinfl_decompress(). It supports decompression into a 32KB
  313. (or larger power of 2) wrapping buffer, or into a memory
  314. block large enough to hold the entire file.
  315. The low-level tdefl/tinfl API's do not make any use of dynamic memory
  316. allocation.
  317. * zlib-style API notes:
  318. miniz.c implements a fairly large subset of zlib. There's enough
  319. functionality present for it to be a drop-in
  320. zlib replacement in many apps:
  321. The z_stream struct, optional memory allocation callbacks
  322. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  323. inflateInit/inflateInit2/inflate/inflateEnd
  324. compress, compress2, compressBound, uncompress
  325. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
  326. routines.
  327. Supports raw deflate streams or standard zlib streams with adler-32
  328. checking.
  329. Limitations:
  330. The callback API's are not implemented yet. No support for gzip headers or
  331. zlib static dictionaries.
  332. I've tried to closely emulate zlib's various flavors of stream flushing
  333. and return status codes, but
  334. there are no guarantees that miniz.c pulls this off perfectly.
  335. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
  336. originally written by
  337. Alex Evans. Supports 1-4 bytes/pixel images.
  338. * ZIP archive API notes:
  339. The ZIP archive API's where designed with simplicity and efficiency in
  340. mind, with just enough abstraction to
  341. get the job done with minimal fuss. There are simple API's to retrieve file
  342. information, read files from
  343. existing archives, create new archives, append new files to existing
  344. archives, or clone archive data from
  345. one archive to another. It supports archives located in memory or the heap,
  346. on disk (using stdio.h),
  347. or you can specify custom file read/write callbacks.
  348. - Archive reading: Just call this function to read a single file from a
  349. disk archive:
  350. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
  351. char *pArchive_name,
  352. size_t *pSize, mz_uint zip_flags);
  353. For more complex cases, use the "mz_zip_reader" functions. Upon opening an
  354. archive, the entire central
  355. directory is located and read as-is into memory, and subsequent file access
  356. only occurs when reading individual files.
  357. - Archives file scanning: The simple way is to use this function to scan a
  358. loaded archive for a specific file:
  359. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  360. const char *pComment, mz_uint flags);
  361. The locate operation can optionally check file comments too, which (as one
  362. example) can be used to identify
  363. multiple versions of the same file in an archive. This function uses a
  364. simple linear search through the central
  365. directory, so it's not very fast.
  366. Alternately, you can iterate through all the files in an archive (using
  367. mz_zip_reader_get_num_files()) and
  368. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  369. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
  370. immediately writes compressed file data
  371. to disk and builds an exact image of the central directory in memory. The
  372. central directory image is written
  373. all at once at the end of the archive file when the archive is finalized.
  374. The archive writer can optionally align each file's local header and file
  375. data to any power of 2 alignment,
  376. which can be useful when the archive will be read from optical media. Also,
  377. the writer supports placing
  378. arbitrary data blobs at the very beginning of ZIP archives. Archives
  379. written using either feature are still
  380. readable by any ZIP tool.
  381. - Archive appending: The simple way to add a single file to an archive is
  382. to call this function:
  383. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
  384. const char *pArchive_name,
  385. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
  386. comment_size, mz_uint level_and_flags);
  387. The archive will be created if it doesn't already exist, otherwise it'll be
  388. appended to.
  389. Note the appending is done in-place and is not an atomic operation, so if
  390. something goes wrong
  391. during the operation it's possible the archive could be left without a
  392. central directory (although the local
  393. file headers and file data will be fine, so the archive will be
  394. recoverable).
  395. For more complex archive modification scenarios:
  396. 1. The safest way is to use a mz_zip_reader to read the existing archive,
  397. cloning only those bits you want to
  398. preserve into a new archive using using the
  399. mz_zip_writer_add_from_zip_reader() function (which compiles the
  400. compressed file data as-is). When you're done, delete the old archive and
  401. rename the newly written archive, and
  402. you're done. This is safe but requires a bunch of temporary disk space or
  403. heap memory.
  404. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
  405. mz_zip_writer_init_from_reader(),
  406. append new files as needed, then finalize the archive which will write an
  407. updated central directory to the
  408. original archive. (This is basically what
  409. mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  410. possibility that the archive's central directory could be lost with this
  411. method if anything goes wrong, though.
  412. - ZIP archive support limitations:
  413. No zip64 or spanning support. Extraction functions can only handle
  414. unencrypted, stored or deflated files.
  415. Requires streams capable of seeking.
  416. * This is a header file library, like stb_image.c. To get only a header file,
  417. either cut and paste the
  418. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
  419. include miniz.c from it.
  420. * Important: For best perf. be sure to customize the below macros for your
  421. target platform:
  422. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  423. #define MINIZ_LITTLE_ENDIAN 1
  424. #define MINIZ_HAS_64BIT_REGISTERS 1
  425. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
  426. including miniz.c to ensure miniz
  427. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
  428. able to process large files
  429. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  430. */
  431. #ifndef MINIZ_HEADER_INCLUDED
  432. #define MINIZ_HEADER_INCLUDED
  433. #include <stdlib.h>
  434. // Defines to completely disable specific portions of miniz.c:
  435. // If all macros here are defined the only functionality remaining will be
  436. // CRC-32, adler-32, tinfl, and tdefl.
  437. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
  438. // stdio for file I/O.
  439. //#define MINIZ_NO_STDIO
  440. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
  441. // to get the current time, or
  442. // get/set file times, and the C run-time funcs that get/set times won't be
  443. // called.
  444. // The current downside is the times written to your archives will be from 1979.
  445. //#define MINIZ_NO_TIME
  446. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  447. //#define MINIZ_NO_ARCHIVE_APIS
  448. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
  449. // API's.
  450. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  451. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
  452. // API's.
  453. //#define MINIZ_NO_ZLIB_APIS
  454. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
  455. // conflicts against stock zlib.
  456. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  457. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  458. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
  459. // user alloc/free/realloc
  460. // callbacks to the zlib and archive API's, and a few stand-alone helper API's
  461. // which don't provide custom user
  462. // functions (such as tdefl_compress_mem_to_heap() and
  463. // tinfl_decompress_mem_to_heap()) won't work.
  464. //#define MINIZ_NO_MALLOC
  465. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  466. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
  467. // on Linux
  468. #define MINIZ_NO_TIME
  469. #endif
  470. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  471. #include <time.h>
  472. #endif
  473. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
  474. defined(__i386) || defined(__i486__) || defined(__i486) || \
  475. defined(i386) || defined(__ia64__) || defined(__x86_64__)
  476. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  477. #define MINIZ_X86_OR_X64_CPU 1
  478. #endif
  479. #if defined(__sparcv9)
  480. // Big endian
  481. #else
  482. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  483. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  484. #define MINIZ_LITTLE_ENDIAN 1
  485. #endif
  486. #endif
  487. #if MINIZ_X86_OR_X64_CPU
  488. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
  489. // integer loads and stores from unaligned addresses.
  490. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  491. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
  492. 0 // disable to suppress compiler warnings
  493. #endif
  494. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
  495. defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
  496. defined(__x86_64__)
  497. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
  498. // reasonably fast (and don't involve compiler generated calls to helper
  499. // functions).
  500. #define MINIZ_HAS_64BIT_REGISTERS 1
  501. #endif
  502. #ifdef __cplusplus
  503. extern "C" {
  504. #endif
  505. // ------------------- zlib-style API Definitions.
  506. // For more compatibility with zlib, miniz.c uses unsigned long for some
  507. // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  508. typedef unsigned long mz_ulong;
  509. // mz_free() internally uses the MZ_FREE() macro (which by default calls free()
  510. // unless you've modified the MZ_MALLOC macro) to release a block allocated from
  511. // the heap.
  512. void mz_free(void *p);
  513. #define MZ_ADLER32_INIT (1)
  514. // mz_adler32() returns the initial adler-32 value to use when called with
  515. // ptr==NULL.
  516. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  517. #define MZ_CRC32_INIT (0)
  518. // mz_crc32() returns the initial CRC-32 value to use when called with
  519. // ptr==NULL.
  520. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  521. // Compression strategies.
  522. enum {
  523. MZ_DEFAULT_STRATEGY = 0,
  524. MZ_FILTERED = 1,
  525. MZ_HUFFMAN_ONLY = 2,
  526. MZ_RLE = 3,
  527. MZ_FIXED = 4
  528. };
  529. // Method
  530. #define MZ_DEFLATED 8
  531. #ifndef MINIZ_NO_ZLIB_APIS
  532. // Heap allocation callbacks.
  533. // Note that mz_alloc_func parameter types purpsosely differ from zlib's:
  534. // items/size is size_t, not unsigned long.
  535. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  536. typedef void (*mz_free_func)(void *opaque, void *address);
  537. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
  538. size_t size);
  539. #define MZ_VERSION "9.1.15"
  540. #define MZ_VERNUM 0x91F0
  541. #define MZ_VER_MAJOR 9
  542. #define MZ_VER_MINOR 1
  543. #define MZ_VER_REVISION 15
  544. #define MZ_VER_SUBREVISION 0
  545. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
  546. // other values are for advanced use (refer to the zlib docs).
  547. enum {
  548. MZ_NO_FLUSH = 0,
  549. MZ_PARTIAL_FLUSH = 1,
  550. MZ_SYNC_FLUSH = 2,
  551. MZ_FULL_FLUSH = 3,
  552. MZ_FINISH = 4,
  553. MZ_BLOCK = 5
  554. };
  555. // Return status codes. MZ_PARAM_ERROR is non-standard.
  556. enum {
  557. MZ_OK = 0,
  558. MZ_STREAM_END = 1,
  559. MZ_NEED_DICT = 2,
  560. MZ_ERRNO = -1,
  561. MZ_STREAM_ERROR = -2,
  562. MZ_DATA_ERROR = -3,
  563. MZ_MEM_ERROR = -4,
  564. MZ_BUF_ERROR = -5,
  565. MZ_VERSION_ERROR = -6,
  566. MZ_PARAM_ERROR = -10000
  567. };
  568. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best
  569. // possible compression (not zlib compatible, and may be very slow),
  570. // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  571. enum {
  572. MZ_NO_COMPRESSION = 0,
  573. MZ_BEST_SPEED = 1,
  574. MZ_BEST_COMPRESSION = 9,
  575. MZ_UBER_COMPRESSION = 10,
  576. MZ_DEFAULT_LEVEL = 6,
  577. MZ_DEFAULT_COMPRESSION = -1
  578. };
  579. // Window bits
  580. #define MZ_DEFAULT_WINDOW_BITS 15
  581. struct mz_internal_state;
  582. // Compression/decompression stream struct.
  583. typedef struct mz_stream_s {
  584. const unsigned char *next_in; // pointer to next byte to read
  585. unsigned int avail_in; // number of bytes available at next_in
  586. mz_ulong total_in; // total number of bytes consumed so far
  587. unsigned char *next_out; // pointer to next byte to write
  588. unsigned int avail_out; // number of bytes that can be written to next_out
  589. mz_ulong total_out; // total number of bytes produced so far
  590. char *msg; // error msg (unused)
  591. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  592. mz_alloc_func
  593. zalloc; // optional heap allocation function (defaults to malloc)
  594. mz_free_func zfree; // optional heap free function (defaults to free)
  595. void *opaque; // heap alloc function user pointer
  596. int data_type; // data_type (unused)
  597. mz_ulong adler; // adler32 of the source or uncompressed data
  598. mz_ulong reserved; // not used
  599. } mz_stream;
  600. typedef mz_stream *mz_streamp;
  601. // Returns the version string of miniz.c.
  602. const char *mz_version(void);
  603. // mz_deflateInit() initializes a compressor with default options:
  604. // Parameters:
  605. // pStream must point to an initialized mz_stream struct.
  606. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  607. // level 1 enables a specially optimized compression function that's been
  608. // optimized purely for performance, not ratio.
  609. // (This special func. is currently only enabled when
  610. // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  611. // Return values:
  612. // MZ_OK on success.
  613. // MZ_STREAM_ERROR if the stream is bogus.
  614. // MZ_PARAM_ERROR if the input parameters are bogus.
  615. // MZ_MEM_ERROR on out of memory.
  616. int mz_deflateInit(mz_streamp pStream, int level);
  617. // mz_deflateInit2() is like mz_deflate(), except with more control:
  618. // Additional parameters:
  619. // method must be MZ_DEFLATED
  620. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
  621. // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
  622. // header or footer)
  623. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  624. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  625. int mem_level, int strategy);
  626. // Quickly resets a compressor without having to reallocate anything. Same as
  627. // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  628. int mz_deflateReset(mz_streamp pStream);
  629. // mz_deflate() compresses the input to output, consuming as much of the input
  630. // and producing as much output as possible.
  631. // Parameters:
  632. // pStream is the stream to read from and write to. You must initialize/update
  633. // the next_in, avail_in, next_out, and avail_out members.
  634. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
  635. // MZ_FINISH.
  636. // Return values:
  637. // MZ_OK on success (when flushing, or if more input is needed but not
  638. // available, and/or there's more output to be written but the output buffer
  639. // is full).
  640. // MZ_STREAM_END if all input has been consumed and all output bytes have been
  641. // written. Don't call mz_deflate() on the stream anymore.
  642. // MZ_STREAM_ERROR if the stream is bogus.
  643. // MZ_PARAM_ERROR if one of the parameters is invalid.
  644. // MZ_BUF_ERROR if no forward progress is possible because the input and/or
  645. // output buffers are empty. (Fill up the input buffer or free up some output
  646. // space and try again.)
  647. int mz_deflate(mz_streamp pStream, int flush);
  648. // mz_deflateEnd() deinitializes a compressor:
  649. // Return values:
  650. // MZ_OK on success.
  651. // MZ_STREAM_ERROR if the stream is bogus.
  652. int mz_deflateEnd(mz_streamp pStream);
  653. // mz_deflateBound() returns a (very) conservative upper bound on the amount of
  654. // data that could be generated by deflate(), assuming flush is set to only
  655. // MZ_NO_FLUSH or MZ_FINISH.
  656. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  657. // Single-call compression functions mz_compress() and mz_compress2():
  658. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on
  659. // failure.
  660. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  661. const unsigned char *pSource, mz_ulong source_len);
  662. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  663. const unsigned char *pSource, mz_ulong source_len, int level);
  664. // mz_compressBound() returns a (very) conservative upper bound on the amount of
  665. // data that could be generated by calling mz_compress().
  666. mz_ulong mz_compressBound(mz_ulong source_len);
  667. // Initializes a decompressor.
  668. int mz_inflateInit(mz_streamp pStream);
  669. // mz_inflateInit2() is like mz_inflateInit() with an additional option that
  670. // controls the window size and whether or not the stream has been wrapped with
  671. // a zlib header/footer:
  672. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
  673. // -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  674. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  675. // Decompresses the input stream to the output, consuming only as much of the
  676. // input as needed, and writing as much to the output as possible.
  677. // Parameters:
  678. // pStream is the stream to read from and write to. You must initialize/update
  679. // the next_in, avail_in, next_out, and avail_out members.
  680. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  681. // On the first call, if flush is MZ_FINISH it's assumed the input and output
  682. // buffers are both sized large enough to decompress the entire stream in a
  683. // single call (this is slightly faster).
  684. // MZ_FINISH implies that there are no more source bytes available beside
  685. // what's already in the input buffer, and that the output buffer is large
  686. // enough to hold the rest of the decompressed data.
  687. // Return values:
  688. // MZ_OK on success. Either more input is needed but not available, and/or
  689. // there's more output to be written but the output buffer is full.
  690. // MZ_STREAM_END if all needed input has been consumed and all output bytes
  691. // have been written. For zlib streams, the adler-32 of the decompressed data
  692. // has also been verified.
  693. // MZ_STREAM_ERROR if the stream is bogus.
  694. // MZ_DATA_ERROR if the deflate stream is invalid.
  695. // MZ_PARAM_ERROR if one of the parameters is invalid.
  696. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is
  697. // empty but the inflater needs more input to continue, or if the output
  698. // buffer is not large enough. Call mz_inflate() again
  699. // with more input data, or with more room in the output buffer (except when
  700. // using single call decompression, described above).
  701. int mz_inflate(mz_streamp pStream, int flush);
  702. // Deinitializes a decompressor.
  703. int mz_inflateEnd(mz_streamp pStream);
  704. // Single-call decompression.
  705. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on
  706. // failure.
  707. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  708. const unsigned char *pSource, mz_ulong source_len);
  709. // Returns a string description of the specified error code, or NULL if the
  710. // error code is invalid.
  711. const char *mz_error(int err);
  712. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
  713. // as a drop-in replacement for the subset of zlib that miniz.c supports.
  714. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
  715. // use zlib in the same project.
  716. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  717. typedef unsigned char Byte;
  718. typedef unsigned int uInt;
  719. typedef mz_ulong uLong;
  720. typedef Byte Bytef;
  721. typedef uInt uIntf;
  722. typedef char charf;
  723. typedef int intf;
  724. typedef void *voidpf;
  725. typedef uLong uLongf;
  726. typedef void *voidp;
  727. typedef void *const voidpc;
  728. #define Z_NULL 0
  729. #define Z_NO_FLUSH MZ_NO_FLUSH
  730. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  731. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  732. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  733. #define Z_FINISH MZ_FINISH
  734. #define Z_BLOCK MZ_BLOCK
  735. #define Z_OK MZ_OK
  736. #define Z_STREAM_END MZ_STREAM_END
  737. #define Z_NEED_DICT MZ_NEED_DICT
  738. #define Z_ERRNO MZ_ERRNO
  739. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  740. #define Z_DATA_ERROR MZ_DATA_ERROR
  741. #define Z_MEM_ERROR MZ_MEM_ERROR
  742. #define Z_BUF_ERROR MZ_BUF_ERROR
  743. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  744. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  745. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  746. #define Z_BEST_SPEED MZ_BEST_SPEED
  747. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  748. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  749. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  750. #define Z_FILTERED MZ_FILTERED
  751. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  752. #define Z_RLE MZ_RLE
  753. #define Z_FIXED MZ_FIXED
  754. #define Z_DEFLATED MZ_DEFLATED
  755. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  756. #define alloc_func mz_alloc_func
  757. #define free_func mz_free_func
  758. #define internal_state mz_internal_state
  759. #define z_stream mz_stream
  760. #define deflateInit mz_deflateInit
  761. #define deflateInit2 mz_deflateInit2
  762. #define deflateReset mz_deflateReset
  763. #define deflate mz_deflate
  764. #define deflateEnd mz_deflateEnd
  765. #define deflateBound mz_deflateBound
  766. #define compress mz_compress
  767. #define compress2 mz_compress2
  768. #define compressBound mz_compressBound
  769. #define inflateInit mz_inflateInit
  770. #define inflateInit2 mz_inflateInit2
  771. #define inflate mz_inflate
  772. #define inflateEnd mz_inflateEnd
  773. #define uncompress mz_uncompress
  774. #define crc32 mz_crc32
  775. #define adler32 mz_adler32
  776. #define MAX_WBITS 15
  777. #define MAX_MEM_LEVEL 9
  778. #define zError mz_error
  779. #define ZLIB_VERSION MZ_VERSION
  780. #define ZLIB_VERNUM MZ_VERNUM
  781. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  782. #define ZLIB_VER_MINOR MZ_VER_MINOR
  783. #define ZLIB_VER_REVISION MZ_VER_REVISION
  784. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  785. #define zlibVersion mz_version
  786. #define zlib_version mz_version()
  787. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  788. #endif // MINIZ_NO_ZLIB_APIS
  789. // ------------------- Types and macros
  790. typedef unsigned char mz_uint8;
  791. typedef signed short mz_int16;
  792. typedef unsigned short mz_uint16;
  793. typedef unsigned int mz_uint32;
  794. typedef unsigned int mz_uint;
  795. typedef long long mz_int64;
  796. typedef unsigned long long mz_uint64;
  797. typedef int mz_bool;
  798. #define MZ_FALSE (0)
  799. #define MZ_TRUE (1)
  800. // An attempt to work around MSVC's spammy "warning C4127: conditional
  801. // expression is constant" message.
  802. #ifdef _MSC_VER
  803. #define MZ_MACRO_END while (0, 0)
  804. #else
  805. #define MZ_MACRO_END while (0)
  806. #endif
  807. // ------------------- ZIP archive reading/writing
  808. #ifndef MINIZ_NO_ARCHIVE_APIS
  809. enum {
  810. MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
  811. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  812. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  813. };
  814. typedef struct {
  815. mz_uint32 m_file_index;
  816. mz_uint32 m_central_dir_ofs;
  817. mz_uint16 m_version_made_by;
  818. mz_uint16 m_version_needed;
  819. mz_uint16 m_bit_flag;
  820. mz_uint16 m_method;
  821. #ifndef MINIZ_NO_TIME
  822. time_t m_time;
  823. #endif
  824. mz_uint32 m_crc32;
  825. mz_uint64 m_comp_size;
  826. mz_uint64 m_uncomp_size;
  827. mz_uint16 m_internal_attr;
  828. mz_uint32 m_external_attr;
  829. mz_uint64 m_local_header_ofs;
  830. mz_uint32 m_comment_size;
  831. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  832. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  833. } mz_zip_archive_file_stat;
  834. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
  835. void *pBuf, size_t n);
  836. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
  837. const void *pBuf, size_t n);
  838. struct mz_zip_internal_state_tag;
  839. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  840. typedef enum {
  841. MZ_ZIP_MODE_INVALID = 0,
  842. MZ_ZIP_MODE_READING = 1,
  843. MZ_ZIP_MODE_WRITING = 2,
  844. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  845. } mz_zip_mode;
  846. typedef struct mz_zip_archive_tag {
  847. mz_uint64 m_archive_size;
  848. mz_uint64 m_central_directory_file_ofs;
  849. mz_uint m_total_files;
  850. mz_zip_mode m_zip_mode;
  851. mz_uint m_file_offset_alignment;
  852. mz_alloc_func m_pAlloc;
  853. mz_free_func m_pFree;
  854. mz_realloc_func m_pRealloc;
  855. void *m_pAlloc_opaque;
  856. mz_file_read_func m_pRead;
  857. mz_file_write_func m_pWrite;
  858. void *m_pIO_opaque;
  859. mz_zip_internal_state *m_pState;
  860. } mz_zip_archive;
  861. typedef enum {
  862. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  863. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  864. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  865. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  866. } mz_zip_flags;
  867. // ZIP archive reading
  868. // Inits a ZIP archive reader.
  869. // These functions read and validate the archive's central directory.
  870. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  871. mz_uint32 flags);
  872. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  873. size_t size, mz_uint32 flags);
  874. #ifndef MINIZ_NO_STDIO
  875. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  876. mz_uint32 flags);
  877. #endif
  878. // Returns the total number of files in the archive.
  879. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  880. // Returns detailed information about an archive file entry.
  881. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  882. mz_zip_archive_file_stat *pStat);
  883. // Determines if an archive file entry is a directory entry.
  884. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  885. mz_uint file_index);
  886. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  887. mz_uint file_index);
  888. // Retrieves the filename of an archive file entry.
  889. // Returns the number of bytes written to pFilename, or if filename_buf_size is
  890. // 0 this function returns the number of bytes needed to fully store the
  891. // filename.
  892. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  893. char *pFilename, mz_uint filename_buf_size);
  894. // Attempts to locates a file in the archive's central directory.
  895. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  896. // Returns -1 if the file cannot be found.
  897. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  898. const char *pComment, mz_uint flags);
  899. // Extracts a archive file to a memory buffer using no memory allocation.
  900. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  901. mz_uint file_index, void *pBuf,
  902. size_t buf_size, mz_uint flags,
  903. void *pUser_read_buf,
  904. size_t user_read_buf_size);
  905. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  906. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  907. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  908. // Extracts a archive file to a memory buffer.
  909. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  910. void *pBuf, size_t buf_size,
  911. mz_uint flags);
  912. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  913. const char *pFilename, void *pBuf,
  914. size_t buf_size, mz_uint flags);
  915. // Extracts a archive file to a dynamically allocated heap buffer.
  916. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  917. size_t *pSize, mz_uint flags);
  918. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  919. const char *pFilename, size_t *pSize,
  920. mz_uint flags);
  921. // Extracts a archive file using a callback function to output the file's data.
  922. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  923. mz_uint file_index,
  924. mz_file_write_func pCallback,
  925. void *pOpaque, mz_uint flags);
  926. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  927. const char *pFilename,
  928. mz_file_write_func pCallback,
  929. void *pOpaque, mz_uint flags);
  930. #ifndef MINIZ_NO_STDIO
  931. // Extracts a archive file to a disk file and sets its last accessed and
  932. // modified times.
  933. // This function only extracts files, not archive directory records.
  934. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  935. const char *pDst_filename, mz_uint flags);
  936. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  937. const char *pArchive_filename,
  938. const char *pDst_filename,
  939. mz_uint flags);
  940. #endif
  941. // Ends archive reading, freeing all allocations, and closing the input archive
  942. // file if mz_zip_reader_init_file() was used.
  943. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  944. // ZIP archive writing
  945. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  946. // Inits a ZIP archive writer.
  947. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  948. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  949. size_t size_to_reserve_at_beginning,
  950. size_t initial_allocation_size);
  951. #ifndef MINIZ_NO_STDIO
  952. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  953. mz_uint64 size_to_reserve_at_beginning);
  954. #endif
  955. // Converts a ZIP archive reader object into a writer object, to allow efficient
  956. // in-place file appends to occur on an existing archive.
  957. // For archives opened using mz_zip_reader_init_file, pFilename must be the
  958. // archive's filename so it can be reopened for writing. If the file can't be
  959. // reopened, mz_zip_reader_end() will be called.
  960. // For archives opened using mz_zip_reader_init_mem, the memory block must be
  961. // growable using the realloc callback (which defaults to realloc unless you've
  962. // overridden it).
  963. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
  964. // user provided m_pWrite function cannot be NULL.
  965. // Note: In-place archive modification is not recommended unless you know what
  966. // you're doing, because if execution stops or something goes wrong before
  967. // the archive is finalized the file's central directory will be hosed.
  968. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  969. const char *pFilename);
  970. // Adds the contents of a memory buffer to an archive. These functions record
  971. // the current local time into the archive.
  972. // To add a directory entry, call this method with an archive name ending in a
  973. // forwardslash with empty buffer.
  974. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  975. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  976. // just set to MZ_DEFAULT_COMPRESSION.
  977. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  978. const void *pBuf, size_t buf_size,
  979. mz_uint level_and_flags);
  980. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  981. const char *pArchive_name, const void *pBuf,
  982. size_t buf_size, const void *pComment,
  983. mz_uint16 comment_size,
  984. mz_uint level_and_flags, mz_uint64 uncomp_size,
  985. mz_uint32 uncomp_crc32);
  986. #ifndef MINIZ_NO_STDIO
  987. // Adds the contents of a disk file to an archive. This function also records
  988. // the disk file's modified time into the archive.
  989. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  990. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  991. // just set to MZ_DEFAULT_COMPRESSION.
  992. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  993. const char *pSrc_filename, const void *pComment,
  994. mz_uint16 comment_size, mz_uint level_and_flags);
  995. #endif
  996. // Adds a file to an archive by fully cloning the data from another archive.
  997. // This function fully clones the source file's compressed data (no
  998. // recompression), along with its full filename, extra data, and comment fields.
  999. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  1000. mz_zip_archive *pSource_zip,
  1001. mz_uint file_index);
  1002. // Finalizes the archive by writing the central directory records followed by
  1003. // the end of central directory record.
  1004. // After an archive is finalized, the only valid call on the mz_zip_archive
  1005. // struct is mz_zip_writer_end().
  1006. // An archive must be manually finalized by calling this function for it to be
  1007. // valid.
  1008. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  1009. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  1010. size_t *pSize);
  1011. // Ends archive writing, freeing all allocations, and closing the output file if
  1012. // mz_zip_writer_init_file() was used.
  1013. // Note for the archive to be valid, it must have been finalized before ending.
  1014. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  1015. // Misc. high-level helper functions:
  1016. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
  1017. // appends a memory blob to a ZIP archive.
  1018. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1019. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1020. // just set to MZ_DEFAULT_COMPRESSION.
  1021. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  1022. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  1023. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  1024. mz_uint level_and_flags);
  1025. // Reads a single file from an archive into a heap block.
  1026. // Returns NULL on failure.
  1027. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  1028. const char *pArchive_name,
  1029. size_t *pSize, mz_uint zip_flags);
  1030. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1031. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  1032. // ------------------- Low-level Decompression API Definitions
  1033. // Decompression flags used by tinfl_decompress().
  1034. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
  1035. // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
  1036. // input is a raw deflate stream.
  1037. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
  1038. // beyond the end of the supplied input buffer. If clear, the input buffer
  1039. // contains all remaining input.
  1040. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
  1041. // enough to hold the entire decompressed stream. If clear, the output buffer is
  1042. // at least the size of the dictionary (typically 32KB).
  1043. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
  1044. // decompressed bytes.
  1045. enum {
  1046. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  1047. TINFL_FLAG_HAS_MORE_INPUT = 2,
  1048. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  1049. TINFL_FLAG_COMPUTE_ADLER32 = 8
  1050. };
  1051. // High level decompression functions:
  1052. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
  1053. // allocated via malloc().
  1054. // On entry:
  1055. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
  1056. // to decompress.
  1057. // On return:
  1058. // Function returns a pointer to the decompressed data, or NULL on failure.
  1059. // *pOut_len will be set to the decompressed data's size, which could be larger
  1060. // than src_buf_len on uncompressible data.
  1061. // The caller must call mz_free() on the returned block when it's no longer
  1062. // needed.
  1063. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1064. size_t *pOut_len, int flags);
  1065. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
  1066. // in memory.
  1067. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
  1068. // written on success.
  1069. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  1070. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1071. const void *pSrc_buf, size_t src_buf_len,
  1072. int flags);
  1073. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an
  1074. // internal 32KB buffer, and a user provided callback function will be called to
  1075. // flush the buffer.
  1076. // Returns 1 on success or 0 on failure.
  1077. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
  1078. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  1079. tinfl_put_buf_func_ptr pPut_buf_func,
  1080. void *pPut_buf_user, int flags);
  1081. struct tinfl_decompressor_tag;
  1082. typedef struct tinfl_decompressor_tag tinfl_decompressor;
  1083. // Max size of LZ dictionary.
  1084. #define TINFL_LZ_DICT_SIZE 32768
  1085. // Return status.
  1086. typedef enum {
  1087. TINFL_STATUS_BAD_PARAM = -3,
  1088. TINFL_STATUS_ADLER32_MISMATCH = -2,
  1089. TINFL_STATUS_FAILED = -1,
  1090. TINFL_STATUS_DONE = 0,
  1091. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  1092. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  1093. } tinfl_status;
  1094. // Initializes the decompressor to its initial state.
  1095. #define tinfl_init(r) \
  1096. do { \
  1097. (r)->m_state = 0; \
  1098. } \
  1099. MZ_MACRO_END
  1100. #define tinfl_get_adler32(r) (r)->m_check_adler32
  1101. // Main low-level decompressor coroutine function. This is the only function
  1102. // actually needed for decompression. All the other functions are just
  1103. // high-level helpers for improved usability.
  1104. // This is a universal API, i.e. it can be used as a building block to build any
  1105. // desired higher level decompression API. In the limit case, it can be called
  1106. // once per every byte input or output.
  1107. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  1108. const mz_uint8 *pIn_buf_next,
  1109. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  1110. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  1111. const mz_uint32 decomp_flags);
  1112. // Internal/private bits follow.
  1113. enum {
  1114. TINFL_MAX_HUFF_TABLES = 3,
  1115. TINFL_MAX_HUFF_SYMBOLS_0 = 288,
  1116. TINFL_MAX_HUFF_SYMBOLS_1 = 32,
  1117. TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  1118. TINFL_FAST_LOOKUP_BITS = 10,
  1119. TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  1120. };
  1121. typedef struct {
  1122. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  1123. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
  1124. m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  1125. } tinfl_huff_table;
  1126. #ifndef MINIZ_HAS_64BIT_REGISTERS
  1127. # define MINIZ_HAS_64BIT_REGISTERS 0
  1128. #endif
  1129. #ifndef TINFL_USE_64BIT_BITBUF
  1130. # if MINIZ_HAS_64BIT_REGISTERS
  1131. # define TINFL_USE_64BIT_BITBUF 1
  1132. # else
  1133. # define TINFL_USE_64BIT_BITBUF 0
  1134. # endif
  1135. #endif
  1136. #if TINFL_USE_64BIT_BITBUF
  1137. typedef mz_uint64 tinfl_bit_buf_t;
  1138. #define TINFL_BITBUF_SIZE (64)
  1139. #else
  1140. typedef mz_uint32 tinfl_bit_buf_t;
  1141. #define TINFL_BITBUF_SIZE (32)
  1142. #endif
  1143. struct tinfl_decompressor_tag {
  1144. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
  1145. m_check_adler32, m_dist, m_counter, m_num_extra,
  1146. m_table_sizes[TINFL_MAX_HUFF_TABLES];
  1147. tinfl_bit_buf_t m_bit_buf;
  1148. size_t m_dist_from_out_buf_start;
  1149. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  1150. mz_uint8 m_raw_header[4],
  1151. m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  1152. };
  1153. // ------------------- Low-level Compression API Definitions
  1154. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
  1155. // slower, and raw/dynamic blocks will be output more frequently).
  1156. #define TDEFL_LESS_MEMORY 0
  1157. // tdefl_init() compression flags logically OR'd together (low 12 bits contain
  1158. // the max. number of probes per dictionary search):
  1159. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
  1160. // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
  1161. // compression), 4095=Huffman+LZ (slowest/best compression).
  1162. enum {
  1163. TDEFL_HUFFMAN_ONLY = 0,
  1164. TDEFL_DEFAULT_MAX_PROBES = 128,
  1165. TDEFL_MAX_PROBES_MASK = 0xFFF
  1166. };
  1167. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
  1168. // the deflate data, and the Adler-32 of the source data at the end. Otherwise,
  1169. // you'll get raw deflate data.
  1170. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
  1171. // when not writing zlib headers).
  1172. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
  1173. // efficient lazy parsing.
  1174. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
  1175. // initialization time to the minimum, but the output may vary from run to run
  1176. // given the same input (depending on the contents of memory).
  1177. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  1178. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  1179. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  1180. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  1181. // The low 12 bits are reserved to control the max # of hash probes per
  1182. // dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  1183. enum {
  1184. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  1185. TDEFL_COMPUTE_ADLER32 = 0x02000,
  1186. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  1187. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  1188. TDEFL_RLE_MATCHES = 0x10000,
  1189. TDEFL_FILTER_MATCHES = 0x20000,
  1190. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  1191. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  1192. };
  1193. // High level compression functions:
  1194. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
  1195. // allocated via malloc().
  1196. // On entry:
  1197. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  1198. // flags: The max match finder probes (default is 128) logically OR'd against
  1199. // the above flags. Higher probes are slower but improve compression.
  1200. // On return:
  1201. // Function returns a pointer to the compressed data, or NULL on failure.
  1202. // *pOut_len will be set to the compressed data's size, which could be larger
  1203. // than src_buf_len on uncompressible data.
  1204. // The caller must free() the returned block when it's no longer needed.
  1205. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1206. size_t *pOut_len, int flags);
  1207. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in
  1208. // memory.
  1209. // Returns 0 on failure.
  1210. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1211. const void *pSrc_buf, size_t src_buf_len,
  1212. int flags);
  1213. // Compresses an image to a compressed PNG file in memory.
  1214. // On entry:
  1215. // pImage, w, h, and num_chans describe the image to compress. num_chans may be
  1216. // 1, 2, 3, or 4.
  1217. // The image pitch in bytes per scanline will be w*num_chans. The leftmost
  1218. // pixel on the top scanline is stored first in memory.
  1219. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
  1220. // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  1221. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL
  1222. // apps).
  1223. // On return:
  1224. // Function returns a pointer to the compressed data, or NULL on failure.
  1225. // *pLen_out will be set to the size of the PNG image file.
  1226. // The caller must mz_free() the returned heap block (which will typically be
  1227. // larger than *pLen_out) when it's no longer needed.
  1228. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  1229. int h, int num_chans,
  1230. size_t *pLen_out,
  1231. mz_uint level, mz_bool flip);
  1232. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  1233. int num_chans, size_t *pLen_out);
  1234. // Output stream interface. The compressor uses this interface to write
  1235. // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  1236. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
  1237. void *pUser);
  1238. // tdefl_compress_mem_to_output() compresses a block to an output stream. The
  1239. // above helpers use this function internally.
  1240. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  1241. tdefl_put_buf_func_ptr pPut_buf_func,
  1242. void *pPut_buf_user, int flags);
  1243. enum {
  1244. TDEFL_MAX_HUFF_TABLES = 3,
  1245. TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
  1246. TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
  1247. TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
  1248. TDEFL_LZ_DICT_SIZE = 32768,
  1249. TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
  1250. TDEFL_MIN_MATCH_LEN = 3,
  1251. TDEFL_MAX_MATCH_LEN = 258
  1252. };
  1253. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
  1254. // output block (using static/fixed Huffman codes).
  1255. #if TDEFL_LESS_MEMORY
  1256. enum {
  1257. TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
  1258. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1259. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1260. TDEFL_LZ_HASH_BITS = 12,
  1261. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1262. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1263. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1264. };
  1265. #else
  1266. enum {
  1267. TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
  1268. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1269. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1270. TDEFL_LZ_HASH_BITS = 15,
  1271. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1272. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1273. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1274. };
  1275. #endif
  1276. // The low-level tdefl functions below may be used directly if the above helper
  1277. // functions aren't flexible enough. The low-level functions don't make any heap
  1278. // allocations, unlike the above helper functions.
  1279. typedef enum {
  1280. TDEFL_STATUS_BAD_PARAM = -2,
  1281. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  1282. TDEFL_STATUS_OKAY = 0,
  1283. TDEFL_STATUS_DONE = 1,
  1284. } tdefl_status;
  1285. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  1286. typedef enum {
  1287. TDEFL_NO_FLUSH = 0,
  1288. TDEFL_SYNC_FLUSH = 2,
  1289. TDEFL_FULL_FLUSH = 3,
  1290. TDEFL_FINISH = 4
  1291. } tdefl_flush;
  1292. // tdefl's compression state structure.
  1293. typedef struct {
  1294. tdefl_put_buf_func_ptr m_pPut_buf_func;
  1295. void *m_pPut_buf_user;
  1296. mz_uint m_flags, m_max_probes[2];
  1297. int m_greedy_parsing;
  1298. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  1299. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  1300. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
  1301. m_bit_buffer;
  1302. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
  1303. m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
  1304. m_wants_to_finish;
  1305. tdefl_status m_prev_return_status;
  1306. const void *m_pIn_buf;
  1307. void *m_pOut_buf;
  1308. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  1309. tdefl_flush m_flush;
  1310. const mz_uint8 *m_pSrc;
  1311. size_t m_src_buf_left, m_out_buf_ofs;
  1312. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  1313. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1314. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1315. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1316. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  1317. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  1318. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  1319. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  1320. } tdefl_compressor;
  1321. // Initializes the compressor.
  1322. // There is no corresponding deinit() function because the tdefl API's do not
  1323. // dynamically allocate memory.
  1324. // pBut_buf_func: If NULL, output data will be supplied to the specified
  1325. // callback. In this case, the user should call the tdefl_compress_buffer() API
  1326. // for compression.
  1327. // If pBut_buf_func is NULL the user should always call the tdefl_compress()
  1328. // API.
  1329. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
  1330. // etc.)
  1331. tdefl_status tdefl_init(tdefl_compressor *d,
  1332. tdefl_put_buf_func_ptr pPut_buf_func,
  1333. void *pPut_buf_user, int flags);
  1334. // Compresses a block of data, consuming as much of the specified input buffer
  1335. // as possible, and writing as much compressed data to the specified output
  1336. // buffer as possible.
  1337. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  1338. size_t *pIn_buf_size, void *pOut_buf,
  1339. size_t *pOut_buf_size, tdefl_flush flush);
  1340. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
  1341. // non-NULL tdefl_put_buf_func_ptr.
  1342. // tdefl_compress_buffer() always consumes the entire input buffer.
  1343. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  1344. size_t in_buf_size, tdefl_flush flush);
  1345. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  1346. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  1347. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
  1348. // defined, because it uses some of its macros.
  1349. #ifndef MINIZ_NO_ZLIB_APIS
  1350. // Create tdefl_compress() flags given zlib-style compression parameters.
  1351. // level may range from [0,10] (where 10 is absolute max compression, but may be
  1352. // much slower on some files)
  1353. // window_bits may be -15 (raw deflate) or 15 (zlib)
  1354. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
  1355. // MZ_RLE, or MZ_FIXED
  1356. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  1357. int strategy);
  1358. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  1359. #ifdef __cplusplus
  1360. }
  1361. #endif
  1362. #endif // MINIZ_HEADER_INCLUDED
  1363. // ------------------- End of Header: Implementation follows. (If you only want
  1364. // the header, define MINIZ_HEADER_FILE_ONLY.)
  1365. #ifndef MINIZ_HEADER_FILE_ONLY
  1366. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
  1367. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
  1368. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
  1369. #include <string.h>
  1370. #include <assert.h>
  1371. #define MZ_ASSERT(x) assert(x)
  1372. #ifdef MINIZ_NO_MALLOC
  1373. #define MZ_MALLOC(x) NULL
  1374. #define MZ_FREE(x) (void) x, ((void)0)
  1375. #define MZ_REALLOC(p, x) NULL
  1376. #else
  1377. #define MZ_MALLOC(x) malloc(x)
  1378. #define MZ_FREE(x) free(x)
  1379. #define MZ_REALLOC(p, x) realloc(p, x)
  1380. #endif
  1381. #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
  1382. #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
  1383. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  1384. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1385. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  1386. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  1387. #else
  1388. #define MZ_READ_LE16(p) \
  1389. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1390. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  1391. #define MZ_READ_LE32(p) \
  1392. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1393. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
  1394. ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
  1395. ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  1396. #endif
  1397. #ifdef _MSC_VER
  1398. #define MZ_FORCEINLINE __forceinline
  1399. #elif defined(__GNUC__)
  1400. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  1401. #else
  1402. #define MZ_FORCEINLINE inline
  1403. #endif
  1404. #ifdef __cplusplus
  1405. extern "C" {
  1406. #endif
  1407. // ------------------- zlib-style API's
  1408. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
  1409. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
  1410. size_t block_len = buf_len % 5552;
  1411. if (!ptr)
  1412. return MZ_ADLER32_INIT;
  1413. while (buf_len) {
  1414. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  1415. s1 += ptr[0], s2 += s1;
  1416. s1 += ptr[1], s2 += s1;
  1417. s1 += ptr[2], s2 += s1;
  1418. s1 += ptr[3], s2 += s1;
  1419. s1 += ptr[4], s2 += s1;
  1420. s1 += ptr[5], s2 += s1;
  1421. s1 += ptr[6], s2 += s1;
  1422. s1 += ptr[7], s2 += s1;
  1423. }
  1424. for (; i < block_len; ++i)
  1425. s1 += *ptr++, s2 += s1;
  1426. s1 %= 65521U, s2 %= 65521U;
  1427. buf_len -= block_len;
  1428. block_len = 5552;
  1429. }
  1430. return (s2 << 16) + s1;
  1431. }
  1432. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
  1433. // implementation that balances processor cache usage against speed":
  1434. // http://www.geocities.com/malbrain/
  1435. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
  1436. static const mz_uint32 s_crc32[16] = {
  1437. 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
  1438. 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
  1439. 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
  1440. mz_uint32 crcu32 = (mz_uint32)crc;
  1441. if (!ptr)
  1442. return MZ_CRC32_INIT;
  1443. crcu32 = ~crcu32;
  1444. while (buf_len--) {
  1445. mz_uint8 b = *ptr++;
  1446. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
  1447. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
  1448. }
  1449. return ~crcu32;
  1450. }
  1451. void mz_free(void *p) { MZ_FREE(p); }
  1452. #ifndef MINIZ_NO_ZLIB_APIS
  1453. static void *def_alloc_func(void *opaque, size_t items, size_t size) {
  1454. (void)opaque, (void)items, (void)size;
  1455. return MZ_MALLOC(items * size);
  1456. }
  1457. static void def_free_func(void *opaque, void *address) {
  1458. (void)opaque, (void)address;
  1459. MZ_FREE(address);
  1460. }
  1461. static void *def_realloc_func(void *opaque, void *address, size_t items,
  1462. size_t size) {
  1463. (void)opaque, (void)address, (void)items, (void)size;
  1464. return MZ_REALLOC(address, items * size);
  1465. }
  1466. const char *mz_version(void) { return MZ_VERSION; }
  1467. int mz_deflateInit(mz_streamp pStream, int level) {
  1468. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
  1469. MZ_DEFAULT_STRATEGY);
  1470. }
  1471. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  1472. int mem_level, int strategy) {
  1473. tdefl_compressor *pComp;
  1474. mz_uint comp_flags =
  1475. TDEFL_COMPUTE_ADLER32 |
  1476. tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  1477. if (!pStream)
  1478. return MZ_STREAM_ERROR;
  1479. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
  1480. ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1481. (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
  1482. return MZ_PARAM_ERROR;
  1483. pStream->data_type = 0;
  1484. pStream->adler = MZ_ADLER32_INIT;
  1485. pStream->msg = NULL;
  1486. pStream->reserved = 0;
  1487. pStream->total_in = 0;
  1488. pStream->total_out = 0;
  1489. if (!pStream->zalloc)
  1490. pStream->zalloc = def_alloc_func;
  1491. if (!pStream->zfree)
  1492. pStream->zfree = def_free_func;
  1493. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
  1494. sizeof(tdefl_compressor));
  1495. if (!pComp)
  1496. return MZ_MEM_ERROR;
  1497. pStream->state = (struct mz_internal_state *)pComp;
  1498. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
  1499. mz_deflateEnd(pStream);
  1500. return MZ_PARAM_ERROR;
  1501. }
  1502. return MZ_OK;
  1503. }
  1504. int mz_deflateReset(mz_streamp pStream) {
  1505. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
  1506. (!pStream->zfree))
  1507. return MZ_STREAM_ERROR;
  1508. pStream->total_in = pStream->total_out = 0;
  1509. tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
  1510. ((tdefl_compressor *)pStream->state)->m_flags);
  1511. return MZ_OK;
  1512. }
  1513. int mz_deflate(mz_streamp pStream, int flush) {
  1514. size_t in_bytes, out_bytes;
  1515. mz_ulong orig_total_in, orig_total_out;
  1516. int mz_status = MZ_OK;
  1517. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
  1518. (!pStream->next_out))
  1519. return MZ_STREAM_ERROR;
  1520. if (!pStream->avail_out)
  1521. return MZ_BUF_ERROR;
  1522. if (flush == MZ_PARTIAL_FLUSH)
  1523. flush = MZ_SYNC_FLUSH;
  1524. if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
  1525. TDEFL_STATUS_DONE)
  1526. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  1527. orig_total_in = pStream->total_in;
  1528. orig_total_out = pStream->total_out;
  1529. for (;;) {
  1530. tdefl_status defl_status;
  1531. in_bytes = pStream->avail_in;
  1532. out_bytes = pStream->avail_out;
  1533. defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
  1534. pStream->next_in, &in_bytes, pStream->next_out,
  1535. &out_bytes, (tdefl_flush)flush);
  1536. pStream->next_in += (mz_uint)in_bytes;
  1537. pStream->avail_in -= (mz_uint)in_bytes;
  1538. pStream->total_in += (mz_uint)in_bytes;
  1539. pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
  1540. pStream->next_out += (mz_uint)out_bytes;
  1541. pStream->avail_out -= (mz_uint)out_bytes;
  1542. pStream->total_out += (mz_uint)out_bytes;
  1543. if (defl_status < 0) {
  1544. mz_status = MZ_STREAM_ERROR;
  1545. break;
  1546. } else if (defl_status == TDEFL_STATUS_DONE) {
  1547. mz_status = MZ_STREAM_END;
  1548. break;
  1549. } else if (!pStream->avail_out)
  1550. break;
  1551. else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
  1552. if ((flush) || (pStream->total_in != orig_total_in) ||
  1553. (pStream->total_out != orig_total_out))
  1554. break;
  1555. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  1556. }
  1557. }
  1558. return mz_status;
  1559. }
  1560. int mz_deflateEnd(mz_streamp pStream) {
  1561. if (!pStream)
  1562. return MZ_STREAM_ERROR;
  1563. if (pStream->state) {
  1564. pStream->zfree(pStream->opaque, pStream->state);
  1565. pStream->state = NULL;
  1566. }
  1567. return MZ_OK;
  1568. }
  1569. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
  1570. (void)pStream;
  1571. // This is really over conservative. (And lame, but it's actually pretty
  1572. // tricky to compute a true upper bound given the way tdefl's blocking works.)
  1573. return MZ_MAX(128 + (source_len * 110) / 100,
  1574. 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  1575. }
  1576. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  1577. const unsigned char *pSource, mz_ulong source_len, int level) {
  1578. int status;
  1579. mz_stream stream;
  1580. memset(&stream, 0, sizeof(stream));
  1581. // In case mz_ulong is 64-bits (argh I hate longs).
  1582. if ((source_len | *pDest_len) > 0xFFFFFFFFU)
  1583. return MZ_PARAM_ERROR;
  1584. stream.next_in = pSource;
  1585. stream.avail_in = (mz_uint32)source_len;
  1586. stream.next_out = pDest;
  1587. stream.avail_out = (mz_uint32)*pDest_len;
  1588. status = mz_deflateInit(&stream, level);
  1589. if (status != MZ_OK)
  1590. return status;
  1591. status = mz_deflate(&stream, MZ_FINISH);
  1592. if (status != MZ_STREAM_END) {
  1593. mz_deflateEnd(&stream);
  1594. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1595. }
  1596. *pDest_len = stream.total_out;
  1597. return mz_deflateEnd(&stream);
  1598. }
  1599. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  1600. const unsigned char *pSource, mz_ulong source_len) {
  1601. return mz_compress2(pDest, pDest_len, pSource, source_len,
  1602. MZ_DEFAULT_COMPRESSION);
  1603. }
  1604. mz_ulong mz_compressBound(mz_ulong source_len) {
  1605. return mz_deflateBound(NULL, source_len);
  1606. }
  1607. typedef struct {
  1608. tinfl_decompressor m_decomp;
  1609. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
  1610. int m_window_bits;
  1611. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1612. tinfl_status m_last_status;
  1613. } inflate_state;
  1614. int mz_inflateInit2(mz_streamp pStream, int window_bits) {
  1615. inflate_state *pDecomp;
  1616. if (!pStream)
  1617. return MZ_STREAM_ERROR;
  1618. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1619. (-window_bits != MZ_DEFAULT_WINDOW_BITS))
  1620. return MZ_PARAM_ERROR;
  1621. pStream->data_type = 0;
  1622. pStream->adler = 0;
  1623. pStream->msg = NULL;
  1624. pStream->total_in = 0;
  1625. pStream->total_out = 0;
  1626. pStream->reserved = 0;
  1627. if (!pStream->zalloc)
  1628. pStream->zalloc = def_alloc_func;
  1629. if (!pStream->zfree)
  1630. pStream->zfree = def_free_func;
  1631. pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
  1632. sizeof(inflate_state));
  1633. if (!pDecomp)
  1634. return MZ_MEM_ERROR;
  1635. pStream->state = (struct mz_internal_state *)pDecomp;
  1636. tinfl_init(&pDecomp->m_decomp);
  1637. pDecomp->m_dict_ofs = 0;
  1638. pDecomp->m_dict_avail = 0;
  1639. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1640. pDecomp->m_first_call = 1;
  1641. pDecomp->m_has_flushed = 0;
  1642. pDecomp->m_window_bits = window_bits;
  1643. return MZ_OK;
  1644. }
  1645. int mz_inflateInit(mz_streamp pStream) {
  1646. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1647. }
  1648. int mz_inflate(mz_streamp pStream, int flush) {
  1649. inflate_state *pState;
  1650. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1651. size_t in_bytes, out_bytes, orig_avail_in;
  1652. tinfl_status status;
  1653. if ((!pStream) || (!pStream->state))
  1654. return MZ_STREAM_ERROR;
  1655. if (flush == MZ_PARTIAL_FLUSH)
  1656. flush = MZ_SYNC_FLUSH;
  1657. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
  1658. return MZ_STREAM_ERROR;
  1659. pState = (inflate_state *)pStream->state;
  1660. if (pState->m_window_bits > 0)
  1661. decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1662. orig_avail_in = pStream->avail_in;
  1663. first_call = pState->m_first_call;
  1664. pState->m_first_call = 0;
  1665. if (pState->m_last_status < 0)
  1666. return MZ_DATA_ERROR;
  1667. if (pState->m_has_flushed && (flush != MZ_FINISH))
  1668. return MZ_STREAM_ERROR;
  1669. pState->m_has_flushed |= (flush == MZ_FINISH);
  1670. if ((flush == MZ_FINISH) && (first_call)) {
  1671. // MZ_FINISH on the first call implies that the input and output buffers are
  1672. // large enough to hold the entire compressed/decompressed file.
  1673. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1674. in_bytes = pStream->avail_in;
  1675. out_bytes = pStream->avail_out;
  1676. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
  1677. pStream->next_out, pStream->next_out, &out_bytes,
  1678. decomp_flags);
  1679. pState->m_last_status = status;
  1680. pStream->next_in += (mz_uint)in_bytes;
  1681. pStream->avail_in -= (mz_uint)in_bytes;
  1682. pStream->total_in += (mz_uint)in_bytes;
  1683. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1684. pStream->next_out += (mz_uint)out_bytes;
  1685. pStream->avail_out -= (mz_uint)out_bytes;
  1686. pStream->total_out += (mz_uint)out_bytes;
  1687. if (status < 0)
  1688. return MZ_DATA_ERROR;
  1689. else if (status != TINFL_STATUS_DONE) {
  1690. pState->m_last_status = TINFL_STATUS_FAILED;
  1691. return MZ_BUF_ERROR;
  1692. }
  1693. return MZ_STREAM_END;
  1694. }
  1695. // flush != MZ_FINISH then we must assume there's more input.
  1696. if (flush != MZ_FINISH)
  1697. decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1698. if (pState->m_dict_avail) {
  1699. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1700. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1701. pStream->next_out += n;
  1702. pStream->avail_out -= n;
  1703. pStream->total_out += n;
  1704. pState->m_dict_avail -= n;
  1705. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1706. return ((pState->m_last_status == TINFL_STATUS_DONE) &&
  1707. (!pState->m_dict_avail))
  1708. ? MZ_STREAM_END
  1709. : MZ_OK;
  1710. }
  1711. for (;;) {
  1712. in_bytes = pStream->avail_in;
  1713. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1714. status = tinfl_decompress(
  1715. &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
  1716. pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1717. pState->m_last_status = status;
  1718. pStream->next_in += (mz_uint)in_bytes;
  1719. pStream->avail_in -= (mz_uint)in_bytes;
  1720. pStream->total_in += (mz_uint)in_bytes;
  1721. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1722. pState->m_dict_avail = (mz_uint)out_bytes;
  1723. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1724. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1725. pStream->next_out += n;
  1726. pStream->avail_out -= n;
  1727. pStream->total_out += n;
  1728. pState->m_dict_avail -= n;
  1729. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1730. if (status < 0)
  1731. return MZ_DATA_ERROR; // Stream is corrupted (there could be some
  1732. // uncompressed data left in the output dictionary -
  1733. // oh well).
  1734. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1735. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
  1736. // without supplying more input or by setting flush
  1737. // to MZ_FINISH.
  1738. else if (flush == MZ_FINISH) {
  1739. // The output buffer MUST be large to hold the remaining uncompressed data
  1740. // when flush==MZ_FINISH.
  1741. if (status == TINFL_STATUS_DONE)
  1742. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1743. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
  1744. // at least 1 more byte on the way. If there's no more room left in the
  1745. // output buffer then something is wrong.
  1746. else if (!pStream->avail_out)
  1747. return MZ_BUF_ERROR;
  1748. } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
  1749. (!pStream->avail_out) || (pState->m_dict_avail))
  1750. break;
  1751. }
  1752. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
  1753. ? MZ_STREAM_END
  1754. : MZ_OK;
  1755. }
  1756. int mz_inflateEnd(mz_streamp pStream) {
  1757. if (!pStream)
  1758. return MZ_STREAM_ERROR;
  1759. if (pStream->state) {
  1760. pStream->zfree(pStream->opaque, pStream->state);
  1761. pStream->state = NULL;
  1762. }
  1763. return MZ_OK;
  1764. }
  1765. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  1766. const unsigned char *pSource, mz_ulong source_len) {
  1767. mz_stream stream;
  1768. int status;
  1769. memset(&stream, 0, sizeof(stream));
  1770. // In case mz_ulong is 64-bits (argh I hate longs).
  1771. if ((source_len | *pDest_len) > 0xFFFFFFFFU)
  1772. return MZ_PARAM_ERROR;
  1773. stream.next_in = pSource;
  1774. stream.avail_in = (mz_uint32)source_len;
  1775. stream.next_out = pDest;
  1776. stream.avail_out = (mz_uint32)*pDest_len;
  1777. status = mz_inflateInit(&stream);
  1778. if (status != MZ_OK)
  1779. return status;
  1780. status = mz_inflate(&stream, MZ_FINISH);
  1781. if (status != MZ_STREAM_END) {
  1782. mz_inflateEnd(&stream);
  1783. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
  1784. : status;
  1785. }
  1786. *pDest_len = stream.total_out;
  1787. return mz_inflateEnd(&stream);
  1788. }
  1789. const char *mz_error(int err) {
  1790. static struct {
  1791. int m_err;
  1792. const char *m_pDesc;
  1793. } s_error_descs[] = {{MZ_OK, ""},
  1794. {MZ_STREAM_END, "stream end"},
  1795. {MZ_NEED_DICT, "need dictionary"},
  1796. {MZ_ERRNO, "file error"},
  1797. {MZ_STREAM_ERROR, "stream error"},
  1798. {MZ_DATA_ERROR, "data error"},
  1799. {MZ_MEM_ERROR, "out of memory"},
  1800. {MZ_BUF_ERROR, "buf error"},
  1801. {MZ_VERSION_ERROR, "version error"},
  1802. {MZ_PARAM_ERROR, "parameter error"}};
  1803. mz_uint i;
  1804. for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
  1805. if (s_error_descs[i].m_err == err)
  1806. return s_error_descs[i].m_pDesc;
  1807. return NULL;
  1808. }
  1809. #endif // MINIZ_NO_ZLIB_APIS
  1810. // ------------------- Low-level Decompression (completely independent from all
  1811. // compression API's)
  1812. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  1813. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  1814. #define TINFL_CR_BEGIN \
  1815. switch (r->m_state) { \
  1816. case 0:
  1817. #define TINFL_CR_RETURN(state_index, result) \
  1818. do { \
  1819. status = result; \
  1820. r->m_state = state_index; \
  1821. goto common_exit; \
  1822. case state_index: \
  1823. ; \
  1824. } \
  1825. MZ_MACRO_END
  1826. #define TINFL_CR_RETURN_FOREVER(state_index, result) \
  1827. do { \
  1828. for (;;) { \
  1829. TINFL_CR_RETURN(state_index, result); \
  1830. } \
  1831. } \
  1832. MZ_MACRO_END
  1833. #define TINFL_CR_FINISH }
  1834. // TODO: If the caller has indicated that there's no more input, and we attempt
  1835. // to read beyond the input buf, then something is wrong with the input because
  1836. // the inflator never
  1837. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
  1838. // the stream with 0's in this scenario.
  1839. #define TINFL_GET_BYTE(state_index, c) \
  1840. do { \
  1841. if (pIn_buf_cur >= pIn_buf_end) { \
  1842. for (;;) { \
  1843. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  1844. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  1845. if (pIn_buf_cur < pIn_buf_end) { \
  1846. c = *pIn_buf_cur++; \
  1847. break; \
  1848. } \
  1849. } else { \
  1850. c = 0; \
  1851. break; \
  1852. } \
  1853. } \
  1854. } else \
  1855. c = *pIn_buf_cur++; \
  1856. } \
  1857. MZ_MACRO_END
  1858. #define TINFL_NEED_BITS(state_index, n) \
  1859. do { \
  1860. mz_uint c; \
  1861. TINFL_GET_BYTE(state_index, c); \
  1862. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  1863. num_bits += 8; \
  1864. } while (num_bits < (mz_uint)(n))
  1865. #define TINFL_SKIP_BITS(state_index, n) \
  1866. do { \
  1867. if (num_bits < (mz_uint)(n)) { \
  1868. TINFL_NEED_BITS(state_index, n); \
  1869. } \
  1870. bit_buf >>= (n); \
  1871. num_bits -= (n); \
  1872. } \
  1873. MZ_MACRO_END
  1874. #define TINFL_GET_BITS(state_index, b, n) \
  1875. do { \
  1876. if (num_bits < (mz_uint)(n)) { \
  1877. TINFL_NEED_BITS(state_index, n); \
  1878. } \
  1879. b = bit_buf & ((1 << (n)) - 1); \
  1880. bit_buf >>= (n); \
  1881. num_bits -= (n); \
  1882. } \
  1883. MZ_MACRO_END
  1884. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
  1885. // remaining in the input buffer falls below 2.
  1886. // It reads just enough bytes from the input stream that are needed to decode
  1887. // the next Huffman code (and absolutely no more). It works by trying to fully
  1888. // decode a
  1889. // Huffman code by using whatever bits are currently present in the bit buffer.
  1890. // If this fails, it reads another byte, and tries again until it succeeds or
  1891. // until the
  1892. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  1893. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  1894. do { \
  1895. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  1896. if (temp >= 0) { \
  1897. code_len = temp >> 9; \
  1898. if ((code_len) && (num_bits >= code_len)) \
  1899. break; \
  1900. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  1901. code_len = TINFL_FAST_LOOKUP_BITS; \
  1902. do { \
  1903. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  1904. } while ((temp < 0) && (num_bits >= (code_len + 1))); \
  1905. if (temp >= 0) \
  1906. break; \
  1907. } \
  1908. TINFL_GET_BYTE(state_index, c); \
  1909. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  1910. num_bits += 8; \
  1911. } while (num_bits < 15);
  1912. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
  1913. // than you would initially expect because the zlib API expects the decompressor
  1914. // to never read
  1915. // beyond the final byte of the deflate stream. (In other words, when this macro
  1916. // wants to read another byte from the input, it REALLY needs another byte in
  1917. // order to fully
  1918. // decode the next Huffman code.) Handling this properly is particularly
  1919. // important on raw deflate (non-zlib) streams, which aren't followed by a byte
  1920. // aligned adler-32.
  1921. // The slow path is only executed at the very end of the input buffer.
  1922. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
  1923. do { \
  1924. int temp; \
  1925. mz_uint code_len, c; \
  1926. if (num_bits < 15) { \
  1927. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  1928. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  1929. } else { \
  1930. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
  1931. (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
  1932. pIn_buf_cur += 2; \
  1933. num_bits += 16; \
  1934. } \
  1935. } \
  1936. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
  1937. 0) \
  1938. code_len = temp >> 9, temp &= 511; \
  1939. else { \
  1940. code_len = TINFL_FAST_LOOKUP_BITS; \
  1941. do { \
  1942. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  1943. } while (temp < 0); \
  1944. } \
  1945. sym = temp; \
  1946. bit_buf >>= code_len; \
  1947. num_bits -= code_len; \
  1948. } \
  1949. MZ_MACRO_END
  1950. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  1951. const mz_uint8 *pIn_buf_next,
  1952. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  1953. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  1954. const mz_uint32 decomp_flags) {
  1955. static const int s_length_base[31] = {
  1956. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  1957. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  1958. static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
  1959. 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  1960. 4, 4, 5, 5, 5, 5, 0, 0, 0};
  1961. static const int s_dist_base[32] = {
  1962. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
  1963. 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
  1964. 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
  1965. static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  1966. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  1967. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
  1968. static const mz_uint8 s_length_dezigzag[19] = {
  1969. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  1970. static const int s_min_table_sizes[3] = {257, 1, 4};
  1971. tinfl_status status = TINFL_STATUS_FAILED;
  1972. mz_uint32 num_bits, dist, counter, num_extra;
  1973. tinfl_bit_buf_t bit_buf;
  1974. const mz_uint8 *pIn_buf_cur = pIn_buf_next,
  1975. *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  1976. mz_uint8 *pOut_buf_cur = pOut_buf_next,
  1977. *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  1978. size_t out_buf_size_mask =
  1979. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
  1980. ? (size_t)-1
  1981. : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
  1982. dist_from_out_buf_start;
  1983. // Ensure the output buffer's size is a power of 2, unless the output buffer
  1984. // is large enough to hold the entire output file (in which case it doesn't
  1985. // matter).
  1986. if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
  1987. (pOut_buf_next < pOut_buf_start)) {
  1988. *pIn_buf_size = *pOut_buf_size = 0;
  1989. return TINFL_STATUS_BAD_PARAM;
  1990. }
  1991. num_bits = r->m_num_bits;
  1992. bit_buf = r->m_bit_buf;
  1993. dist = r->m_dist;
  1994. counter = r->m_counter;
  1995. num_extra = r->m_num_extra;
  1996. dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  1997. TINFL_CR_BEGIN
  1998. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
  1999. r->m_z_adler32 = r->m_check_adler32 = 1;
  2000. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2001. TINFL_GET_BYTE(1, r->m_zhdr0);
  2002. TINFL_GET_BYTE(2, r->m_zhdr1);
  2003. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
  2004. (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  2005. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  2006. counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
  2007. ((out_buf_size_mask + 1) <
  2008. (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
  2009. if (counter) {
  2010. TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
  2011. }
  2012. }
  2013. do {
  2014. TINFL_GET_BITS(3, r->m_final, 3);
  2015. r->m_type = r->m_final >> 1;
  2016. if (r->m_type == 0) {
  2017. TINFL_SKIP_BITS(5, num_bits & 7);
  2018. for (counter = 0; counter < 4; ++counter) {
  2019. if (num_bits)
  2020. TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
  2021. else
  2022. TINFL_GET_BYTE(7, r->m_raw_header[counter]);
  2023. }
  2024. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
  2025. (mz_uint)(0xFFFF ^
  2026. (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
  2027. TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
  2028. }
  2029. while ((counter) && (num_bits)) {
  2030. TINFL_GET_BITS(51, dist, 8);
  2031. while (pOut_buf_cur >= pOut_buf_end) {
  2032. TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
  2033. }
  2034. *pOut_buf_cur++ = (mz_uint8)dist;
  2035. counter--;
  2036. }
  2037. while (counter) {
  2038. size_t n;
  2039. while (pOut_buf_cur >= pOut_buf_end) {
  2040. TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
  2041. }
  2042. while (pIn_buf_cur >= pIn_buf_end) {
  2043. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
  2044. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  2045. } else {
  2046. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  2047. }
  2048. }
  2049. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
  2050. (size_t)(pIn_buf_end - pIn_buf_cur)),
  2051. counter);
  2052. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
  2053. pIn_buf_cur += n;
  2054. pOut_buf_cur += n;
  2055. counter -= (mz_uint)n;
  2056. }
  2057. } else if (r->m_type == 3) {
  2058. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  2059. } else {
  2060. if (r->m_type == 1) {
  2061. mz_uint8 *p = r->m_tables[0].m_code_size;
  2062. mz_uint i;
  2063. r->m_table_sizes[0] = 288;
  2064. r->m_table_sizes[1] = 32;
  2065. TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  2066. for (i = 0; i <= 143; ++i)
  2067. *p++ = 8;
  2068. for (; i <= 255; ++i)
  2069. *p++ = 9;
  2070. for (; i <= 279; ++i)
  2071. *p++ = 7;
  2072. for (; i <= 287; ++i)
  2073. *p++ = 8;
  2074. } else {
  2075. for (counter = 0; counter < 3; counter++) {
  2076. TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
  2077. r->m_table_sizes[counter] += s_min_table_sizes[counter];
  2078. }
  2079. MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
  2080. for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
  2081. mz_uint s;
  2082. TINFL_GET_BITS(14, s, 3);
  2083. r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
  2084. }
  2085. r->m_table_sizes[2] = 19;
  2086. }
  2087. for (; (int)r->m_type >= 0; r->m_type--) {
  2088. int tree_next, tree_cur;
  2089. tinfl_huff_table *pTable;
  2090. mz_uint i, j, used_syms, total, sym_index, next_code[17],
  2091. total_syms[16];
  2092. pTable = &r->m_tables[r->m_type];
  2093. MZ_CLEAR_OBJ(total_syms);
  2094. MZ_CLEAR_OBJ(pTable->m_look_up);
  2095. MZ_CLEAR_OBJ(pTable->m_tree);
  2096. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
  2097. total_syms[pTable->m_code_size[i]]++;
  2098. used_syms = 0, total = 0;
  2099. next_code[0] = next_code[1] = 0;
  2100. for (i = 1; i <= 15; ++i) {
  2101. used_syms += total_syms[i];
  2102. next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
  2103. }
  2104. if ((65536 != total) && (used_syms > 1)) {
  2105. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  2106. }
  2107. for (tree_next = -1, sym_index = 0;
  2108. sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
  2109. mz_uint rev_code = 0, l, cur_code,
  2110. code_size = pTable->m_code_size[sym_index];
  2111. if (!code_size)
  2112. continue;
  2113. cur_code = next_code[code_size]++;
  2114. for (l = code_size; l > 0; l--, cur_code >>= 1)
  2115. rev_code = (rev_code << 1) | (cur_code & 1);
  2116. if (code_size <= TINFL_FAST_LOOKUP_BITS) {
  2117. mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
  2118. while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
  2119. pTable->m_look_up[rev_code] = k;
  2120. rev_code += (1 << code_size);
  2121. }
  2122. continue;
  2123. }
  2124. if (0 ==
  2125. (tree_cur = pTable->m_look_up[rev_code &
  2126. (TINFL_FAST_LOOKUP_SIZE - 1)])) {
  2127. pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
  2128. (mz_int16)tree_next;
  2129. tree_cur = tree_next;
  2130. tree_next -= 2;
  2131. }
  2132. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  2133. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
  2134. tree_cur -= ((rev_code >>= 1) & 1);
  2135. if (!pTable->m_tree[-tree_cur - 1]) {
  2136. pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
  2137. tree_cur = tree_next;
  2138. tree_next -= 2;
  2139. } else
  2140. tree_cur = pTable->m_tree[-tree_cur - 1];
  2141. }
  2142. tree_cur -= ((rev_code >>= 1) & 1);
  2143. pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  2144. }
  2145. if (r->m_type == 2) {
  2146. for (counter = 0;
  2147. counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
  2148. mz_uint s;
  2149. TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
  2150. if (dist < 16) {
  2151. r->m_len_codes[counter++] = (mz_uint8)dist;
  2152. continue;
  2153. }
  2154. if ((dist == 16) && (!counter)) {
  2155. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  2156. }
  2157. num_extra = "\02\03\07"[dist - 16];
  2158. TINFL_GET_BITS(18, s, num_extra);
  2159. s += "\03\03\013"[dist - 16];
  2160. TINFL_MEMSET(r->m_len_codes + counter,
  2161. (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
  2162. counter += s;
  2163. }
  2164. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
  2165. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  2166. }
  2167. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
  2168. r->m_table_sizes[0]);
  2169. TINFL_MEMCPY(r->m_tables[1].m_code_size,
  2170. r->m_len_codes + r->m_table_sizes[0],
  2171. r->m_table_sizes[1]);
  2172. }
  2173. }
  2174. for (;;) {
  2175. mz_uint8 *pSrc;
  2176. for (;;) {
  2177. if (((pIn_buf_end - pIn_buf_cur) < 4) ||
  2178. ((pOut_buf_end - pOut_buf_cur) < 2)) {
  2179. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  2180. if (counter >= 256)
  2181. break;
  2182. while (pOut_buf_cur >= pOut_buf_end) {
  2183. TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
  2184. }
  2185. *pOut_buf_cur++ = (mz_uint8)counter;
  2186. } else {
  2187. int sym2;
  2188. mz_uint code_len;
  2189. #if TINFL_USE_64BIT_BITBUF
  2190. if (num_bits < 30) {
  2191. bit_buf |=
  2192. (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
  2193. pIn_buf_cur += 4;
  2194. num_bits += 32;
  2195. }
  2196. #else
  2197. if (num_bits < 15) {
  2198. bit_buf |=
  2199. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2200. pIn_buf_cur += 2;
  2201. num_bits += 16;
  2202. }
  2203. #endif
  2204. if ((sym2 =
  2205. r->m_tables[0]
  2206. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2207. 0)
  2208. code_len = sym2 >> 9;
  2209. else {
  2210. code_len = TINFL_FAST_LOOKUP_BITS;
  2211. do {
  2212. sym2 = r->m_tables[0]
  2213. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2214. } while (sym2 < 0);
  2215. }
  2216. counter = sym2;
  2217. bit_buf >>= code_len;
  2218. num_bits -= code_len;
  2219. if (counter & 256)
  2220. break;
  2221. #if !TINFL_USE_64BIT_BITBUF
  2222. if (num_bits < 15) {
  2223. bit_buf |=
  2224. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2225. pIn_buf_cur += 2;
  2226. num_bits += 16;
  2227. }
  2228. #endif
  2229. if ((sym2 =
  2230. r->m_tables[0]
  2231. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2232. 0)
  2233. code_len = sym2 >> 9;
  2234. else {
  2235. code_len = TINFL_FAST_LOOKUP_BITS;
  2236. do {
  2237. sym2 = r->m_tables[0]
  2238. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2239. } while (sym2 < 0);
  2240. }
  2241. bit_buf >>= code_len;
  2242. num_bits -= code_len;
  2243. pOut_buf_cur[0] = (mz_uint8)counter;
  2244. if (sym2 & 256) {
  2245. pOut_buf_cur++;
  2246. counter = sym2;
  2247. break;
  2248. }
  2249. pOut_buf_cur[1] = (mz_uint8)sym2;
  2250. pOut_buf_cur += 2;
  2251. }
  2252. }
  2253. if ((counter &= 511) == 256)
  2254. break;
  2255. num_extra = s_length_extra[counter - 257];
  2256. counter = s_length_base[counter - 257];
  2257. if (num_extra) {
  2258. mz_uint extra_bits;
  2259. TINFL_GET_BITS(25, extra_bits, num_extra);
  2260. counter += extra_bits;
  2261. }
  2262. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  2263. num_extra = s_dist_extra[dist];
  2264. dist = s_dist_base[dist];
  2265. if (num_extra) {
  2266. mz_uint extra_bits;
  2267. TINFL_GET_BITS(27, extra_bits, num_extra);
  2268. dist += extra_bits;
  2269. }
  2270. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  2271. if ((dist > dist_from_out_buf_start) &&
  2272. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
  2273. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  2274. }
  2275. pSrc = pOut_buf_start +
  2276. ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  2277. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
  2278. while (counter--) {
  2279. while (pOut_buf_cur >= pOut_buf_end) {
  2280. TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
  2281. }
  2282. *pOut_buf_cur++ =
  2283. pOut_buf_start[(dist_from_out_buf_start++ - dist) &
  2284. out_buf_size_mask];
  2285. }
  2286. continue;
  2287. }
  2288. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2289. else if ((counter >= 9) && (counter <= dist)) {
  2290. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  2291. do {
  2292. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  2293. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  2294. pOut_buf_cur += 8;
  2295. } while ((pSrc += 8) < pSrc_end);
  2296. if ((counter &= 7) < 3) {
  2297. if (counter) {
  2298. pOut_buf_cur[0] = pSrc[0];
  2299. if (counter > 1)
  2300. pOut_buf_cur[1] = pSrc[1];
  2301. pOut_buf_cur += counter;
  2302. }
  2303. continue;
  2304. }
  2305. }
  2306. #endif
  2307. do {
  2308. pOut_buf_cur[0] = pSrc[0];
  2309. pOut_buf_cur[1] = pSrc[1];
  2310. pOut_buf_cur[2] = pSrc[2];
  2311. pOut_buf_cur += 3;
  2312. pSrc += 3;
  2313. } while ((int)(counter -= 3) > 2);
  2314. if ((int)counter > 0) {
  2315. pOut_buf_cur[0] = pSrc[0];
  2316. if ((int)counter > 1)
  2317. pOut_buf_cur[1] = pSrc[1];
  2318. pOut_buf_cur += counter;
  2319. }
  2320. }
  2321. }
  2322. } while (!(r->m_final & 1));
  2323. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2324. TINFL_SKIP_BITS(32, num_bits & 7);
  2325. for (counter = 0; counter < 4; ++counter) {
  2326. mz_uint s;
  2327. if (num_bits)
  2328. TINFL_GET_BITS(41, s, 8);
  2329. else
  2330. TINFL_GET_BYTE(42, s);
  2331. r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
  2332. }
  2333. }
  2334. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  2335. TINFL_CR_FINISH
  2336. common_exit:
  2337. r->m_num_bits = num_bits;
  2338. r->m_bit_buf = bit_buf;
  2339. r->m_dist = dist;
  2340. r->m_counter = counter;
  2341. r->m_num_extra = num_extra;
  2342. r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  2343. *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
  2344. *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  2345. if ((decomp_flags &
  2346. (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
  2347. (status >= 0)) {
  2348. const mz_uint8 *ptr = pOut_buf_next;
  2349. size_t buf_len = *pOut_buf_size;
  2350. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
  2351. s2 = r->m_check_adler32 >> 16;
  2352. size_t block_len = buf_len % 5552;
  2353. while (buf_len) {
  2354. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  2355. s1 += ptr[0], s2 += s1;
  2356. s1 += ptr[1], s2 += s1;
  2357. s1 += ptr[2], s2 += s1;
  2358. s1 += ptr[3], s2 += s1;
  2359. s1 += ptr[4], s2 += s1;
  2360. s1 += ptr[5], s2 += s1;
  2361. s1 += ptr[6], s2 += s1;
  2362. s1 += ptr[7], s2 += s1;
  2363. }
  2364. for (; i < block_len; ++i)
  2365. s1 += *ptr++, s2 += s1;
  2366. s1 %= 65521U, s2 %= 65521U;
  2367. buf_len -= block_len;
  2368. block_len = 5552;
  2369. }
  2370. r->m_check_adler32 = (s2 << 16) + s1;
  2371. if ((status == TINFL_STATUS_DONE) &&
  2372. (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
  2373. (r->m_check_adler32 != r->m_z_adler32))
  2374. status = TINFL_STATUS_ADLER32_MISMATCH;
  2375. }
  2376. return status;
  2377. }
  2378. // Higher level helper functions.
  2379. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  2380. size_t *pOut_len, int flags) {
  2381. tinfl_decompressor decomp;
  2382. void *pBuf = NULL, *pNew_buf;
  2383. size_t src_buf_ofs = 0, out_buf_capacity = 0;
  2384. *pOut_len = 0;
  2385. tinfl_init(&decomp);
  2386. for (;;) {
  2387. size_t src_buf_size = src_buf_len - src_buf_ofs,
  2388. dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  2389. tinfl_status status = tinfl_decompress(
  2390. &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
  2391. (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
  2392. &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2393. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2394. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
  2395. MZ_FREE(pBuf);
  2396. *pOut_len = 0;
  2397. return NULL;
  2398. }
  2399. src_buf_ofs += src_buf_size;
  2400. *pOut_len += dst_buf_size;
  2401. if (status == TINFL_STATUS_DONE)
  2402. break;
  2403. new_out_buf_capacity = out_buf_capacity * 2;
  2404. if (new_out_buf_capacity < 128)
  2405. new_out_buf_capacity = 128;
  2406. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  2407. if (!pNew_buf) {
  2408. MZ_FREE(pBuf);
  2409. *pOut_len = 0;
  2410. return NULL;
  2411. }
  2412. pBuf = pNew_buf;
  2413. out_buf_capacity = new_out_buf_capacity;
  2414. }
  2415. return pBuf;
  2416. }
  2417. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  2418. const void *pSrc_buf, size_t src_buf_len,
  2419. int flags) {
  2420. tinfl_decompressor decomp;
  2421. tinfl_status status;
  2422. tinfl_init(&decomp);
  2423. status =
  2424. tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
  2425. (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
  2426. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2427. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2428. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
  2429. : out_buf_len;
  2430. }
  2431. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  2432. tinfl_put_buf_func_ptr pPut_buf_func,
  2433. void *pPut_buf_user, int flags) {
  2434. int result = 0;
  2435. tinfl_decompressor decomp;
  2436. mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
  2437. size_t in_buf_ofs = 0, dict_ofs = 0;
  2438. if (!pDict)
  2439. return TINFL_STATUS_FAILED;
  2440. tinfl_init(&decomp);
  2441. for (;;) {
  2442. size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
  2443. dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  2444. tinfl_status status =
  2445. tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
  2446. &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  2447. (flags &
  2448. ~(TINFL_FLAG_HAS_MORE_INPUT |
  2449. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  2450. in_buf_ofs += in_buf_size;
  2451. if ((dst_buf_size) &&
  2452. (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  2453. break;
  2454. if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
  2455. result = (status == TINFL_STATUS_DONE);
  2456. break;
  2457. }
  2458. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  2459. }
  2460. MZ_FREE(pDict);
  2461. *pIn_buf_size = in_buf_ofs;
  2462. return result;
  2463. }
  2464. // ------------------- Low-level Compression (independent from all decompression
  2465. // API's)
  2466. // Purposely making these tables static for faster init and thread safety.
  2467. static const mz_uint16 s_tdefl_len_sym[256] = {
  2468. 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
  2469. 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
  2470. 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
  2471. 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
  2472. 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  2473. 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
  2474. 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
  2475. 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
  2476. 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
  2477. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
  2478. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
  2479. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
  2480. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
  2481. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  2482. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
  2483. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2484. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2485. 285};
  2486. static const mz_uint8 s_tdefl_len_extra[256] = {
  2487. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
  2488. 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  2489. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  2490. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2491. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2492. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2493. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2494. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2495. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2496. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2497. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
  2498. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  2499. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  2500. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
  2501. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2502. 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2503. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2504. 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2505. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
  2506. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2507. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2508. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2509. 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2510. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2511. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2512. 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2513. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2514. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2515. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2516. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2517. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2518. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2519. 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2520. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2521. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2522. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2523. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2524. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2525. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
  2526. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  2527. 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,
  2528. 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,
  2529. 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,
  2530. 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,
  2531. 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,
  2532. 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,
  2533. 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,
  2534. 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,
  2535. 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,
  2536. 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,
  2537. 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,
  2538. 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,
  2539. 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,
  2540. 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,
  2541. 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,
  2542. 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,
  2543. 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,
  2544. 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,
  2545. 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,
  2546. 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,
  2547. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
  2548. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  2549. 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
  2550. 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
  2551. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  2552. 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2553. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2554. 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  2555. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
  2556. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  2557. 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
  2558. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
  2559. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2560. 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2561. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2562. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2563. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
  2564. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
  2565. // values.
  2566. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  2567. static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
  2568. tdefl_sym_freq *pSyms0,
  2569. tdefl_sym_freq *pSyms1) {
  2570. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  2571. tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  2572. MZ_CLEAR_OBJ(hist);
  2573. for (i = 0; i < num_syms; i++) {
  2574. mz_uint freq = pSyms0[i].m_key;
  2575. hist[freq & 0xFF]++;
  2576. hist[256 + ((freq >> 8) & 0xFF)]++;
  2577. }
  2578. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  2579. total_passes--;
  2580. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
  2581. const mz_uint32 *pHist = &hist[pass << 8];
  2582. mz_uint offsets[256], cur_ofs = 0;
  2583. for (i = 0; i < 256; i++) {
  2584. offsets[i] = cur_ofs;
  2585. cur_ofs += pHist[i];
  2586. }
  2587. for (i = 0; i < num_syms; i++)
  2588. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
  2589. pCur_syms[i];
  2590. {
  2591. tdefl_sym_freq *t = pCur_syms;
  2592. pCur_syms = pNew_syms;
  2593. pNew_syms = t;
  2594. }
  2595. }
  2596. return pCur_syms;
  2597. }
  2598. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
  2599. // [email protected], Jyrki Katajainen, [email protected], November 1996.
  2600. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
  2601. int root, leaf, next, avbl, used, dpth;
  2602. if (n == 0)
  2603. return;
  2604. else if (n == 1) {
  2605. A[0].m_key = 1;
  2606. return;
  2607. }
  2608. A[0].m_key += A[1].m_key;
  2609. root = 0;
  2610. leaf = 2;
  2611. for (next = 1; next < n - 1; next++) {
  2612. if (leaf >= n || A[root].m_key < A[leaf].m_key) {
  2613. A[next].m_key = A[root].m_key;
  2614. A[root++].m_key = (mz_uint16)next;
  2615. } else
  2616. A[next].m_key = A[leaf++].m_key;
  2617. if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
  2618. A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
  2619. A[root++].m_key = (mz_uint16)next;
  2620. } else
  2621. A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  2622. }
  2623. A[n - 2].m_key = 0;
  2624. for (next = n - 3; next >= 0; next--)
  2625. A[next].m_key = A[A[next].m_key].m_key + 1;
  2626. avbl = 1;
  2627. used = dpth = 0;
  2628. root = n - 2;
  2629. next = n - 1;
  2630. while (avbl > 0) {
  2631. while (root >= 0 && (int)A[root].m_key == dpth) {
  2632. used++;
  2633. root--;
  2634. }
  2635. while (avbl > used) {
  2636. A[next--].m_key = (mz_uint16)(dpth);
  2637. avbl--;
  2638. }
  2639. avbl = 2 * used;
  2640. dpth++;
  2641. used = 0;
  2642. }
  2643. }
  2644. // Limits canonical Huffman code table's max code size.
  2645. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  2646. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
  2647. int code_list_len,
  2648. int max_code_size) {
  2649. int i;
  2650. mz_uint32 total = 0;
  2651. if (code_list_len <= 1)
  2652. return;
  2653. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
  2654. pNum_codes[max_code_size] += pNum_codes[i];
  2655. for (i = max_code_size; i > 0; i--)
  2656. total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  2657. while (total != (1UL << max_code_size)) {
  2658. pNum_codes[max_code_size]--;
  2659. for (i = max_code_size - 1; i > 0; i--)
  2660. if (pNum_codes[i]) {
  2661. pNum_codes[i]--;
  2662. pNum_codes[i + 1] += 2;
  2663. break;
  2664. }
  2665. total--;
  2666. }
  2667. }
  2668. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
  2669. int table_len, int code_size_limit,
  2670. int static_table) {
  2671. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
  2672. mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
  2673. MZ_CLEAR_OBJ(num_codes);
  2674. if (static_table) {
  2675. for (i = 0; i < table_len; i++)
  2676. num_codes[d->m_huff_code_sizes[table_num][i]]++;
  2677. } else {
  2678. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
  2679. *pSyms;
  2680. int num_used_syms = 0;
  2681. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  2682. for (i = 0; i < table_len; i++)
  2683. if (pSym_count[i]) {
  2684. syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
  2685. syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
  2686. }
  2687. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
  2688. tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  2689. for (i = 0; i < num_used_syms; i++)
  2690. num_codes[pSyms[i].m_key]++;
  2691. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
  2692. code_size_limit);
  2693. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
  2694. MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  2695. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  2696. for (l = num_codes[i]; l > 0; l--)
  2697. d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  2698. }
  2699. next_code[1] = 0;
  2700. for (j = 0, i = 2; i <= code_size_limit; i++)
  2701. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  2702. for (i = 0; i < table_len; i++) {
  2703. mz_uint rev_code = 0, code, code_size;
  2704. if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0)
  2705. continue;
  2706. code = next_code[code_size]++;
  2707. for (l = code_size; l > 0; l--, code >>= 1)
  2708. rev_code = (rev_code << 1) | (code & 1);
  2709. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  2710. }
  2711. }
  2712. #define TDEFL_PUT_BITS(b, l) \
  2713. do { \
  2714. mz_uint bits = b; \
  2715. mz_uint len = l; \
  2716. MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  2717. d->m_bit_buffer |= (bits << d->m_bits_in); \
  2718. d->m_bits_in += len; \
  2719. while (d->m_bits_in >= 8) { \
  2720. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  2721. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  2722. d->m_bit_buffer >>= 8; \
  2723. d->m_bits_in -= 8; \
  2724. } \
  2725. } \
  2726. MZ_MACRO_END
  2727. #define TDEFL_RLE_PREV_CODE_SIZE() \
  2728. { \
  2729. if (rle_repeat_count) { \
  2730. if (rle_repeat_count < 3) { \
  2731. d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
  2732. d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  2733. while (rle_repeat_count--) \
  2734. packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  2735. } else { \
  2736. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
  2737. packed_code_sizes[num_packed_code_sizes++] = 16; \
  2738. packed_code_sizes[num_packed_code_sizes++] = \
  2739. (mz_uint8)(rle_repeat_count - 3); \
  2740. } \
  2741. rle_repeat_count = 0; \
  2742. } \
  2743. }
  2744. #define TDEFL_RLE_ZERO_CODE_SIZE() \
  2745. { \
  2746. if (rle_z_count) { \
  2747. if (rle_z_count < 3) { \
  2748. d->m_huff_count[2][0] = \
  2749. (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
  2750. while (rle_z_count--) \
  2751. packed_code_sizes[num_packed_code_sizes++] = 0; \
  2752. } else if (rle_z_count <= 10) { \
  2753. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
  2754. packed_code_sizes[num_packed_code_sizes++] = 17; \
  2755. packed_code_sizes[num_packed_code_sizes++] = \
  2756. (mz_uint8)(rle_z_count - 3); \
  2757. } else { \
  2758. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
  2759. packed_code_sizes[num_packed_code_sizes++] = 18; \
  2760. packed_code_sizes[num_packed_code_sizes++] = \
  2761. (mz_uint8)(rle_z_count - 11); \
  2762. } \
  2763. rle_z_count = 0; \
  2764. } \
  2765. }
  2766. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
  2767. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2768. static void tdefl_start_dynamic_block(tdefl_compressor *d) {
  2769. int num_lit_codes, num_dist_codes, num_bit_lengths;
  2770. mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
  2771. rle_repeat_count, packed_code_sizes_index;
  2772. mz_uint8
  2773. code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2774. packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2775. prev_code_size = 0xFF;
  2776. d->m_huff_count[0][256] = 1;
  2777. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  2778. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  2779. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
  2780. if (d->m_huff_code_sizes[0][num_lit_codes - 1])
  2781. break;
  2782. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
  2783. if (d->m_huff_code_sizes[1][num_dist_codes - 1])
  2784. break;
  2785. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  2786. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
  2787. num_dist_codes);
  2788. total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
  2789. num_packed_code_sizes = 0;
  2790. rle_z_count = 0;
  2791. rle_repeat_count = 0;
  2792. memset(&d->m_huff_count[2][0], 0,
  2793. sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  2794. for (i = 0; i < total_code_sizes_to_pack; i++) {
  2795. mz_uint8 code_size = code_sizes_to_pack[i];
  2796. if (!code_size) {
  2797. TDEFL_RLE_PREV_CODE_SIZE();
  2798. if (++rle_z_count == 138) {
  2799. TDEFL_RLE_ZERO_CODE_SIZE();
  2800. }
  2801. } else {
  2802. TDEFL_RLE_ZERO_CODE_SIZE();
  2803. if (code_size != prev_code_size) {
  2804. TDEFL_RLE_PREV_CODE_SIZE();
  2805. d->m_huff_count[2][code_size] =
  2806. (mz_uint16)(d->m_huff_count[2][code_size] + 1);
  2807. packed_code_sizes[num_packed_code_sizes++] = code_size;
  2808. } else if (++rle_repeat_count == 6) {
  2809. TDEFL_RLE_PREV_CODE_SIZE();
  2810. }
  2811. }
  2812. prev_code_size = code_size;
  2813. }
  2814. if (rle_repeat_count) {
  2815. TDEFL_RLE_PREV_CODE_SIZE();
  2816. } else {
  2817. TDEFL_RLE_ZERO_CODE_SIZE();
  2818. }
  2819. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  2820. TDEFL_PUT_BITS(2, 2);
  2821. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  2822. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  2823. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
  2824. if (d->m_huff_code_sizes
  2825. [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
  2826. break;
  2827. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
  2828. TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  2829. for (i = 0; (int)i < num_bit_lengths; i++)
  2830. TDEFL_PUT_BITS(
  2831. d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  2832. for (packed_code_sizes_index = 0;
  2833. packed_code_sizes_index < num_packed_code_sizes;) {
  2834. mz_uint code = packed_code_sizes[packed_code_sizes_index++];
  2835. MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  2836. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  2837. if (code >= 16)
  2838. TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
  2839. "\02\03\07"[code - 16]);
  2840. }
  2841. }
  2842. static void tdefl_start_static_block(tdefl_compressor *d) {
  2843. mz_uint i;
  2844. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  2845. for (i = 0; i <= 143; ++i)
  2846. *p++ = 8;
  2847. for (; i <= 255; ++i)
  2848. *p++ = 9;
  2849. for (; i <= 279; ++i)
  2850. *p++ = 7;
  2851. for (; i <= 287; ++i)
  2852. *p++ = 8;
  2853. memset(d->m_huff_code_sizes[1], 5, 32);
  2854. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  2855. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  2856. TDEFL_PUT_BITS(1, 2);
  2857. }
  2858. static const mz_uint mz_bitmasks[17] = {
  2859. 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  2860. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
  2861. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
  2862. MINIZ_HAS_64BIT_REGISTERS
  2863. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  2864. mz_uint flags;
  2865. mz_uint8 *pLZ_codes;
  2866. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  2867. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  2868. mz_uint64 bit_buffer = d->m_bit_buffer;
  2869. mz_uint bits_in = d->m_bits_in;
  2870. #define TDEFL_PUT_BITS_FAST(b, l) \
  2871. { \
  2872. bit_buffer |= (((mz_uint64)(b)) << bits_in); \
  2873. bits_in += (l); \
  2874. }
  2875. flags = 1;
  2876. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
  2877. flags >>= 1) {
  2878. if (flags == 1)
  2879. flags = *pLZ_codes++ | 0x100;
  2880. if (flags & 1) {
  2881. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  2882. mz_uint match_len = pLZ_codes[0],
  2883. match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
  2884. pLZ_codes += 3;
  2885. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2886. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  2887. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2888. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  2889. s_tdefl_len_extra[match_len]);
  2890. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  2891. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  2892. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  2893. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  2894. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  2895. sym = (match_dist < 512) ? s0 : s1;
  2896. num_extra_bits = (match_dist < 512) ? n0 : n1;
  2897. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  2898. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
  2899. d->m_huff_code_sizes[1][sym]);
  2900. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
  2901. num_extra_bits);
  2902. } else {
  2903. mz_uint lit = *pLZ_codes++;
  2904. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2905. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  2906. d->m_huff_code_sizes[0][lit]);
  2907. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  2908. flags >>= 1;
  2909. lit = *pLZ_codes++;
  2910. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2911. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  2912. d->m_huff_code_sizes[0][lit]);
  2913. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  2914. flags >>= 1;
  2915. lit = *pLZ_codes++;
  2916. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2917. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  2918. d->m_huff_code_sizes[0][lit]);
  2919. }
  2920. }
  2921. }
  2922. if (pOutput_buf >= d->m_pOutput_buf_end)
  2923. return MZ_FALSE;
  2924. *(mz_uint64 *)pOutput_buf = bit_buffer;
  2925. pOutput_buf += (bits_in >> 3);
  2926. bit_buffer >>= (bits_in & ~7);
  2927. bits_in &= 7;
  2928. }
  2929. #undef TDEFL_PUT_BITS_FAST
  2930. d->m_pOutput_buf = pOutput_buf;
  2931. d->m_bits_in = 0;
  2932. d->m_bit_buffer = 0;
  2933. while (bits_in) {
  2934. mz_uint32 n = MZ_MIN(bits_in, 16);
  2935. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  2936. bit_buffer >>= n;
  2937. bits_in -= n;
  2938. }
  2939. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  2940. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  2941. }
  2942. #else
  2943. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  2944. mz_uint flags;
  2945. mz_uint8 *pLZ_codes;
  2946. flags = 1;
  2947. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
  2948. flags >>= 1) {
  2949. if (flags == 1)
  2950. flags = *pLZ_codes++ | 0x100;
  2951. if (flags & 1) {
  2952. mz_uint sym, num_extra_bits;
  2953. mz_uint match_len = pLZ_codes[0],
  2954. match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
  2955. pLZ_codes += 3;
  2956. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2957. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  2958. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  2959. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  2960. s_tdefl_len_extra[match_len]);
  2961. if (match_dist < 512) {
  2962. sym = s_tdefl_small_dist_sym[match_dist];
  2963. num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  2964. } else {
  2965. sym = s_tdefl_large_dist_sym[match_dist >> 8];
  2966. num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  2967. }
  2968. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  2969. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  2970. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  2971. } else {
  2972. mz_uint lit = *pLZ_codes++;
  2973. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  2974. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  2975. }
  2976. }
  2977. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  2978. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  2979. }
  2980. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
  2981. // MINIZ_HAS_64BIT_REGISTERS
  2982. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
  2983. if (static_block)
  2984. tdefl_start_static_block(d);
  2985. else
  2986. tdefl_start_dynamic_block(d);
  2987. return tdefl_compress_lz_codes(d);
  2988. }
  2989. static int tdefl_flush_block(tdefl_compressor *d, int flush) {
  2990. mz_uint saved_bit_buf, saved_bits_in;
  2991. mz_uint8 *pSaved_output_buf;
  2992. mz_bool comp_block_succeeded = MZ_FALSE;
  2993. int n, use_raw_block =
  2994. ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
  2995. (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  2996. mz_uint8 *pOutput_buf_start =
  2997. ((d->m_pPut_buf_func == NULL) &&
  2998. ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
  2999. ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
  3000. : d->m_output_buf;
  3001. d->m_pOutput_buf = pOutput_buf_start;
  3002. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  3003. MZ_ASSERT(!d->m_output_flush_remaining);
  3004. d->m_output_flush_ofs = 0;
  3005. d->m_output_flush_remaining = 0;
  3006. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  3007. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  3008. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
  3009. TDEFL_PUT_BITS(0x78, 8);
  3010. TDEFL_PUT_BITS(0x01, 8);
  3011. }
  3012. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  3013. pSaved_output_buf = d->m_pOutput_buf;
  3014. saved_bit_buf = d->m_bit_buffer;
  3015. saved_bits_in = d->m_bits_in;
  3016. if (!use_raw_block)
  3017. comp_block_succeeded =
  3018. tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
  3019. (d->m_total_lz_bytes < 48));
  3020. // If the block gets expanded, forget the current contents of the output
  3021. // buffer and send a raw block instead.
  3022. if (((use_raw_block) ||
  3023. ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
  3024. d->m_total_lz_bytes))) &&
  3025. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
  3026. mz_uint i;
  3027. d->m_pOutput_buf = pSaved_output_buf;
  3028. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3029. TDEFL_PUT_BITS(0, 2);
  3030. if (d->m_bits_in) {
  3031. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3032. }
  3033. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
  3034. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  3035. }
  3036. for (i = 0; i < d->m_total_lz_bytes; ++i) {
  3037. TDEFL_PUT_BITS(
  3038. d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
  3039. 8);
  3040. }
  3041. }
  3042. // Check for the extremely unlikely (if not impossible) case of the compressed
  3043. // block not fitting into the output buffer when using dynamic codes.
  3044. else if (!comp_block_succeeded) {
  3045. d->m_pOutput_buf = pSaved_output_buf;
  3046. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3047. tdefl_compress_block(d, MZ_TRUE);
  3048. }
  3049. if (flush) {
  3050. if (flush == TDEFL_FINISH) {
  3051. if (d->m_bits_in) {
  3052. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3053. }
  3054. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
  3055. mz_uint i, a = d->m_adler32;
  3056. for (i = 0; i < 4; i++) {
  3057. TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
  3058. a <<= 8;
  3059. }
  3060. }
  3061. } else {
  3062. mz_uint i, z = 0;
  3063. TDEFL_PUT_BITS(0, 3);
  3064. if (d->m_bits_in) {
  3065. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3066. }
  3067. for (i = 2; i; --i, z ^= 0xFFFF) {
  3068. TDEFL_PUT_BITS(z & 0xFFFF, 16);
  3069. }
  3070. }
  3071. }
  3072. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  3073. memset(&d->m_huff_count[0][0], 0,
  3074. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3075. memset(&d->m_huff_count[1][0], 0,
  3076. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3077. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3078. d->m_pLZ_flags = d->m_lz_code_buf;
  3079. d->m_num_flags_left = 8;
  3080. d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
  3081. d->m_total_lz_bytes = 0;
  3082. d->m_block_index++;
  3083. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
  3084. if (d->m_pPut_buf_func) {
  3085. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3086. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  3087. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  3088. } else if (pOutput_buf_start == d->m_output_buf) {
  3089. int bytes_to_copy = (int)MZ_MIN(
  3090. (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  3091. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
  3092. bytes_to_copy);
  3093. d->m_out_buf_ofs += bytes_to_copy;
  3094. if ((n -= bytes_to_copy) != 0) {
  3095. d->m_output_flush_ofs = bytes_to_copy;
  3096. d->m_output_flush_remaining = n;
  3097. }
  3098. } else {
  3099. d->m_out_buf_ofs += n;
  3100. }
  3101. }
  3102. return d->m_output_flush_remaining;
  3103. }
  3104. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3105. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
  3106. static MZ_FORCEINLINE void
  3107. tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3108. mz_uint max_match_len, mz_uint *pMatch_dist,
  3109. mz_uint *pMatch_len) {
  3110. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3111. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3112. probe_len;
  3113. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3114. const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
  3115. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
  3116. s01 = TDEFL_READ_UNALIGNED_WORD(s);
  3117. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3118. if (max_match_len <= match_len)
  3119. return;
  3120. for (;;) {
  3121. for (;;) {
  3122. if (--num_probes_left == 0)
  3123. return;
  3124. #define TDEFL_PROBE \
  3125. next_probe_pos = d->m_next[probe_pos]; \
  3126. if ((!next_probe_pos) || \
  3127. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3128. return; \
  3129. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3130. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
  3131. break;
  3132. TDEFL_PROBE;
  3133. TDEFL_PROBE;
  3134. TDEFL_PROBE;
  3135. }
  3136. if (!dist)
  3137. break;
  3138. q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3139. if (TDEFL_READ_UNALIGNED_WORD(q) != s01)
  3140. continue;
  3141. p = s;
  3142. probe_len = 32;
  3143. do {
  3144. } while (
  3145. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3146. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3147. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3148. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3149. (--probe_len > 0));
  3150. if (!probe_len) {
  3151. *pMatch_dist = dist;
  3152. *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
  3153. break;
  3154. } else if ((probe_len = ((mz_uint)(p - s) * 2) +
  3155. (mz_uint)(*(const mz_uint8 *)p ==
  3156. *(const mz_uint8 *)q)) > match_len) {
  3157. *pMatch_dist = dist;
  3158. if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
  3159. max_match_len)
  3160. break;
  3161. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  3162. }
  3163. }
  3164. }
  3165. #else
  3166. static MZ_FORCEINLINE void
  3167. tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3168. mz_uint max_match_len, mz_uint *pMatch_dist,
  3169. mz_uint *pMatch_len) {
  3170. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3171. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3172. probe_len;
  3173. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3174. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  3175. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  3176. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3177. if (max_match_len <= match_len)
  3178. return;
  3179. for (;;) {
  3180. for (;;) {
  3181. if (--num_probes_left == 0)
  3182. return;
  3183. #define TDEFL_PROBE \
  3184. next_probe_pos = d->m_next[probe_pos]; \
  3185. if ((!next_probe_pos) || \
  3186. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3187. return; \
  3188. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3189. if ((d->m_dict[probe_pos + match_len] == c0) && \
  3190. (d->m_dict[probe_pos + match_len - 1] == c1)) \
  3191. break;
  3192. TDEFL_PROBE;
  3193. TDEFL_PROBE;
  3194. TDEFL_PROBE;
  3195. }
  3196. if (!dist)
  3197. break;
  3198. p = s;
  3199. q = d->m_dict + probe_pos;
  3200. for (probe_len = 0; probe_len < max_match_len; probe_len++)
  3201. if (*p++ != *q++)
  3202. break;
  3203. if (probe_len > match_len) {
  3204. *pMatch_dist = dist;
  3205. if ((*pMatch_len = match_len = probe_len) == max_match_len)
  3206. return;
  3207. c0 = d->m_dict[pos + match_len];
  3208. c1 = d->m_dict[pos + match_len - 1];
  3209. }
  3210. }
  3211. }
  3212. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3213. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3214. static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
  3215. // Faster, minimally featured LZRW1-style match+parse loop with better
  3216. // register utilization. Intended for applications where raw throughput is
  3217. // valued more highly than ratio.
  3218. mz_uint lookahead_pos = d->m_lookahead_pos,
  3219. lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
  3220. total_lz_bytes = d->m_total_lz_bytes,
  3221. num_flags_left = d->m_num_flags_left;
  3222. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  3223. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3224. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
  3225. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  3226. mz_uint dst_pos =
  3227. (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  3228. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3229. d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  3230. d->m_src_buf_left -= num_bytes_to_process;
  3231. lookahead_size += num_bytes_to_process;
  3232. while (num_bytes_to_process) {
  3233. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  3234. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  3235. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3236. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
  3237. MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  3238. d->m_pSrc += n;
  3239. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  3240. num_bytes_to_process -= n;
  3241. }
  3242. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  3243. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
  3244. break;
  3245. while (lookahead_size >= 4) {
  3246. mz_uint cur_match_dist, cur_match_len = 1;
  3247. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  3248. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  3249. mz_uint hash =
  3250. (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
  3251. TDEFL_LEVEL1_HASH_SIZE_MASK;
  3252. mz_uint probe_pos = d->m_hash[hash];
  3253. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  3254. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
  3255. dict_size) &&
  3256. ((*(const mz_uint32 *)(d->m_dict +
  3257. (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
  3258. 0xFFFFFF) == first_trigram)) {
  3259. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  3260. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3261. mz_uint32 probe_len = 32;
  3262. do {
  3263. } while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
  3264. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3265. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3266. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3267. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3268. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3269. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3270. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3271. (--probe_len > 0));
  3272. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
  3273. (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  3274. if (!probe_len)
  3275. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  3276. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
  3277. ((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3278. (cur_match_dist >= 8U * 1024U))) {
  3279. cur_match_len = 1;
  3280. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3281. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3282. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3283. } else {
  3284. mz_uint32 s0, s1;
  3285. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  3286. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
  3287. (cur_match_dist >= 1) &&
  3288. (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  3289. cur_match_dist--;
  3290. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  3291. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  3292. pLZ_code_buf += 3;
  3293. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  3294. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  3295. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  3296. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  3297. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
  3298. TDEFL_MIN_MATCH_LEN]]++;
  3299. }
  3300. } else {
  3301. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3302. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3303. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3304. }
  3305. if (--num_flags_left == 0) {
  3306. num_flags_left = 8;
  3307. pLZ_flags = pLZ_code_buf++;
  3308. }
  3309. total_lz_bytes += cur_match_len;
  3310. lookahead_pos += cur_match_len;
  3311. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  3312. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  3313. MZ_ASSERT(lookahead_size >= cur_match_len);
  3314. lookahead_size -= cur_match_len;
  3315. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3316. int n;
  3317. d->m_lookahead_pos = lookahead_pos;
  3318. d->m_lookahead_size = lookahead_size;
  3319. d->m_dict_size = dict_size;
  3320. d->m_total_lz_bytes = total_lz_bytes;
  3321. d->m_pLZ_code_buf = pLZ_code_buf;
  3322. d->m_pLZ_flags = pLZ_flags;
  3323. d->m_num_flags_left = num_flags_left;
  3324. if ((n = tdefl_flush_block(d, 0)) != 0)
  3325. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3326. total_lz_bytes = d->m_total_lz_bytes;
  3327. pLZ_code_buf = d->m_pLZ_code_buf;
  3328. pLZ_flags = d->m_pLZ_flags;
  3329. num_flags_left = d->m_num_flags_left;
  3330. }
  3331. }
  3332. while (lookahead_size) {
  3333. mz_uint8 lit = d->m_dict[cur_pos];
  3334. total_lz_bytes++;
  3335. *pLZ_code_buf++ = lit;
  3336. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3337. if (--num_flags_left == 0) {
  3338. num_flags_left = 8;
  3339. pLZ_flags = pLZ_code_buf++;
  3340. }
  3341. d->m_huff_count[0][lit]++;
  3342. lookahead_pos++;
  3343. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  3344. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3345. lookahead_size--;
  3346. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3347. int n;
  3348. d->m_lookahead_pos = lookahead_pos;
  3349. d->m_lookahead_size = lookahead_size;
  3350. d->m_dict_size = dict_size;
  3351. d->m_total_lz_bytes = total_lz_bytes;
  3352. d->m_pLZ_code_buf = pLZ_code_buf;
  3353. d->m_pLZ_flags = pLZ_flags;
  3354. d->m_num_flags_left = num_flags_left;
  3355. if ((n = tdefl_flush_block(d, 0)) != 0)
  3356. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3357. total_lz_bytes = d->m_total_lz_bytes;
  3358. pLZ_code_buf = d->m_pLZ_code_buf;
  3359. pLZ_flags = d->m_pLZ_flags;
  3360. num_flags_left = d->m_num_flags_left;
  3361. }
  3362. }
  3363. }
  3364. d->m_lookahead_pos = lookahead_pos;
  3365. d->m_lookahead_size = lookahead_size;
  3366. d->m_dict_size = dict_size;
  3367. d->m_total_lz_bytes = total_lz_bytes;
  3368. d->m_pLZ_code_buf = pLZ_code_buf;
  3369. d->m_pLZ_flags = pLZ_flags;
  3370. d->m_num_flags_left = num_flags_left;
  3371. return MZ_TRUE;
  3372. }
  3373. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3374. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
  3375. mz_uint8 lit) {
  3376. d->m_total_lz_bytes++;
  3377. *d->m_pLZ_code_buf++ = lit;
  3378. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
  3379. if (--d->m_num_flags_left == 0) {
  3380. d->m_num_flags_left = 8;
  3381. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3382. }
  3383. d->m_huff_count[0][lit]++;
  3384. }
  3385. static MZ_FORCEINLINE void
  3386. tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) {
  3387. mz_uint32 s0, s1;
  3388. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
  3389. (match_dist <= TDEFL_LZ_DICT_SIZE));
  3390. d->m_total_lz_bytes += match_len;
  3391. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  3392. match_dist -= 1;
  3393. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  3394. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
  3395. d->m_pLZ_code_buf += 3;
  3396. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
  3397. if (--d->m_num_flags_left == 0) {
  3398. d->m_num_flags_left = 8;
  3399. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3400. }
  3401. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3402. s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  3403. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  3404. if (match_len >= TDEFL_MIN_MATCH_LEN)
  3405. d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  3406. }
  3407. static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
  3408. const mz_uint8 *pSrc = d->m_pSrc;
  3409. size_t src_buf_left = d->m_src_buf_left;
  3410. tdefl_flush flush = d->m_flush;
  3411. while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
  3412. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  3413. // Update dictionary and hash chains. Keeps the lookahead size equal to
  3414. // TDEFL_MAX_MATCH_LEN.
  3415. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
  3416. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3417. TDEFL_LZ_DICT_SIZE_MASK,
  3418. ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  3419. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3420. << TDEFL_LZ_HASH_SHIFT) ^
  3421. d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3422. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3423. src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  3424. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  3425. src_buf_left -= num_bytes_to_process;
  3426. d->m_lookahead_size += num_bytes_to_process;
  3427. while (pSrc != pSrc_end) {
  3428. mz_uint8 c = *pSrc++;
  3429. d->m_dict[dst_pos] = c;
  3430. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3431. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3432. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  3433. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3434. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3435. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3436. ins_pos++;
  3437. }
  3438. } else {
  3439. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
  3440. mz_uint8 c = *pSrc++;
  3441. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3442. TDEFL_LZ_DICT_SIZE_MASK;
  3443. src_buf_left--;
  3444. d->m_dict[dst_pos] = c;
  3445. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3446. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3447. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
  3448. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  3449. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3450. << (TDEFL_LZ_HASH_SHIFT * 2)) ^
  3451. (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
  3452. << TDEFL_LZ_HASH_SHIFT) ^
  3453. c) &
  3454. (TDEFL_LZ_HASH_SIZE - 1);
  3455. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3456. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3457. }
  3458. }
  3459. }
  3460. d->m_dict_size =
  3461. MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  3462. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  3463. break;
  3464. // Simple lazy/greedy parsing state machine.
  3465. len_to_move = 1;
  3466. cur_match_dist = 0;
  3467. cur_match_len =
  3468. d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
  3469. cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3470. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
  3471. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
  3472. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3473. cur_match_len = 0;
  3474. while (cur_match_len < d->m_lookahead_size) {
  3475. if (d->m_dict[cur_pos + cur_match_len] != c)
  3476. break;
  3477. cur_match_len++;
  3478. }
  3479. if (cur_match_len < TDEFL_MIN_MATCH_LEN)
  3480. cur_match_len = 0;
  3481. else
  3482. cur_match_dist = 1;
  3483. }
  3484. } else {
  3485. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
  3486. d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  3487. }
  3488. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3489. (cur_match_dist >= 8U * 1024U)) ||
  3490. (cur_pos == cur_match_dist) ||
  3491. ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
  3492. cur_match_dist = cur_match_len = 0;
  3493. }
  3494. if (d->m_saved_match_len) {
  3495. if (cur_match_len > d->m_saved_match_len) {
  3496. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  3497. if (cur_match_len >= 128) {
  3498. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3499. d->m_saved_match_len = 0;
  3500. len_to_move = cur_match_len;
  3501. } else {
  3502. d->m_saved_lit = d->m_dict[cur_pos];
  3503. d->m_saved_match_dist = cur_match_dist;
  3504. d->m_saved_match_len = cur_match_len;
  3505. }
  3506. } else {
  3507. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  3508. len_to_move = d->m_saved_match_len - 1;
  3509. d->m_saved_match_len = 0;
  3510. }
  3511. } else if (!cur_match_dist)
  3512. tdefl_record_literal(d,
  3513. d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  3514. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
  3515. (cur_match_len >= 128)) {
  3516. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3517. len_to_move = cur_match_len;
  3518. } else {
  3519. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
  3520. d->m_saved_match_dist = cur_match_dist;
  3521. d->m_saved_match_len = cur_match_len;
  3522. }
  3523. // Move the lookahead forward by len_to_move bytes.
  3524. d->m_lookahead_pos += len_to_move;
  3525. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  3526. d->m_lookahead_size -= len_to_move;
  3527. d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
  3528. // Check if it's time to flush the current LZ codes to the internal output
  3529. // buffer.
  3530. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  3531. ((d->m_total_lz_bytes > 31 * 1024) &&
  3532. (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
  3533. d->m_total_lz_bytes) ||
  3534. (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
  3535. int n;
  3536. d->m_pSrc = pSrc;
  3537. d->m_src_buf_left = src_buf_left;
  3538. if ((n = tdefl_flush_block(d, 0)) != 0)
  3539. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3540. }
  3541. }
  3542. d->m_pSrc = pSrc;
  3543. d->m_src_buf_left = src_buf_left;
  3544. return MZ_TRUE;
  3545. }
  3546. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
  3547. if (d->m_pIn_buf_size) {
  3548. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3549. }
  3550. if (d->m_pOut_buf_size) {
  3551. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
  3552. d->m_output_flush_remaining);
  3553. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
  3554. d->m_output_buf + d->m_output_flush_ofs, n);
  3555. d->m_output_flush_ofs += (mz_uint)n;
  3556. d->m_output_flush_remaining -= (mz_uint)n;
  3557. d->m_out_buf_ofs += n;
  3558. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  3559. }
  3560. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
  3561. : TDEFL_STATUS_OKAY;
  3562. }
  3563. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  3564. size_t *pIn_buf_size, void *pOut_buf,
  3565. size_t *pOut_buf_size, tdefl_flush flush) {
  3566. if (!d) {
  3567. if (pIn_buf_size)
  3568. *pIn_buf_size = 0;
  3569. if (pOut_buf_size)
  3570. *pOut_buf_size = 0;
  3571. return TDEFL_STATUS_BAD_PARAM;
  3572. }
  3573. d->m_pIn_buf = pIn_buf;
  3574. d->m_pIn_buf_size = pIn_buf_size;
  3575. d->m_pOut_buf = pOut_buf;
  3576. d->m_pOut_buf_size = pOut_buf_size;
  3577. d->m_pSrc = (const mz_uint8 *)(pIn_buf);
  3578. d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  3579. d->m_out_buf_ofs = 0;
  3580. d->m_flush = flush;
  3581. if (((d->m_pPut_buf_func != NULL) ==
  3582. ((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
  3583. (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  3584. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
  3585. (pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
  3586. (pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
  3587. if (pIn_buf_size)
  3588. *pIn_buf_size = 0;
  3589. if (pOut_buf_size)
  3590. *pOut_buf_size = 0;
  3591. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  3592. }
  3593. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  3594. if ((d->m_output_flush_remaining) || (d->m_finished))
  3595. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3596. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3597. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  3598. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  3599. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
  3600. TDEFL_RLE_MATCHES)) == 0)) {
  3601. if (!tdefl_compress_fast(d))
  3602. return d->m_prev_return_status;
  3603. } else
  3604. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3605. {
  3606. if (!tdefl_compress_normal(d))
  3607. return d->m_prev_return_status;
  3608. }
  3609. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
  3610. (pIn_buf))
  3611. d->m_adler32 =
  3612. (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
  3613. d->m_pSrc - (const mz_uint8 *)pIn_buf);
  3614. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
  3615. (!d->m_output_flush_remaining)) {
  3616. if (tdefl_flush_block(d, flush) < 0)
  3617. return d->m_prev_return_status;
  3618. d->m_finished = (flush == TDEFL_FINISH);
  3619. if (flush == TDEFL_FULL_FLUSH) {
  3620. MZ_CLEAR_OBJ(d->m_hash);
  3621. MZ_CLEAR_OBJ(d->m_next);
  3622. d->m_dict_size = 0;
  3623. }
  3624. }
  3625. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3626. }
  3627. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  3628. size_t in_buf_size, tdefl_flush flush) {
  3629. MZ_ASSERT(d->m_pPut_buf_func);
  3630. return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  3631. }
  3632. tdefl_status tdefl_init(tdefl_compressor *d,
  3633. tdefl_put_buf_func_ptr pPut_buf_func,
  3634. void *pPut_buf_user, int flags) {
  3635. d->m_pPut_buf_func = pPut_buf_func;
  3636. d->m_pPut_buf_user = pPut_buf_user;
  3637. d->m_flags = (mz_uint)(flags);
  3638. d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
  3639. d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  3640. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  3641. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))
  3642. MZ_CLEAR_OBJ(d->m_hash);
  3643. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
  3644. d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  3645. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
  3646. d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  3647. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3648. d->m_pLZ_flags = d->m_lz_code_buf;
  3649. d->m_num_flags_left = 8;
  3650. d->m_pOutput_buf = d->m_output_buf;
  3651. d->m_pOutput_buf_end = d->m_output_buf;
  3652. d->m_prev_return_status = TDEFL_STATUS_OKAY;
  3653. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
  3654. d->m_adler32 = 1;
  3655. d->m_pIn_buf = NULL;
  3656. d->m_pOut_buf = NULL;
  3657. d->m_pIn_buf_size = NULL;
  3658. d->m_pOut_buf_size = NULL;
  3659. d->m_flush = TDEFL_NO_FLUSH;
  3660. d->m_pSrc = NULL;
  3661. d->m_src_buf_left = 0;
  3662. d->m_out_buf_ofs = 0;
  3663. memset(&d->m_huff_count[0][0], 0,
  3664. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3665. memset(&d->m_huff_count[1][0], 0,
  3666. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3667. return TDEFL_STATUS_OKAY;
  3668. }
  3669. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
  3670. return d->m_prev_return_status;
  3671. }
  3672. mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
  3673. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  3674. tdefl_put_buf_func_ptr pPut_buf_func,
  3675. void *pPut_buf_user, int flags) {
  3676. tdefl_compressor *pComp;
  3677. mz_bool succeeded;
  3678. if (((buf_len) && (!pBuf)) || (!pPut_buf_func))
  3679. return MZ_FALSE;
  3680. pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3681. if (!pComp)
  3682. return MZ_FALSE;
  3683. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
  3684. TDEFL_STATUS_OKAY);
  3685. succeeded =
  3686. succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
  3687. TDEFL_STATUS_DONE);
  3688. MZ_FREE(pComp);
  3689. return succeeded;
  3690. }
  3691. typedef struct {
  3692. size_t m_size, m_capacity;
  3693. mz_uint8 *m_pBuf;
  3694. mz_bool m_expandable;
  3695. } tdefl_output_buffer;
  3696. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
  3697. void *pUser) {
  3698. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  3699. size_t new_size = p->m_size + len;
  3700. if (new_size > p->m_capacity) {
  3701. size_t new_capacity = p->m_capacity;
  3702. mz_uint8 *pNew_buf;
  3703. if (!p->m_expandable)
  3704. return MZ_FALSE;
  3705. do {
  3706. new_capacity = MZ_MAX(128U, new_capacity << 1U);
  3707. } while (new_size > new_capacity);
  3708. pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
  3709. if (!pNew_buf)
  3710. return MZ_FALSE;
  3711. p->m_pBuf = pNew_buf;
  3712. p->m_capacity = new_capacity;
  3713. }
  3714. memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
  3715. p->m_size = new_size;
  3716. return MZ_TRUE;
  3717. }
  3718. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  3719. size_t *pOut_len, int flags) {
  3720. tdefl_output_buffer out_buf;
  3721. MZ_CLEAR_OBJ(out_buf);
  3722. if (!pOut_len)
  3723. return MZ_FALSE;
  3724. else
  3725. *pOut_len = 0;
  3726. out_buf.m_expandable = MZ_TRUE;
  3727. if (!tdefl_compress_mem_to_output(
  3728. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3729. return NULL;
  3730. *pOut_len = out_buf.m_size;
  3731. return out_buf.m_pBuf;
  3732. }
  3733. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  3734. const void *pSrc_buf, size_t src_buf_len,
  3735. int flags) {
  3736. tdefl_output_buffer out_buf;
  3737. MZ_CLEAR_OBJ(out_buf);
  3738. if (!pOut_buf)
  3739. return 0;
  3740. out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
  3741. out_buf.m_capacity = out_buf_len;
  3742. if (!tdefl_compress_mem_to_output(
  3743. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3744. return 0;
  3745. return out_buf.m_size;
  3746. }
  3747. #ifndef MINIZ_NO_ZLIB_APIS
  3748. static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
  3749. 128, 256, 512, 768, 1500};
  3750. // level may actually range from [0,10] (10 is a "hidden" max level, where we
  3751. // want a bit more compression and it's fine if throughput to fall off a cliff
  3752. // on some files).
  3753. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  3754. int strategy) {
  3755. mz_uint comp_flags =
  3756. s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
  3757. ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  3758. if (window_bits > 0)
  3759. comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  3760. if (!level)
  3761. comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  3762. else if (strategy == MZ_FILTERED)
  3763. comp_flags |= TDEFL_FILTER_MATCHES;
  3764. else if (strategy == MZ_HUFFMAN_ONLY)
  3765. comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  3766. else if (strategy == MZ_FIXED)
  3767. comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  3768. else if (strategy == MZ_RLE)
  3769. comp_flags |= TDEFL_RLE_MATCHES;
  3770. return comp_flags;
  3771. }
  3772. #endif // MINIZ_NO_ZLIB_APIS
  3773. #ifdef _MSC_VER
  3774. #pragma warning(push)
  3775. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  3776. // aggregate initializer (also supported by GNU
  3777. // C and C99, so no big deal)
  3778. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  3779. // 'int', possible loss of data
  3780. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to 'int',
  3781. // possible loss of data
  3782. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  3783. // deprecated. Instead, use the ISO C and C++
  3784. // conformant name: _strdup.
  3785. #endif
  3786. // Simple PNG writer function by Alex Evans, 2011. Released into the public
  3787. // domain: https://gist.github.com/908299, more context at
  3788. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  3789. // This is actually a modification of Alex's original code so PNG files
  3790. // generated by this function pass pngcheck.
  3791. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  3792. int h, int num_chans,
  3793. size_t *pLen_out,
  3794. mz_uint level, mz_bool flip) {
  3795. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
  3796. // defined.
  3797. static const mz_uint s_tdefl_png_num_probes[11] = {
  3798. 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
  3799. tdefl_compressor *pComp =
  3800. (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3801. tdefl_output_buffer out_buf;
  3802. int i, bpl = w * num_chans, y, z;
  3803. mz_uint32 c;
  3804. *pLen_out = 0;
  3805. if (!pComp)
  3806. return NULL;
  3807. MZ_CLEAR_OBJ(out_buf);
  3808. out_buf.m_expandable = MZ_TRUE;
  3809. out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
  3810. if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
  3811. MZ_FREE(pComp);
  3812. return NULL;
  3813. }
  3814. // write dummy header
  3815. for (z = 41; z; --z)
  3816. tdefl_output_buffer_putter(&z, 1, &out_buf);
  3817. // compress image data
  3818. tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf,
  3819. s_tdefl_png_num_probes[MZ_MIN(10, level)] |
  3820. TDEFL_WRITE_ZLIB_HEADER);
  3821. for (y = 0; y < h; ++y) {
  3822. tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
  3823. tdefl_compress_buffer(pComp,
  3824. (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
  3825. bpl, TDEFL_NO_FLUSH);
  3826. }
  3827. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
  3828. TDEFL_STATUS_DONE) {
  3829. MZ_FREE(pComp);
  3830. MZ_FREE(out_buf.m_pBuf);
  3831. return NULL;
  3832. }
  3833. // write real header
  3834. *pLen_out = out_buf.m_size - 41;
  3835. {
  3836. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  3837. mz_uint8 pnghdr[41] = {
  3838. 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
  3839. 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0,
  3840. (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0,
  3841. 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16),
  3842. (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41,
  3843. 0x54};
  3844. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
  3845. for (i = 0; i < 4; ++i, c <<= 8)
  3846. ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
  3847. memcpy(out_buf.m_pBuf, pnghdr, 41);
  3848. }
  3849. // write footer (IDAT CRC-32, followed by IEND chunk)
  3850. if (!tdefl_output_buffer_putter(
  3851. "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
  3852. *pLen_out = 0;
  3853. MZ_FREE(pComp);
  3854. MZ_FREE(out_buf.m_pBuf);
  3855. return NULL;
  3856. }
  3857. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
  3858. *pLen_out + 4);
  3859. for (i = 0; i < 4; ++i, c <<= 8)
  3860. (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
  3861. // compute final size of file, grab compressed data buffer and return
  3862. *pLen_out += 57;
  3863. MZ_FREE(pComp);
  3864. return out_buf.m_pBuf;
  3865. }
  3866. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  3867. int num_chans, size_t *pLen_out) {
  3868. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
  3869. // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
  3870. // where #defined out)
  3871. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
  3872. pLen_out, 6, MZ_FALSE);
  3873. }
  3874. // ------------------- .ZIP archive reading
  3875. #ifndef MINIZ_NO_ARCHIVE_APIS
  3876. #ifdef MINIZ_NO_STDIO
  3877. #define MZ_FILE void *
  3878. #else
  3879. #include <stdio.h>
  3880. #include <sys/stat.h>
  3881. #if defined(_MSC_VER) //|| defined(__MINGW64__)
  3882. static FILE *mz_fopen(const char *pFilename, const char *pMode) {
  3883. FILE *pFile = NULL;
  3884. fopen_s(&pFile, pFilename, pMode);
  3885. return pFile;
  3886. }
  3887. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
  3888. FILE *pFile = NULL;
  3889. if (freopen_s(&pFile, pPath, pMode, pStream))
  3890. return NULL;
  3891. return pFile;
  3892. }
  3893. #ifndef MINIZ_NO_TIME
  3894. #include <sys/utime.h>
  3895. #endif
  3896. #define MZ_FILE FILE
  3897. #define MZ_FOPEN mz_fopen
  3898. #define MZ_FCLOSE fclose
  3899. #define MZ_FREAD fread
  3900. #define MZ_FWRITE fwrite
  3901. #define MZ_FTELL64 _ftelli64
  3902. #define MZ_FSEEK64 _fseeki64
  3903. #define MZ_FILE_STAT_STRUCT _stat
  3904. #define MZ_FILE_STAT _stat
  3905. #define MZ_FFLUSH fflush
  3906. #define MZ_FREOPEN mz_freopen
  3907. #define MZ_DELETE_FILE remove
  3908. #elif defined(__MINGW32__)
  3909. #ifndef MINIZ_NO_TIME
  3910. #include <sys/utime.h>
  3911. #endif
  3912. #define MZ_FILE FILE
  3913. #define MZ_FOPEN(f, m) fopen(f, m)
  3914. #define MZ_FCLOSE fclose
  3915. #define MZ_FREAD fread
  3916. #define MZ_FWRITE fwrite
  3917. #define MZ_FTELL64 ftello64
  3918. #define MZ_FSEEK64 fseeko64
  3919. #define MZ_FILE_STAT_STRUCT _stat
  3920. #define MZ_FILE_STAT _stat
  3921. #define MZ_FFLUSH fflush
  3922. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  3923. #define MZ_DELETE_FILE remove
  3924. #elif defined(__TINYC__)
  3925. #ifndef MINIZ_NO_TIME
  3926. #include <sys/utime.h>
  3927. #endif
  3928. #define MZ_FILE FILE
  3929. #define MZ_FOPEN(f, m) fopen(f, m)
  3930. #define MZ_FCLOSE fclose
  3931. #define MZ_FREAD fread
  3932. #define MZ_FWRITE fwrite
  3933. #define MZ_FTELL64 ftell
  3934. #define MZ_FSEEK64 fseek
  3935. #define MZ_FILE_STAT_STRUCT stat
  3936. #define MZ_FILE_STAT stat
  3937. #define MZ_FFLUSH fflush
  3938. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  3939. #define MZ_DELETE_FILE remove
  3940. #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
  3941. #ifndef MINIZ_NO_TIME
  3942. #include <utime.h>
  3943. #endif
  3944. #define MZ_FILE FILE
  3945. #define MZ_FOPEN(f, m) fopen64(f, m)
  3946. #define MZ_FCLOSE fclose
  3947. #define MZ_FREAD fread
  3948. #define MZ_FWRITE fwrite
  3949. #define MZ_FTELL64 ftello64
  3950. #define MZ_FSEEK64 fseeko64
  3951. #define MZ_FILE_STAT_STRUCT stat64
  3952. #define MZ_FILE_STAT stat64
  3953. #define MZ_FFLUSH fflush
  3954. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  3955. #define MZ_DELETE_FILE remove
  3956. #else
  3957. #ifndef MINIZ_NO_TIME
  3958. #include <utime.h>
  3959. #endif
  3960. #define MZ_FILE FILE
  3961. #define MZ_FOPEN(f, m) fopen(f, m)
  3962. #define MZ_FCLOSE fclose
  3963. #define MZ_FREAD fread
  3964. #define MZ_FWRITE fwrite
  3965. #define MZ_FTELL64 ftello
  3966. #define MZ_FSEEK64 fseeko
  3967. #define MZ_FILE_STAT_STRUCT stat
  3968. #define MZ_FILE_STAT stat
  3969. #define MZ_FFLUSH fflush
  3970. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  3971. #define MZ_DELETE_FILE remove
  3972. #endif // #ifdef _MSC_VER
  3973. #endif // #ifdef MINIZ_NO_STDIO
  3974. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  3975. // Various ZIP archive enums. To completely avoid cross platform compiler
  3976. // alignment and platform endian issues, miniz.c doesn't use structs for any of
  3977. // this stuff.
  3978. enum {
  3979. // ZIP archive identifiers and record sizes
  3980. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
  3981. MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
  3982. MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  3983. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
  3984. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
  3985. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  3986. // Central directory header record offsets
  3987. MZ_ZIP_CDH_SIG_OFS = 0,
  3988. MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
  3989. MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
  3990. MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  3991. MZ_ZIP_CDH_METHOD_OFS = 10,
  3992. MZ_ZIP_CDH_FILE_TIME_OFS = 12,
  3993. MZ_ZIP_CDH_FILE_DATE_OFS = 14,
  3994. MZ_ZIP_CDH_CRC32_OFS = 16,
  3995. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
  3996. MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
  3997. MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
  3998. MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  3999. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
  4000. MZ_ZIP_CDH_DISK_START_OFS = 34,
  4001. MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
  4002. MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
  4003. MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  4004. // Local directory header offsets
  4005. MZ_ZIP_LDH_SIG_OFS = 0,
  4006. MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
  4007. MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
  4008. MZ_ZIP_LDH_METHOD_OFS = 8,
  4009. MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  4010. MZ_ZIP_LDH_FILE_DATE_OFS = 12,
  4011. MZ_ZIP_LDH_CRC32_OFS = 14,
  4012. MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
  4013. MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  4014. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
  4015. MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  4016. // End of central directory offsets
  4017. MZ_ZIP_ECDH_SIG_OFS = 0,
  4018. MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
  4019. MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
  4020. MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  4021. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
  4022. MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
  4023. MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
  4024. MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  4025. };
  4026. typedef struct {
  4027. void *m_p;
  4028. size_t m_size, m_capacity;
  4029. mz_uint m_element_size;
  4030. } mz_zip_array;
  4031. struct mz_zip_internal_state_tag {
  4032. mz_zip_array m_central_dir;
  4033. mz_zip_array m_central_dir_offsets;
  4034. mz_zip_array m_sorted_central_dir_offsets;
  4035. MZ_FILE *m_pFile;
  4036. void *m_pMem;
  4037. size_t m_mem_size;
  4038. size_t m_mem_capacity;
  4039. };
  4040. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
  4041. (array_ptr)->m_element_size = element_size
  4042. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
  4043. ((element_type *)((array_ptr)->m_p))[index]
  4044. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
  4045. mz_zip_array *pArray) {
  4046. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  4047. memset(pArray, 0, sizeof(mz_zip_array));
  4048. }
  4049. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
  4050. mz_zip_array *pArray,
  4051. size_t min_new_capacity,
  4052. mz_uint growing) {
  4053. void *pNew_p;
  4054. size_t new_capacity = min_new_capacity;
  4055. MZ_ASSERT(pArray->m_element_size);
  4056. if (pArray->m_capacity >= min_new_capacity)
  4057. return MZ_TRUE;
  4058. if (growing) {
  4059. new_capacity = MZ_MAX(1, pArray->m_capacity);
  4060. while (new_capacity < min_new_capacity)
  4061. new_capacity *= 2;
  4062. }
  4063. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
  4064. pArray->m_element_size, new_capacity)))
  4065. return MZ_FALSE;
  4066. pArray->m_p = pNew_p;
  4067. pArray->m_capacity = new_capacity;
  4068. return MZ_TRUE;
  4069. }
  4070. static MZ_FORCEINLINE mz_bool
  4071. mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray,
  4072. size_t new_capacity, mz_uint growing) {
  4073. if (new_capacity > pArray->m_capacity) {
  4074. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
  4075. return MZ_FALSE;
  4076. }
  4077. return MZ_TRUE;
  4078. }
  4079. static MZ_FORCEINLINE mz_bool
  4080. mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size,
  4081. mz_uint growing) {
  4082. if (new_size > pArray->m_capacity) {
  4083. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
  4084. return MZ_FALSE;
  4085. }
  4086. pArray->m_size = new_size;
  4087. return MZ_TRUE;
  4088. }
  4089. static MZ_FORCEINLINE mz_bool
  4090. mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) {
  4091. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  4092. }
  4093. static MZ_FORCEINLINE mz_bool
  4094. mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray,
  4095. const void *pElements, size_t n) {
  4096. size_t orig_size = pArray->m_size;
  4097. if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
  4098. return MZ_FALSE;
  4099. memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
  4100. pElements, n * pArray->m_element_size);
  4101. return MZ_TRUE;
  4102. }
  4103. #ifndef MINIZ_NO_TIME
  4104. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
  4105. struct tm tm;
  4106. memset(&tm, 0, sizeof(tm));
  4107. tm.tm_isdst = -1;
  4108. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
  4109. tm.tm_mon = ((dos_date >> 5) & 15) - 1;
  4110. tm.tm_mday = dos_date & 31;
  4111. tm.tm_hour = (dos_time >> 11) & 31;
  4112. tm.tm_min = (dos_time >> 5) & 63;
  4113. tm.tm_sec = (dos_time << 1) & 62;
  4114. return mktime(&tm);
  4115. }
  4116. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
  4117. mz_uint16 *pDOS_date) {
  4118. #ifdef _MSC_VER
  4119. struct tm tm_struct;
  4120. struct tm *tm = &tm_struct;
  4121. errno_t err = localtime_s(tm, &time);
  4122. if (err) {
  4123. *pDOS_date = 0;
  4124. *pDOS_time = 0;
  4125. return;
  4126. }
  4127. #else
  4128. struct tm *tm = localtime(&time);
  4129. #endif
  4130. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
  4131. ((tm->tm_sec) >> 1));
  4132. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
  4133. ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  4134. }
  4135. #endif
  4136. #ifndef MINIZ_NO_STDIO
  4137. static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
  4138. mz_uint16 *pDOS_time,
  4139. mz_uint16 *pDOS_date) {
  4140. #ifdef MINIZ_NO_TIME
  4141. (void)pFilename;
  4142. *pDOS_date = *pDOS_time = 0;
  4143. #else
  4144. struct MZ_FILE_STAT_STRUCT file_stat;
  4145. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
  4146. // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  4147. if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
  4148. return MZ_FALSE;
  4149. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  4150. #endif // #ifdef MINIZ_NO_TIME
  4151. return MZ_TRUE;
  4152. }
  4153. #ifndef MINIZ_NO_TIME
  4154. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
  4155. time_t modified_time) {
  4156. struct utimbuf t;
  4157. t.actime = access_time;
  4158. t.modtime = modified_time;
  4159. return !utime(pFilename, &t);
  4160. }
  4161. #endif // #ifndef MINIZ_NO_TIME
  4162. #endif // #ifndef MINIZ_NO_STDIO
  4163. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
  4164. mz_uint32 flags) {
  4165. (void)flags;
  4166. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  4167. return MZ_FALSE;
  4168. if (!pZip->m_pAlloc)
  4169. pZip->m_pAlloc = def_alloc_func;
  4170. if (!pZip->m_pFree)
  4171. pZip->m_pFree = def_free_func;
  4172. if (!pZip->m_pRealloc)
  4173. pZip->m_pRealloc = def_realloc_func;
  4174. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  4175. pZip->m_archive_size = 0;
  4176. pZip->m_central_directory_file_ofs = 0;
  4177. pZip->m_total_files = 0;
  4178. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  4179. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  4180. return MZ_FALSE;
  4181. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  4182. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  4183. sizeof(mz_uint8));
  4184. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  4185. sizeof(mz_uint32));
  4186. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  4187. sizeof(mz_uint32));
  4188. return MZ_TRUE;
  4189. }
  4190. static MZ_FORCEINLINE mz_bool
  4191. mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
  4192. const mz_zip_array *pCentral_dir_offsets,
  4193. mz_uint l_index, mz_uint r_index) {
  4194. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4195. pCentral_dir_array, mz_uint8,
  4196. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4197. l_index)),
  4198. *pE;
  4199. const mz_uint8 *pR =
  4200. &MZ_ZIP_ARRAY_ELEMENT(
  4201. pCentral_dir_array, mz_uint8,
  4202. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  4203. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
  4204. r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4205. mz_uint8 l = 0, r = 0;
  4206. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4207. pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4208. pE = pL + MZ_MIN(l_len, r_len);
  4209. while (pL < pE) {
  4210. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  4211. break;
  4212. pL++;
  4213. pR++;
  4214. }
  4215. return (pL == pE) ? (l_len < r_len) : (l < r);
  4216. }
  4217. #define MZ_SWAP_UINT32(a, b) \
  4218. do { \
  4219. mz_uint32 t = a; \
  4220. a = b; \
  4221. b = t; \
  4222. } \
  4223. MZ_MACRO_END
  4224. // Heap sort of lowercased filenames, used to help accelerate plain central
  4225. // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
  4226. // but it could allocate memory.)
  4227. static void
  4228. mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) {
  4229. mz_zip_internal_state *pState = pZip->m_pState;
  4230. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4231. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4232. mz_uint32 *pIndices =
  4233. &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
  4234. 0);
  4235. const int size = pZip->m_total_files;
  4236. int start = (size - 2) >> 1, end;
  4237. while (start >= 0) {
  4238. int child, root = start;
  4239. for (;;) {
  4240. if ((child = (root << 1) + 1) >= size)
  4241. break;
  4242. child +=
  4243. (((child + 1) < size) &&
  4244. (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4245. pIndices[child], pIndices[child + 1])));
  4246. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4247. pIndices[root], pIndices[child]))
  4248. break;
  4249. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4250. root = child;
  4251. }
  4252. start--;
  4253. }
  4254. end = size - 1;
  4255. while (end > 0) {
  4256. int child, root = 0;
  4257. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  4258. for (;;) {
  4259. if ((child = (root << 1) + 1) >= end)
  4260. break;
  4261. child +=
  4262. (((child + 1) < end) &&
  4263. mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4264. pIndices[child], pIndices[child + 1]));
  4265. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4266. pIndices[root], pIndices[child]))
  4267. break;
  4268. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4269. root = child;
  4270. }
  4271. end--;
  4272. }
  4273. }
  4274. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
  4275. mz_uint32 flags) {
  4276. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  4277. mz_uint64 cdir_ofs;
  4278. mz_int64 cur_file_ofs;
  4279. const mz_uint8 *p;
  4280. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
  4281. mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  4282. mz_bool sort_central_dir =
  4283. ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  4284. // Basic sanity checks - reject files which are too small, and check the first
  4285. // 4 bytes of the file to make sure a local header is there.
  4286. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4287. return MZ_FALSE;
  4288. // Find the end of central directory record by scanning the file from the end
  4289. // towards the beginning.
  4290. cur_file_ofs =
  4291. MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  4292. for (;;) {
  4293. int i,
  4294. n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  4295. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  4296. return MZ_FALSE;
  4297. for (i = n - 4; i >= 0; --i)
  4298. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
  4299. break;
  4300. if (i >= 0) {
  4301. cur_file_ofs += i;
  4302. break;
  4303. }
  4304. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
  4305. (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  4306. return MZ_FALSE;
  4307. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  4308. }
  4309. // Read and verify the end of central directory record.
  4310. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4311. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
  4312. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4313. return MZ_FALSE;
  4314. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
  4315. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  4316. ((pZip->m_total_files =
  4317. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
  4318. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  4319. return MZ_FALSE;
  4320. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  4321. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  4322. if (((num_this_disk | cdir_disk_index) != 0) &&
  4323. ((num_this_disk != 1) || (cdir_disk_index != 1)))
  4324. return MZ_FALSE;
  4325. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
  4326. pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  4327. return MZ_FALSE;
  4328. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  4329. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
  4330. return MZ_FALSE;
  4331. pZip->m_central_directory_file_ofs = cdir_ofs;
  4332. if (pZip->m_total_files) {
  4333. mz_uint i, n;
  4334. // Read the entire central directory into a heap block, and allocate another
  4335. // heap block to hold the unsorted central dir file record offsets, and
  4336. // another to hold the sorted indices.
  4337. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
  4338. MZ_FALSE)) ||
  4339. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
  4340. pZip->m_total_files, MZ_FALSE)))
  4341. return MZ_FALSE;
  4342. if (sort_central_dir) {
  4343. if (!mz_zip_array_resize(pZip,
  4344. &pZip->m_pState->m_sorted_central_dir_offsets,
  4345. pZip->m_total_files, MZ_FALSE))
  4346. return MZ_FALSE;
  4347. }
  4348. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
  4349. pZip->m_pState->m_central_dir.m_p,
  4350. cdir_size) != cdir_size)
  4351. return MZ_FALSE;
  4352. // Now create an index into the central directory file records, do some
  4353. // basic sanity checking on each record, and check for zip64 entries (which
  4354. // are not yet supported).
  4355. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  4356. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
  4357. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  4358. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
  4359. (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  4360. return MZ_FALSE;
  4361. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4362. i) =
  4363. (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  4364. if (sort_central_dir)
  4365. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
  4366. mz_uint32, i) = i;
  4367. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4368. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4369. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
  4370. (decomp_size != comp_size)) ||
  4371. (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
  4372. (comp_size == 0xFFFFFFFF))
  4373. return MZ_FALSE;
  4374. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  4375. if ((disk_index != num_this_disk) && (disk_index != 1))
  4376. return MZ_FALSE;
  4377. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
  4378. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  4379. return MZ_FALSE;
  4380. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4381. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4382. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  4383. MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
  4384. n)
  4385. return MZ_FALSE;
  4386. n -= total_header_size;
  4387. p += total_header_size;
  4388. }
  4389. }
  4390. if (sort_central_dir)
  4391. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  4392. return MZ_TRUE;
  4393. }
  4394. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  4395. mz_uint32 flags) {
  4396. if ((!pZip) || (!pZip->m_pRead))
  4397. return MZ_FALSE;
  4398. if (!mz_zip_reader_init_internal(pZip, flags))
  4399. return MZ_FALSE;
  4400. pZip->m_archive_size = size;
  4401. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4402. mz_zip_reader_end(pZip);
  4403. return MZ_FALSE;
  4404. }
  4405. return MZ_TRUE;
  4406. }
  4407. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
  4408. void *pBuf, size_t n) {
  4409. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4410. size_t s = (file_ofs >= pZip->m_archive_size)
  4411. ? 0
  4412. : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  4413. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  4414. return s;
  4415. }
  4416. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  4417. size_t size, mz_uint32 flags) {
  4418. if (!mz_zip_reader_init_internal(pZip, flags))
  4419. return MZ_FALSE;
  4420. pZip->m_archive_size = size;
  4421. pZip->m_pRead = mz_zip_mem_read_func;
  4422. pZip->m_pIO_opaque = pZip;
  4423. #ifdef __cplusplus
  4424. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  4425. #else
  4426. pZip->m_pState->m_pMem = (void *)pMem;
  4427. #endif
  4428. pZip->m_pState->m_mem_size = size;
  4429. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4430. mz_zip_reader_end(pZip);
  4431. return MZ_FALSE;
  4432. }
  4433. return MZ_TRUE;
  4434. }
  4435. #ifndef MINIZ_NO_STDIO
  4436. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
  4437. void *pBuf, size_t n) {
  4438. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4439. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  4440. if (((mz_int64)file_ofs < 0) ||
  4441. (((cur_ofs != (mz_int64)file_ofs)) &&
  4442. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  4443. return 0;
  4444. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  4445. }
  4446. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  4447. mz_uint32 flags) {
  4448. mz_uint64 file_size;
  4449. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  4450. if (!pFile)
  4451. return MZ_FALSE;
  4452. if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
  4453. MZ_FCLOSE(pFile);
  4454. return MZ_FALSE;
  4455. }
  4456. file_size = MZ_FTELL64(pFile);
  4457. if (!mz_zip_reader_init_internal(pZip, flags)) {
  4458. MZ_FCLOSE(pFile);
  4459. return MZ_FALSE;
  4460. }
  4461. pZip->m_pRead = mz_zip_file_read_func;
  4462. pZip->m_pIO_opaque = pZip;
  4463. pZip->m_pState->m_pFile = pFile;
  4464. pZip->m_archive_size = file_size;
  4465. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4466. mz_zip_reader_end(pZip);
  4467. return MZ_FALSE;
  4468. }
  4469. return MZ_TRUE;
  4470. }
  4471. #endif // #ifndef MINIZ_NO_STDIO
  4472. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
  4473. return pZip ? pZip->m_total_files : 0;
  4474. }
  4475. static MZ_FORCEINLINE const mz_uint8 *
  4476. mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) {
  4477. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
  4478. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4479. return NULL;
  4480. return &MZ_ZIP_ARRAY_ELEMENT(
  4481. &pZip->m_pState->m_central_dir, mz_uint8,
  4482. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
  4483. mz_uint32, file_index));
  4484. }
  4485. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  4486. mz_uint file_index) {
  4487. mz_uint m_bit_flag;
  4488. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4489. if (!p)
  4490. return MZ_FALSE;
  4491. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4492. return (m_bit_flag & 1);
  4493. }
  4494. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  4495. mz_uint file_index) {
  4496. mz_uint filename_len, external_attr;
  4497. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4498. if (!p)
  4499. return MZ_FALSE;
  4500. // First see if the filename ends with a '/' character.
  4501. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4502. if (filename_len) {
  4503. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  4504. return MZ_TRUE;
  4505. }
  4506. // Bugfix: This code was also checking if the internal attribute was non-zero,
  4507. // which wasn't correct.
  4508. // Most/all zip writers (hopefully) set DOS file/directory attributes in the
  4509. // low 16-bits, so check for the DOS directory flag and ignore the source OS
  4510. // ID in the created by field.
  4511. // FIXME: Remove this check? Is it necessary - we already check the filename.
  4512. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4513. if ((external_attr & 0x10) != 0)
  4514. return MZ_TRUE;
  4515. return MZ_FALSE;
  4516. }
  4517. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  4518. mz_zip_archive_file_stat *pStat) {
  4519. mz_uint n;
  4520. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4521. if ((!p) || (!pStat))
  4522. return MZ_FALSE;
  4523. // Unpack the central directory record.
  4524. pStat->m_file_index = file_index;
  4525. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
  4526. &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  4527. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  4528. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  4529. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4530. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  4531. #ifndef MINIZ_NO_TIME
  4532. pStat->m_time =
  4533. mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
  4534. MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  4535. #endif
  4536. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  4537. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4538. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4539. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  4540. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4541. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4542. // Copy as much of the filename and comment as possible.
  4543. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4544. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  4545. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4546. pStat->m_filename[n] = '\0';
  4547. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4548. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  4549. pStat->m_comment_size = n;
  4550. memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4551. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4552. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4553. n);
  4554. pStat->m_comment[n] = '\0';
  4555. return MZ_TRUE;
  4556. }
  4557. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  4558. char *pFilename, mz_uint filename_buf_size) {
  4559. mz_uint n;
  4560. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4561. if (!p) {
  4562. if (filename_buf_size)
  4563. pFilename[0] = '\0';
  4564. return 0;
  4565. }
  4566. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4567. if (filename_buf_size) {
  4568. n = MZ_MIN(n, filename_buf_size - 1);
  4569. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4570. pFilename[n] = '\0';
  4571. }
  4572. return n + 1;
  4573. }
  4574. static MZ_FORCEINLINE mz_bool
  4575. mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len,
  4576. mz_uint flags) {
  4577. mz_uint i;
  4578. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
  4579. return 0 == memcmp(pA, pB, len);
  4580. for (i = 0; i < len; ++i)
  4581. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
  4582. return MZ_FALSE;
  4583. return MZ_TRUE;
  4584. }
  4585. static MZ_FORCEINLINE int
  4586. mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array,
  4587. const mz_zip_array *pCentral_dir_offsets,
  4588. mz_uint l_index, const char *pR, mz_uint r_len) {
  4589. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4590. pCentral_dir_array, mz_uint8,
  4591. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4592. l_index)),
  4593. *pE;
  4594. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4595. mz_uint8 l = 0, r = 0;
  4596. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4597. pE = pL + MZ_MIN(l_len, r_len);
  4598. while (pL < pE) {
  4599. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  4600. break;
  4601. pL++;
  4602. pR++;
  4603. }
  4604. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  4605. }
  4606. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
  4607. const char *pFilename) {
  4608. mz_zip_internal_state *pState = pZip->m_pState;
  4609. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4610. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4611. mz_uint32 *pIndices =
  4612. &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
  4613. 0);
  4614. const int size = pZip->m_total_files;
  4615. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  4616. int l = 0, h = size - 1;
  4617. while (l <= h) {
  4618. int m = (l + h) >> 1, file_index = pIndices[m],
  4619. comp =
  4620. mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
  4621. file_index, pFilename, filename_len);
  4622. if (!comp)
  4623. return file_index;
  4624. else if (comp < 0)
  4625. l = m + 1;
  4626. else
  4627. h = m - 1;
  4628. }
  4629. return -1;
  4630. }
  4631. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  4632. const char *pComment, mz_uint flags) {
  4633. mz_uint file_index;
  4634. size_t name_len, comment_len;
  4635. if ((!pZip) || (!pZip->m_pState) || (!pName) ||
  4636. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4637. return -1;
  4638. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
  4639. (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  4640. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  4641. name_len = strlen(pName);
  4642. if (name_len > 0xFFFF)
  4643. return -1;
  4644. comment_len = pComment ? strlen(pComment) : 0;
  4645. if (comment_len > 0xFFFF)
  4646. return -1;
  4647. for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
  4648. const mz_uint8 *pHeader =
  4649. &MZ_ZIP_ARRAY_ELEMENT(
  4650. &pZip->m_pState->m_central_dir, mz_uint8,
  4651. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
  4652. mz_uint32, file_index));
  4653. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4654. const char *pFilename =
  4655. (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4656. if (filename_len < name_len)
  4657. continue;
  4658. if (comment_len) {
  4659. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4660. file_comment_len =
  4661. MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4662. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  4663. if ((file_comment_len != comment_len) ||
  4664. (!mz_zip_reader_string_equal(pComment, pFile_comment,
  4665. file_comment_len, flags)))
  4666. continue;
  4667. }
  4668. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
  4669. int ofs = filename_len - 1;
  4670. do {
  4671. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
  4672. (pFilename[ofs] == ':'))
  4673. break;
  4674. } while (--ofs >= 0);
  4675. ofs++;
  4676. pFilename += ofs;
  4677. filename_len -= ofs;
  4678. }
  4679. if ((filename_len == name_len) &&
  4680. (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  4681. return file_index;
  4682. }
  4683. return -1;
  4684. }
  4685. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  4686. mz_uint file_index, void *pBuf,
  4687. size_t buf_size, mz_uint flags,
  4688. void *pUser_read_buf,
  4689. size_t user_read_buf_size) {
  4690. int status = TINFL_STATUS_DONE;
  4691. mz_uint64 needed_size, cur_file_ofs, comp_remaining,
  4692. out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  4693. mz_zip_archive_file_stat file_stat;
  4694. void *pRead_buf;
  4695. mz_uint32
  4696. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  4697. sizeof(mz_uint32)];
  4698. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4699. tinfl_decompressor inflator;
  4700. if ((buf_size) && (!pBuf))
  4701. return MZ_FALSE;
  4702. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  4703. return MZ_FALSE;
  4704. // Empty file, or a directory (but not always a directory - I've seen odd zips
  4705. // with directories that have compressed data which inflates to 0 bytes)
  4706. if (!file_stat.m_comp_size)
  4707. return MZ_TRUE;
  4708. // Entry is a subdirectory (I've seen old zips with dir entries which have
  4709. // compressed deflate data which inflates to 0 bytes, but these entries claim
  4710. // to uncompress to 512 bytes in the headers).
  4711. // I'm torn how to handle this case - should it fail instead?
  4712. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  4713. return MZ_TRUE;
  4714. // Encryption and patch files are not supported.
  4715. if (file_stat.m_bit_flag & (1 | 32))
  4716. return MZ_FALSE;
  4717. // This function only supports stored and deflate.
  4718. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  4719. (file_stat.m_method != MZ_DEFLATED))
  4720. return MZ_FALSE;
  4721. // Ensure supplied output buffer is large enough.
  4722. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
  4723. : file_stat.m_uncomp_size;
  4724. if (buf_size < needed_size)
  4725. return MZ_FALSE;
  4726. // Read and parse the local directory entry.
  4727. cur_file_ofs = file_stat.m_local_header_ofs;
  4728. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  4729. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  4730. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4731. return MZ_FALSE;
  4732. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4733. return MZ_FALSE;
  4734. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  4735. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  4736. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4737. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  4738. return MZ_FALSE;
  4739. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  4740. // The file is stored or the caller has requested the compressed data.
  4741. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4742. (size_t)needed_size) != needed_size)
  4743. return MZ_FALSE;
  4744. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
  4745. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4746. (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  4747. }
  4748. // Decompress the file either directly from memory or from a file input
  4749. // buffer.
  4750. tinfl_init(&inflator);
  4751. if (pZip->m_pState->m_pMem) {
  4752. // Read directly from the archive in memory.
  4753. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  4754. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  4755. comp_remaining = 0;
  4756. } else if (pUser_read_buf) {
  4757. // Use a user provided read buffer.
  4758. if (!user_read_buf_size)
  4759. return MZ_FALSE;
  4760. pRead_buf = (mz_uint8 *)pUser_read_buf;
  4761. read_buf_size = user_read_buf_size;
  4762. read_buf_avail = 0;
  4763. comp_remaining = file_stat.m_comp_size;
  4764. } else {
  4765. // Temporarily allocate a read buffer.
  4766. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  4767. #ifdef _MSC_VER
  4768. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  4769. (read_buf_size > 0x7FFFFFFF))
  4770. #else
  4771. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  4772. #endif
  4773. return MZ_FALSE;
  4774. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4775. (size_t)read_buf_size)))
  4776. return MZ_FALSE;
  4777. read_buf_avail = 0;
  4778. comp_remaining = file_stat.m_comp_size;
  4779. }
  4780. do {
  4781. size_t in_buf_size,
  4782. out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  4783. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  4784. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4785. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4786. (size_t)read_buf_avail) != read_buf_avail) {
  4787. status = TINFL_STATUS_FAILED;
  4788. break;
  4789. }
  4790. cur_file_ofs += read_buf_avail;
  4791. comp_remaining -= read_buf_avail;
  4792. read_buf_ofs = 0;
  4793. }
  4794. in_buf_size = (size_t)read_buf_avail;
  4795. status = tinfl_decompress(
  4796. &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  4797. (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
  4798. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
  4799. (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  4800. read_buf_avail -= in_buf_size;
  4801. read_buf_ofs += in_buf_size;
  4802. out_buf_ofs += out_buf_size;
  4803. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  4804. if (status == TINFL_STATUS_DONE) {
  4805. // Make sure the entire file was decompressed, and check its CRC.
  4806. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  4807. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4808. (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  4809. status = TINFL_STATUS_FAILED;
  4810. }
  4811. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  4812. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4813. return status == TINFL_STATUS_DONE;
  4814. }
  4815. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  4816. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  4817. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
  4818. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  4819. if (file_index < 0)
  4820. return MZ_FALSE;
  4821. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  4822. flags, pUser_read_buf,
  4823. user_read_buf_size);
  4824. }
  4825. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  4826. void *pBuf, size_t buf_size,
  4827. mz_uint flags) {
  4828. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  4829. flags, NULL, 0);
  4830. }
  4831. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  4832. const char *pFilename, void *pBuf,
  4833. size_t buf_size, mz_uint flags) {
  4834. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
  4835. buf_size, flags, NULL, 0);
  4836. }
  4837. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  4838. size_t *pSize, mz_uint flags) {
  4839. mz_uint64 comp_size, uncomp_size, alloc_size;
  4840. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4841. void *pBuf;
  4842. if (pSize)
  4843. *pSize = 0;
  4844. if (!p)
  4845. return NULL;
  4846. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4847. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4848. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  4849. #ifdef _MSC_VER
  4850. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  4851. #else
  4852. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  4853. #endif
  4854. return NULL;
  4855. if (NULL ==
  4856. (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  4857. return NULL;
  4858. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
  4859. flags)) {
  4860. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4861. return NULL;
  4862. }
  4863. if (pSize)
  4864. *pSize = (size_t)alloc_size;
  4865. return pBuf;
  4866. }
  4867. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  4868. const char *pFilename, size_t *pSize,
  4869. mz_uint flags) {
  4870. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  4871. if (file_index < 0) {
  4872. if (pSize)
  4873. *pSize = 0;
  4874. return MZ_FALSE;
  4875. }
  4876. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  4877. }
  4878. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  4879. mz_uint file_index,
  4880. mz_file_write_func pCallback,
  4881. void *pOpaque, mz_uint flags) {
  4882. int status = TINFL_STATUS_DONE;
  4883. mz_uint file_crc32 = MZ_CRC32_INIT;
  4884. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
  4885. out_buf_ofs = 0, cur_file_ofs;
  4886. mz_zip_archive_file_stat file_stat;
  4887. void *pRead_buf = NULL;
  4888. void *pWrite_buf = NULL;
  4889. mz_uint32
  4890. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  4891. sizeof(mz_uint32)];
  4892. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4893. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  4894. return MZ_FALSE;
  4895. // Empty file, or a directory (but not always a directory - I've seen odd zips
  4896. // with directories that have compressed data which inflates to 0 bytes)
  4897. if (!file_stat.m_comp_size)
  4898. return MZ_TRUE;
  4899. // Entry is a subdirectory (I've seen old zips with dir entries which have
  4900. // compressed deflate data which inflates to 0 bytes, but these entries claim
  4901. // to uncompress to 512 bytes in the headers).
  4902. // I'm torn how to handle this case - should it fail instead?
  4903. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  4904. return MZ_TRUE;
  4905. // Encryption and patch files are not supported.
  4906. if (file_stat.m_bit_flag & (1 | 32))
  4907. return MZ_FALSE;
  4908. // This function only supports stored and deflate.
  4909. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  4910. (file_stat.m_method != MZ_DEFLATED))
  4911. return MZ_FALSE;
  4912. // Read and parse the local directory entry.
  4913. cur_file_ofs = file_stat.m_local_header_ofs;
  4914. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  4915. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  4916. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4917. return MZ_FALSE;
  4918. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4919. return MZ_FALSE;
  4920. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  4921. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  4922. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4923. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  4924. return MZ_FALSE;
  4925. // Decompress the file either directly from memory or from a file input
  4926. // buffer.
  4927. if (pZip->m_pState->m_pMem) {
  4928. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  4929. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  4930. comp_remaining = 0;
  4931. } else {
  4932. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  4933. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4934. (size_t)read_buf_size)))
  4935. return MZ_FALSE;
  4936. read_buf_avail = 0;
  4937. comp_remaining = file_stat.m_comp_size;
  4938. }
  4939. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  4940. // The file is stored or the caller has requested the compressed data.
  4941. if (pZip->m_pState->m_pMem) {
  4942. #ifdef _MSC_VER
  4943. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  4944. (file_stat.m_comp_size > 0xFFFFFFFF))
  4945. #else
  4946. if (((sizeof(size_t) == sizeof(mz_uint32))) &&
  4947. (file_stat.m_comp_size > 0xFFFFFFFF))
  4948. #endif
  4949. return MZ_FALSE;
  4950. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  4951. (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  4952. status = TINFL_STATUS_FAILED;
  4953. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  4954. file_crc32 =
  4955. (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
  4956. (size_t)file_stat.m_comp_size);
  4957. cur_file_ofs += file_stat.m_comp_size;
  4958. out_buf_ofs += file_stat.m_comp_size;
  4959. comp_remaining = 0;
  4960. } else {
  4961. while (comp_remaining) {
  4962. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4963. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4964. (size_t)read_buf_avail) != read_buf_avail) {
  4965. status = TINFL_STATUS_FAILED;
  4966. break;
  4967. }
  4968. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  4969. file_crc32 = (mz_uint32)mz_crc32(
  4970. file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  4971. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  4972. (size_t)read_buf_avail) != read_buf_avail) {
  4973. status = TINFL_STATUS_FAILED;
  4974. break;
  4975. }
  4976. cur_file_ofs += read_buf_avail;
  4977. out_buf_ofs += read_buf_avail;
  4978. comp_remaining -= read_buf_avail;
  4979. }
  4980. }
  4981. } else {
  4982. tinfl_decompressor inflator;
  4983. tinfl_init(&inflator);
  4984. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4985. TINFL_LZ_DICT_SIZE)))
  4986. status = TINFL_STATUS_FAILED;
  4987. else {
  4988. do {
  4989. mz_uint8 *pWrite_buf_cur =
  4990. (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  4991. size_t in_buf_size,
  4992. out_buf_size =
  4993. TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  4994. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  4995. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4996. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4997. (size_t)read_buf_avail) != read_buf_avail) {
  4998. status = TINFL_STATUS_FAILED;
  4999. break;
  5000. }
  5001. cur_file_ofs += read_buf_avail;
  5002. comp_remaining -= read_buf_avail;
  5003. read_buf_ofs = 0;
  5004. }
  5005. in_buf_size = (size_t)read_buf_avail;
  5006. status = tinfl_decompress(
  5007. &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  5008. (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
  5009. comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  5010. read_buf_avail -= in_buf_size;
  5011. read_buf_ofs += in_buf_size;
  5012. if (out_buf_size) {
  5013. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
  5014. out_buf_size) {
  5015. status = TINFL_STATUS_FAILED;
  5016. break;
  5017. }
  5018. file_crc32 =
  5019. (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  5020. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
  5021. status = TINFL_STATUS_FAILED;
  5022. break;
  5023. }
  5024. }
  5025. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
  5026. (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  5027. }
  5028. }
  5029. if ((status == TINFL_STATUS_DONE) &&
  5030. (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
  5031. // Make sure the entire file was decompressed, and check its CRC.
  5032. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  5033. (file_crc32 != file_stat.m_crc32))
  5034. status = TINFL_STATUS_FAILED;
  5035. }
  5036. if (!pZip->m_pState->m_pMem)
  5037. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5038. if (pWrite_buf)
  5039. pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  5040. return status == TINFL_STATUS_DONE;
  5041. }
  5042. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  5043. const char *pFilename,
  5044. mz_file_write_func pCallback,
  5045. void *pOpaque, mz_uint flags) {
  5046. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5047. if (file_index < 0)
  5048. return MZ_FALSE;
  5049. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
  5050. flags);
  5051. }
  5052. #ifndef MINIZ_NO_STDIO
  5053. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
  5054. const void *pBuf, size_t n) {
  5055. (void)ofs;
  5056. return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
  5057. }
  5058. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  5059. const char *pDst_filename,
  5060. mz_uint flags) {
  5061. mz_bool status;
  5062. mz_zip_archive_file_stat file_stat;
  5063. MZ_FILE *pFile;
  5064. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  5065. return MZ_FALSE;
  5066. pFile = MZ_FOPEN(pDst_filename, "wb");
  5067. if (!pFile)
  5068. return MZ_FALSE;
  5069. status = mz_zip_reader_extract_to_callback(
  5070. pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  5071. if (MZ_FCLOSE(pFile) == EOF)
  5072. return MZ_FALSE;
  5073. #ifndef MINIZ_NO_TIME
  5074. if (status)
  5075. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  5076. #endif
  5077. return status;
  5078. }
  5079. #endif // #ifndef MINIZ_NO_STDIO
  5080. mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
  5081. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  5082. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5083. return MZ_FALSE;
  5084. if (pZip->m_pState) {
  5085. mz_zip_internal_state *pState = pZip->m_pState;
  5086. pZip->m_pState = NULL;
  5087. mz_zip_array_clear(pZip, &pState->m_central_dir);
  5088. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  5089. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  5090. #ifndef MINIZ_NO_STDIO
  5091. if (pState->m_pFile) {
  5092. MZ_FCLOSE(pState->m_pFile);
  5093. pState->m_pFile = NULL;
  5094. }
  5095. #endif // #ifndef MINIZ_NO_STDIO
  5096. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  5097. }
  5098. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  5099. return MZ_TRUE;
  5100. }
  5101. #ifndef MINIZ_NO_STDIO
  5102. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  5103. const char *pArchive_filename,
  5104. const char *pDst_filename,
  5105. mz_uint flags) {
  5106. int file_index =
  5107. mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  5108. if (file_index < 0)
  5109. return MZ_FALSE;
  5110. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  5111. }
  5112. #endif
  5113. // ------------------- .ZIP archive writing
  5114. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  5115. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
  5116. p[0] = (mz_uint8)v;
  5117. p[1] = (mz_uint8)(v >> 8);
  5118. }
  5119. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
  5120. p[0] = (mz_uint8)v;
  5121. p[1] = (mz_uint8)(v >> 8);
  5122. p[2] = (mz_uint8)(v >> 16);
  5123. p[3] = (mz_uint8)(v >> 24);
  5124. }
  5125. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  5126. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  5127. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
  5128. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
  5129. (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  5130. return MZ_FALSE;
  5131. if (pZip->m_file_offset_alignment) {
  5132. // Ensure user specified file offset alignment is a power of 2.
  5133. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  5134. return MZ_FALSE;
  5135. }
  5136. if (!pZip->m_pAlloc)
  5137. pZip->m_pAlloc = def_alloc_func;
  5138. if (!pZip->m_pFree)
  5139. pZip->m_pFree = def_free_func;
  5140. if (!pZip->m_pRealloc)
  5141. pZip->m_pRealloc = def_realloc_func;
  5142. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5143. pZip->m_archive_size = existing_size;
  5144. pZip->m_central_directory_file_ofs = 0;
  5145. pZip->m_total_files = 0;
  5146. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  5147. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  5148. return MZ_FALSE;
  5149. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  5150. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  5151. sizeof(mz_uint8));
  5152. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  5153. sizeof(mz_uint32));
  5154. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  5155. sizeof(mz_uint32));
  5156. return MZ_TRUE;
  5157. }
  5158. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
  5159. const void *pBuf, size_t n) {
  5160. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5161. mz_zip_internal_state *pState = pZip->m_pState;
  5162. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  5163. #ifdef _MSC_VER
  5164. if ((!n) ||
  5165. ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5166. #else
  5167. if ((!n) ||
  5168. ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5169. #endif
  5170. return 0;
  5171. if (new_size > pState->m_mem_capacity) {
  5172. void *pNew_block;
  5173. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
  5174. while (new_capacity < new_size)
  5175. new_capacity *= 2;
  5176. if (NULL == (pNew_block = pZip->m_pRealloc(
  5177. pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  5178. return 0;
  5179. pState->m_pMem = pNew_block;
  5180. pState->m_mem_capacity = new_capacity;
  5181. }
  5182. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  5183. pState->m_mem_size = (size_t)new_size;
  5184. return n;
  5185. }
  5186. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  5187. size_t size_to_reserve_at_beginning,
  5188. size_t initial_allocation_size) {
  5189. pZip->m_pWrite = mz_zip_heap_write_func;
  5190. pZip->m_pIO_opaque = pZip;
  5191. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  5192. return MZ_FALSE;
  5193. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
  5194. size_to_reserve_at_beginning))) {
  5195. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
  5196. pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
  5197. mz_zip_writer_end(pZip);
  5198. return MZ_FALSE;
  5199. }
  5200. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  5201. }
  5202. return MZ_TRUE;
  5203. }
  5204. #ifndef MINIZ_NO_STDIO
  5205. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
  5206. const void *pBuf, size_t n) {
  5207. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5208. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  5209. if (((mz_int64)file_ofs < 0) ||
  5210. (((cur_ofs != (mz_int64)file_ofs)) &&
  5211. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  5212. return 0;
  5213. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  5214. }
  5215. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  5216. mz_uint64 size_to_reserve_at_beginning) {
  5217. MZ_FILE *pFile;
  5218. pZip->m_pWrite = mz_zip_file_write_func;
  5219. pZip->m_pIO_opaque = pZip;
  5220. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  5221. return MZ_FALSE;
  5222. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
  5223. mz_zip_writer_end(pZip);
  5224. return MZ_FALSE;
  5225. }
  5226. pZip->m_pState->m_pFile = pFile;
  5227. if (size_to_reserve_at_beginning) {
  5228. mz_uint64 cur_ofs = 0;
  5229. char buf[4096];
  5230. MZ_CLEAR_OBJ(buf);
  5231. do {
  5232. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  5233. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
  5234. mz_zip_writer_end(pZip);
  5235. return MZ_FALSE;
  5236. }
  5237. cur_ofs += n;
  5238. size_to_reserve_at_beginning -= n;
  5239. } while (size_to_reserve_at_beginning);
  5240. }
  5241. return MZ_TRUE;
  5242. }
  5243. #endif // #ifndef MINIZ_NO_STDIO
  5244. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  5245. const char *pFilename) {
  5246. mz_zip_internal_state *pState;
  5247. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5248. return MZ_FALSE;
  5249. // No sense in trying to write to an archive that's already at the support max
  5250. // size
  5251. if ((pZip->m_total_files == 0xFFFF) ||
  5252. ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5253. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  5254. return MZ_FALSE;
  5255. pState = pZip->m_pState;
  5256. if (pState->m_pFile) {
  5257. #ifdef MINIZ_NO_STDIO
  5258. pFilename;
  5259. return MZ_FALSE;
  5260. #else
  5261. // Archive is being read from stdio - try to reopen as writable.
  5262. if (pZip->m_pIO_opaque != pZip)
  5263. return MZ_FALSE;
  5264. if (!pFilename)
  5265. return MZ_FALSE;
  5266. pZip->m_pWrite = mz_zip_file_write_func;
  5267. if (NULL ==
  5268. (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
  5269. // The mz_zip_archive is now in a bogus state because pState->m_pFile is
  5270. // NULL, so just close it.
  5271. mz_zip_reader_end(pZip);
  5272. return MZ_FALSE;
  5273. }
  5274. #endif // #ifdef MINIZ_NO_STDIO
  5275. } else if (pState->m_pMem) {
  5276. // Archive lives in a memory block. Assume it's from the heap that we can
  5277. // resize using the realloc callback.
  5278. if (pZip->m_pIO_opaque != pZip)
  5279. return MZ_FALSE;
  5280. pState->m_mem_capacity = pState->m_mem_size;
  5281. pZip->m_pWrite = mz_zip_heap_write_func;
  5282. }
  5283. // Archive is being read via a user provided read function - make sure the
  5284. // user has specified a write function too.
  5285. else if (!pZip->m_pWrite)
  5286. return MZ_FALSE;
  5287. // Start writing new files at the archive's current central directory
  5288. // location.
  5289. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  5290. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5291. pZip->m_central_directory_file_ofs = 0;
  5292. return MZ_TRUE;
  5293. }
  5294. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  5295. const void *pBuf, size_t buf_size,
  5296. mz_uint level_and_flags) {
  5297. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
  5298. level_and_flags, 0, 0);
  5299. }
  5300. typedef struct {
  5301. mz_zip_archive *m_pZip;
  5302. mz_uint64 m_cur_archive_file_ofs;
  5303. mz_uint64 m_comp_size;
  5304. } mz_zip_writer_add_state;
  5305. static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
  5306. void *pUser) {
  5307. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  5308. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
  5309. pState->m_cur_archive_file_ofs, pBuf,
  5310. len) != len)
  5311. return MZ_FALSE;
  5312. pState->m_cur_archive_file_ofs += len;
  5313. pState->m_comp_size += len;
  5314. return MZ_TRUE;
  5315. }
  5316. static mz_bool mz_zip_writer_create_local_dir_header(
  5317. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5318. mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5319. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5320. mz_uint16 dos_time, mz_uint16 dos_date) {
  5321. (void)pZip;
  5322. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  5323. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  5324. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5325. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  5326. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  5327. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  5328. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  5329. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  5330. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  5331. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5332. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  5333. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  5334. return MZ_TRUE;
  5335. }
  5336. static mz_bool mz_zip_writer_create_central_dir_header(
  5337. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5338. mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
  5339. mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
  5340. mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
  5341. mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
  5342. (void)pZip;
  5343. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5344. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  5345. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5346. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  5347. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  5348. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  5349. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  5350. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  5351. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  5352. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5353. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  5354. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  5355. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  5356. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  5357. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  5358. return MZ_TRUE;
  5359. }
  5360. static mz_bool mz_zip_writer_add_to_central_dir(
  5361. mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
  5362. const void *pExtra, mz_uint16 extra_size, const void *pComment,
  5363. mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5364. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5365. mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
  5366. mz_uint32 ext_attributes) {
  5367. mz_zip_internal_state *pState = pZip->m_pState;
  5368. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  5369. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  5370. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5371. // No zip64 support yet
  5372. if ((local_header_ofs > 0xFFFFFFFF) ||
  5373. (((mz_uint64)pState->m_central_dir.m_size +
  5374. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
  5375. comment_size) > 0xFFFFFFFF))
  5376. return MZ_FALSE;
  5377. if (!mz_zip_writer_create_central_dir_header(
  5378. pZip, central_dir_header, filename_size, extra_size, comment_size,
  5379. uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
  5380. dos_date, local_header_ofs, ext_attributes))
  5381. return MZ_FALSE;
  5382. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
  5383. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  5384. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
  5385. filename_size)) ||
  5386. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
  5387. extra_size)) ||
  5388. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
  5389. comment_size)) ||
  5390. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
  5391. &central_dir_ofs, 1))) {
  5392. // Try to push the central directory array back into its original state.
  5393. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5394. MZ_FALSE);
  5395. return MZ_FALSE;
  5396. }
  5397. return MZ_TRUE;
  5398. }
  5399. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
  5400. // Basic ZIP archive filename validity checks: Valid filenames cannot start
  5401. // with a forward slash, cannot contain a drive letter, and cannot use
  5402. // DOS-style backward slashes.
  5403. if (*pArchive_name == '/')
  5404. return MZ_FALSE;
  5405. while (*pArchive_name) {
  5406. if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
  5407. return MZ_FALSE;
  5408. pArchive_name++;
  5409. }
  5410. return MZ_TRUE;
  5411. }
  5412. static mz_uint
  5413. mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) {
  5414. mz_uint32 n;
  5415. if (!pZip->m_file_offset_alignment)
  5416. return 0;
  5417. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  5418. return (pZip->m_file_offset_alignment - n) &
  5419. (pZip->m_file_offset_alignment - 1);
  5420. }
  5421. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
  5422. mz_uint64 cur_file_ofs, mz_uint32 n) {
  5423. char buf[4096];
  5424. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  5425. while (n) {
  5426. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  5427. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  5428. return MZ_FALSE;
  5429. cur_file_ofs += s;
  5430. n -= s;
  5431. }
  5432. return MZ_TRUE;
  5433. }
  5434. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  5435. const char *pArchive_name, const void *pBuf,
  5436. size_t buf_size, const void *pComment,
  5437. mz_uint16 comment_size,
  5438. mz_uint level_and_flags, mz_uint64 uncomp_size,
  5439. mz_uint32 uncomp_crc32) {
  5440. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  5441. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  5442. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5443. cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  5444. size_t archive_name_size;
  5445. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5446. tdefl_compressor *pComp = NULL;
  5447. mz_bool store_data_uncompressed;
  5448. mz_zip_internal_state *pState;
  5449. if ((int)level_and_flags < 0)
  5450. level_and_flags = MZ_DEFAULT_LEVEL;
  5451. level = level_and_flags & 0xF;
  5452. store_data_uncompressed =
  5453. ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  5454. if ((!pZip) || (!pZip->m_pState) ||
  5455. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
  5456. (!pArchive_name) || ((comment_size) && (!pComment)) ||
  5457. (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  5458. return MZ_FALSE;
  5459. pState = pZip->m_pState;
  5460. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  5461. return MZ_FALSE;
  5462. // No zip64 support yet
  5463. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
  5464. return MZ_FALSE;
  5465. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  5466. return MZ_FALSE;
  5467. #ifndef MINIZ_NO_TIME
  5468. {
  5469. time_t cur_time;
  5470. time(&cur_time);
  5471. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  5472. }
  5473. #endif // #ifndef MINIZ_NO_TIME
  5474. archive_name_size = strlen(pArchive_name);
  5475. if (archive_name_size > 0xFFFF)
  5476. return MZ_FALSE;
  5477. num_alignment_padding_bytes =
  5478. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5479. // no zip64 support yet
  5480. if ((pZip->m_total_files == 0xFFFF) ||
  5481. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5482. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5483. comment_size + archive_name_size) > 0xFFFFFFFF))
  5484. return MZ_FALSE;
  5485. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
  5486. // Set DOS Subdirectory attribute bit.
  5487. ext_attributes |= 0x10;
  5488. // Subdirectories cannot contain data.
  5489. if ((buf_size) || (uncomp_size))
  5490. return MZ_FALSE;
  5491. }
  5492. // Try to do any allocations before writing to the archive, so if an
  5493. // allocation fails the file remains unmodified. (A good idea if we're doing
  5494. // an in-place modification.)
  5495. if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir,
  5496. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5497. archive_name_size + comment_size)) ||
  5498. (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  5499. return MZ_FALSE;
  5500. if ((!store_data_uncompressed) && (buf_size)) {
  5501. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5502. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  5503. return MZ_FALSE;
  5504. }
  5505. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
  5506. num_alignment_padding_bytes +
  5507. sizeof(local_dir_header))) {
  5508. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5509. return MZ_FALSE;
  5510. }
  5511. local_dir_header_ofs += num_alignment_padding_bytes;
  5512. if (pZip->m_file_offset_alignment) {
  5513. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5514. 0);
  5515. }
  5516. cur_archive_file_ofs +=
  5517. num_alignment_padding_bytes + sizeof(local_dir_header);
  5518. MZ_CLEAR_OBJ(local_dir_header);
  5519. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5520. archive_name_size) != archive_name_size) {
  5521. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5522. return MZ_FALSE;
  5523. }
  5524. cur_archive_file_ofs += archive_name_size;
  5525. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
  5526. uncomp_crc32 =
  5527. (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
  5528. uncomp_size = buf_size;
  5529. if (uncomp_size <= 3) {
  5530. level = 0;
  5531. store_data_uncompressed = MZ_TRUE;
  5532. }
  5533. }
  5534. if (store_data_uncompressed) {
  5535. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
  5536. buf_size) != buf_size) {
  5537. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5538. return MZ_FALSE;
  5539. }
  5540. cur_archive_file_ofs += buf_size;
  5541. comp_size = buf_size;
  5542. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  5543. method = MZ_DEFLATED;
  5544. } else if (buf_size) {
  5545. mz_zip_writer_add_state state;
  5546. state.m_pZip = pZip;
  5547. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5548. state.m_comp_size = 0;
  5549. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5550. tdefl_create_comp_flags_from_zip_params(
  5551. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5552. TDEFL_STATUS_OKAY) ||
  5553. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
  5554. TDEFL_STATUS_DONE)) {
  5555. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5556. return MZ_FALSE;
  5557. }
  5558. comp_size = state.m_comp_size;
  5559. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5560. method = MZ_DEFLATED;
  5561. }
  5562. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5563. pComp = NULL;
  5564. // no zip64 support yet
  5565. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5566. return MZ_FALSE;
  5567. if (!mz_zip_writer_create_local_dir_header(
  5568. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5569. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5570. return MZ_FALSE;
  5571. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5572. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5573. return MZ_FALSE;
  5574. if (!mz_zip_writer_add_to_central_dir(
  5575. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5576. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5577. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5578. return MZ_FALSE;
  5579. pZip->m_total_files++;
  5580. pZip->m_archive_size = cur_archive_file_ofs;
  5581. return MZ_TRUE;
  5582. }
  5583. #ifndef MINIZ_NO_STDIO
  5584. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  5585. const char *pSrc_filename, const void *pComment,
  5586. mz_uint16 comment_size,
  5587. mz_uint level_and_flags) {
  5588. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  5589. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  5590. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5591. cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
  5592. comp_size = 0;
  5593. size_t archive_name_size;
  5594. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5595. MZ_FILE *pSrc_file = NULL;
  5596. if ((int)level_and_flags < 0)
  5597. level_and_flags = MZ_DEFAULT_LEVEL;
  5598. level = level_and_flags & 0xF;
  5599. if ((!pZip) || (!pZip->m_pState) ||
  5600. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
  5601. ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  5602. return MZ_FALSE;
  5603. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  5604. return MZ_FALSE;
  5605. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  5606. return MZ_FALSE;
  5607. archive_name_size = strlen(pArchive_name);
  5608. if (archive_name_size > 0xFFFF)
  5609. return MZ_FALSE;
  5610. num_alignment_padding_bytes =
  5611. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5612. // no zip64 support yet
  5613. if ((pZip->m_total_files == 0xFFFF) ||
  5614. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5615. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5616. comment_size + archive_name_size) > 0xFFFFFFFF))
  5617. return MZ_FALSE;
  5618. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  5619. return MZ_FALSE;
  5620. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  5621. if (!pSrc_file)
  5622. return MZ_FALSE;
  5623. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  5624. uncomp_size = MZ_FTELL64(pSrc_file);
  5625. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  5626. if (uncomp_size > 0xFFFFFFFF) {
  5627. // No zip64 support yet
  5628. MZ_FCLOSE(pSrc_file);
  5629. return MZ_FALSE;
  5630. }
  5631. if (uncomp_size <= 3)
  5632. level = 0;
  5633. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
  5634. num_alignment_padding_bytes +
  5635. sizeof(local_dir_header))) {
  5636. MZ_FCLOSE(pSrc_file);
  5637. return MZ_FALSE;
  5638. }
  5639. local_dir_header_ofs += num_alignment_padding_bytes;
  5640. if (pZip->m_file_offset_alignment) {
  5641. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5642. 0);
  5643. }
  5644. cur_archive_file_ofs +=
  5645. num_alignment_padding_bytes + sizeof(local_dir_header);
  5646. MZ_CLEAR_OBJ(local_dir_header);
  5647. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5648. archive_name_size) != archive_name_size) {
  5649. MZ_FCLOSE(pSrc_file);
  5650. return MZ_FALSE;
  5651. }
  5652. cur_archive_file_ofs += archive_name_size;
  5653. if (uncomp_size) {
  5654. mz_uint64 uncomp_remaining = uncomp_size;
  5655. void *pRead_buf =
  5656. pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  5657. if (!pRead_buf) {
  5658. MZ_FCLOSE(pSrc_file);
  5659. return MZ_FALSE;
  5660. }
  5661. if (!level) {
  5662. while (uncomp_remaining) {
  5663. mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  5664. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
  5665. (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
  5666. n) != n)) {
  5667. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5668. MZ_FCLOSE(pSrc_file);
  5669. return MZ_FALSE;
  5670. }
  5671. uncomp_crc32 =
  5672. (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  5673. uncomp_remaining -= n;
  5674. cur_archive_file_ofs += n;
  5675. }
  5676. comp_size = uncomp_size;
  5677. } else {
  5678. mz_bool result = MZ_FALSE;
  5679. mz_zip_writer_add_state state;
  5680. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5681. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  5682. if (!pComp) {
  5683. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5684. MZ_FCLOSE(pSrc_file);
  5685. return MZ_FALSE;
  5686. }
  5687. state.m_pZip = pZip;
  5688. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5689. state.m_comp_size = 0;
  5690. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5691. tdefl_create_comp_flags_from_zip_params(
  5692. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5693. TDEFL_STATUS_OKAY) {
  5694. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5695. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5696. MZ_FCLOSE(pSrc_file);
  5697. return MZ_FALSE;
  5698. }
  5699. for (;;) {
  5700. size_t in_buf_size =
  5701. (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5702. tdefl_status status;
  5703. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  5704. break;
  5705. uncomp_crc32 = (mz_uint32)mz_crc32(
  5706. uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  5707. uncomp_remaining -= in_buf_size;
  5708. status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size,
  5709. uncomp_remaining ? TDEFL_NO_FLUSH
  5710. : TDEFL_FINISH);
  5711. if (status == TDEFL_STATUS_DONE) {
  5712. result = MZ_TRUE;
  5713. break;
  5714. } else if (status != TDEFL_STATUS_OKAY)
  5715. break;
  5716. }
  5717. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5718. if (!result) {
  5719. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5720. MZ_FCLOSE(pSrc_file);
  5721. return MZ_FALSE;
  5722. }
  5723. comp_size = state.m_comp_size;
  5724. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5725. method = MZ_DEFLATED;
  5726. }
  5727. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5728. }
  5729. MZ_FCLOSE(pSrc_file);
  5730. pSrc_file = NULL;
  5731. // no zip64 support yet
  5732. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5733. return MZ_FALSE;
  5734. if (!mz_zip_writer_create_local_dir_header(
  5735. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5736. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5737. return MZ_FALSE;
  5738. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5739. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5740. return MZ_FALSE;
  5741. if (!mz_zip_writer_add_to_central_dir(
  5742. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5743. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5744. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5745. return MZ_FALSE;
  5746. pZip->m_total_files++;
  5747. pZip->m_archive_size = cur_archive_file_ofs;
  5748. return MZ_TRUE;
  5749. }
  5750. #endif // #ifndef MINIZ_NO_STDIO
  5751. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  5752. mz_zip_archive *pSource_zip,
  5753. mz_uint file_index) {
  5754. mz_uint n, bit_flags, num_alignment_padding_bytes;
  5755. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  5756. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  5757. mz_uint32
  5758. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5759. sizeof(mz_uint32)];
  5760. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5761. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5762. size_t orig_central_dir_size;
  5763. mz_zip_internal_state *pState;
  5764. void *pBuf;
  5765. const mz_uint8 *pSrc_central_header;
  5766. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  5767. return MZ_FALSE;
  5768. if (NULL ==
  5769. (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  5770. return MZ_FALSE;
  5771. pState = pZip->m_pState;
  5772. num_alignment_padding_bytes =
  5773. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5774. // no zip64 support yet
  5775. if ((pZip->m_total_files == 0xFFFF) ||
  5776. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5777. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
  5778. 0xFFFFFFFF))
  5779. return MZ_FALSE;
  5780. cur_src_file_ofs =
  5781. MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  5782. cur_dst_file_ofs = pZip->m_archive_size;
  5783. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
  5784. pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5785. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5786. return MZ_FALSE;
  5787. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5788. return MZ_FALSE;
  5789. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5790. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
  5791. num_alignment_padding_bytes))
  5792. return MZ_FALSE;
  5793. cur_dst_file_ofs += num_alignment_padding_bytes;
  5794. local_dir_header_ofs = cur_dst_file_ofs;
  5795. if (pZip->m_file_offset_alignment) {
  5796. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5797. 0);
  5798. }
  5799. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
  5800. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5801. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5802. return MZ_FALSE;
  5803. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5804. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5805. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5806. comp_bytes_remaining =
  5807. n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5808. if (NULL ==
  5809. (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5810. (size_t)MZ_MAX(sizeof(mz_uint32) * 4,
  5811. MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
  5812. comp_bytes_remaining)))))
  5813. return MZ_FALSE;
  5814. while (comp_bytes_remaining) {
  5815. n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  5816. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5817. n) != n) {
  5818. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5819. return MZ_FALSE;
  5820. }
  5821. cur_src_file_ofs += n;
  5822. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5823. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5824. return MZ_FALSE;
  5825. }
  5826. cur_dst_file_ofs += n;
  5827. comp_bytes_remaining -= n;
  5828. }
  5829. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  5830. if (bit_flags & 8) {
  5831. // Copy data descriptor
  5832. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5833. sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
  5834. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5835. return MZ_FALSE;
  5836. }
  5837. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  5838. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5839. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5840. return MZ_FALSE;
  5841. }
  5842. cur_src_file_ofs += n;
  5843. cur_dst_file_ofs += n;
  5844. }
  5845. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5846. // no zip64 support yet
  5847. if (cur_dst_file_ofs > 0xFFFFFFFF)
  5848. return MZ_FALSE;
  5849. orig_central_dir_size = pState->m_central_dir.m_size;
  5850. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5851. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
  5852. local_dir_header_ofs);
  5853. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
  5854. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  5855. return MZ_FALSE;
  5856. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  5857. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  5858. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  5859. if (!mz_zip_array_push_back(
  5860. pZip, &pState->m_central_dir,
  5861. pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
  5862. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5863. MZ_FALSE);
  5864. return MZ_FALSE;
  5865. }
  5866. if (pState->m_central_dir.m_size > 0xFFFFFFFF)
  5867. return MZ_FALSE;
  5868. n = (mz_uint32)orig_central_dir_size;
  5869. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
  5870. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5871. MZ_FALSE);
  5872. return MZ_FALSE;
  5873. }
  5874. pZip->m_total_files++;
  5875. pZip->m_archive_size = cur_dst_file_ofs;
  5876. return MZ_TRUE;
  5877. }
  5878. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
  5879. mz_zip_internal_state *pState;
  5880. mz_uint64 central_dir_ofs, central_dir_size;
  5881. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  5882. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  5883. return MZ_FALSE;
  5884. pState = pZip->m_pState;
  5885. // no zip64 support yet
  5886. if ((pZip->m_total_files > 0xFFFF) ||
  5887. ((pZip->m_archive_size + pState->m_central_dir.m_size +
  5888. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  5889. return MZ_FALSE;
  5890. central_dir_ofs = 0;
  5891. central_dir_size = 0;
  5892. if (pZip->m_total_files) {
  5893. // Write central directory
  5894. central_dir_ofs = pZip->m_archive_size;
  5895. central_dir_size = pState->m_central_dir.m_size;
  5896. pZip->m_central_directory_file_ofs = central_dir_ofs;
  5897. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
  5898. pState->m_central_dir.m_p,
  5899. (size_t)central_dir_size) != central_dir_size)
  5900. return MZ_FALSE;
  5901. pZip->m_archive_size += central_dir_size;
  5902. }
  5903. // Write end of central directory record
  5904. MZ_CLEAR_OBJ(hdr);
  5905. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
  5906. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  5907. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
  5908. pZip->m_total_files);
  5909. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  5910. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  5911. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  5912. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
  5913. sizeof(hdr)) != sizeof(hdr))
  5914. return MZ_FALSE;
  5915. #ifndef MINIZ_NO_STDIO
  5916. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
  5917. return MZ_FALSE;
  5918. #endif // #ifndef MINIZ_NO_STDIO
  5919. pZip->m_archive_size += sizeof(hdr);
  5920. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  5921. return MZ_TRUE;
  5922. }
  5923. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  5924. size_t *pSize) {
  5925. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
  5926. return MZ_FALSE;
  5927. if (pZip->m_pWrite != mz_zip_heap_write_func)
  5928. return MZ_FALSE;
  5929. if (!mz_zip_writer_finalize_archive(pZip))
  5930. return MZ_FALSE;
  5931. *pBuf = pZip->m_pState->m_pMem;
  5932. *pSize = pZip->m_pState->m_mem_size;
  5933. pZip->m_pState->m_pMem = NULL;
  5934. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  5935. return MZ_TRUE;
  5936. }
  5937. mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
  5938. mz_zip_internal_state *pState;
  5939. mz_bool status = MZ_TRUE;
  5940. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  5941. ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
  5942. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  5943. return MZ_FALSE;
  5944. pState = pZip->m_pState;
  5945. pZip->m_pState = NULL;
  5946. mz_zip_array_clear(pZip, &pState->m_central_dir);
  5947. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  5948. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  5949. #ifndef MINIZ_NO_STDIO
  5950. if (pState->m_pFile) {
  5951. MZ_FCLOSE(pState->m_pFile);
  5952. pState->m_pFile = NULL;
  5953. }
  5954. #endif // #ifndef MINIZ_NO_STDIO
  5955. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
  5956. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  5957. pState->m_pMem = NULL;
  5958. }
  5959. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  5960. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  5961. return status;
  5962. }
  5963. #ifndef MINIZ_NO_STDIO
  5964. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  5965. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  5966. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  5967. mz_uint level_and_flags) {
  5968. mz_bool status, created_new_archive = MZ_FALSE;
  5969. mz_zip_archive zip_archive;
  5970. struct MZ_FILE_STAT_STRUCT file_stat;
  5971. MZ_CLEAR_OBJ(zip_archive);
  5972. if ((int)level_and_flags < 0)
  5973. level_and_flags = MZ_DEFAULT_LEVEL;
  5974. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
  5975. ((comment_size) && (!pComment)) ||
  5976. ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  5977. return MZ_FALSE;
  5978. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  5979. return MZ_FALSE;
  5980. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
  5981. // Create a new archive.
  5982. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  5983. return MZ_FALSE;
  5984. created_new_archive = MZ_TRUE;
  5985. } else {
  5986. // Append to an existing archive.
  5987. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
  5988. level_and_flags |
  5989. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  5990. return MZ_FALSE;
  5991. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
  5992. mz_zip_reader_end(&zip_archive);
  5993. return MZ_FALSE;
  5994. }
  5995. }
  5996. status =
  5997. mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
  5998. pComment, comment_size, level_and_flags, 0, 0);
  5999. // Always finalize, even if adding failed for some reason, so we have a valid
  6000. // central directory. (This may not always succeed, but we can try.)
  6001. if (!mz_zip_writer_finalize_archive(&zip_archive))
  6002. status = MZ_FALSE;
  6003. if (!mz_zip_writer_end(&zip_archive))
  6004. status = MZ_FALSE;
  6005. if ((!status) && (created_new_archive)) {
  6006. // It's a new archive and something went wrong, so just delete it.
  6007. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  6008. (void)ignoredStatus;
  6009. }
  6010. return status;
  6011. }
  6012. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  6013. const char *pArchive_name,
  6014. size_t *pSize, mz_uint flags) {
  6015. int file_index;
  6016. mz_zip_archive zip_archive;
  6017. void *p = NULL;
  6018. if (pSize)
  6019. *pSize = 0;
  6020. if ((!pZip_filename) || (!pArchive_name))
  6021. return NULL;
  6022. MZ_CLEAR_OBJ(zip_archive);
  6023. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
  6024. flags |
  6025. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6026. return NULL;
  6027. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
  6028. flags)) >= 0)
  6029. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  6030. mz_zip_reader_end(&zip_archive);
  6031. return p;
  6032. }
  6033. #endif // #ifndef MINIZ_NO_STDIO
  6034. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  6035. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  6036. #ifdef __cplusplus
  6037. }
  6038. #endif
  6039. #endif // MINIZ_HEADER_FILE_ONLY
  6040. /*
  6041. This is free and unencumbered software released into the public domain.
  6042. Anyone is free to copy, modify, publish, use, compile, sell, or
  6043. distribute this software, either in source code form or as a compiled
  6044. binary, for any purpose, commercial or non-commercial, and by any
  6045. means.
  6046. In jurisdictions that recognize copyright laws, the author or authors
  6047. of this software dedicate any and all copyright interest in the
  6048. software to the public domain. We make this dedication for the benefit
  6049. of the public at large and to the detriment of our heirs and
  6050. successors. We intend this dedication to be an overt act of
  6051. relinquishment in perpetuity of all present and future rights to this
  6052. software under copyright law.
  6053. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6054. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6055. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  6056. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6057. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6058. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  6059. OTHER DEALINGS IN THE SOFTWARE.
  6060. For more information, please refer to <http://unlicense.org/>
  6061. */
  6062. // ---------------------- end of miniz ----------------------------------------
  6063. }
  6064. bool IsBigEndian(void) {
  6065. union {
  6066. unsigned int i;
  6067. char c[4];
  6068. } bint = {0x01020304};
  6069. return bint.c[0] == 1;
  6070. }
  6071. void swap2(unsigned short *val) {
  6072. unsigned short tmp = *val;
  6073. unsigned char *dst = (unsigned char *)val;
  6074. unsigned char *src = (unsigned char *)&tmp;
  6075. dst[0] = src[1];
  6076. dst[1] = src[0];
  6077. }
  6078. void swap4(unsigned int *val) {
  6079. unsigned int tmp = *val;
  6080. unsigned char *dst = (unsigned char *)val;
  6081. unsigned char *src = (unsigned char *)&tmp;
  6082. dst[0] = src[3];
  6083. dst[1] = src[2];
  6084. dst[2] = src[1];
  6085. dst[3] = src[0];
  6086. }
  6087. void swap8(unsigned long long *val) {
  6088. unsigned long long tmp = (*val);
  6089. unsigned char *dst = (unsigned char *)val;
  6090. unsigned char *src = (unsigned char *)&tmp;
  6091. dst[0] = src[7];
  6092. dst[1] = src[6];
  6093. dst[2] = src[5];
  6094. dst[3] = src[4];
  6095. dst[4] = src[3];
  6096. dst[5] = src[2];
  6097. dst[6] = src[1];
  6098. dst[7] = src[0];
  6099. }
  6100. // https://gist.github.com/rygorous/2156668
  6101. // Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
  6102. union FP32 {
  6103. unsigned int u;
  6104. float f;
  6105. struct {
  6106. #if MINIZ_LITTLE_ENDIAN
  6107. unsigned int Mantissa : 23;
  6108. unsigned int Exponent : 8;
  6109. unsigned int Sign : 1;
  6110. #else
  6111. unsigned int Sign : 1;
  6112. unsigned int Exponent : 8;
  6113. unsigned int Mantissa : 23;
  6114. #endif
  6115. } s;
  6116. };
  6117. union FP16 {
  6118. unsigned short u;
  6119. struct {
  6120. #if MINIZ_LITTLE_ENDIAN
  6121. unsigned int Mantissa : 10;
  6122. unsigned int Exponent : 5;
  6123. unsigned int Sign : 1;
  6124. #else
  6125. unsigned int Sign : 1;
  6126. unsigned int Exponent : 5;
  6127. unsigned int Mantissa : 10;
  6128. #endif
  6129. } s;
  6130. };
  6131. FP32 half_to_float(FP16 h) {
  6132. static const FP32 magic = {113 << 23};
  6133. static const unsigned int shifted_exp = 0x7c00
  6134. << 13; // exponent mask after shift
  6135. FP32 o;
  6136. o.u = (h.u & 0x7fff) << 13; // exponent/mantissa bits
  6137. unsigned int exp_ = shifted_exp & o.u; // just the exponent
  6138. o.u += (127 - 15) << 23; // exponent adjust
  6139. // handle exponent special cases
  6140. if (exp_ == shifted_exp) // Inf/NaN?
  6141. o.u += (128 - 16) << 23; // extra exp adjust
  6142. else if (exp_ == 0) // Zero/Denormal?
  6143. {
  6144. o.u += 1 << 23; // extra exp adjust
  6145. o.f -= magic.f; // renormalize
  6146. }
  6147. o.u |= (h.u & 0x8000) << 16; // sign bit
  6148. return o;
  6149. }
  6150. FP16 float_to_half_full(FP32 f) {
  6151. FP16 o = {0};
  6152. // Based on ISPC reference code (with minor modifications)
  6153. if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
  6154. o.s.Exponent = 0;
  6155. else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
  6156. {
  6157. o.s.Exponent = 31;
  6158. o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
  6159. } else // Normalized number
  6160. {
  6161. // Exponent unbias the single, then bias the halfp
  6162. int newexp = f.s.Exponent - 127 + 15;
  6163. if (newexp >= 31) // Overflow, return signed infinity
  6164. o.s.Exponent = 31;
  6165. else if (newexp <= 0) // Underflow
  6166. {
  6167. if ((14 - newexp) <= 24) // Mantissa might be non-zero
  6168. {
  6169. unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
  6170. o.s.Mantissa = mant >> (14 - newexp);
  6171. if ((mant >> (13 - newexp)) & 1) // Check for rounding
  6172. o.u++; // Round, might overflow into exp bit, but this is OK
  6173. }
  6174. } else {
  6175. o.s.Exponent = newexp;
  6176. o.s.Mantissa = f.s.Mantissa >> 13;
  6177. if (f.s.Mantissa & 0x1000) // Check for rounding
  6178. o.u++; // Round, might overflow to inf, this is OK
  6179. }
  6180. }
  6181. o.s.Sign = f.s.Sign;
  6182. return o;
  6183. }
  6184. // NOTE: From OpenEXR code
  6185. // #define IMF_INCREASING_Y 0
  6186. // #define IMF_DECREASING_Y 1
  6187. // #define IMF_RAMDOM_Y 2
  6188. //
  6189. // #define IMF_NO_COMPRESSION 0
  6190. // #define IMF_RLE_COMPRESSION 1
  6191. // #define IMF_ZIPS_COMPRESSION 2
  6192. // #define IMF_ZIP_COMPRESSION 3
  6193. // #define IMF_PIZ_COMPRESSION 4
  6194. // #define IMF_PXR24_COMPRESSION 5
  6195. // #define IMF_B44_COMPRESSION 6
  6196. // #define IMF_B44A_COMPRESSION 7
  6197. const char *ReadString(std::string &s, const char *ptr) {
  6198. // Read untile NULL(\0).
  6199. const char *p = ptr;
  6200. const char *q = ptr;
  6201. while ((*q) != 0)
  6202. q++;
  6203. s = std::string(p, q);
  6204. return q + 1; // skip '\0'
  6205. }
  6206. const char *ReadAttribute(std::string &name, std::string &ty,
  6207. std::vector<unsigned char> &data, const char *ptr) {
  6208. if ((*ptr) == 0) {
  6209. // end of attribute.
  6210. return NULL;
  6211. }
  6212. const char *p = ReadString(name, ptr);
  6213. p = ReadString(ty, p);
  6214. int dataLen;
  6215. memcpy(&dataLen, p, sizeof(int));
  6216. p += 4;
  6217. if (IsBigEndian()) {
  6218. swap4(reinterpret_cast<unsigned int *>(&dataLen));
  6219. }
  6220. data.resize(dataLen);
  6221. memcpy(&data.at(0), p, dataLen);
  6222. p += dataLen;
  6223. return p;
  6224. }
  6225. void WriteAttribute(FILE *fp, const char *name, const char *type,
  6226. const unsigned char *data, int len) {
  6227. size_t n = fwrite(name, 1, strlen(name) + 1, fp);
  6228. assert(n == strlen(name) + 1);
  6229. n = fwrite(type, 1, strlen(type) + 1, fp);
  6230. assert(n == strlen(type) + 1);
  6231. int outLen = len;
  6232. if (IsBigEndian()) {
  6233. swap4(reinterpret_cast<unsigned int *>(&outLen));
  6234. }
  6235. n = fwrite(&outLen, 1, sizeof(int), fp);
  6236. assert(n == sizeof(int));
  6237. n = fwrite(data, 1, len, fp);
  6238. assert(n == (size_t)len);
  6239. (void)n;
  6240. }
  6241. void WriteAttributeToMemory(std::vector<unsigned char> &out, const char *name,
  6242. const char *type, const unsigned char *data,
  6243. int len) {
  6244. out.insert(out.end(), name, name + strlen(name) + 1);
  6245. out.insert(out.end(), type, type + strlen(type) + 1);
  6246. int outLen = len;
  6247. if (IsBigEndian()) {
  6248. swap4(reinterpret_cast<unsigned int *>(&outLen));
  6249. }
  6250. out.insert(out.end(), reinterpret_cast<unsigned char *>(&outLen),
  6251. reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
  6252. out.insert(out.end(), data, data + len);
  6253. }
  6254. typedef struct {
  6255. std::string name; // less than 255 bytes long
  6256. int pixelType;
  6257. unsigned char pLinear;
  6258. int xSampling;
  6259. int ySampling;
  6260. } ChannelInfo;
  6261. void ReadChannelInfo(std::vector<ChannelInfo> &channels,
  6262. const std::vector<unsigned char> &data) {
  6263. const char *p = reinterpret_cast<const char *>(&data.at(0));
  6264. for (;;) {
  6265. if ((*p) == 0) {
  6266. break;
  6267. }
  6268. ChannelInfo info;
  6269. p = ReadString(info.name, p);
  6270. memcpy(&info.pixelType, p, sizeof(int));
  6271. p += 4;
  6272. info.pLinear = p[0]; // uchar
  6273. p += 1 + 3; // reserved: uchar[3]
  6274. memcpy(&info.xSampling, p, sizeof(int)); // int
  6275. p += 4;
  6276. memcpy(&info.ySampling, p, sizeof(int)); // int
  6277. p += 4;
  6278. if (IsBigEndian()) {
  6279. swap4(reinterpret_cast<unsigned int *>(&info.pixelType));
  6280. swap4(reinterpret_cast<unsigned int *>(&info.xSampling));
  6281. swap4(reinterpret_cast<unsigned int *>(&info.ySampling));
  6282. }
  6283. channels.push_back(info);
  6284. }
  6285. }
  6286. void WriteChannelInfo(std::vector<unsigned char> &data,
  6287. const std::vector<ChannelInfo> &channels) {
  6288. size_t sz = 0;
  6289. // Calculate total size.
  6290. for (size_t c = 0; c < channels.size(); c++) {
  6291. sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
  6292. sz += 16; // 4 * int
  6293. }
  6294. data.resize(sz + 1);
  6295. unsigned char *p = &data.at(0);
  6296. for (size_t c = 0; c < channels.size(); c++) {
  6297. memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
  6298. p += strlen(channels[c].name.c_str());
  6299. (*p) = '\0';
  6300. p++;
  6301. int pixelType = channels[c].pixelType;
  6302. int xSampling = channels[c].xSampling;
  6303. int ySampling = channels[c].ySampling;
  6304. if (IsBigEndian()) {
  6305. swap4(reinterpret_cast<unsigned int *>(&pixelType));
  6306. swap4(reinterpret_cast<unsigned int *>(&xSampling));
  6307. swap4(reinterpret_cast<unsigned int *>(&ySampling));
  6308. }
  6309. memcpy(p, &pixelType, sizeof(int));
  6310. p += sizeof(int);
  6311. (*p) = channels[c].pLinear;
  6312. p += 4;
  6313. memcpy(p, &xSampling, sizeof(int));
  6314. p += sizeof(int);
  6315. memcpy(p, &ySampling, sizeof(int));
  6316. p += sizeof(int);
  6317. }
  6318. (*p) = '\0';
  6319. }
  6320. void CompressZip(unsigned char *dst, unsigned long long &compressedSize,
  6321. const unsigned char *src, unsigned long srcSize) {
  6322. std::vector<unsigned char> tmpBuf(srcSize);
  6323. //
  6324. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6325. // ImfZipCompressor.cpp
  6326. //
  6327. //
  6328. // Reorder the pixel data.
  6329. //
  6330. {
  6331. char *t1 = (char *)&tmpBuf.at(0);
  6332. char *t2 = (char *)&tmpBuf.at(0) + (srcSize + 1) / 2;
  6333. const char *stop = (const char *)src + srcSize;
  6334. while (true) {
  6335. if ((const char *)src < stop)
  6336. *(t1++) = *(src++);
  6337. else
  6338. break;
  6339. if ((const char *)src < stop)
  6340. *(t2++) = *(src++);
  6341. else
  6342. break;
  6343. }
  6344. }
  6345. //
  6346. // Predictor.
  6347. //
  6348. {
  6349. unsigned char *t = &tmpBuf.at(0) + 1;
  6350. unsigned char *stop = &tmpBuf.at(0) + srcSize;
  6351. int p = t[-1];
  6352. while (t < stop) {
  6353. int d = int(t[0]) - p + (128 + 256);
  6354. p = t[0];
  6355. t[0] = d;
  6356. ++t;
  6357. }
  6358. }
  6359. //
  6360. // Compress the data using miniz
  6361. //
  6362. miniz::mz_ulong outSize = miniz::mz_compressBound(srcSize);
  6363. int ret = miniz::mz_compress(dst, &outSize,
  6364. (const unsigned char *)&tmpBuf.at(0), srcSize);
  6365. assert(ret == miniz::MZ_OK);
  6366. (void)ret;
  6367. compressedSize = outSize;
  6368. }
  6369. void DecompressZip(unsigned char *dst, unsigned long &uncompressedSize,
  6370. const unsigned char *src, unsigned long srcSize) {
  6371. std::vector<unsigned char> tmpBuf(uncompressedSize);
  6372. int ret =
  6373. miniz::mz_uncompress(&tmpBuf.at(0), &uncompressedSize, src, srcSize);
  6374. assert(ret == miniz::MZ_OK);
  6375. (void)ret;
  6376. //
  6377. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6378. // ImfZipCompressor.cpp
  6379. //
  6380. // Predictor.
  6381. {
  6382. unsigned char *t = &tmpBuf.at(0) + 1;
  6383. unsigned char *stop = &tmpBuf.at(0) + uncompressedSize;
  6384. while (t < stop) {
  6385. int d = int(t[-1]) + int(t[0]) - 128;
  6386. t[0] = d;
  6387. ++t;
  6388. }
  6389. }
  6390. // Reorder the pixel data.
  6391. {
  6392. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6393. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6394. (uncompressedSize + 1) / 2;
  6395. char *s = reinterpret_cast<char *>(dst);
  6396. char *stop = s + uncompressedSize;
  6397. while (true) {
  6398. if (s < stop)
  6399. *(s++) = *(t1++);
  6400. else
  6401. break;
  6402. if (s < stop)
  6403. *(s++) = *(t2++);
  6404. else
  6405. break;
  6406. }
  6407. }
  6408. }
  6409. //
  6410. // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
  6411. //
  6412. // -----------------------------------------------------------------
  6413. // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
  6414. // Digital Ltd. LLC)
  6415. // (3 clause BSD license)
  6416. //
  6417. struct PIZChannelData {
  6418. unsigned short *start;
  6419. unsigned short *end;
  6420. int nx;
  6421. int ny;
  6422. int ys;
  6423. int size;
  6424. };
  6425. //-----------------------------------------------------------------------------
  6426. //
  6427. // 16-bit Haar Wavelet encoding and decoding
  6428. //
  6429. // The source code in this file is derived from the encoding
  6430. // and decoding routines written by Christian Rouet for his
  6431. // PIZ image file format.
  6432. //
  6433. //-----------------------------------------------------------------------------
  6434. //
  6435. // Wavelet basis functions without modulo arithmetic; they produce
  6436. // the best compression ratios when the wavelet-transformed data are
  6437. // Huffman-encoded, but the wavelet transform works only for 14-bit
  6438. // data (untransformed data values must be less than (1 << 14)).
  6439. //
  6440. #if 0 // @todo
  6441. inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
  6442. unsigned short &h) {
  6443. short as = a;
  6444. short bs = b;
  6445. short ms = (as + bs) >> 1;
  6446. short ds = as - bs;
  6447. l = ms;
  6448. h = ds;
  6449. }
  6450. #endif
  6451. inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
  6452. unsigned short &b) {
  6453. short ls = l;
  6454. short hs = h;
  6455. int hi = hs;
  6456. int ai = ls + (hi & 1) + (hi >> 1);
  6457. short as = ai;
  6458. short bs = ai - hi;
  6459. a = as;
  6460. b = bs;
  6461. }
  6462. //
  6463. // Wavelet basis functions with modulo arithmetic; they work with full
  6464. // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
  6465. // compress the data quite as well.
  6466. //
  6467. const int NBITS = 16;
  6468. const int A_OFFSET = 1 << (NBITS - 1);
  6469. // const int M_OFFSET = 1 << (NBITS - 1);
  6470. const int MOD_MASK = (1 << NBITS) - 1;
  6471. #if 0 // @ood
  6472. inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
  6473. unsigned short &h) {
  6474. int ao = (a + A_OFFSET) & MOD_MASK;
  6475. int m = ((ao + b) >> 1);
  6476. int d = ao - b;
  6477. if (d < 0)
  6478. m = (m + M_OFFSET) & MOD_MASK;
  6479. d &= MOD_MASK;
  6480. l = m;
  6481. h = d;
  6482. }
  6483. #endif
  6484. inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
  6485. unsigned short &b) {
  6486. int m = l;
  6487. int d = h;
  6488. int bb = (m - (d >> 1)) & MOD_MASK;
  6489. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  6490. b = bb;
  6491. a = aa;
  6492. }
  6493. //
  6494. // 2D Wavelet encoding:
  6495. //
  6496. #if 0 // @todo
  6497. void wav2Encode(unsigned short *in, // io: values are transformed in place
  6498. int nx, // i : x size
  6499. int ox, // i : x offset
  6500. int ny, // i : y size
  6501. int oy, // i : y offset
  6502. unsigned short mx) // i : maximum in[x][y] value
  6503. {
  6504. bool w14 = (mx < (1 << 14));
  6505. int n = (nx > ny) ? ny : nx;
  6506. int p = 1; // == 1 << level
  6507. int p2 = 2; // == 1 << (level+1)
  6508. //
  6509. // Hierachical loop on smaller dimension n
  6510. //
  6511. while (p2 <= n) {
  6512. unsigned short *py = in;
  6513. unsigned short *ey = in + oy * (ny - p2);
  6514. int oy1 = oy * p;
  6515. int oy2 = oy * p2;
  6516. int ox1 = ox * p;
  6517. int ox2 = ox * p2;
  6518. unsigned short i00, i01, i10, i11;
  6519. //
  6520. // Y loop
  6521. //
  6522. for (; py <= ey; py += oy2) {
  6523. unsigned short *px = py;
  6524. unsigned short *ex = py + ox * (nx - p2);
  6525. //
  6526. // X loop
  6527. //
  6528. for (; px <= ex; px += ox2) {
  6529. unsigned short *p01 = px + ox1;
  6530. unsigned short *p10 = px + oy1;
  6531. unsigned short *p11 = p10 + ox1;
  6532. //
  6533. // 2D wavelet encoding
  6534. //
  6535. if (w14) {
  6536. wenc14(*px, *p01, i00, i01);
  6537. wenc14(*p10, *p11, i10, i11);
  6538. wenc14(i00, i10, *px, *p10);
  6539. wenc14(i01, i11, *p01, *p11);
  6540. } else {
  6541. wenc16(*px, *p01, i00, i01);
  6542. wenc16(*p10, *p11, i10, i11);
  6543. wenc16(i00, i10, *px, *p10);
  6544. wenc16(i01, i11, *p01, *p11);
  6545. }
  6546. }
  6547. //
  6548. // Encode (1D) odd column (still in Y loop)
  6549. //
  6550. if (nx & p) {
  6551. unsigned short *p10 = px + oy1;
  6552. if (w14)
  6553. wenc14(*px, *p10, i00, *p10);
  6554. else
  6555. wenc16(*px, *p10, i00, *p10);
  6556. *px = i00;
  6557. }
  6558. }
  6559. //
  6560. // Encode (1D) odd line (must loop in X)
  6561. //
  6562. if (ny & p) {
  6563. unsigned short *px = py;
  6564. unsigned short *ex = py + ox * (nx - p2);
  6565. for (; px <= ex; px += ox2) {
  6566. unsigned short *p01 = px + ox1;
  6567. if (w14)
  6568. wenc14(*px, *p01, i00, *p01);
  6569. else
  6570. wenc16(*px, *p01, i00, *p01);
  6571. *px = i00;
  6572. }
  6573. }
  6574. //
  6575. // Next level
  6576. //
  6577. p = p2;
  6578. p2 <<= 1;
  6579. }
  6580. }
  6581. #endif
  6582. //
  6583. // 2D Wavelet decoding:
  6584. //
  6585. void wav2Decode(unsigned short *in, // io: values are transformed in place
  6586. int nx, // i : x size
  6587. int ox, // i : x offset
  6588. int ny, // i : y size
  6589. int oy, // i : y offset
  6590. unsigned short mx) // i : maximum in[x][y] value
  6591. {
  6592. bool w14 = (mx < (1 << 14));
  6593. int n = (nx > ny) ? ny : nx;
  6594. int p = 1;
  6595. int p2;
  6596. //
  6597. // Search max level
  6598. //
  6599. while (p <= n)
  6600. p <<= 1;
  6601. p >>= 1;
  6602. p2 = p;
  6603. p >>= 1;
  6604. //
  6605. // Hierarchical loop on smaller dimension n
  6606. //
  6607. while (p >= 1) {
  6608. unsigned short *py = in;
  6609. unsigned short *ey = in + oy * (ny - p2);
  6610. int oy1 = oy * p;
  6611. int oy2 = oy * p2;
  6612. int ox1 = ox * p;
  6613. int ox2 = ox * p2;
  6614. unsigned short i00, i01, i10, i11;
  6615. //
  6616. // Y loop
  6617. //
  6618. for (; py <= ey; py += oy2) {
  6619. unsigned short *px = py;
  6620. unsigned short *ex = py + ox * (nx - p2);
  6621. //
  6622. // X loop
  6623. //
  6624. for (; px <= ex; px += ox2) {
  6625. unsigned short *p01 = px + ox1;
  6626. unsigned short *p10 = px + oy1;
  6627. unsigned short *p11 = p10 + ox1;
  6628. //
  6629. // 2D wavelet decoding
  6630. //
  6631. if (w14) {
  6632. wdec14(*px, *p10, i00, i10);
  6633. wdec14(*p01, *p11, i01, i11);
  6634. wdec14(i00, i01, *px, *p01);
  6635. wdec14(i10, i11, *p10, *p11);
  6636. } else {
  6637. wdec16(*px, *p10, i00, i10);
  6638. wdec16(*p01, *p11, i01, i11);
  6639. wdec16(i00, i01, *px, *p01);
  6640. wdec16(i10, i11, *p10, *p11);
  6641. }
  6642. }
  6643. //
  6644. // Decode (1D) odd column (still in Y loop)
  6645. //
  6646. if (nx & p) {
  6647. unsigned short *p10 = px + oy1;
  6648. if (w14)
  6649. wdec14(*px, *p10, i00, *p10);
  6650. else
  6651. wdec16(*px, *p10, i00, *p10);
  6652. *px = i00;
  6653. }
  6654. }
  6655. //
  6656. // Decode (1D) odd line (must loop in X)
  6657. //
  6658. if (ny & p) {
  6659. unsigned short *px = py;
  6660. unsigned short *ex = py + ox * (nx - p2);
  6661. for (; px <= ex; px += ox2) {
  6662. unsigned short *p01 = px + ox1;
  6663. if (w14)
  6664. wdec14(*px, *p01, i00, *p01);
  6665. else
  6666. wdec16(*px, *p01, i00, *p01);
  6667. *px = i00;
  6668. }
  6669. }
  6670. //
  6671. // Next level
  6672. //
  6673. p2 = p;
  6674. p >>= 1;
  6675. }
  6676. }
  6677. //-----------------------------------------------------------------------------
  6678. //
  6679. // 16-bit Huffman compression and decompression.
  6680. //
  6681. // The source code in this file is derived from the 8-bit
  6682. // Huffman compression and decompression routines written
  6683. // by Christian Rouet for his PIZ image file format.
  6684. //
  6685. //-----------------------------------------------------------------------------
  6686. // Adds some modification for tinyexr.
  6687. const int HUF_ENCBITS = 16; // literal (value) bit length
  6688. const int HUF_DECBITS = 14; // decoding bit size (>= 8)
  6689. const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
  6690. const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  6691. const int HUF_DECMASK = HUF_DECSIZE - 1;
  6692. struct HufDec { // short code long code
  6693. //-------------------------------
  6694. int len : 8; // code length 0
  6695. int lit : 24; // lit p size
  6696. int *p; // 0 lits
  6697. };
  6698. inline long long hufLength(long long code) { return code & 63; }
  6699. inline long long hufCode(long long code) { return code >> 6; }
  6700. #if 0
  6701. inline void outputBits(int nBits, long long bits, long long &c, int &lc,
  6702. char *&out) {
  6703. c <<= nBits;
  6704. lc += nBits;
  6705. c |= bits;
  6706. while (lc >= 8)
  6707. *out++ = (c >> (lc -= 8));
  6708. }
  6709. #endif
  6710. inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
  6711. while (lc < nBits) {
  6712. c = (c << 8) | *(unsigned char *)(in++);
  6713. lc += 8;
  6714. }
  6715. lc -= nBits;
  6716. return (c >> lc) & ((1 << nBits) - 1);
  6717. }
  6718. //
  6719. // ENCODING TABLE BUILDING & (UN)PACKING
  6720. //
  6721. //
  6722. // Build a "canonical" Huffman code table:
  6723. // - for each (uncompressed) symbol, hcode contains the length
  6724. // of the corresponding code (in the compressed data)
  6725. // - canonical codes are computed and stored in hcode
  6726. // - the rules for constructing canonical codes are as follows:
  6727. // * shorter codes (if filled with zeroes to the right)
  6728. // have a numerically higher value than longer codes
  6729. // * for codes with the same length, numerical values
  6730. // increase with numerical symbol values
  6731. // - because the canonical code table can be constructed from
  6732. // symbol lengths alone, the code table can be transmitted
  6733. // without sending the actual code values
  6734. // - see http://www.compressconsult.com/huffman/
  6735. //
  6736. void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
  6737. long long n[59];
  6738. //
  6739. // For each i from 0 through 58, count the
  6740. // number of different codes of length i, and
  6741. // store the count in n[i].
  6742. //
  6743. for (int i = 0; i <= 58; ++i)
  6744. n[i] = 0;
  6745. for (int i = 0; i < HUF_ENCSIZE; ++i)
  6746. n[hcode[i]] += 1;
  6747. //
  6748. // For each i from 58 through 1, compute the
  6749. // numerically lowest code with length i, and
  6750. // store that code in n[i].
  6751. //
  6752. long long c = 0;
  6753. for (int i = 58; i > 0; --i) {
  6754. long long nc = ((c + n[i]) >> 1);
  6755. n[i] = c;
  6756. c = nc;
  6757. }
  6758. //
  6759. // hcode[i] contains the length, l, of the
  6760. // code for symbol i. Assign the next available
  6761. // code of length l to the symbol and store both
  6762. // l and the code in hcode[i].
  6763. //
  6764. for (int i = 0; i < HUF_ENCSIZE; ++i) {
  6765. int l = hcode[i];
  6766. if (l > 0)
  6767. hcode[i] = l | (n[l]++ << 6);
  6768. }
  6769. }
  6770. //
  6771. // Compute Huffman codes (based on frq input) and store them in frq:
  6772. // - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
  6773. // - max code length is 58 bits;
  6774. // - codes outside the range [im-iM] have a null length (unused values);
  6775. // - original frequencies are destroyed;
  6776. // - encoding tables are used by hufEncode() and hufBuildDecTable();
  6777. //
  6778. #if 0 // @todo
  6779. struct FHeapCompare {
  6780. bool operator()(long long *a, long long *b) { return *a > *b; }
  6781. };
  6782. void hufBuildEncTable(
  6783. long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
  6784. int *im, // o: min frq index
  6785. int *iM) // o: max frq index
  6786. {
  6787. //
  6788. // This function assumes that when it is called, array frq
  6789. // indicates the frequency of all possible symbols in the data
  6790. // that are to be Huffman-encoded. (frq[i] contains the number
  6791. // of occurrences of symbol i in the data.)
  6792. //
  6793. // The loop below does three things:
  6794. //
  6795. // 1) Finds the minimum and maximum indices that point
  6796. // to non-zero entries in frq:
  6797. //
  6798. // frq[im] != 0, and frq[i] == 0 for all i < im
  6799. // frq[iM] != 0, and frq[i] == 0 for all i > iM
  6800. //
  6801. // 2) Fills array fHeap with pointers to all non-zero
  6802. // entries in frq.
  6803. //
  6804. // 3) Initializes array hlink such that hlink[i] == i
  6805. // for all array entries.
  6806. //
  6807. int hlink[HUF_ENCSIZE];
  6808. long long *fHeap[HUF_ENCSIZE];
  6809. *im = 0;
  6810. while (!frq[*im])
  6811. (*im)++;
  6812. int nf = 0;
  6813. for (int i = *im; i < HUF_ENCSIZE; i++) {
  6814. hlink[i] = i;
  6815. if (frq[i]) {
  6816. fHeap[nf] = &frq[i];
  6817. nf++;
  6818. *iM = i;
  6819. }
  6820. }
  6821. //
  6822. // Add a pseudo-symbol, with a frequency count of 1, to frq;
  6823. // adjust the fHeap and hlink array accordingly. Function
  6824. // hufEncode() uses the pseudo-symbol for run-length encoding.
  6825. //
  6826. (*iM)++;
  6827. frq[*iM] = 1;
  6828. fHeap[nf] = &frq[*iM];
  6829. nf++;
  6830. //
  6831. // Build an array, scode, such that scode[i] contains the number
  6832. // of bits assigned to symbol i. Conceptually this is done by
  6833. // constructing a tree whose leaves are the symbols with non-zero
  6834. // frequency:
  6835. //
  6836. // Make a heap that contains all symbols with a non-zero frequency,
  6837. // with the least frequent symbol on top.
  6838. //
  6839. // Repeat until only one symbol is left on the heap:
  6840. //
  6841. // Take the two least frequent symbols off the top of the heap.
  6842. // Create a new node that has first two nodes as children, and
  6843. // whose frequency is the sum of the frequencies of the first
  6844. // two nodes. Put the new node back into the heap.
  6845. //
  6846. // The last node left on the heap is the root of the tree. For each
  6847. // leaf node, the distance between the root and the leaf is the length
  6848. // of the code for the corresponding symbol.
  6849. //
  6850. // The loop below doesn't actually build the tree; instead we compute
  6851. // the distances of the leaves from the root on the fly. When a new
  6852. // node is added to the heap, then that node's descendants are linked
  6853. // into a single linear list that starts at the new node, and the code
  6854. // lengths of the descendants (that is, their distance from the root
  6855. // of the tree) are incremented by one.
  6856. //
  6857. std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  6858. long long scode[HUF_ENCSIZE];
  6859. memset(scode, 0, sizeof(long long) * HUF_ENCSIZE);
  6860. while (nf > 1) {
  6861. //
  6862. // Find the indices, mm and m, of the two smallest non-zero frq
  6863. // values in fHeap, add the smallest frq to the second-smallest
  6864. // frq, and remove the smallest frq value from fHeap.
  6865. //
  6866. int mm = fHeap[0] - frq;
  6867. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  6868. --nf;
  6869. int m = fHeap[0] - frq;
  6870. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  6871. frq[m] += frq[mm];
  6872. std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  6873. //
  6874. // The entries in scode are linked into lists with the
  6875. // entries in hlink serving as "next" pointers and with
  6876. // the end of a list marked by hlink[j] == j.
  6877. //
  6878. // Traverse the lists that start at scode[m] and scode[mm].
  6879. // For each element visited, increment the length of the
  6880. // corresponding code by one bit. (If we visit scode[j]
  6881. // during the traversal, then the code for symbol j becomes
  6882. // one bit longer.)
  6883. //
  6884. // Merge the lists that start at scode[m] and scode[mm]
  6885. // into a single list that starts at scode[m].
  6886. //
  6887. //
  6888. // Add a bit to all codes in the first list.
  6889. //
  6890. for (int j = m; true; j = hlink[j]) {
  6891. scode[j]++;
  6892. assert(scode[j] <= 58);
  6893. if (hlink[j] == j) {
  6894. //
  6895. // Merge the two lists.
  6896. //
  6897. hlink[j] = mm;
  6898. break;
  6899. }
  6900. }
  6901. //
  6902. // Add a bit to all codes in the second list
  6903. //
  6904. for (int j = mm; true; j = hlink[j]) {
  6905. scode[j]++;
  6906. assert(scode[j] <= 58);
  6907. if (hlink[j] == j)
  6908. break;
  6909. }
  6910. }
  6911. //
  6912. // Build a canonical Huffman code table, replacing the code
  6913. // lengths in scode with (code, code length) pairs. Copy the
  6914. // code table from scode into frq.
  6915. //
  6916. hufCanonicalCodeTable(scode);
  6917. memcpy(frq, scode, sizeof(long long) * HUF_ENCSIZE);
  6918. }
  6919. #endif
  6920. //
  6921. // Pack an encoding table:
  6922. // - only code lengths, not actual codes, are stored
  6923. // - runs of zeroes are compressed as follows:
  6924. //
  6925. // unpacked packed
  6926. // --------------------------------
  6927. // 1 zero 0 (6 bits)
  6928. // 2 zeroes 59
  6929. // 3 zeroes 60
  6930. // 4 zeroes 61
  6931. // 5 zeroes 62
  6932. // n zeroes (6 or more) 63 n-6 (6 + 8 bits)
  6933. //
  6934. const int SHORT_ZEROCODE_RUN = 59;
  6935. const int LONG_ZEROCODE_RUN = 63;
  6936. const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  6937. // const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
  6938. #if 0
  6939. void hufPackEncTable(const long long *hcode, // i : encoding table [HUF_ENCSIZE]
  6940. int im, // i : min hcode index
  6941. int iM, // i : max hcode index
  6942. char **pcode) // o: ptr to packed table (updated)
  6943. {
  6944. char *p = *pcode;
  6945. long long c = 0;
  6946. int lc = 0;
  6947. for (; im <= iM; im++) {
  6948. int l = hufLength(hcode[im]);
  6949. if (l == 0) {
  6950. int zerun = 1;
  6951. while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
  6952. if (hufLength(hcode[im + 1]) > 0)
  6953. break;
  6954. im++;
  6955. zerun++;
  6956. }
  6957. if (zerun >= 2) {
  6958. if (zerun >= SHORTEST_LONG_RUN) {
  6959. outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
  6960. outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
  6961. } else {
  6962. outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
  6963. }
  6964. continue;
  6965. }
  6966. }
  6967. outputBits(6, l, c, lc, p);
  6968. }
  6969. if (lc > 0)
  6970. *p++ = (unsigned char)(c << (8 - lc));
  6971. *pcode = p;
  6972. }
  6973. #endif
  6974. //
  6975. // Unpack an encoding table packed by hufPackEncTable():
  6976. //
  6977. bool hufUnpackEncTable(const char **pcode, // io: ptr to packed table (updated)
  6978. int ni, // i : input size (in bytes)
  6979. int im, // i : min hcode index
  6980. int iM, // i : max hcode index
  6981. long long *hcode) // o: encoding table [HUF_ENCSIZE]
  6982. {
  6983. memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
  6984. const char *p = *pcode;
  6985. long long c = 0;
  6986. int lc = 0;
  6987. for (; im <= iM; im++) {
  6988. if (p - *pcode > ni) {
  6989. return false;
  6990. }
  6991. long long l = hcode[im] = getBits(6, c, lc, p); // code length
  6992. if (l == (long long)LONG_ZEROCODE_RUN) {
  6993. if (p - *pcode > ni) {
  6994. return false;
  6995. }
  6996. int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
  6997. if (im + zerun > iM + 1) {
  6998. return false;
  6999. }
  7000. while (zerun--)
  7001. hcode[im++] = 0;
  7002. im--;
  7003. } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
  7004. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  7005. if (im + zerun > iM + 1) {
  7006. return false;
  7007. }
  7008. while (zerun--)
  7009. hcode[im++] = 0;
  7010. im--;
  7011. }
  7012. }
  7013. *pcode = const_cast<char *>(p);
  7014. hufCanonicalCodeTable(hcode);
  7015. return true;
  7016. }
  7017. //
  7018. // DECODING TABLE BUILDING
  7019. //
  7020. //
  7021. // Clear a newly allocated decoding table so that it contains only zeroes.
  7022. //
  7023. void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
  7024. // decoding table [HUF_DECSIZE]
  7025. {
  7026. for (int i = 0; i < HUF_DECSIZE; i++) {
  7027. hdecod[i].len = 0;
  7028. hdecod[i].lit = 0;
  7029. hdecod[i].p = NULL;
  7030. }
  7031. // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
  7032. }
  7033. //
  7034. // Build a decoding hash table based on the encoding table hcode:
  7035. // - short codes (<= HUF_DECBITS) are resolved with a single table access;
  7036. // - long code entry allocations are not optimized, because long codes are
  7037. // unfrequent;
  7038. // - decoding tables are used by hufDecode();
  7039. //
  7040. bool hufBuildDecTable(const long long *hcode, // i : encoding table
  7041. int im, // i : min index in hcode
  7042. int iM, // i : max index in hcode
  7043. HufDec *hdecod) // o: (allocated by caller)
  7044. // decoding table [HUF_DECSIZE]
  7045. {
  7046. //
  7047. // Init hashtable & loop on all codes.
  7048. // Assumes that hufClearDecTable(hdecod) has already been called.
  7049. //
  7050. for (; im <= iM; im++) {
  7051. long long c = hufCode(hcode[im]);
  7052. int l = hufLength(hcode[im]);
  7053. if (c >> l) {
  7054. //
  7055. // Error: c is supposed to be an l-bit code,
  7056. // but c contains a value that is greater
  7057. // than the largest l-bit number.
  7058. //
  7059. // invalidTableEntry();
  7060. return false;
  7061. }
  7062. if (l > HUF_DECBITS) {
  7063. //
  7064. // Long code: add a secondary entry
  7065. //
  7066. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  7067. if (pl->len) {
  7068. //
  7069. // Error: a short code has already
  7070. // been stored in table entry *pl.
  7071. //
  7072. // invalidTableEntry();
  7073. return false;
  7074. }
  7075. pl->lit++;
  7076. if (pl->p) {
  7077. int *p = pl->p;
  7078. pl->p = new int[pl->lit];
  7079. for (int i = 0; i < pl->lit - 1; ++i)
  7080. pl->p[i] = p[i];
  7081. delete[] p;
  7082. } else {
  7083. pl->p = new int[1];
  7084. }
  7085. pl->p[pl->lit - 1] = im;
  7086. } else if (l) {
  7087. //
  7088. // Short code: init all primary entries
  7089. //
  7090. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  7091. for (long long i = (long long)1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
  7092. if (pl->len || pl->p) {
  7093. //
  7094. // Error: a short code or a long code has
  7095. // already been stored in table entry *pl.
  7096. //
  7097. // invalidTableEntry();
  7098. return false;
  7099. }
  7100. pl->len = l;
  7101. pl->lit = im;
  7102. }
  7103. }
  7104. }
  7105. return true;
  7106. }
  7107. //
  7108. // Free the long code entries of a decoding table built by hufBuildDecTable()
  7109. //
  7110. void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
  7111. {
  7112. for (int i = 0; i < HUF_DECSIZE; i++) {
  7113. if (hdecod[i].p) {
  7114. delete[] hdecod[i].p;
  7115. hdecod[i].p = 0;
  7116. }
  7117. }
  7118. }
  7119. //
  7120. // ENCODING
  7121. //
  7122. #if 0 // @todo
  7123. inline void outputCode(long long code, long long &c, int &lc, char *&out) {
  7124. outputBits(hufLength(code), hufCode(code), c, lc, out);
  7125. }
  7126. inline void sendCode(long long sCode, int runCount, long long runCode,
  7127. long long &c, int &lc, char *&out) {
  7128. //
  7129. // Output a run of runCount instances of the symbol sCount.
  7130. // Output the symbols explicitly, or if that is shorter, output
  7131. // the sCode symbol once followed by a runCode symbol and runCount
  7132. // expressed as an 8-bit number.
  7133. //
  7134. if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
  7135. outputCode(sCode, c, lc, out);
  7136. outputCode(runCode, c, lc, out);
  7137. outputBits(8, runCount, c, lc, out);
  7138. } else {
  7139. while (runCount-- >= 0)
  7140. outputCode(sCode, c, lc, out);
  7141. }
  7142. }
  7143. //
  7144. // Encode (compress) ni values based on the Huffman encoding table hcode:
  7145. //
  7146. int hufEncode // return: output size (in bits)
  7147. (const long long *hcode, // i : encoding table
  7148. const unsigned short *in, // i : uncompressed input buffer
  7149. const int ni, // i : input buffer size (in bytes)
  7150. int rlc, // i : rl code
  7151. char *out) // o: compressed output buffer
  7152. {
  7153. char *outStart = out;
  7154. long long c = 0; // bits not yet written to out
  7155. int lc = 0; // number of valid bits in c (LSB)
  7156. int s = in[0];
  7157. int cs = 0;
  7158. //
  7159. // Loop on input values
  7160. //
  7161. for (int i = 1; i < ni; i++) {
  7162. //
  7163. // Count same values or send code
  7164. //
  7165. if (s == in[i] && cs < 255) {
  7166. cs++;
  7167. } else {
  7168. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7169. cs = 0;
  7170. }
  7171. s = in[i];
  7172. }
  7173. //
  7174. // Send remaining code
  7175. //
  7176. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7177. if (lc)
  7178. *out = (c << (8 - lc)) & 0xff;
  7179. return (out - outStart) * 8 + lc;
  7180. }
  7181. #endif
  7182. //
  7183. // DECODING
  7184. //
  7185. //
  7186. // In order to force the compiler to inline them,
  7187. // getChar() and getCode() are implemented as macros
  7188. // instead of "inline" functions.
  7189. //
  7190. #define getChar(c, lc, in) \
  7191. { \
  7192. c = (c << 8) | *(unsigned char *)(in++); \
  7193. lc += 8; \
  7194. }
  7195. #define getCode(po, rlc, c, lc, in, out, oe) \
  7196. { \
  7197. if (po == rlc) { \
  7198. if (lc < 8) \
  7199. getChar(c, lc, in); \
  7200. \
  7201. lc -= 8; \
  7202. \
  7203. unsigned char cs = (c >> lc); \
  7204. \
  7205. if (out + cs > oe) \
  7206. return false; \
  7207. \
  7208. unsigned short s = out[-1]; \
  7209. \
  7210. while (cs-- > 0) \
  7211. *out++ = s; \
  7212. } else if (out < oe) { \
  7213. *out++ = po; \
  7214. } else { \
  7215. return false; \
  7216. } \
  7217. }
  7218. //
  7219. // Decode (uncompress) ni bits based on encoding & decoding tables:
  7220. //
  7221. bool hufDecode(const long long *hcode, // i : encoding table
  7222. const HufDec *hdecod, // i : decoding table
  7223. const char *in, // i : compressed input buffer
  7224. int ni, // i : input size (in bits)
  7225. int rlc, // i : run-length code
  7226. int no, // i : expected output size (in bytes)
  7227. unsigned short *out) // o: uncompressed output buffer
  7228. {
  7229. long long c = 0;
  7230. int lc = 0;
  7231. unsigned short *outb = out;
  7232. unsigned short *oe = out + no;
  7233. const char *ie = in + (ni + 7) / 8; // input byte size
  7234. //
  7235. // Loop on input bytes
  7236. //
  7237. while (in < ie) {
  7238. getChar(c, lc, in);
  7239. //
  7240. // Access decoding table
  7241. //
  7242. while (lc >= HUF_DECBITS) {
  7243. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  7244. if (pl.len) {
  7245. //
  7246. // Get short code
  7247. //
  7248. lc -= pl.len;
  7249. getCode(pl.lit, rlc, c, lc, in, out, oe);
  7250. } else {
  7251. if (!pl.p) {
  7252. return false;
  7253. }
  7254. // invalidCode(); // wrong code
  7255. //
  7256. // Search long code
  7257. //
  7258. int j;
  7259. for (j = 0; j < pl.lit; j++) {
  7260. int l = hufLength(hcode[pl.p[j]]);
  7261. while (lc < l && in < ie) // get more bits
  7262. getChar(c, lc, in);
  7263. if (lc >= l) {
  7264. if (hufCode(hcode[pl.p[j]]) ==
  7265. ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
  7266. //
  7267. // Found : get long code
  7268. //
  7269. lc -= l;
  7270. getCode(pl.p[j], rlc, c, lc, in, out, oe);
  7271. break;
  7272. }
  7273. }
  7274. }
  7275. if (j == pl.lit) {
  7276. return false;
  7277. // invalidCode(); // Not found
  7278. }
  7279. }
  7280. }
  7281. }
  7282. //
  7283. // Get remaining (short) codes
  7284. //
  7285. int i = (8 - ni) & 7;
  7286. c >>= i;
  7287. lc -= i;
  7288. while (lc > 0) {
  7289. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  7290. if (pl.len) {
  7291. lc -= pl.len;
  7292. getCode(pl.lit, rlc, c, lc, in, out, oe);
  7293. } else {
  7294. return false;
  7295. // invalidCode(); // wrong (long) code
  7296. }
  7297. }
  7298. if (out - outb != no) {
  7299. return false;
  7300. }
  7301. // notEnoughData ();
  7302. return true;
  7303. }
  7304. #if 0 // @todo
  7305. void countFrequencies(long long freq[HUF_ENCSIZE],
  7306. const unsigned short data[/*n*/], int n) {
  7307. for (int i = 0; i < HUF_ENCSIZE; ++i)
  7308. freq[i] = 0;
  7309. for (int i = 0; i < n; ++i)
  7310. ++freq[data[i]];
  7311. }
  7312. void writeUInt(char buf[4], unsigned int i) {
  7313. unsigned char *b = (unsigned char *)buf;
  7314. b[0] = i;
  7315. b[1] = i >> 8;
  7316. b[2] = i >> 16;
  7317. b[3] = i >> 24;
  7318. }
  7319. #endif
  7320. unsigned int readUInt(const char buf[4]) {
  7321. const unsigned char *b = (const unsigned char *)buf;
  7322. return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
  7323. ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
  7324. }
  7325. //
  7326. // EXTERNAL INTERFACE
  7327. //
  7328. #if 0 // @todo
  7329. int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) {
  7330. if (nRaw == 0)
  7331. return 0;
  7332. long long freq[HUF_ENCSIZE];
  7333. countFrequencies(freq, raw, nRaw);
  7334. int im = 0;
  7335. int iM = 0;
  7336. hufBuildEncTable(freq, &im, &iM);
  7337. char *tableStart = compressed + 20;
  7338. char *tableEnd = tableStart;
  7339. hufPackEncTable(freq, im, iM, &tableEnd);
  7340. int tableLength = tableEnd - tableStart;
  7341. char *dataStart = tableEnd;
  7342. int nBits = hufEncode(freq, raw, nRaw, iM, dataStart);
  7343. int dataLength = (nBits + 7) / 8;
  7344. writeUInt(compressed, im);
  7345. writeUInt(compressed + 4, iM);
  7346. writeUInt(compressed + 8, tableLength);
  7347. writeUInt(compressed + 12, nBits);
  7348. writeUInt(compressed + 16, 0); // room for future extensions
  7349. return dataStart + dataLength - compressed;
  7350. }
  7351. #endif
  7352. bool hufUncompress(const char compressed[], int nCompressed,
  7353. unsigned short raw[], int nRaw) {
  7354. if (nCompressed == 0) {
  7355. if (nRaw != 0)
  7356. return false;
  7357. return false;
  7358. }
  7359. int im = readUInt(compressed);
  7360. int iM = readUInt(compressed + 4);
  7361. // int tableLength = readUInt (compressed + 8);
  7362. int nBits = readUInt(compressed + 12);
  7363. if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
  7364. return false;
  7365. const char *ptr = compressed + 20;
  7366. //
  7367. // Fast decoder needs at least 2x64-bits of compressed data, and
  7368. // needs to be run-able on this platform. Otherwise, fall back
  7369. // to the original decoder
  7370. //
  7371. // if (FastHufDecoder::enabled() && nBits > 128)
  7372. //{
  7373. // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
  7374. // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
  7375. //}
  7376. // else
  7377. {
  7378. std::vector<long long> freq(HUF_ENCSIZE);
  7379. std::vector<HufDec> hdec(HUF_DECSIZE);
  7380. hufClearDecTable(&hdec.at(0));
  7381. hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
  7382. &freq.at(0));
  7383. {
  7384. if (nBits > 8 * (nCompressed - (ptr - compressed))) {
  7385. return false;
  7386. }
  7387. hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
  7388. hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, nRaw, raw);
  7389. }
  7390. // catch (...)
  7391. //{
  7392. // hufFreeDecTable (hdec);
  7393. // throw;
  7394. //}
  7395. hufFreeDecTable(&hdec.at(0));
  7396. }
  7397. return true;
  7398. }
  7399. //
  7400. // Functions to compress the range of values in the pixel data
  7401. //
  7402. const int USHORT_RANGE = (1 << 16);
  7403. const int BITMAP_SIZE = (USHORT_RANGE >> 3);
  7404. #if 0 // @todo
  7405. void bitmapFromData(const unsigned short data[/*nData*/], int nData,
  7406. unsigned char bitmap[BITMAP_SIZE],
  7407. unsigned short &minNonZero, unsigned short &maxNonZero) {
  7408. for (int i = 0; i < BITMAP_SIZE; ++i)
  7409. bitmap[i] = 0;
  7410. for (int i = 0; i < nData; ++i)
  7411. bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
  7412. bitmap[0] &= ~1; // zero is not explicitly stored in
  7413. // the bitmap; we assume that the
  7414. // data always contain zeroes
  7415. minNonZero = BITMAP_SIZE - 1;
  7416. maxNonZero = 0;
  7417. for (int i = 0; i < BITMAP_SIZE; ++i) {
  7418. if (bitmap[i]) {
  7419. if (minNonZero > i)
  7420. minNonZero = i;
  7421. if (maxNonZero < i)
  7422. maxNonZero = i;
  7423. }
  7424. }
  7425. }
  7426. unsigned short forwardLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
  7427. unsigned short lut[USHORT_RANGE]) {
  7428. int k = 0;
  7429. for (int i = 0; i < USHORT_RANGE; ++i) {
  7430. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  7431. lut[i] = k++;
  7432. else
  7433. lut[i] = 0;
  7434. }
  7435. return k - 1; // maximum value stored in lut[],
  7436. } // i.e. number of ones in bitmap minus 1
  7437. #endif
  7438. unsigned short reverseLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
  7439. unsigned short lut[USHORT_RANGE]) {
  7440. int k = 0;
  7441. for (int i = 0; i < USHORT_RANGE; ++i) {
  7442. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  7443. lut[k++] = i;
  7444. }
  7445. int n = k - 1;
  7446. while (k < USHORT_RANGE)
  7447. lut[k++] = 0;
  7448. return n; // maximum k where lut[k] is non-zero,
  7449. } // i.e. number of ones in bitmap minus 1
  7450. void applyLut(const unsigned short lut[USHORT_RANGE],
  7451. unsigned short data[/*nData*/], int nData) {
  7452. for (int i = 0; i < nData; ++i)
  7453. data[i] = lut[data[i]];
  7454. }
  7455. #if 0 // @todo
  7456. bool CompressPiz(unsigned char *outPtr, unsigned int &outSize) {
  7457. unsigned char bitmap[BITMAP_SIZE];
  7458. unsigned short minNonZero;
  7459. unsigned short maxNonZero;
  7460. if (IsBigEndian()) {
  7461. // @todo { PIZ compression on BigEndian architecture. }
  7462. assert(0);
  7463. return false;
  7464. }
  7465. std::vector<unsigned short> tmpBuffer;
  7466. int nData = tmpBuffer.size();
  7467. bitmapFromData(&tmpBuffer.at(0), nData, bitmap, minNonZero, maxNonZero);
  7468. unsigned short lut[USHORT_RANGE];
  7469. //unsigned short maxValue = forwardLutFromBitmap(bitmap, lut);
  7470. applyLut(lut, &tmpBuffer.at(0), nData);
  7471. //
  7472. // Store range compression info in _outBuffer
  7473. //
  7474. char *buf = reinterpret_cast<char *>(outPtr);
  7475. memcpy(buf, &minNonZero, sizeof(unsigned short));
  7476. buf += sizeof(unsigned short);
  7477. memcpy(buf, &maxNonZero, sizeof(unsigned short));
  7478. buf += sizeof(unsigned short);
  7479. if (minNonZero <= maxNonZero) {
  7480. memcpy(buf, (char *)&bitmap[0] + minNonZero, maxNonZero - minNonZero + 1);
  7481. buf += maxNonZero - minNonZero + 1;
  7482. }
  7483. #if 0 // @todo
  7484. //
  7485. // Apply wavelet encoding
  7486. //
  7487. for (int i = 0; i < channels; ++i)
  7488. {
  7489. ChannelData &cd = _channelData[i];
  7490. for (int j = 0; j < cd.size; ++j)
  7491. {
  7492. wav2Encode (cd.start + j,
  7493. cd.nx, cd.size,
  7494. cd.ny, cd.nx * cd.size,
  7495. maxValue);
  7496. }
  7497. }
  7498. //
  7499. // Apply Huffman encoding; append the result to _outBuffer
  7500. //
  7501. char *lengthPtr = buf;
  7502. int zero = 0;
  7503. memcpy(buf, &zero, sizeof(int)); buf += sizeof(int);
  7504. int length = hufCompress (_tmpBuffer, tmpBufferEnd - _tmpBuffer, buf);
  7505. memcpy(lengthPtr, tmpBuffer, length);
  7506. //Xdr::write <CharPtrIO> (lengthPtr, length);
  7507. outPtr = _outBuffer;
  7508. return buf - _outBuffer + length;
  7509. #endif
  7510. assert(0);
  7511. return true;
  7512. }
  7513. #endif
  7514. bool DecompressPiz(unsigned char *outPtr, unsigned int &,
  7515. const unsigned char *inPtr, size_t tmpBufSize,
  7516. const std::vector<ChannelInfo> &channelInfo, int dataWidth,
  7517. int numLines) {
  7518. unsigned char bitmap[BITMAP_SIZE];
  7519. unsigned short minNonZero;
  7520. unsigned short maxNonZero;
  7521. if (IsBigEndian()) {
  7522. // @todo { PIZ compression on BigEndian architecture. }
  7523. assert(0);
  7524. return false;
  7525. }
  7526. memset(bitmap, 0, BITMAP_SIZE);
  7527. const unsigned char *ptr = inPtr;
  7528. minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
  7529. maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
  7530. ptr += 4;
  7531. if (maxNonZero >= BITMAP_SIZE) {
  7532. return false;
  7533. }
  7534. if (minNonZero <= maxNonZero) {
  7535. memcpy((char *)&bitmap[0] + minNonZero, ptr, maxNonZero - minNonZero + 1);
  7536. ptr += maxNonZero - minNonZero + 1;
  7537. }
  7538. unsigned short lut[USHORT_RANGE];
  7539. memset(lut, 0, sizeof(unsigned short) * USHORT_RANGE);
  7540. unsigned short maxValue = reverseLutFromBitmap(bitmap, lut);
  7541. //
  7542. // Huffman decoding
  7543. //
  7544. int length;
  7545. length = *(reinterpret_cast<const int *>(ptr));
  7546. ptr += sizeof(int);
  7547. std::vector<unsigned short> tmpBuffer(tmpBufSize);
  7548. hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer.at(0),
  7549. tmpBufSize);
  7550. //
  7551. // Wavelet decoding
  7552. //
  7553. std::vector<PIZChannelData> channelData(channelInfo.size());
  7554. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  7555. for (size_t i = 0; i < channelInfo.size(); ++i) {
  7556. const ChannelInfo &chan = channelInfo[i];
  7557. int pixelSize = sizeof(int); // UINT and FLOAT
  7558. if (chan.pixelType == TINYEXR_PIXELTYPE_HALF) {
  7559. pixelSize = sizeof(short);
  7560. }
  7561. channelData[i].start = tmpBufferEnd;
  7562. channelData[i].end = channelData[i].start;
  7563. channelData[i].nx = dataWidth;
  7564. channelData[i].ny = numLines;
  7565. // channelData[i].ys = 1;
  7566. channelData[i].size = pixelSize / sizeof(short);
  7567. tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
  7568. }
  7569. for (size_t i = 0; i < channelData.size(); ++i) {
  7570. PIZChannelData &cd = channelData[i];
  7571. for (int j = 0; j < cd.size; ++j) {
  7572. wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  7573. maxValue);
  7574. }
  7575. }
  7576. //
  7577. // Expand the pixel data to their original range
  7578. //
  7579. applyLut(lut, &tmpBuffer.at(0), tmpBufSize);
  7580. // @todo { Xdr }
  7581. for (int y = 0; y < numLines; y++) {
  7582. for (size_t i = 0; i < channelData.size(); ++i) {
  7583. PIZChannelData &cd = channelData[i];
  7584. // if (modp (y, cd.ys) != 0)
  7585. // continue;
  7586. int n = cd.nx * cd.size;
  7587. memcpy(outPtr, cd.end, n * sizeof(unsigned short));
  7588. outPtr += n * sizeof(unsigned short);
  7589. cd.end += n;
  7590. }
  7591. }
  7592. return true;
  7593. }
  7594. //
  7595. // -----------------------------------------------------------------
  7596. //
  7597. } // namespace
  7598. int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
  7599. const char **err) {
  7600. if (out_rgba == NULL) {
  7601. if (err) {
  7602. (*err) = "Invalid argument.\n";
  7603. }
  7604. return -1;
  7605. }
  7606. EXRImage exrImage;
  7607. InitEXRImage(&exrImage);
  7608. {
  7609. int ret = ParseMultiChannelEXRHeaderFromFile(&exrImage, filename, err);
  7610. if (ret != 0) {
  7611. return ret;
  7612. }
  7613. }
  7614. // Read HALF channel as FLOAT.
  7615. for (int i = 0; i < exrImage.num_channels; i++) {
  7616. if (exrImage.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  7617. exrImage.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  7618. }
  7619. }
  7620. {
  7621. int ret = LoadMultiChannelEXRFromFile(&exrImage, filename, err);
  7622. if (ret != 0) {
  7623. return ret;
  7624. }
  7625. }
  7626. // RGBA
  7627. int idxR = -1;
  7628. int idxG = -1;
  7629. int idxB = -1;
  7630. int idxA = -1;
  7631. for (int c = 0; c < exrImage.num_channels; c++) {
  7632. if (strcmp(exrImage.channel_names[c], "R") == 0) {
  7633. idxR = c;
  7634. } else if (strcmp(exrImage.channel_names[c], "G") == 0) {
  7635. idxG = c;
  7636. } else if (strcmp(exrImage.channel_names[c], "B") == 0) {
  7637. idxB = c;
  7638. } else if (strcmp(exrImage.channel_names[c], "A") == 0) {
  7639. idxA = c;
  7640. }
  7641. }
  7642. if (idxR == -1) {
  7643. if (err) {
  7644. (*err) = "R channel not found\n";
  7645. }
  7646. // @todo { free exrImage }
  7647. return -1;
  7648. }
  7649. if (idxG == -1) {
  7650. if (err) {
  7651. (*err) = "G channel not found\n";
  7652. }
  7653. // @todo { free exrImage }
  7654. return -1;
  7655. }
  7656. if (idxB == -1) {
  7657. if (err) {
  7658. (*err) = "B channel not found\n";
  7659. }
  7660. // @todo { free exrImage }
  7661. return -1;
  7662. }
  7663. (*out_rgba) =
  7664. (float *)malloc(4 * sizeof(float) * exrImage.width * exrImage.height);
  7665. for (int i = 0; i < exrImage.width * exrImage.height; i++) {
  7666. (*out_rgba)[4 * i + 0] =
  7667. reinterpret_cast<float **>(exrImage.images)[idxR][i];
  7668. (*out_rgba)[4 * i + 1] =
  7669. reinterpret_cast<float **>(exrImage.images)[idxG][i];
  7670. (*out_rgba)[4 * i + 2] =
  7671. reinterpret_cast<float **>(exrImage.images)[idxB][i];
  7672. if (idxA > 0) {
  7673. (*out_rgba)[4 * i + 3] =
  7674. reinterpret_cast<float **>(exrImage.images)[idxA][i];
  7675. } else {
  7676. (*out_rgba)[4 * i + 3] = 1.0;
  7677. }
  7678. }
  7679. (*width) = exrImage.width;
  7680. (*height) = exrImage.height;
  7681. // @todo { free exrImage }
  7682. return 0;
  7683. }
  7684. int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
  7685. int *numCustomAttributes, int *width, int *height,
  7686. const unsigned char *memory) {
  7687. if (memory == NULL) {
  7688. // Invalid argument
  7689. return -1;
  7690. }
  7691. const char *buf = reinterpret_cast<const char *>(memory);
  7692. const char *marker = &buf[0];
  7693. // Header check.
  7694. {
  7695. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  7696. if (memcmp(marker, header, 4) != 0) {
  7697. // if (err) {
  7698. // (*err) = "Header mismatch.";
  7699. //}
  7700. return -3;
  7701. }
  7702. marker += 4;
  7703. }
  7704. // Version, scanline.
  7705. {
  7706. // must be [2, 0, 0, 0]
  7707. if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
  7708. // if (err) {
  7709. // (*err) = "Unsupported version or scanline.";
  7710. //}
  7711. return -4;
  7712. }
  7713. marker += 4;
  7714. }
  7715. int dx = -1;
  7716. int dy = -1;
  7717. int dw = -1;
  7718. int dh = -1;
  7719. int lineOrder = 0; // @fixme
  7720. int displayWindow[4] = {-1, -1, -1, -1}; // @fixme
  7721. float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
  7722. float screenWindowWidth = 1.0f; // @fixme
  7723. int numChannels = -1;
  7724. float pixelAspectRatio = 1.0f; // @fixme
  7725. std::vector<ChannelInfo> channels;
  7726. std::vector<EXRAttribute> attribs;
  7727. if (numCustomAttributes) {
  7728. (*numCustomAttributes) = 0;
  7729. }
  7730. // Read attributes
  7731. for (;;) {
  7732. std::string attrName;
  7733. std::string attrType;
  7734. std::vector<unsigned char> data;
  7735. const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
  7736. if (marker_next == NULL) {
  7737. marker++; // skip '\0'
  7738. break;
  7739. }
  7740. if (attrName.compare("compression") == TINYEXR_COMPRESSIONTYPE_NONE) {
  7741. // mwkm
  7742. // 0 : NO_COMPRESSION
  7743. // 1 : RLE
  7744. // 2 : ZIPS (Single scanline)
  7745. // 3 : ZIP (16-line block)
  7746. // 4 : PIZ (32-line block)
  7747. if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
  7748. // if (err) {
  7749. // (*err) = "Unsupported compression type.";
  7750. //}
  7751. return -5;
  7752. }
  7753. } else if (attrName.compare("channels") == 0) {
  7754. // name: zero-terminated string, from 1 to 255 bytes long
  7755. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  7756. // pLinear: unsigned char, possible values are 0 and 1
  7757. // reserved: three chars, should be zero
  7758. // xSampling: int
  7759. // ySampling: int
  7760. ReadChannelInfo(channels, data);
  7761. numChannels = channels.size();
  7762. if (numChannels < 1) {
  7763. // if (err) {
  7764. // (*err) = "Invalid channels format.";
  7765. //}
  7766. return -6;
  7767. }
  7768. } else if (attrName.compare("dataWindow") == 0) {
  7769. memcpy(&dx, &data.at(0), sizeof(int));
  7770. memcpy(&dy, &data.at(4), sizeof(int));
  7771. memcpy(&dw, &data.at(8), sizeof(int));
  7772. memcpy(&dh, &data.at(12), sizeof(int));
  7773. if (IsBigEndian()) {
  7774. swap4(reinterpret_cast<unsigned int *>(&dx));
  7775. swap4(reinterpret_cast<unsigned int *>(&dy));
  7776. swap4(reinterpret_cast<unsigned int *>(&dw));
  7777. swap4(reinterpret_cast<unsigned int *>(&dh));
  7778. }
  7779. } else if (attrName.compare("displayWindow") == 0) {
  7780. memcpy(&displayWindow[0], &data.at(0), sizeof(int));
  7781. memcpy(&displayWindow[1], &data.at(4), sizeof(int));
  7782. memcpy(&displayWindow[2], &data.at(8), sizeof(int));
  7783. memcpy(&displayWindow[3], &data.at(12), sizeof(int));
  7784. if (IsBigEndian()) {
  7785. swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
  7786. swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
  7787. swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
  7788. swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
  7789. }
  7790. } else if (attrName.compare("lineOrder") == 0) {
  7791. memcpy(&lineOrder, &data.at(0), sizeof(float));
  7792. if (IsBigEndian()) {
  7793. swap4(reinterpret_cast<unsigned int *>(&lineOrder));
  7794. }
  7795. } else if (attrName.compare("pixelAspectRatio") == 0) {
  7796. memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
  7797. if (IsBigEndian()) {
  7798. swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
  7799. }
  7800. } else if (attrName.compare("screenWindowCenter") == 0) {
  7801. memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
  7802. memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
  7803. if (IsBigEndian()) {
  7804. swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
  7805. swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
  7806. }
  7807. } else if (attrName.compare("screenWindowWidth") == 0) {
  7808. memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
  7809. if (IsBigEndian()) {
  7810. swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
  7811. }
  7812. } else {
  7813. // Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
  7814. if (numCustomAttributes &&
  7815. ((*numCustomAttributes) < TINYEXR_MAX_ATTRIBUTES)) {
  7816. EXRAttribute attrib;
  7817. attrib.name = strdup(attrName.c_str());
  7818. attrib.type = strdup(attrType.c_str());
  7819. attrib.size = data.size();
  7820. attrib.value = (unsigned char *)malloc(data.size());
  7821. memcpy((char *)attrib.value, &data.at(0), data.size());
  7822. attribs.push_back(attrib);
  7823. }
  7824. }
  7825. marker = marker_next;
  7826. }
  7827. assert(dx >= 0);
  7828. assert(dy >= 0);
  7829. assert(dw >= 0);
  7830. assert(dh >= 0);
  7831. assert(numChannels >= 1);
  7832. int dataWidth = dw - dx + 1;
  7833. int dataHeight = dh - dy + 1;
  7834. (*width) = dataWidth;
  7835. (*height) = dataHeight;
  7836. if (numCustomAttributes) {
  7837. assert(attribs.size() < TINYEXR_MAX_ATTRIBUTES);
  7838. (*numCustomAttributes) = attribs.size();
  7839. // Assume the pointer to customAttributes has enough memory to store.
  7840. for (int i = 0; i < (int)attribs.size(); i++) {
  7841. customAttributes[i] = attribs[i];
  7842. }
  7843. }
  7844. return 0;
  7845. }
  7846. int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
  7847. const char **err) {
  7848. if (out_rgba == NULL || memory == NULL) {
  7849. if (err) {
  7850. (*err) = "Invalid argument.\n";
  7851. }
  7852. return -1;
  7853. }
  7854. EXRImage exrImage;
  7855. InitEXRImage(&exrImage);
  7856. int ret = LoadMultiChannelEXRFromMemory(&exrImage, memory, err);
  7857. if (ret != 0) {
  7858. return ret;
  7859. }
  7860. // RGBA
  7861. int idxR = -1;
  7862. int idxG = -1;
  7863. int idxB = -1;
  7864. int idxA = -1;
  7865. for (int c = 0; c < exrImage.num_channels; c++) {
  7866. if (strcmp(exrImage.channel_names[c], "R") == 0) {
  7867. idxR = c;
  7868. } else if (strcmp(exrImage.channel_names[c], "G") == 0) {
  7869. idxG = c;
  7870. } else if (strcmp(exrImage.channel_names[c], "B") == 0) {
  7871. idxB = c;
  7872. } else if (strcmp(exrImage.channel_names[c], "A") == 0) {
  7873. idxA = c;
  7874. }
  7875. }
  7876. if (idxR == -1) {
  7877. if (err) {
  7878. (*err) = "R channel not found\n";
  7879. }
  7880. // @todo { free exrImage }
  7881. return -1;
  7882. }
  7883. if (idxG == -1) {
  7884. if (err) {
  7885. (*err) = "G channel not found\n";
  7886. }
  7887. // @todo { free exrImage }
  7888. return -1;
  7889. }
  7890. if (idxB == -1) {
  7891. if (err) {
  7892. (*err) = "B channel not found\n";
  7893. }
  7894. // @todo { free exrImage }
  7895. return -1;
  7896. }
  7897. // Assume `out_rgba` have enough memory allocated.
  7898. for (int i = 0; i < exrImage.width * exrImage.height; i++) {
  7899. out_rgba[4 * i + 0] = reinterpret_cast<float **>(exrImage.images)[idxR][i];
  7900. out_rgba[4 * i + 1] = reinterpret_cast<float **>(exrImage.images)[idxG][i];
  7901. out_rgba[4 * i + 2] = reinterpret_cast<float **>(exrImage.images)[idxB][i];
  7902. if (idxA > 0) {
  7903. out_rgba[4 * i + 3] =
  7904. reinterpret_cast<float **>(exrImage.images)[idxA][i];
  7905. } else {
  7906. out_rgba[4 * i + 3] = 1.0;
  7907. }
  7908. }
  7909. return 0;
  7910. }
  7911. int LoadMultiChannelEXRFromFile(EXRImage *exrImage, const char *filename,
  7912. const char **err) {
  7913. if (exrImage == NULL) {
  7914. if (err) {
  7915. (*err) = "Invalid argument.";
  7916. }
  7917. return -1;
  7918. }
  7919. FILE *fp = fopen(filename, "rb");
  7920. if (!fp) {
  7921. if (err) {
  7922. (*err) = "Cannot read file.";
  7923. }
  7924. return -1;
  7925. }
  7926. size_t filesize;
  7927. // Compute size
  7928. fseek(fp, 0, SEEK_END);
  7929. filesize = ftell(fp);
  7930. fseek(fp, 0, SEEK_SET);
  7931. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  7932. {
  7933. size_t ret;
  7934. ret = fread(&buf[0], 1, filesize, fp);
  7935. assert(ret == filesize);
  7936. fclose(fp);
  7937. (void)ret;
  7938. }
  7939. return LoadMultiChannelEXRFromMemory(exrImage, &buf.at(0), err);
  7940. }
  7941. int LoadMultiChannelEXRFromMemory(EXRImage *exrImage,
  7942. const unsigned char *memory,
  7943. const char **err) {
  7944. if (exrImage == NULL || memory == NULL) {
  7945. if (err) {
  7946. (*err) = "Invalid argument.";
  7947. }
  7948. return -1;
  7949. }
  7950. const char *buf = reinterpret_cast<const char *>(memory);
  7951. const char *head = &buf[0];
  7952. const char *marker = &buf[0];
  7953. // Header check.
  7954. {
  7955. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  7956. if (memcmp(marker, header, 4) != 0) {
  7957. if (err) {
  7958. (*err) = "Header mismatch.";
  7959. }
  7960. return -3;
  7961. }
  7962. marker += 4;
  7963. }
  7964. // Version, scanline.
  7965. {
  7966. // must be [2, 0, 0, 0]
  7967. if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
  7968. if (err) {
  7969. (*err) = "Unsupported version or scanline.";
  7970. }
  7971. return -4;
  7972. }
  7973. marker += 4;
  7974. }
  7975. int dx = -1;
  7976. int dy = -1;
  7977. int dw = -1;
  7978. int dh = -1;
  7979. int numScanlineBlocks = 1; // 16 for ZIP compression.
  7980. int compressionType = -1;
  7981. int numChannels = -1;
  7982. unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
  7983. std::vector<ChannelInfo> channels;
  7984. // Read attributes
  7985. for (;;) {
  7986. std::string attrName;
  7987. std::string attrType;
  7988. std::vector<unsigned char> data;
  7989. const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
  7990. if (marker_next == NULL) {
  7991. marker++; // skip '\0'
  7992. break;
  7993. }
  7994. if (attrName.compare("compression") == 0) {
  7995. // mwkm
  7996. // 0 : NO_COMPRESSION
  7997. // 1 : RLE
  7998. // 2 : ZIPS (Single scanline)
  7999. // 3 : ZIP (16-line block)
  8000. // 4 : PIZ (32-line block)
  8001. if (data[0] != TINYEXR_COMPRESSIONTYPE_NONE &&
  8002. data[0] != TINYEXR_COMPRESSIONTYPE_ZIPS &&
  8003. data[0] != TINYEXR_COMPRESSIONTYPE_ZIP &&
  8004. data[0] != TINYEXR_COMPRESSIONTYPE_PIZ) {
  8005. if (err) {
  8006. (*err) = "Unsupported compression type.";
  8007. }
  8008. return -5;
  8009. }
  8010. compressionType = data[0];
  8011. if (compressionType == TINYEXR_COMPRESSIONTYPE_ZIP) {
  8012. numScanlineBlocks = 16;
  8013. } else if (compressionType == TINYEXR_COMPRESSIONTYPE_PIZ) {
  8014. numScanlineBlocks = 32;
  8015. }
  8016. } else if (attrName.compare("channels") == 0) {
  8017. // name: zero-terminated string, from 1 to 255 bytes long
  8018. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  8019. // pLinear: unsigned char, possible values are 0 and 1
  8020. // reserved: three chars, should be zero
  8021. // xSampling: int
  8022. // ySampling: int
  8023. ReadChannelInfo(channels, data);
  8024. numChannels = channels.size();
  8025. if (numChannels < 1) {
  8026. if (err) {
  8027. (*err) = "Invalid channels format.";
  8028. }
  8029. return -6;
  8030. }
  8031. } else if (attrName.compare("dataWindow") == 0) {
  8032. memcpy(&dx, &data.at(0), sizeof(int));
  8033. memcpy(&dy, &data.at(4), sizeof(int));
  8034. memcpy(&dw, &data.at(8), sizeof(int));
  8035. memcpy(&dh, &data.at(12), sizeof(int));
  8036. if (IsBigEndian()) {
  8037. swap4(reinterpret_cast<unsigned int *>(&dx));
  8038. swap4(reinterpret_cast<unsigned int *>(&dy));
  8039. swap4(reinterpret_cast<unsigned int *>(&dw));
  8040. swap4(reinterpret_cast<unsigned int *>(&dh));
  8041. }
  8042. } else if (attrName.compare("displayWindow") == 0) {
  8043. int x, y, w, h;
  8044. memcpy(&x, &data.at(0), sizeof(int));
  8045. memcpy(&y, &data.at(4), sizeof(int));
  8046. memcpy(&w, &data.at(8), sizeof(int));
  8047. memcpy(&h, &data.at(12), sizeof(int));
  8048. if (IsBigEndian()) {
  8049. swap4(reinterpret_cast<unsigned int *>(&x));
  8050. swap4(reinterpret_cast<unsigned int *>(&y));
  8051. swap4(reinterpret_cast<unsigned int *>(&w));
  8052. swap4(reinterpret_cast<unsigned int *>(&h));
  8053. }
  8054. } else if (attrName.compare("lineOrder") == 0) {
  8055. memcpy(&lineOrder, &data.at(0), sizeof(lineOrder));
  8056. }
  8057. marker = marker_next;
  8058. }
  8059. assert(dx >= 0);
  8060. assert(dy >= 0);
  8061. assert(dw >= 0);
  8062. assert(dh >= 0);
  8063. assert(numChannels >= 1);
  8064. int dataWidth = dw - dx + 1;
  8065. int dataHeight = dh - dy + 1;
  8066. // Read offset tables.
  8067. int numBlocks = dataHeight / numScanlineBlocks;
  8068. if (numBlocks * numScanlineBlocks < dataHeight) {
  8069. numBlocks++;
  8070. }
  8071. std::vector<long long> offsets(numBlocks);
  8072. for (int y = 0; y < numBlocks; y++) {
  8073. long long offset;
  8074. memcpy(&offset, marker, sizeof(long long));
  8075. if (IsBigEndian()) {
  8076. swap8(reinterpret_cast<unsigned long long *>(&offset));
  8077. }
  8078. marker += sizeof(long long); // = 8
  8079. offsets[y] = offset;
  8080. }
  8081. exrImage->images = reinterpret_cast<unsigned char **>(
  8082. (float **)malloc(sizeof(float *) * numChannels));
  8083. std::vector<size_t> channelOffsetList(numChannels);
  8084. int pixelDataSize = 0;
  8085. size_t channelOffset = 0;
  8086. for (int c = 0; c < numChannels; c++) {
  8087. channelOffsetList[c] = channelOffset;
  8088. if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
  8089. pixelDataSize += sizeof(unsigned short);
  8090. channelOffset += sizeof(unsigned short);
  8091. // Alloc internal image for half type.
  8092. if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8093. exrImage->images[c] =
  8094. reinterpret_cast<unsigned char *>((unsigned short *)malloc(
  8095. sizeof(unsigned short) * dataWidth * dataHeight));
  8096. } else if (exrImage->requested_pixel_types[c] ==
  8097. TINYEXR_PIXELTYPE_FLOAT) {
  8098. exrImage->images[c] = reinterpret_cast<unsigned char *>(
  8099. (float *)malloc(sizeof(float) * dataWidth * dataHeight));
  8100. } else {
  8101. assert(0);
  8102. }
  8103. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
  8104. pixelDataSize += sizeof(float);
  8105. channelOffset += sizeof(float);
  8106. exrImage->images[c] = reinterpret_cast<unsigned char *>(
  8107. (float *)malloc(sizeof(float) * dataWidth * dataHeight));
  8108. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
  8109. pixelDataSize += sizeof(unsigned int);
  8110. channelOffset += sizeof(unsigned int);
  8111. exrImage->images[c] = reinterpret_cast<unsigned char *>((
  8112. unsigned int *)malloc(sizeof(unsigned int) * dataWidth * dataHeight));
  8113. } else {
  8114. assert(0);
  8115. }
  8116. }
  8117. #ifdef _OPENMP
  8118. #pragma omp parallel for
  8119. #endif
  8120. for (int y = 0; y < numBlocks; y++) {
  8121. const unsigned char *dataPtr =
  8122. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  8123. // 4 byte: scan line
  8124. // 4 byte: data size
  8125. // ~ : pixel data(uncompressed or compressed)
  8126. int lineNo;
  8127. memcpy(&lineNo, dataPtr, sizeof(int));
  8128. int dataLen;
  8129. memcpy(&dataLen, dataPtr + 4, sizeof(int));
  8130. if (IsBigEndian()) {
  8131. swap4(reinterpret_cast<unsigned int *>(&lineNo));
  8132. swap4(reinterpret_cast<unsigned int *>(&dataLen));
  8133. }
  8134. int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
  8135. int numLines = endLineNo - lineNo;
  8136. if (compressionType == 4) { // PIZ
  8137. // Allocate original data size.
  8138. std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
  8139. unsigned int dstLen;
  8140. size_t tmpBufLen = dataWidth * numLines * pixelDataSize;
  8141. DecompressPiz(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen,
  8142. dataPtr + 8, tmpBufLen, channels, dataWidth, numLines);
  8143. bool isBigEndian = IsBigEndian();
  8144. // For ZIP_COMPRESSION:
  8145. // pixel sample data for channel 0 for scanline 0
  8146. // pixel sample data for channel 1 for scanline 0
  8147. // pixel sample data for channel ... for scanline 0
  8148. // pixel sample data for channel n for scanline 0
  8149. // pixel sample data for channel 0 for scanline 1
  8150. // pixel sample data for channel 1 for scanline 1
  8151. // pixel sample data for channel ... for scanline 1
  8152. // pixel sample data for channel n for scanline 1
  8153. // ...
  8154. for (int c = 0; c < numChannels; c++) {
  8155. if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
  8156. for (int v = 0; v < numLines; v++) {
  8157. const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
  8158. &outBuf.at(v * pixelDataSize * dataWidth +
  8159. channelOffsetList[c] * dataWidth));
  8160. for (int u = 0; u < dataWidth; u++) {
  8161. FP16 hf;
  8162. hf.u = linePtr[u];
  8163. if (isBigEndian) {
  8164. swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8165. }
  8166. if (exrImage->requested_pixel_types[c] ==
  8167. TINYEXR_PIXELTYPE_HALF) {
  8168. unsigned short *image =
  8169. reinterpret_cast<unsigned short **>(exrImage->images)[c];
  8170. if (lineOrder == 0) {
  8171. image += (lineNo + v) * dataWidth + u;
  8172. } else {
  8173. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8174. }
  8175. *image = hf.u;
  8176. } else { // HALF -> FLOAT
  8177. FP32 f32 = half_to_float(hf);
  8178. float *image = reinterpret_cast<float **>(exrImage->images)[c];
  8179. if (lineOrder == 0) {
  8180. image += (lineNo + v) * dataWidth + u;
  8181. } else {
  8182. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8183. }
  8184. *image = f32.f;
  8185. }
  8186. }
  8187. }
  8188. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
  8189. assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8190. for (int v = 0; v < numLines; v++) {
  8191. const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
  8192. &outBuf.at(v * pixelDataSize * dataWidth +
  8193. channelOffsetList[c] * dataWidth));
  8194. for (int u = 0; u < dataWidth; u++) {
  8195. unsigned int val = linePtr[u];
  8196. if (isBigEndian) {
  8197. swap4(&val);
  8198. }
  8199. unsigned int *image =
  8200. reinterpret_cast<unsigned int **>(exrImage->images)[c];
  8201. if (lineOrder == 0) {
  8202. image += (lineNo + v) * dataWidth + u;
  8203. } else {
  8204. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8205. }
  8206. *image = val;
  8207. }
  8208. }
  8209. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
  8210. assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8211. for (int v = 0; v < numLines; v++) {
  8212. const float *linePtr = reinterpret_cast<float *>(
  8213. &outBuf.at(v * pixelDataSize * dataWidth +
  8214. channelOffsetList[c] * dataWidth));
  8215. for (int u = 0; u < dataWidth; u++) {
  8216. float val = linePtr[u];
  8217. if (isBigEndian) {
  8218. swap4(reinterpret_cast<unsigned int *>(&val));
  8219. }
  8220. float *image = reinterpret_cast<float **>(exrImage->images)[c];
  8221. if (lineOrder == 0) {
  8222. image += (lineNo + v) * dataWidth + u;
  8223. } else {
  8224. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8225. }
  8226. *image = val;
  8227. }
  8228. }
  8229. } else {
  8230. assert(0);
  8231. }
  8232. }
  8233. // mwkm, ZIPS or ZIP both good to go
  8234. } else if (compressionType == 2 || compressionType == 3) { // ZIP
  8235. // Allocate original data size.
  8236. std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
  8237. unsigned long dstLen = outBuf.size();
  8238. DecompressZip(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen,
  8239. dataPtr + 8, dataLen);
  8240. bool isBigEndian = IsBigEndian();
  8241. // For ZIP_COMPRESSION:
  8242. // pixel sample data for channel 0 for scanline 0
  8243. // pixel sample data for channel 1 for scanline 0
  8244. // pixel sample data for channel ... for scanline 0
  8245. // pixel sample data for channel n for scanline 0
  8246. // pixel sample data for channel 0 for scanline 1
  8247. // pixel sample data for channel 1 for scanline 1
  8248. // pixel sample data for channel ... for scanline 1
  8249. // pixel sample data for channel n for scanline 1
  8250. // ...
  8251. for (int c = 0; c < numChannels; c++) {
  8252. if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
  8253. for (int v = 0; v < numLines; v++) {
  8254. const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
  8255. &outBuf.at(v * pixelDataSize * dataWidth +
  8256. channelOffsetList[c] * dataWidth));
  8257. for (int u = 0; u < dataWidth; u++) {
  8258. FP16 hf;
  8259. hf.u = linePtr[u];
  8260. if (isBigEndian) {
  8261. swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8262. }
  8263. if (exrImage->requested_pixel_types[c] ==
  8264. TINYEXR_PIXELTYPE_HALF) {
  8265. unsigned short *image =
  8266. reinterpret_cast<unsigned short **>(exrImage->images)[c];
  8267. if (lineOrder == 0) {
  8268. image += (lineNo + v) * dataWidth + u;
  8269. } else {
  8270. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8271. }
  8272. *image = hf.u;
  8273. } else { // HALF -> FLOAT
  8274. FP32 f32 = half_to_float(hf);
  8275. float *image = reinterpret_cast<float **>(exrImage->images)[c];
  8276. if (lineOrder == 0) {
  8277. image += (lineNo + v) * dataWidth + u;
  8278. } else {
  8279. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8280. }
  8281. *image = f32.f;
  8282. }
  8283. }
  8284. }
  8285. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
  8286. assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8287. for (int v = 0; v < numLines; v++) {
  8288. const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
  8289. &outBuf.at(v * pixelDataSize * dataWidth +
  8290. channelOffsetList[c] * dataWidth));
  8291. for (int u = 0; u < dataWidth; u++) {
  8292. unsigned int val = linePtr[u];
  8293. if (isBigEndian) {
  8294. swap4(&val);
  8295. }
  8296. unsigned int *image =
  8297. reinterpret_cast<unsigned int **>(exrImage->images)[c];
  8298. if (lineOrder == 0) {
  8299. image += (lineNo + v) * dataWidth + u;
  8300. } else {
  8301. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8302. }
  8303. *image = val;
  8304. }
  8305. }
  8306. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
  8307. assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8308. for (int v = 0; v < numLines; v++) {
  8309. const float *linePtr = reinterpret_cast<float *>(
  8310. &outBuf.at(v * pixelDataSize * dataWidth +
  8311. channelOffsetList[c] * dataWidth));
  8312. for (int u = 0; u < dataWidth; u++) {
  8313. float val = linePtr[u];
  8314. if (isBigEndian) {
  8315. swap4(reinterpret_cast<unsigned int *>(&val));
  8316. }
  8317. float *image = reinterpret_cast<float **>(exrImage->images)[c];
  8318. if (lineOrder == 0) {
  8319. image += (lineNo + v) * dataWidth + u;
  8320. } else {
  8321. image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
  8322. }
  8323. *image = val;
  8324. }
  8325. }
  8326. } else {
  8327. assert(0);
  8328. }
  8329. }
  8330. } else if (compressionType == 0) { // No compression
  8331. bool isBigEndian = IsBigEndian();
  8332. for (int c = 0; c < numChannels; c++) {
  8333. if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
  8334. const unsigned short *linePtr =
  8335. reinterpret_cast<const unsigned short *>(
  8336. dataPtr + 8 + c * dataWidth * sizeof(unsigned short));
  8337. if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8338. unsigned short *outLine =
  8339. reinterpret_cast<unsigned short *>(exrImage->images[c]);
  8340. if (lineOrder == 0) {
  8341. outLine += y * dataWidth;
  8342. } else {
  8343. outLine += (dataHeight - 1 - y) * dataWidth;
  8344. }
  8345. for (int u = 0; u < dataWidth; u++) {
  8346. FP16 hf;
  8347. hf.u = linePtr[u];
  8348. if (isBigEndian) {
  8349. swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8350. }
  8351. outLine[u] = hf.u;
  8352. }
  8353. } else if (exrImage->requested_pixel_types[c] ==
  8354. TINYEXR_PIXELTYPE_FLOAT) {
  8355. float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
  8356. if (lineOrder == 0) {
  8357. outLine += y * dataWidth;
  8358. } else {
  8359. outLine += (dataHeight - 1 - y) * dataWidth;
  8360. }
  8361. for (int u = 0; u < dataWidth; u++) {
  8362. FP16 hf;
  8363. hf.u = linePtr[u];
  8364. if (isBigEndian) {
  8365. swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8366. }
  8367. FP32 f32 = half_to_float(hf);
  8368. outLine[u] = f32.f;
  8369. }
  8370. } else {
  8371. assert(0);
  8372. }
  8373. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
  8374. const float *linePtr = reinterpret_cast<const float *>(
  8375. dataPtr + 8 + c * dataWidth * sizeof(float));
  8376. float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
  8377. if (lineOrder == 0) {
  8378. outLine += y * dataWidth;
  8379. } else {
  8380. outLine += (dataHeight - 1 - y) * dataWidth;
  8381. }
  8382. for (int u = 0; u < dataWidth; u++) {
  8383. float val = linePtr[u];
  8384. if (isBigEndian) {
  8385. swap4(reinterpret_cast<unsigned int *>(&val));
  8386. }
  8387. outLine[u] = val;
  8388. }
  8389. } else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
  8390. const unsigned int *linePtr = reinterpret_cast<const unsigned int *>(
  8391. dataPtr + 8 + c * dataWidth * sizeof(unsigned int));
  8392. unsigned int *outLine =
  8393. reinterpret_cast<unsigned int *>(exrImage->images[c]);
  8394. if (lineOrder == 0) {
  8395. outLine += y * dataWidth;
  8396. } else {
  8397. outLine += (dataHeight - 1 - y) * dataWidth;
  8398. }
  8399. for (int u = 0; u < dataWidth; u++) {
  8400. unsigned int val = linePtr[u];
  8401. if (isBigEndian) {
  8402. swap4(reinterpret_cast<unsigned int *>(&val));
  8403. }
  8404. outLine[u] = val;
  8405. }
  8406. }
  8407. }
  8408. }
  8409. } // omp parallel
  8410. {
  8411. exrImage->channel_names =
  8412. (const char **)malloc(sizeof(const char *) * numChannels);
  8413. for (int c = 0; c < numChannels; c++) {
  8414. #ifdef _WIN32
  8415. exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
  8416. #else
  8417. exrImage->channel_names[c] = strdup(channels[c].name.c_str());
  8418. #endif
  8419. }
  8420. exrImage->num_channels = numChannels;
  8421. exrImage->width = dataWidth;
  8422. exrImage->height = dataHeight;
  8423. // Fill with requested_pixel_types.
  8424. exrImage->pixel_types = (int *)malloc(sizeof(int *) * numChannels);
  8425. for (int c = 0; c < numChannels; c++) {
  8426. exrImage->pixel_types[c] = exrImage->requested_pixel_types[c];
  8427. }
  8428. }
  8429. return 0; // OK
  8430. }
  8431. // @deprecated
  8432. #if 0
  8433. int SaveEXR(const float *in_rgba, int width, int height, const char *filename,
  8434. const char **err) {
  8435. if (in_rgba == NULL || filename == NULL) {
  8436. if (err) {
  8437. (*err) = "Invalid argument.";
  8438. }
  8439. return -1;
  8440. }
  8441. FILE *fp = fopen(filename, "wb");
  8442. if (!fp) {
  8443. if (err) {
  8444. (*err) = "Cannot write a file.";
  8445. }
  8446. return -1;
  8447. }
  8448. // Header
  8449. {
  8450. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  8451. size_t n = fwrite(header, 1, 4, fp);
  8452. assert(n == 4);
  8453. }
  8454. // Version, scanline.
  8455. {
  8456. const char marker[] = {2, 0, 0, 0};
  8457. size_t n = fwrite(marker, 1, 4, fp);
  8458. assert(n == 4);
  8459. }
  8460. int numScanlineBlocks = 16; // 16 for ZIP compression.
  8461. // Write attributes.
  8462. {
  8463. unsigned char data[] = {
  8464. 'A', 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'B',
  8465. 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'G', 0,
  8466. 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'R', 0, 1,
  8467. 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}; // last 0 =
  8468. // terminator.
  8469. WriteAttribute(fp, "channels", "chlist", data, 18 * 4 + 1); // +1 = null
  8470. }
  8471. {
  8472. int compressionType = 3; // ZIP compression
  8473. WriteAttribute(fp, "compression", "compression",
  8474. reinterpret_cast<const unsigned char *>(&compressionType),
  8475. 1);
  8476. }
  8477. {
  8478. int data[4] = {0, 0, width - 1, height - 1};
  8479. WriteAttribute(fp, "dataWindow", "box2i",
  8480. reinterpret_cast<const unsigned char *>(data),
  8481. sizeof(int) * 4);
  8482. WriteAttribute(fp, "displayWindow", "box2i",
  8483. reinterpret_cast<const unsigned char *>(data),
  8484. sizeof(int) * 4);
  8485. }
  8486. {
  8487. unsigned char lineOrder = 0; // increasingY
  8488. WriteAttribute(fp, "lineOrder", "lineOrder", &lineOrder, 1);
  8489. }
  8490. {
  8491. float aspectRatio = 1.0f;
  8492. WriteAttribute(fp, "pixelAspectRatio", "float",
  8493. reinterpret_cast<const unsigned char *>(&aspectRatio),
  8494. sizeof(float));
  8495. }
  8496. {
  8497. float center[2] = {0.0f, 0.0f};
  8498. WriteAttribute(fp, "screenWindowCenter", "v2f",
  8499. reinterpret_cast<const unsigned char *>(center),
  8500. 2 * sizeof(float));
  8501. }
  8502. {
  8503. float w = (float)width;
  8504. WriteAttribute(fp, "screenWindowWidth", "float",
  8505. reinterpret_cast<const unsigned char *>(&w), sizeof(float));
  8506. }
  8507. { // end of header
  8508. unsigned char e = 0;
  8509. fwrite(&e, 1, 1, fp);
  8510. }
  8511. int numBlocks = height / numScanlineBlocks;
  8512. if (numBlocks * numScanlineBlocks < height) {
  8513. numBlocks++;
  8514. }
  8515. std::vector<long long> offsets(numBlocks);
  8516. size_t headerSize = ftell(fp); // sizeof(header)
  8517. long long offset =
  8518. headerSize +
  8519. numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
  8520. std::vector<unsigned char> data;
  8521. for (int i = 0; i < numBlocks; i++) {
  8522. int startY = numScanlineBlocks * i;
  8523. int endY = (std::min)(numScanlineBlocks * (i + 1), height);
  8524. int h = endY - startY;
  8525. std::vector<unsigned short> buf(4 * width * h);
  8526. for (int y = 0; y < h; y++) {
  8527. for (int x = 0; x < width; x++) {
  8528. FP32 r, g, b, a;
  8529. r.f = in_rgba[4 * ((y + startY) * width + x) + 0];
  8530. g.f = in_rgba[4 * ((y + startY) * width + x) + 1];
  8531. b.f = in_rgba[4 * ((y + startY) * width + x) + 2];
  8532. a.f = in_rgba[4 * ((y + startY) * width + x) + 3];
  8533. FP16 hr, hg, hb, ha;
  8534. hr = float_to_half_full(r);
  8535. hg = float_to_half_full(g);
  8536. hb = float_to_half_full(b);
  8537. ha = float_to_half_full(a);
  8538. // Assume increasing Y
  8539. buf[4 * y * width + 3 * width + x] = hr.u;
  8540. buf[4 * y * width + 2 * width + x] = hg.u;
  8541. buf[4 * y * width + 1 * width + x] = hb.u;
  8542. buf[4 * y * width + 0 * width + x] = ha.u;
  8543. }
  8544. }
  8545. int bound = miniz::mz_compressBound(buf.size() * sizeof(unsigned short));
  8546. std::vector<unsigned char> block(
  8547. miniz::mz_compressBound(buf.size() * sizeof(unsigned short)));
  8548. unsigned long long outSize = block.size();
  8549. CompressZip(&block.at(0), outSize,
  8550. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  8551. buf.size() * sizeof(unsigned short));
  8552. // 4 byte: scan line
  8553. // 4 byte: data size
  8554. // ~ : pixel data(compressed)
  8555. std::vector<unsigned char> header(8);
  8556. unsigned int dataLen = outSize; // truncate
  8557. memcpy(&header.at(0), &startY, sizeof(int));
  8558. memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
  8559. data.insert(data.end(), header.begin(), header.end());
  8560. data.insert(data.end(), block.begin(), block.begin() + dataLen);
  8561. offsets[i] = offset;
  8562. offset += dataLen + 8; // 8 = sizeof(blockHeader)
  8563. }
  8564. fwrite(&offsets.at(0), 1, sizeof(unsigned long long) * numBlocks, fp);
  8565. fwrite(&data.at(0), 1, data.size(), fp);
  8566. fclose(fp);
  8567. return 0; // OK
  8568. }
  8569. #endif
  8570. size_t SaveMultiChannelEXRToMemory(const EXRImage *exrImage,
  8571. unsigned char **memory_out,
  8572. const char **err) {
  8573. if (exrImage == NULL || memory_out == NULL || exrImage->compression < 0 ||
  8574. exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
  8575. if (err) {
  8576. (*err) = "Invalid argument.";
  8577. }
  8578. return 0;
  8579. }
  8580. std::vector<unsigned char> memory;
  8581. // Header
  8582. {
  8583. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  8584. memory.insert(memory.end(), header, header + 4);
  8585. }
  8586. // Version, scanline.
  8587. {
  8588. const char marker[] = {2, 0, 0, 0};
  8589. memory.insert(memory.end(), marker, marker + 4);
  8590. }
  8591. int numScanlineBlocks = 1;
  8592. if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP) {
  8593. numScanlineBlocks = 16;
  8594. } else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
  8595. numScanlineBlocks = 32;
  8596. }
  8597. // Write attributes.
  8598. {
  8599. std::vector<unsigned char> data;
  8600. std::vector<ChannelInfo> channels;
  8601. for (int c = 0; c < exrImage->num_channels; c++) {
  8602. ChannelInfo info;
  8603. info.pLinear = 0;
  8604. info.pixelType = exrImage->requested_pixel_types[c];
  8605. info.xSampling = 1;
  8606. info.ySampling = 1;
  8607. info.name = std::string(exrImage->channel_names[c]);
  8608. channels.push_back(info);
  8609. }
  8610. WriteChannelInfo(data, channels);
  8611. WriteAttributeToMemory(memory, "channels", "chlist", &data.at(0),
  8612. data.size()); // +1 = null
  8613. }
  8614. {
  8615. int comp = exrImage->compression;
  8616. if (IsBigEndian()) {
  8617. swap4(reinterpret_cast<unsigned int *>(&comp));
  8618. }
  8619. WriteAttributeToMemory(memory, "compression", "compression",
  8620. reinterpret_cast<const unsigned char *>(&comp), 1);
  8621. }
  8622. {
  8623. int data[4] = {0, 0, exrImage->width - 1, exrImage->height - 1};
  8624. if (IsBigEndian()) {
  8625. swap4(reinterpret_cast<unsigned int *>(&data[0]));
  8626. swap4(reinterpret_cast<unsigned int *>(&data[1]));
  8627. swap4(reinterpret_cast<unsigned int *>(&data[2]));
  8628. swap4(reinterpret_cast<unsigned int *>(&data[3]));
  8629. }
  8630. WriteAttributeToMemory(memory, "dataWindow", "box2i",
  8631. reinterpret_cast<const unsigned char *>(data),
  8632. sizeof(int) * 4);
  8633. WriteAttributeToMemory(memory, "displayWindow", "box2i",
  8634. reinterpret_cast<const unsigned char *>(data),
  8635. sizeof(int) * 4);
  8636. }
  8637. {
  8638. unsigned char lineOrder = 0; // increasingY
  8639. WriteAttributeToMemory(memory, "lineOrder", "lineOrder", &lineOrder, 1);
  8640. }
  8641. {
  8642. float aspectRatio = 1.0f;
  8643. if (IsBigEndian()) {
  8644. swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
  8645. }
  8646. WriteAttributeToMemory(
  8647. memory, "pixelAspectRatio", "float",
  8648. reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
  8649. }
  8650. {
  8651. float center[2] = {0.0f, 0.0f};
  8652. if (IsBigEndian()) {
  8653. swap4(reinterpret_cast<unsigned int *>(&center[0]));
  8654. swap4(reinterpret_cast<unsigned int *>(&center[1]));
  8655. }
  8656. WriteAttributeToMemory(memory, "screenWindowCenter", "v2f",
  8657. reinterpret_cast<const unsigned char *>(center),
  8658. 2 * sizeof(float));
  8659. }
  8660. {
  8661. float w = (float)exrImage->width;
  8662. if (IsBigEndian()) {
  8663. swap4(reinterpret_cast<unsigned int *>(&w));
  8664. }
  8665. WriteAttributeToMemory(memory, "screenWindowWidth", "float",
  8666. reinterpret_cast<const unsigned char *>(&w),
  8667. sizeof(float));
  8668. }
  8669. // Custom attributes
  8670. if (exrImage->num_custom_attributes > 0) {
  8671. // @todo { endian }
  8672. for (int i = 0; i < exrImage->num_custom_attributes; i++) {
  8673. WriteAttributeToMemory(memory, exrImage->custom_attributes[i].name,
  8674. exrImage->custom_attributes[i].type,
  8675. reinterpret_cast<const unsigned char *>(
  8676. &exrImage->custom_attributes[i].value),
  8677. exrImage->custom_attributes[i].size);
  8678. }
  8679. }
  8680. { // end of header
  8681. unsigned char e = 0;
  8682. memory.push_back(e);
  8683. }
  8684. int numBlocks = exrImage->height / numScanlineBlocks;
  8685. if (numBlocks * numScanlineBlocks < exrImage->height) {
  8686. numBlocks++;
  8687. }
  8688. std::vector<long long> offsets(numBlocks);
  8689. size_t headerSize = memory.size();
  8690. long long offset =
  8691. headerSize +
  8692. numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
  8693. std::vector<unsigned char> data;
  8694. bool isBigEndian = IsBigEndian();
  8695. std::vector<std::vector<unsigned char> > dataList(numBlocks);
  8696. std::vector<size_t> channelOffsetList(exrImage->num_channels);
  8697. int pixelDataSize = 0;
  8698. size_t channelOffset = 0;
  8699. for (int c = 0; c < exrImage->num_channels; c++) {
  8700. channelOffsetList[c] = channelOffset;
  8701. if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8702. pixelDataSize += sizeof(unsigned short);
  8703. channelOffset += sizeof(unsigned short);
  8704. } else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8705. pixelDataSize += sizeof(float);
  8706. channelOffset += sizeof(float);
  8707. } else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  8708. pixelDataSize += sizeof(unsigned int);
  8709. channelOffset += sizeof(unsigned int);
  8710. } else {
  8711. assert(0);
  8712. }
  8713. }
  8714. #ifdef _OPENMP
  8715. #pragma omp parallel for
  8716. #endif
  8717. for (int i = 0; i < numBlocks; i++) {
  8718. int startY = numScanlineBlocks * i;
  8719. int endY = (std::min)(numScanlineBlocks * (i + 1), exrImage->height);
  8720. int h = endY - startY;
  8721. std::vector<unsigned char> buf(exrImage->width * h * pixelDataSize);
  8722. for (int c = 0; c < exrImage->num_channels; c++) {
  8723. if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8724. if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8725. for (int y = 0; y < h; y++) {
  8726. for (int x = 0; x < exrImage->width; x++) {
  8727. FP16 h16;
  8728. h16.u = reinterpret_cast<unsigned short **>(
  8729. exrImage->images)[c][(y + startY) * exrImage->width + x];
  8730. FP32 f32 = half_to_float(h16);
  8731. if (isBigEndian) {
  8732. swap4(reinterpret_cast<unsigned int *>(&f32.f));
  8733. }
  8734. // Assume increasing Y
  8735. float *linePtr = reinterpret_cast<float *>(
  8736. &buf.at(pixelDataSize * y * exrImage->width +
  8737. channelOffsetList[c] * exrImage->width));
  8738. linePtr[x] = f32.f;
  8739. }
  8740. }
  8741. } else if (exrImage->requested_pixel_types[c] ==
  8742. TINYEXR_PIXELTYPE_HALF) {
  8743. for (int y = 0; y < h; y++) {
  8744. for (int x = 0; x < exrImage->width; x++) {
  8745. unsigned short val = reinterpret_cast<unsigned short **>(
  8746. exrImage->images)[c][(y + startY) * exrImage->width + x];
  8747. if (isBigEndian) {
  8748. swap2(&val);
  8749. }
  8750. // Assume increasing Y
  8751. unsigned short *linePtr = reinterpret_cast<unsigned short *>(
  8752. &buf.at(pixelDataSize * y * exrImage->width +
  8753. channelOffsetList[c] * exrImage->width));
  8754. linePtr[x] = val;
  8755. }
  8756. }
  8757. } else {
  8758. assert(0);
  8759. }
  8760. } else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8761. if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8762. for (int y = 0; y < h; y++) {
  8763. for (int x = 0; x < exrImage->width; x++) {
  8764. FP32 f32;
  8765. f32.f = reinterpret_cast<float **>(
  8766. exrImage->images)[c][(y + startY) * exrImage->width + x];
  8767. FP16 h16;
  8768. h16 = float_to_half_full(f32);
  8769. if (isBigEndian) {
  8770. swap2(reinterpret_cast<unsigned short *>(&h16.u));
  8771. }
  8772. // Assume increasing Y
  8773. unsigned short *linePtr = reinterpret_cast<unsigned short *>(
  8774. &buf.at(pixelDataSize * y * exrImage->width +
  8775. channelOffsetList[c] * exrImage->width));
  8776. linePtr[x] = h16.u;
  8777. }
  8778. }
  8779. } else if (exrImage->requested_pixel_types[c] ==
  8780. TINYEXR_PIXELTYPE_FLOAT) {
  8781. for (int y = 0; y < h; y++) {
  8782. for (int x = 0; x < exrImage->width; x++) {
  8783. float val = reinterpret_cast<float **>(
  8784. exrImage->images)[c][(y + startY) * exrImage->width + x];
  8785. if (isBigEndian) {
  8786. swap4(reinterpret_cast<unsigned int *>(&val));
  8787. }
  8788. // Assume increasing Y
  8789. float *linePtr = reinterpret_cast<float *>(
  8790. &buf.at(pixelDataSize * y * exrImage->width +
  8791. channelOffsetList[c] * exrImage->width));
  8792. linePtr[x] = val;
  8793. }
  8794. }
  8795. } else {
  8796. assert(0);
  8797. }
  8798. } else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  8799. for (int y = 0; y < h; y++) {
  8800. for (int x = 0; x < exrImage->width; x++) {
  8801. unsigned int val = reinterpret_cast<unsigned int **>(
  8802. exrImage->images)[c][(y + startY) * exrImage->width + x];
  8803. if (isBigEndian) {
  8804. swap4(&val);
  8805. }
  8806. // Assume increasing Y
  8807. unsigned int *linePtr = reinterpret_cast<unsigned int *>(
  8808. &buf.at(pixelDataSize * y * exrImage->width +
  8809. channelOffsetList[c] * exrImage->width));
  8810. linePtr[x] = val;
  8811. }
  8812. }
  8813. }
  8814. }
  8815. if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_NONE) {
  8816. // 4 byte: scan line
  8817. // 4 byte: data size
  8818. // ~ : pixel data(uncompressed)
  8819. std::vector<unsigned char> header(8);
  8820. unsigned int dataLen = (unsigned int)buf.size();
  8821. memcpy(&header.at(0), &startY, sizeof(int));
  8822. memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
  8823. if (IsBigEndian()) {
  8824. swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  8825. swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  8826. }
  8827. dataList[i].insert(dataList[i].end(), header.begin(), header.end());
  8828. dataList[i].insert(dataList[i].end(), buf.begin(), buf.begin() + dataLen);
  8829. } else if ((exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  8830. (exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  8831. std::vector<unsigned char> block(miniz::mz_compressBound(buf.size()));
  8832. unsigned long long outSize = block.size();
  8833. CompressZip(&block.at(0), outSize,
  8834. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  8835. buf.size());
  8836. // 4 byte: scan line
  8837. // 4 byte: data size
  8838. // ~ : pixel data(compressed)
  8839. std::vector<unsigned char> header(8);
  8840. unsigned int dataLen = outSize; // truncate
  8841. memcpy(&header.at(0), &startY, sizeof(int));
  8842. memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
  8843. if (IsBigEndian()) {
  8844. swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  8845. swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  8846. }
  8847. dataList[i].insert(dataList[i].end(), header.begin(), header.end());
  8848. dataList[i].insert(dataList[i].end(), block.begin(),
  8849. block.begin() + dataLen);
  8850. } else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
  8851. // @todo
  8852. assert(0);
  8853. } else {
  8854. assert(0);
  8855. }
  8856. } // omp parallel
  8857. for (int i = 0; i < numBlocks; i++) {
  8858. data.insert(data.end(), dataList[i].begin(), dataList[i].end());
  8859. offsets[i] = offset;
  8860. if (IsBigEndian()) {
  8861. swap8(reinterpret_cast<unsigned long long *>(&offsets[i]));
  8862. }
  8863. offset += dataList[i].size();
  8864. }
  8865. {
  8866. memory.insert(memory.end(),
  8867. reinterpret_cast<unsigned char *>(&offsets.at(0)),
  8868. reinterpret_cast<unsigned char *>(&offsets.at(0)) +
  8869. sizeof(unsigned long long) * numBlocks);
  8870. }
  8871. { memory.insert(memory.end(), data.begin(), data.end()); }
  8872. assert(memory.size() > 0);
  8873. (*memory_out) = (unsigned char *)malloc(memory.size());
  8874. memcpy((*memory_out), &memory.at(0), memory.size());
  8875. return memory.size(); // OK
  8876. }
  8877. int SaveMultiChannelEXRToFile(const EXRImage *exrImage, const char *filename,
  8878. const char **err) {
  8879. if (exrImage == NULL || filename == NULL || exrImage->compression < 0 ||
  8880. exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
  8881. if (err) {
  8882. (*err) = "Invalid argument.";
  8883. }
  8884. return -1;
  8885. }
  8886. FILE *fp = fopen(filename, "wb");
  8887. if (!fp) {
  8888. if (err) {
  8889. (*err) = "Cannot write a file.";
  8890. }
  8891. return -1;
  8892. }
  8893. unsigned char *mem = NULL;
  8894. size_t mem_size = SaveMultiChannelEXRToMemory(exrImage, &mem, err);
  8895. if ((mem_size > 0) && mem) {
  8896. fwrite(mem, 1, mem_size, fp);
  8897. }
  8898. free(mem);
  8899. fclose(fp);
  8900. return 0; // OK
  8901. }
  8902. int LoadDeepEXR(DeepImage *deepImage, const char *filename, const char **err) {
  8903. if (deepImage == NULL) {
  8904. if (err) {
  8905. (*err) = "Invalid argument.";
  8906. }
  8907. return -1;
  8908. }
  8909. FILE *fp = fopen(filename, "rb");
  8910. if (!fp) {
  8911. if (err) {
  8912. (*err) = "Cannot read file.";
  8913. }
  8914. return -1;
  8915. }
  8916. size_t filesize;
  8917. // Compute size
  8918. fseek(fp, 0, SEEK_END);
  8919. filesize = ftell(fp);
  8920. fseek(fp, 0, SEEK_SET);
  8921. if (filesize == 0) {
  8922. fclose(fp);
  8923. if (err) {
  8924. (*err) = "File size is zero.";
  8925. }
  8926. return -1;
  8927. }
  8928. std::vector<char> buf(filesize); // @todo { use mmap }
  8929. {
  8930. size_t ret;
  8931. ret = fread(&buf[0], 1, filesize, fp);
  8932. assert(ret == filesize);
  8933. (void)ret;
  8934. }
  8935. fclose(fp);
  8936. const char *head = &buf[0];
  8937. const char *marker = &buf[0];
  8938. // Header check.
  8939. {
  8940. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  8941. if (memcmp(marker, header, 4) != 0) {
  8942. if (err) {
  8943. (*err) = "Header mismatch.";
  8944. }
  8945. return -3;
  8946. }
  8947. marker += 4;
  8948. }
  8949. // Version, scanline.
  8950. {
  8951. // ver 2.0, scanline, deep bit on(0x800)
  8952. // must be [2, 0, 0, 0]
  8953. if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
  8954. if (err) {
  8955. (*err) = "Unsupported version or scanline.";
  8956. }
  8957. return -4;
  8958. }
  8959. marker += 4;
  8960. }
  8961. int dx = -1;
  8962. int dy = -1;
  8963. int dw = -1;
  8964. int dh = -1;
  8965. int numScanlineBlocks = 1; // 16 for ZIP compression.
  8966. int compressionType = -1;
  8967. int numChannels = -1;
  8968. std::vector<ChannelInfo> channels;
  8969. // Read attributes
  8970. for (;;) {
  8971. std::string attrName;
  8972. std::string attrType;
  8973. std::vector<unsigned char> data;
  8974. const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
  8975. if (marker_next == NULL) {
  8976. marker++; // skip '\0'
  8977. break;
  8978. }
  8979. if (attrName.compare("compression") == 0) {
  8980. // must be 0:No compression, 1: RLE, 2: ZIPs or 3: ZIP
  8981. if (data[0] > 3) {
  8982. if (err) {
  8983. (*err) = "Unsupported compression type.";
  8984. }
  8985. return -5;
  8986. }
  8987. compressionType = data[0];
  8988. if (compressionType == 3) { // ZIP
  8989. numScanlineBlocks = 16;
  8990. }
  8991. } else if (attrName.compare("channels") == 0) {
  8992. // name: zero-terminated string, from 1 to 255 bytes long
  8993. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  8994. // pLinear: unsigned char, possible values are 0 and 1
  8995. // reserved: three chars, should be zero
  8996. // xSampling: int
  8997. // ySampling: int
  8998. ReadChannelInfo(channels, data);
  8999. numChannels = channels.size();
  9000. if (numChannels < 1) {
  9001. if (err) {
  9002. (*err) = "Invalid channels format.";
  9003. }
  9004. return -6;
  9005. }
  9006. } else if (attrName.compare("dataWindow") == 0) {
  9007. memcpy(&dx, &data.at(0), sizeof(int));
  9008. memcpy(&dy, &data.at(4), sizeof(int));
  9009. memcpy(&dw, &data.at(8), sizeof(int));
  9010. memcpy(&dh, &data.at(12), sizeof(int));
  9011. if (IsBigEndian()) {
  9012. swap4(reinterpret_cast<unsigned int *>(&dx));
  9013. swap4(reinterpret_cast<unsigned int *>(&dy));
  9014. swap4(reinterpret_cast<unsigned int *>(&dw));
  9015. swap4(reinterpret_cast<unsigned int *>(&dh));
  9016. }
  9017. } else if (attrName.compare("displayWindow") == 0) {
  9018. int x;
  9019. int y;
  9020. int w;
  9021. int h;
  9022. memcpy(&x, &data.at(0), sizeof(int));
  9023. memcpy(&y, &data.at(4), sizeof(int));
  9024. memcpy(&w, &data.at(8), sizeof(int));
  9025. memcpy(&h, &data.at(12), sizeof(int));
  9026. if (IsBigEndian()) {
  9027. swap4(reinterpret_cast<unsigned int *>(&x));
  9028. swap4(reinterpret_cast<unsigned int *>(&y));
  9029. swap4(reinterpret_cast<unsigned int *>(&w));
  9030. swap4(reinterpret_cast<unsigned int *>(&h));
  9031. }
  9032. }
  9033. marker = marker_next;
  9034. }
  9035. assert(dx >= 0);
  9036. assert(dy >= 0);
  9037. assert(dw >= 0);
  9038. assert(dh >= 0);
  9039. assert(numChannels >= 1);
  9040. int dataWidth = dw - dx + 1;
  9041. int dataHeight = dh - dy + 1;
  9042. std::vector<float> image(dataWidth * dataHeight * 4); // 4 = RGBA
  9043. // Read offset tables.
  9044. int numBlocks = dataHeight / numScanlineBlocks;
  9045. if (numBlocks * numScanlineBlocks < dataHeight) {
  9046. numBlocks++;
  9047. }
  9048. std::vector<long long> offsets(numBlocks);
  9049. for (int y = 0; y < numBlocks; y++) {
  9050. long long offset;
  9051. memcpy(&offset, marker, sizeof(long long));
  9052. if (IsBigEndian()) {
  9053. swap8(reinterpret_cast<unsigned long long *>(&offset));
  9054. }
  9055. marker += sizeof(long long); // = 8
  9056. offsets[y] = offset;
  9057. }
  9058. if (compressionType != 0 && compressionType != 2 && compressionType != 3) {
  9059. if (err) {
  9060. (*err) = "Unsupported format.";
  9061. }
  9062. return -10;
  9063. }
  9064. deepImage->image = (float ***)malloc(sizeof(float **) * numChannels);
  9065. for (int c = 0; c < numChannels; c++) {
  9066. deepImage->image[c] = (float **)malloc(sizeof(float *) * dataHeight);
  9067. for (int y = 0; y < dataHeight; y++) {
  9068. }
  9069. }
  9070. deepImage->offset_table = (int **)malloc(sizeof(int *) * dataHeight);
  9071. for (int y = 0; y < dataHeight; y++) {
  9072. deepImage->offset_table[y] = (int *)malloc(sizeof(int) * dataWidth);
  9073. }
  9074. for (int y = 0; y < numBlocks; y++) {
  9075. const unsigned char *dataPtr =
  9076. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  9077. // int: y coordinate
  9078. // int64: packed size of pixel offset table
  9079. // int64: packed size of sample data
  9080. // int64: unpacked size of sample data
  9081. // compressed pixel offset table
  9082. // compressed sample data
  9083. int lineNo;
  9084. long long packedOffsetTableSize;
  9085. long long packedSampleDataSize;
  9086. long long unpackedSampleDataSize;
  9087. memcpy(&lineNo, dataPtr, sizeof(int));
  9088. memcpy(&packedOffsetTableSize, dataPtr + 4, sizeof(long long));
  9089. memcpy(&packedSampleDataSize, dataPtr + 12, sizeof(long long));
  9090. memcpy(&unpackedSampleDataSize, dataPtr + 20, sizeof(long long));
  9091. if (IsBigEndian()) {
  9092. swap4(reinterpret_cast<unsigned int *>(&lineNo));
  9093. swap8(reinterpret_cast<unsigned long long *>(&packedOffsetTableSize));
  9094. swap8(reinterpret_cast<unsigned long long *>(&packedSampleDataSize));
  9095. swap8(reinterpret_cast<unsigned long long *>(&unpackedSampleDataSize));
  9096. }
  9097. std::vector<int> pixelOffsetTable(dataWidth);
  9098. // decode pixel offset table.
  9099. {
  9100. unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
  9101. DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  9102. dstLen, dataPtr + 28, packedOffsetTableSize);
  9103. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  9104. for (int i = 0; i < dataWidth; i++) {
  9105. deepImage->offset_table[y][i] = pixelOffsetTable[i];
  9106. }
  9107. }
  9108. std::vector<unsigned char> sampleData(unpackedSampleDataSize);
  9109. // decode sample data.
  9110. {
  9111. unsigned long dstLen = unpackedSampleDataSize;
  9112. DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
  9113. dstLen, dataPtr + 28 + packedOffsetTableSize,
  9114. packedSampleDataSize);
  9115. assert(dstLen == (unsigned long)unpackedSampleDataSize);
  9116. }
  9117. // decode sample
  9118. int sampleSize = -1;
  9119. std::vector<int> channelOffsetList(numChannels);
  9120. {
  9121. int channelOffset = 0;
  9122. for (int i = 0; i < numChannels; i++) {
  9123. channelOffsetList[i] = channelOffset;
  9124. if (channels[i].pixelType == TINYEXR_PIXELTYPE_UINT) { // UINT
  9125. channelOffset += 4;
  9126. } else if (channels[i].pixelType == TINYEXR_PIXELTYPE_HALF) { // half
  9127. channelOffset += 2;
  9128. } else if (channels[i].pixelType == TINYEXR_PIXELTYPE_FLOAT) { // float
  9129. channelOffset += 4;
  9130. } else {
  9131. assert(0);
  9132. }
  9133. }
  9134. sampleSize = channelOffset;
  9135. }
  9136. assert(sampleSize >= 2);
  9137. assert((size_t)(pixelOffsetTable[dataWidth - 1] * sampleSize) ==
  9138. sampleData.size());
  9139. int samplesPerLine = sampleData.size() / sampleSize;
  9140. //
  9141. // Alloc memory
  9142. //
  9143. //
  9144. // pixel data is stored as image[channels][pixel_samples]
  9145. //
  9146. {
  9147. unsigned long long dataOffset = 0;
  9148. for (int c = 0; c < numChannels; c++) {
  9149. deepImage->image[c][y] =
  9150. (float *)malloc(sizeof(float) * samplesPerLine);
  9151. if (channels[c].pixelType == 0) { // UINT
  9152. for (int x = 0; x < samplesPerLine; x++) {
  9153. unsigned int ui = *reinterpret_cast<unsigned int *>(
  9154. &sampleData.at(dataOffset + x * sizeof(int)));
  9155. deepImage->image[c][y][x] = (float)ui; // @fixme
  9156. }
  9157. dataOffset += sizeof(unsigned int) * samplesPerLine;
  9158. } else if (channels[c].pixelType == 1) { // half
  9159. for (int x = 0; x < samplesPerLine; x++) {
  9160. FP16 f16;
  9161. f16.u = *reinterpret_cast<unsigned short *>(
  9162. &sampleData.at(dataOffset + x * sizeof(short)));
  9163. FP32 f32 = half_to_float(f16);
  9164. deepImage->image[c][y][x] = f32.f;
  9165. }
  9166. dataOffset += sizeof(short) * samplesPerLine;
  9167. } else { // float
  9168. for (int x = 0; x < samplesPerLine; x++) {
  9169. float f = *reinterpret_cast<float *>(
  9170. &sampleData.at(dataOffset + x * sizeof(float)));
  9171. deepImage->image[c][y][x] = f;
  9172. }
  9173. dataOffset += sizeof(float) * samplesPerLine;
  9174. }
  9175. }
  9176. }
  9177. } // y
  9178. deepImage->width = dataWidth;
  9179. deepImage->height = dataHeight;
  9180. deepImage->channel_names =
  9181. (const char **)malloc(sizeof(const char *) * numChannels);
  9182. for (int c = 0; c < numChannels; c++) {
  9183. #ifdef _WIN32
  9184. deepImage->channel_names[c] = _strdup(channels[c].name.c_str());
  9185. #else
  9186. deepImage->channel_names[c] = strdup(channels[c].name.c_str());
  9187. #endif
  9188. }
  9189. deepImage->num_channels = numChannels;
  9190. return 0; // OK
  9191. }
  9192. int SaveDeepEXR(const DeepImage *deepImage, const char *filename,
  9193. const char **err) {
  9194. if (deepImage == NULL || filename == NULL) {
  9195. if (err) {
  9196. (*err) = "Invalid argument.";
  9197. }
  9198. return -1;
  9199. }
  9200. FILE *fp = fopen(filename, "rb");
  9201. if (!fp) {
  9202. if (err) {
  9203. (*err) = "Cannot write file.";
  9204. }
  9205. return -1;
  9206. }
  9207. // Write header check.
  9208. {
  9209. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  9210. size_t n = fwrite(header, 1, 4, fp);
  9211. if (n != 4) {
  9212. if (err) {
  9213. (*err) = "Header write failed.";
  9214. }
  9215. fclose(fp);
  9216. return -3;
  9217. }
  9218. }
  9219. // Version, scanline.
  9220. {
  9221. // ver 2.0, scanline, deep bit on(0x800)
  9222. const char data[] = {2, 8, 0, 0};
  9223. size_t n = fwrite(data, 1, 4, fp);
  9224. if (n != 4) {
  9225. if (err) {
  9226. (*err) = "Flag write failed.";
  9227. }
  9228. fclose(fp);
  9229. return -3;
  9230. }
  9231. }
  9232. // Write attributes.
  9233. {
  9234. int data = 2; // ZIPS
  9235. WriteAttribute(fp, "compression", "compression",
  9236. reinterpret_cast<const unsigned char *>(&data), sizeof(int));
  9237. }
  9238. {
  9239. int data[4] = {0, 0, deepImage->width - 1, deepImage->height - 1};
  9240. WriteAttribute(fp, "dataWindow", "box2i",
  9241. reinterpret_cast<const unsigned char *>(data),
  9242. sizeof(int) * 4);
  9243. WriteAttribute(fp, "displayWindow", "box2i",
  9244. reinterpret_cast<const unsigned char *>(data),
  9245. sizeof(int) * 4);
  9246. }
  9247. int numScanlineBlocks = 1;
  9248. // Write offset tables.
  9249. int numBlocks = deepImage->height / numScanlineBlocks;
  9250. if (numBlocks * numScanlineBlocks < deepImage->height) {
  9251. numBlocks++;
  9252. }
  9253. #if 0 // @todo
  9254. std::vector<long long> offsets(numBlocks);
  9255. //std::vector<int> pixelOffsetTable(dataWidth);
  9256. // compress pixel offset table.
  9257. {
  9258. unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
  9259. Compresses(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  9260. dstLen, dataPtr + 28, packedOffsetTableSize);
  9261. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  9262. // int ret =
  9263. // miniz::mz_uncompress(reinterpret_cast<unsigned char
  9264. // *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
  9265. // packedOffsetTableSize);
  9266. // printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
  9267. //
  9268. for (int i = 0; i < dataWidth; i++) {
  9269. // printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
  9270. deepImage->offset_table[y][i] = pixelOffsetTable[i];
  9271. }
  9272. }
  9273. for (int y = 0; y < numBlocks; y++) {
  9274. //long long offset = *(reinterpret_cast<const long long *>(marker));
  9275. // printf("offset[%d] = %lld\n", y, offset);
  9276. //marker += sizeof(long long); // = 8
  9277. offsets[y] = offset;
  9278. }
  9279. // Write offset table.
  9280. fwrite(&offsets.at(0), sizeof(long long), numBlocks, fp);
  9281. for (int y = 0; y < numBlocks; y++) {
  9282. const unsigned char *dataPtr =
  9283. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  9284. // int: y coordinate
  9285. // int64: packed size of pixel offset table
  9286. // int64: packed size of sample data
  9287. // int64: unpacked size of sample data
  9288. // compressed pixel offset table
  9289. // compressed sample data
  9290. int lineNo = *reinterpret_cast<const int *>(dataPtr);
  9291. long long packedOffsetTableSize =
  9292. *reinterpret_cast<const long long *>(dataPtr + 4);
  9293. long long packedSampleDataSize =
  9294. *reinterpret_cast<const long long *>(dataPtr + 12);
  9295. long long unpackedSampleDataSize =
  9296. *reinterpret_cast<const long long *>(dataPtr + 20);
  9297. // printf("line: %d, %lld/%lld/%lld\n", lineNo, packedOffsetTableSize,
  9298. // packedSampleDataSize, unpackedSampleDataSize);
  9299. int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
  9300. int numLines = endLineNo - lineNo;
  9301. // printf("numLines: %d\n", numLines);
  9302. std::vector<int> pixelOffsetTable(dataWidth);
  9303. // decode pixel offset table.
  9304. {
  9305. unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
  9306. DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  9307. dstLen, dataPtr + 28, packedOffsetTableSize);
  9308. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  9309. // int ret =
  9310. // miniz::mz_uncompress(reinterpret_cast<unsigned char
  9311. // *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
  9312. // packedOffsetTableSize);
  9313. // printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
  9314. //
  9315. for (int i = 0; i < dataWidth; i++) {
  9316. // printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
  9317. deepImage->offset_table[y][i] = pixelOffsetTable[i];
  9318. }
  9319. }
  9320. std::vector<unsigned char> sampleData(unpackedSampleDataSize);
  9321. // decode sample data.
  9322. {
  9323. unsigned long dstLen = unpackedSampleDataSize;
  9324. // printf("dstLen = %d\n", dstLen);
  9325. // printf("srcLen = %d\n", packedSampleDataSize);
  9326. DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
  9327. dstLen, dataPtr + 28 + packedOffsetTableSize,
  9328. packedSampleDataSize);
  9329. assert(dstLen == unpackedSampleDataSize);
  9330. }
  9331. // decode sample
  9332. int sampleSize = -1;
  9333. std::vector<int> channelOffsetList(numChannels);
  9334. {
  9335. int channelOffset = 0;
  9336. for (int i = 0; i < numChannels; i++) {
  9337. // printf("offt[%d] = %d\n", i, channelOffset);
  9338. channelOffsetList[i] = channelOffset;
  9339. if (channels[i].pixelType == 0) { // UINT
  9340. channelOffset += 4;
  9341. } else if (channels[i].pixelType == 1) { // half
  9342. channelOffset += 2;
  9343. } else if (channels[i].pixelType == 2) { // float
  9344. channelOffset += 4;
  9345. } else {
  9346. assert(0);
  9347. }
  9348. }
  9349. sampleSize = channelOffset;
  9350. }
  9351. assert(sampleSize >= 2);
  9352. assert(pixelOffsetTable[dataWidth - 1] * sampleSize == sampleData.size());
  9353. int samplesPerLine = sampleData.size() / sampleSize;
  9354. //
  9355. // Alloc memory
  9356. //
  9357. //
  9358. // pixel data is stored as image[channels][pixel_samples]
  9359. //
  9360. {
  9361. unsigned long long dataOffset = 0;
  9362. for (int c = 0; c < numChannels; c++) {
  9363. deepImage->image[c][y] =
  9364. (float *)malloc(sizeof(float) * samplesPerLine);
  9365. // unsigned int channelOffset = channelOffsetList[c];
  9366. // unsigned int i = channelOffset;
  9367. // printf("channel = %d. name = %s. ty = %d\n", c,
  9368. // channels[c].name.c_str(), channels[c].pixelType);
  9369. // printf("dataOffset = %d\n", (int)dataOffset);
  9370. if (channels[c].pixelType == 0) { // UINT
  9371. for (int x = 0; x < samplesPerLine; x++) {
  9372. unsigned int ui = *reinterpret_cast<unsigned int *>(
  9373. &sampleData.at(dataOffset + x * sizeof(int)));
  9374. deepImage->image[c][y][x] = (float)ui; // @fixme
  9375. }
  9376. dataOffset += sizeof(unsigned int) * samplesPerLine;
  9377. } else if (channels[c].pixelType == 1) { // half
  9378. for (int x = 0; x < samplesPerLine; x++) {
  9379. FP16 f16;
  9380. f16.u = *reinterpret_cast<unsigned short *>(
  9381. &sampleData.at(dataOffset + x * sizeof(short)));
  9382. FP32 f32 = half_to_float(f16);
  9383. deepImage->image[c][y][x] = f32.f;
  9384. // printf("c[%d] f(half) = %f (0x%08x)\n", c, f32.f, f16.u);
  9385. }
  9386. dataOffset += sizeof(short) * samplesPerLine;
  9387. } else { // float
  9388. for (int x = 0; x < samplesPerLine; x++) {
  9389. float f = *reinterpret_cast<float *>(
  9390. &sampleData.at(dataOffset + x * sizeof(float)));
  9391. // printf(" f = %f(0x%08x)\n", f, *((unsigned int *)&f));
  9392. deepImage->image[c][y][x] = f;
  9393. }
  9394. dataOffset += sizeof(float) * samplesPerLine;
  9395. }
  9396. }
  9397. // printf("total: %d\n", dataOffset);
  9398. }
  9399. } // y
  9400. #endif
  9401. fclose(fp);
  9402. return 0; // OK
  9403. }
  9404. void InitEXRImage(EXRImage *exrImage) {
  9405. if (exrImage == NULL) {
  9406. return;
  9407. }
  9408. exrImage->num_custom_attributes = 0;
  9409. exrImage->num_channels = 0;
  9410. exrImage->channel_names = NULL;
  9411. exrImage->images = NULL;
  9412. exrImage->pixel_types = NULL;
  9413. exrImage->requested_pixel_types = NULL;
  9414. exrImage->compression = TINYEXR_COMPRESSIONTYPE_ZIP;
  9415. }
  9416. int FreeEXRImage(EXRImage *exrImage) {
  9417. if (exrImage == NULL) {
  9418. return -1; // Err
  9419. }
  9420. for (int i = 0; i < exrImage->num_channels; i++) {
  9421. if (exrImage->channel_names && exrImage->channel_names[i]) {
  9422. free((char *)exrImage->channel_names[i]); // remove const
  9423. }
  9424. if (exrImage->images && exrImage->images[i]) {
  9425. free(exrImage->images[i]);
  9426. }
  9427. }
  9428. if (exrImage->channel_names) {
  9429. free(exrImage->channel_names);
  9430. }
  9431. if (exrImage->images) {
  9432. free(exrImage->images);
  9433. }
  9434. if (exrImage->pixel_types) {
  9435. free(exrImage->pixel_types);
  9436. }
  9437. if (exrImage->requested_pixel_types) {
  9438. free(exrImage->requested_pixel_types);
  9439. }
  9440. for (int i = 0; i < exrImage->num_custom_attributes; i++) {
  9441. if (exrImage->custom_attributes[i].name) {
  9442. free(exrImage->custom_attributes[i].name);
  9443. }
  9444. if (exrImage->custom_attributes[i].type) {
  9445. free(exrImage->custom_attributes[i].type);
  9446. }
  9447. if (exrImage->custom_attributes[i].value) {
  9448. free(exrImage->custom_attributes[i].value);
  9449. }
  9450. }
  9451. return 0;
  9452. }
  9453. int ParseMultiChannelEXRHeaderFromFile(EXRImage *exrImage, const char *filename,
  9454. const char **err) {
  9455. if (exrImage == NULL) {
  9456. if (err) {
  9457. (*err) = "Invalid argument.";
  9458. }
  9459. return -1;
  9460. }
  9461. FILE *fp = fopen(filename, "rb");
  9462. if (!fp) {
  9463. if (err) {
  9464. (*err) = "Cannot read file.";
  9465. }
  9466. return -1;
  9467. }
  9468. size_t filesize;
  9469. // Compute size
  9470. fseek(fp, 0, SEEK_END);
  9471. filesize = ftell(fp);
  9472. fseek(fp, 0, SEEK_SET);
  9473. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  9474. {
  9475. size_t ret;
  9476. ret = fread(&buf[0], 1, filesize, fp);
  9477. assert(ret == filesize);
  9478. fclose(fp);
  9479. (void)ret;
  9480. }
  9481. return ParseMultiChannelEXRHeaderFromMemory(exrImage, &buf.at(0), err);
  9482. }
  9483. int ParseMultiChannelEXRHeaderFromMemory(EXRImage *exrImage,
  9484. const unsigned char *memory,
  9485. const char **err) {
  9486. if (exrImage == NULL || memory == NULL) {
  9487. if (err) {
  9488. (*err) = "Invalid argument.";
  9489. }
  9490. return -1;
  9491. }
  9492. const char *buf = reinterpret_cast<const char *>(memory);
  9493. const char *marker = &buf[0];
  9494. // Header check.
  9495. {
  9496. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  9497. if (memcmp(marker, header, 4) != 0) {
  9498. if (err) {
  9499. (*err) = "Header mismatch.";
  9500. }
  9501. return -3;
  9502. }
  9503. marker += 4;
  9504. }
  9505. // Version, scanline.
  9506. {
  9507. // must be [2, 0, 0, 0]
  9508. if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
  9509. if (err) {
  9510. (*err) = "Unsupported version or scanline.";
  9511. }
  9512. return -4;
  9513. }
  9514. marker += 4;
  9515. }
  9516. int dx = -1;
  9517. int dy = -1;
  9518. int dw = -1;
  9519. int dh = -1;
  9520. int numChannels = -1;
  9521. int displayWindow[4] = {-1, -1, -1, -1}; // @fixme.
  9522. float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
  9523. float screenWindowWidth = 1.0f; // @fixme
  9524. float pixelAspectRatio = 1.0f;
  9525. unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
  9526. std::vector<ChannelInfo> channels;
  9527. int compressionType = 0; // @fixme
  9528. int numCustomAttributes = 0;
  9529. std::vector<EXRAttribute> customAttribs;
  9530. // Read attributes
  9531. for (;;) {
  9532. std::string attrName;
  9533. std::string attrType;
  9534. std::vector<unsigned char> data;
  9535. const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
  9536. if (marker_next == NULL) {
  9537. marker++; // skip '\0'
  9538. break;
  9539. }
  9540. if (attrName.compare("compression") == 0) {
  9541. // must be 0:No compression, 1: RLE, 2: ZIPs, 3: ZIP or 4: PIZ
  9542. if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
  9543. if (err) {
  9544. (*err) = "Unsupported compression type.";
  9545. }
  9546. return -5;
  9547. }
  9548. compressionType = data[0];
  9549. } else if (attrName.compare("channels") == 0) {
  9550. // name: zero-terminated string, from 1 to 255 bytes long
  9551. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  9552. // pLinear: unsigned char, possible values are 0 and 1
  9553. // reserved: three chars, should be zero
  9554. // xSampling: int
  9555. // ySampling: int
  9556. ReadChannelInfo(channels, data);
  9557. numChannels = channels.size();
  9558. if (numChannels < 1) {
  9559. if (err) {
  9560. (*err) = "Invalid channels format.";
  9561. }
  9562. return -6;
  9563. }
  9564. } else if (attrName.compare("dataWindow") == 0) {
  9565. memcpy(&dx, &data.at(0), sizeof(int));
  9566. memcpy(&dy, &data.at(4), sizeof(int));
  9567. memcpy(&dw, &data.at(8), sizeof(int));
  9568. memcpy(&dh, &data.at(12), sizeof(int));
  9569. if (IsBigEndian()) {
  9570. swap4(reinterpret_cast<unsigned int *>(&dx));
  9571. swap4(reinterpret_cast<unsigned int *>(&dy));
  9572. swap4(reinterpret_cast<unsigned int *>(&dw));
  9573. swap4(reinterpret_cast<unsigned int *>(&dh));
  9574. }
  9575. } else if (attrName.compare("displayWindow") == 0) {
  9576. memcpy(&displayWindow[0], &data.at(0), sizeof(int));
  9577. memcpy(&displayWindow[1], &data.at(4), sizeof(int));
  9578. memcpy(&displayWindow[2], &data.at(8), sizeof(int));
  9579. memcpy(&displayWindow[3], &data.at(12), sizeof(int));
  9580. if (IsBigEndian()) {
  9581. swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
  9582. swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
  9583. swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
  9584. swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
  9585. }
  9586. } else if (attrName.compare("lineOrder") == 0) {
  9587. int order;
  9588. memcpy(&order, &data.at(0), sizeof(int));
  9589. if (IsBigEndian()) {
  9590. swap4(reinterpret_cast<unsigned int *>(&order));
  9591. }
  9592. lineOrder = (unsigned char)order;
  9593. } else if (attrName.compare("pixelAspectRatio") == 0) {
  9594. memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
  9595. if (IsBigEndian()) {
  9596. swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
  9597. }
  9598. } else if (attrName.compare("screenWindowCenter") == 0) {
  9599. memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
  9600. memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
  9601. if (IsBigEndian()) {
  9602. swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
  9603. swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
  9604. }
  9605. } else if (attrName.compare("screenWindowWidth") == 0) {
  9606. memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
  9607. if (IsBigEndian()) {
  9608. swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
  9609. }
  9610. } else {
  9611. // Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
  9612. if (numCustomAttributes < TINYEXR_MAX_ATTRIBUTES) {
  9613. EXRAttribute attrib;
  9614. attrib.name = strdup(attrName.c_str());
  9615. attrib.type = strdup(attrType.c_str());
  9616. attrib.size = data.size();
  9617. attrib.value = (unsigned char *)malloc(data.size());
  9618. memcpy((char *)attrib.value, &data.at(0), data.size());
  9619. customAttribs.push_back(attrib);
  9620. }
  9621. }
  9622. marker = marker_next;
  9623. }
  9624. assert(dx >= 0);
  9625. assert(dy >= 0);
  9626. assert(dw >= 0);
  9627. assert(dh >= 0);
  9628. assert(numChannels >= 1);
  9629. int dataWidth = dw - dx + 1;
  9630. int dataHeight = dh - dy + 1;
  9631. {
  9632. exrImage->channel_names =
  9633. (const char **)malloc(sizeof(const char *) * numChannels);
  9634. for (int c = 0; c < numChannels; c++) {
  9635. #ifdef _WIN32
  9636. exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
  9637. #else
  9638. exrImage->channel_names[c] = strdup(channels[c].name.c_str());
  9639. #endif
  9640. }
  9641. exrImage->num_channels = numChannels;
  9642. exrImage->width = dataWidth;
  9643. exrImage->height = dataHeight;
  9644. exrImage->pixel_aspect_ratio = pixelAspectRatio;
  9645. exrImage->screen_window_center[0] = screenWindowCenter[0];
  9646. exrImage->screen_window_center[1] = screenWindowCenter[1];
  9647. exrImage->screen_window_width = screenWindowWidth;
  9648. exrImage->display_window[0] = displayWindow[0];
  9649. exrImage->display_window[1] = displayWindow[1];
  9650. exrImage->display_window[2] = displayWindow[2];
  9651. exrImage->display_window[3] = displayWindow[3];
  9652. exrImage->data_window[0] = dx;
  9653. exrImage->data_window[1] = dy;
  9654. exrImage->data_window[2] = dw;
  9655. exrImage->data_window[3] = dh;
  9656. exrImage->line_order = lineOrder;
  9657. exrImage->compression = compressionType;
  9658. exrImage->pixel_types = (int *)malloc(sizeof(int) * numChannels);
  9659. for (int c = 0; c < numChannels; c++) {
  9660. exrImage->pixel_types[c] = channels[c].pixelType;
  9661. }
  9662. // Initially fill with values of `pixel-types`
  9663. exrImage->requested_pixel_types = (int *)malloc(sizeof(int) * numChannels);
  9664. for (int c = 0; c < numChannels; c++) {
  9665. exrImage->requested_pixel_types[c] = channels[c].pixelType;
  9666. }
  9667. }
  9668. if (numCustomAttributes > 0) {
  9669. assert(customAttribs.size() < TINYEXR_MAX_ATTRIBUTES);
  9670. exrImage->num_custom_attributes = numCustomAttributes;
  9671. for (int i = 0; i < (int)customAttribs.size(); i++) {
  9672. exrImage->custom_attributes[i] = customAttribs[i];
  9673. }
  9674. }
  9675. return 0; // OK
  9676. }
  9677. #ifdef _MSC_VER
  9678. #pragma warning(pop)
  9679. #endif
  9680. #endif
  9681. #endif // __TINYEXR_H__