tinyexr.h 459 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201
  1. /*
  2. Copyright (c) 2014 - 2018, Syoyo Fujita and many contributors.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of the Syoyo Fujita nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  18. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. // TinyEXR contains some OpenEXR code, which is licensed under ------------
  26. ///////////////////////////////////////////////////////////////////////////
  27. //
  28. // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
  29. // Digital Ltd. LLC
  30. //
  31. // All rights reserved.
  32. //
  33. // Redistribution and use in source and binary forms, with or without
  34. // modification, are permitted provided that the following conditions are
  35. // met:
  36. // * Redistributions of source code must retain the above copyright
  37. // notice, this list of conditions and the following disclaimer.
  38. // * Redistributions in binary form must reproduce the above
  39. // copyright notice, this list of conditions and the following disclaimer
  40. // in the documentation and/or other materials provided with the
  41. // distribution.
  42. // * Neither the name of Industrial Light & Magic nor the names of
  43. // its contributors may be used to endorse or promote products derived
  44. // from this software without specific prior written permission.
  45. //
  46. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  47. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  48. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  49. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  50. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  51. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  52. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  53. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  54. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  55. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  56. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  57. //
  58. ///////////////////////////////////////////////////////////////////////////
  59. // End of OpenEXR license -------------------------------------------------
  60. #ifndef TINYEXR_H_
  61. #define TINYEXR_H_
  62. //
  63. //
  64. // Do this:
  65. // #define TINYEXR_IMPLEMENTATION
  66. // before you include this file in *one* C or C++ file to create the
  67. // implementation.
  68. //
  69. // // i.e. it should look like this:
  70. // #include ...
  71. // #include ...
  72. // #include ...
  73. // #define TINYEXR_IMPLEMENTATION
  74. // #include "tinyexr.h"
  75. //
  76. //
  77. #include <stddef.h> // for size_t
  78. #include <stdint.h> // guess stdint.h is available(C99)
  79. #ifdef __cplusplus
  80. extern "C" {
  81. #endif
  82. // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib
  83. // required if this flas is 0.
  84. #ifndef TINYEXR_USE_MINIZ
  85. #define TINYEXR_USE_MINIZ (1)
  86. #endif
  87. // Disable PIZ comporession when applying cpplint.
  88. #ifndef TINYEXR_USE_PIZ
  89. #define TINYEXR_USE_PIZ (1)
  90. #endif
  91. #ifndef TINYEXR_USE_ZFP
  92. #define TINYEXR_USE_ZFP (0) // TinyEXR extension.
  93. // http://computation.llnl.gov/projects/floating-point-compression
  94. #endif
  95. #define TINYEXR_SUCCESS (0)
  96. #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)
  97. #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)
  98. #define TINYEXR_ERROR_INVALID_ARGUMENT (-3)
  99. #define TINYEXR_ERROR_INVALID_DATA (-4)
  100. #define TINYEXR_ERROR_INVALID_FILE (-5)
  101. #define TINYEXR_ERROR_INVALID_PARAMETER (-5)
  102. #define TINYEXR_ERROR_CANT_OPEN_FILE (-6)
  103. #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-7)
  104. #define TINYEXR_ERROR_INVALID_HEADER (-8)
  105. #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-9)
  106. #define TINYEXR_ERROR_CANT_WRITE_FILE (-10)
  107. #define TINYEXR_ERROR_SERIALZATION_FAILED (-11)
  108. // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }
  109. // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
  110. #define TINYEXR_PIXELTYPE_UINT (0)
  111. #define TINYEXR_PIXELTYPE_HALF (1)
  112. #define TINYEXR_PIXELTYPE_FLOAT (2)
  113. #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)
  114. #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)
  115. #define TINYEXR_COMPRESSIONTYPE_NONE (0)
  116. #define TINYEXR_COMPRESSIONTYPE_RLE (1)
  117. #define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
  118. #define TINYEXR_COMPRESSIONTYPE_ZIP (3)
  119. #define TINYEXR_COMPRESSIONTYPE_PIZ (4)
  120. #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension
  121. #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)
  122. #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)
  123. #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)
  124. #define TINYEXR_TILE_ONE_LEVEL (0)
  125. #define TINYEXR_TILE_MIPMAP_LEVELS (1)
  126. #define TINYEXR_TILE_RIPMAP_LEVELS (2)
  127. #define TINYEXR_TILE_ROUND_DOWN (0)
  128. #define TINYEXR_TILE_ROUND_UP (1)
  129. typedef struct _EXRVersion {
  130. int version; // this must be 2
  131. int tiled; // tile format image
  132. int long_name; // long name attribute
  133. int non_image; // deep image(EXR 2.0)
  134. int multipart; // multi-part(EXR 2.0)
  135. } EXRVersion;
  136. typedef struct _EXRAttribute {
  137. char name[256]; // name and type are up to 255 chars long.
  138. char type[256];
  139. unsigned char *value; // uint8_t*
  140. int size;
  141. int pad0;
  142. } EXRAttribute;
  143. typedef struct _EXRChannelInfo {
  144. char name[256]; // less than 255 bytes long
  145. int pixel_type;
  146. int x_sampling;
  147. int y_sampling;
  148. unsigned char p_linear;
  149. unsigned char pad[3];
  150. } EXRChannelInfo;
  151. typedef struct _EXRTile {
  152. int offset_x;
  153. int offset_y;
  154. int level_x;
  155. int level_y;
  156. int width; // actual width in a tile.
  157. int height; // actual height int a tile.
  158. unsigned char **images; // image[channels][pixels]
  159. } EXRTile;
  160. typedef struct _EXRHeader {
  161. float pixel_aspect_ratio;
  162. int line_order;
  163. int data_window[4];
  164. int display_window[4];
  165. float screen_window_center[2];
  166. float screen_window_width;
  167. int chunk_count;
  168. // Properties for tiled format(`tiledesc`).
  169. int tiled;
  170. int tile_size_x;
  171. int tile_size_y;
  172. int tile_level_mode;
  173. int tile_rounding_mode;
  174. int long_name;
  175. int non_image;
  176. int multipart;
  177. unsigned int header_len;
  178. // Custom attributes(exludes required attributes(e.g. `channels`,
  179. // `compression`, etc)
  180. int num_custom_attributes;
  181. EXRAttribute *custom_attributes; // array of EXRAttribute. size =
  182. // `num_custom_attributes`.
  183. EXRChannelInfo *channels; // [num_channels]
  184. int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
  185. // each channel. This is overwritten with `requested_pixel_types` when
  186. // loading.
  187. int num_channels;
  188. int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)
  189. int *requested_pixel_types; // Filled initially by
  190. // ParseEXRHeaderFrom(Meomory|File), then users
  191. // can edit it(only valid for HALF pixel type
  192. // channel)
  193. } EXRHeader;
  194. typedef struct _EXRMultiPartHeader {
  195. int num_headers;
  196. EXRHeader *headers;
  197. } EXRMultiPartHeader;
  198. typedef struct _EXRImage {
  199. EXRTile *tiles; // Tiled pixel data. The application must reconstruct image
  200. // from tiles manually. NULL if scanline format.
  201. unsigned char **images; // image[channels][pixels]. NULL if tiled format.
  202. int width;
  203. int height;
  204. int num_channels;
  205. // Properties for tile format.
  206. int num_tiles;
  207. } EXRImage;
  208. typedef struct _EXRMultiPartImage {
  209. int num_images;
  210. EXRImage *images;
  211. } EXRMultiPartImage;
  212. typedef struct _DeepImage {
  213. const char **channel_names;
  214. float ***image; // image[channels][scanlines][samples]
  215. int **offset_table; // offset_table[scanline][offsets]
  216. int num_channels;
  217. int width;
  218. int height;
  219. int pad0;
  220. } DeepImage;
  221. // @deprecated { to be removed. }
  222. // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel
  223. // alpha) or RGB(A) channels.
  224. // Application must free image data as returned by `out_rgba`
  225. // Result image format is: float x RGBA x width x hight
  226. // Returns negative value and may set error string in `err` when there's an
  227. // error
  228. extern int LoadEXR(float **out_rgba, int *width, int *height,
  229. const char *filename, const char **err);
  230. // @deprecated { to be removed. }
  231. // Simple wrapper API for ParseEXRHeaderFromFile.
  232. // checking given file is a EXR file(by just look up header)
  233. // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for others
  234. extern int IsEXR(const char *filename);
  235. // @deprecated { to be removed. }
  236. // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
  237. // components must be 1(Grayscale), 3(RGB) or 4(RGBA).
  238. // Input image format is: `float x width x height`, or `float x RGB(A) x width x
  239. // hight`
  240. // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
  241. // value.
  242. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
  243. // Use ZIP compression by default.
  244. // Returns negative value and may set error string in `err` when there's an
  245. // error
  246. extern int SaveEXR(const float *data, const int width, const int height,
  247. const int components, const int save_as_fp16,
  248. const char *filename, const char **err);
  249. // Initialize EXRHeader struct
  250. extern void InitEXRHeader(EXRHeader *exr_header);
  251. // Initialize EXRImage struct
  252. extern void InitEXRImage(EXRImage *exr_image);
  253. // Free's internal data of EXRHeader struct
  254. extern int FreeEXRHeader(EXRHeader *exr_header);
  255. // Free's internal data of EXRImage struct
  256. extern int FreeEXRImage(EXRImage *exr_image);
  257. // Free's error message
  258. extern void FreeEXRErrorMessage(const char *msg);
  259. // Parse EXR version header of a file.
  260. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);
  261. // Parse EXR version header from memory-mapped EXR data.
  262. extern int ParseEXRVersionFromMemory(EXRVersion *version,
  263. const unsigned char *memory, size_t size);
  264. // Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
  265. // When there was an error message, Application must free `err` with
  266. // FreeEXRErrorMessage()
  267. extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,
  268. const char *filename, const char **err);
  269. // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
  270. // When there was an error message, Application must free `err` with
  271. // FreeEXRErrorMessage()
  272. extern int ParseEXRHeaderFromMemory(EXRHeader *header,
  273. const EXRVersion *version,
  274. const unsigned char *memory, size_t size,
  275. const char **err);
  276. // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
  277. // array.
  278. // When there was an error message, Application must free `err` with
  279. // FreeEXRErrorMessage()
  280. extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,
  281. int *num_headers,
  282. const EXRVersion *version,
  283. const char *filename,
  284. const char **err);
  285. // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
  286. // array
  287. // When there was an error message, Application must free `err` with
  288. // FreeEXRErrorMessage()
  289. extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,
  290. int *num_headers,
  291. const EXRVersion *version,
  292. const unsigned char *memory,
  293. size_t size, const char **err);
  294. // Loads single-part OpenEXR image from a file.
  295. // Application must setup `ParseEXRHeaderFromFile` before calling this function.
  296. // Application can free EXRImage using `FreeEXRImage`
  297. // Returns negative value and may set error string in `err` when there's an
  298. // error
  299. // When there was an error message, Application must free `err` with
  300. // FreeEXRErrorMessage()
  301. extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,
  302. const char *filename, const char **err);
  303. // Loads single-part OpenEXR image from a memory.
  304. // Application must setup `EXRHeader` with
  305. // `ParseEXRHeaderFromMemory` before calling this function.
  306. // Application can free EXRImage using `FreeEXRImage`
  307. // Returns negative value and may set error string in `err` when there's an
  308. // error
  309. // When there was an error message, Application must free `err` with
  310. // FreeEXRErrorMessage()
  311. extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,
  312. const unsigned char *memory,
  313. const size_t size, const char **err);
  314. // Loads multi-part OpenEXR image from a file.
  315. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
  316. // function.
  317. // Application can free EXRImage using `FreeEXRImage`
  318. // Returns negative value and may set error string in `err` when there's an
  319. // error
  320. // When there was an error message, Application must free `err` with
  321. // FreeEXRErrorMessage()
  322. extern int LoadEXRMultipartImageFromFile(EXRImage *images,
  323. const EXRHeader **headers,
  324. unsigned int num_parts,
  325. const char *filename,
  326. const char **err);
  327. // Loads multi-part OpenEXR image from a memory.
  328. // Application must setup `EXRHeader*` array with
  329. // `ParseEXRMultipartHeaderFromMemory` before calling this function.
  330. // Application can free EXRImage using `FreeEXRImage`
  331. // Returns negative value and may set error string in `err` when there's an
  332. // error
  333. // When there was an error message, Application must free `err` with
  334. // FreeEXRErrorMessage()
  335. extern int LoadEXRMultipartImageFromMemory(EXRImage *images,
  336. const EXRHeader **headers,
  337. unsigned int num_parts,
  338. const unsigned char *memory,
  339. const size_t size, const char **err);
  340. // Saves multi-channel, single-frame OpenEXR image to a file.
  341. // Returns negative value and may set error string in `err` when there's an
  342. // error
  343. // When there was an error message, Application must free `err` with
  344. // FreeEXRErrorMessage()
  345. extern int SaveEXRImageToFile(const EXRImage *image,
  346. const EXRHeader *exr_header, const char *filename,
  347. const char **err);
  348. // Saves multi-channel, single-frame OpenEXR image to a memory.
  349. // Image is compressed using EXRImage.compression value.
  350. // Return the number of bytes if success.
  351. // Return zero and will set error string in `err` when there's an
  352. // error.
  353. // When there was an error message, Application must free `err` with
  354. // FreeEXRErrorMessage()
  355. extern size_t SaveEXRImageToMemory(const EXRImage *image,
  356. const EXRHeader *exr_header,
  357. unsigned char **memory, const char **err);
  358. // Loads single-frame OpenEXR deep image.
  359. // Application must free memory of variables in DeepImage(image, offset_table)
  360. // Returns negative value and may set error string in `err` when there's an
  361. // error
  362. // When there was an error message, Application must free `err` with
  363. // FreeEXRErrorMessage()
  364. extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
  365. const char **err);
  366. // NOT YET IMPLEMENTED:
  367. // Saves single-frame OpenEXR deep image.
  368. // Returns negative value and may set error string in `err` when there's an
  369. // error
  370. // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
  371. // const char **err);
  372. // NOT YET IMPLEMENTED:
  373. // Loads multi-part OpenEXR deep image.
  374. // Application must free memory of variables in DeepImage(image, offset_table)
  375. // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
  376. // char *filename,
  377. // const char **err);
  378. // For emscripten.
  379. // Loads single-frame OpenEXR image from memory. Assume EXR image contains
  380. // RGB(A) channels.
  381. // Returns negative value and may set error string in `err` when there's an
  382. // error
  383. // When there was an error message, Application must free `err` with
  384. // FreeEXRErrorMessage()
  385. extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  386. const unsigned char *memory, size_t size,
  387. const char **err);
  388. #ifdef __cplusplus
  389. }
  390. #endif
  391. #endif // TINYEXR_H_
  392. #ifdef TINYEXR_IMPLEMENTATION
  393. #ifndef TINYEXR_IMPLEMENTATION_DEIFNED
  394. #define TINYEXR_IMPLEMENTATION_DEIFNED
  395. #include <algorithm>
  396. #include <cassert>
  397. #include <cstdio>
  398. #include <cstdlib>
  399. #include <cstring>
  400. #include <iostream>
  401. #include <sstream>
  402. #include <limits>
  403. #include <string>
  404. #include <vector>
  405. #if __cplusplus > 199711L
  406. // C++11
  407. #include <cstdint>
  408. #endif // __cplusplus > 199711L
  409. #ifdef _OPENMP
  410. #include <omp.h>
  411. #endif
  412. #if TINYEXR_USE_MINIZ
  413. #else
  414. // Issue #46. Please include your own zlib-compatible API header before
  415. // including `tinyexr.h`
  416. //#include "zlib.h"
  417. #endif
  418. #if TINYEXR_USE_ZFP
  419. #include "zfp.h"
  420. #endif
  421. namespace tinyexr {
  422. #if __cplusplus > 199711L
  423. // C++11
  424. typedef uint64_t tinyexr_uint64;
  425. typedef int64_t tinyexr_int64;
  426. #else
  427. // Although `long long` is not a standard type pre C++11, assume it is defined
  428. // as a compiler's extension.
  429. #ifdef __clang__
  430. #pragma clang diagnostic push
  431. #pragma clang diagnostic ignored "-Wc++11-long-long"
  432. #endif
  433. typedef unsigned long long tinyexr_uint64;
  434. typedef long long tinyexr_int64;
  435. #ifdef __clang__
  436. #pragma clang diagnostic pop
  437. #endif
  438. #endif
  439. #if TINYEXR_USE_MINIZ
  440. namespace miniz {
  441. #ifdef __clang__
  442. #pragma clang diagnostic push
  443. #pragma clang diagnostic ignored "-Wc++11-long-long"
  444. #pragma clang diagnostic ignored "-Wold-style-cast"
  445. #pragma clang diagnostic ignored "-Wpadded"
  446. #pragma clang diagnostic ignored "-Wsign-conversion"
  447. #pragma clang diagnostic ignored "-Wc++11-extensions"
  448. #pragma clang diagnostic ignored "-Wconversion"
  449. #pragma clang diagnostic ignored "-Wunused-function"
  450. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  451. #pragma clang diagnostic ignored "-Wundef"
  452. #if __has_warning("-Wcomma")
  453. #pragma clang diagnostic ignored "-Wcomma"
  454. #endif
  455. #if __has_warning("-Wmacro-redefined")
  456. #pragma clang diagnostic ignored "-Wmacro-redefined"
  457. #endif
  458. #if __has_warning("-Wcast-qual")
  459. #pragma clang diagnostic ignored "-Wcast-qual"
  460. #endif
  461. #if __has_warning("-Wzero-as-null-pointer-constant")
  462. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  463. #endif
  464. #if __has_warning("-Wtautological-constant-compare")
  465. #pragma clang diagnostic ignored "-Wtautological-constant-compare"
  466. #endif
  467. #endif
  468. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
  469. reading/writing/appending, PNG writing
  470. See "unlicense" statement at the end of this file.
  471. Rich Geldreich <[email protected]>, last updated Oct. 13, 2013
  472. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
  473. http://www.ietf.org/rfc/rfc1951.txt
  474. Most API's defined in miniz.c are optional. For example, to disable the
  475. archive related functions just define
  476. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
  477. (see the list below for more macros).
  478. * Change History
  479. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
  480. release with Zip64 support (almost there!):
  481. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
  482. (thanks [email protected]) which could cause locate files to not find
  483. files. This bug
  484. would only have occured in earlier versions if you explicitly used this
  485. flag, OR if you used mz_zip_extract_archive_file_to_heap() or
  486. mz_zip_add_mem_to_archive_file_in_place()
  487. (which used this flag). If you can't switch to v1.15 but want to fix
  488. this bug, just remove the uses of this flag from both helper funcs (and of
  489. course don't use the flag).
  490. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
  491. pUser_read_buf is not NULL and compressed size is > uncompressed size
  492. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
  493. compressed data from directory entries, to account for weird zipfiles which
  494. contain zero-size compressed data on dir entries.
  495. Hopefully this fix won't cause any issues on weird zip archives,
  496. because it assumes the low 16-bits of zip external attributes are DOS
  497. attributes (which I believe they always are in practice).
  498. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
  499. internal attributes, just the filename and external attributes
  500. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  501. - Added cmake support for Linux builds which builds all the examples,
  502. tested with clang v3.3 and gcc v4.6.
  503. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  504. - Merged MZ_FORCEINLINE fix from hdeanclark
  505. - Fix <time.h> include before config #ifdef, thanks emil.brink
  506. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
  507. (super useful for OpenGL apps), and explicit control over the compression
  508. level (so you can
  509. set it to 1 for real-time compression).
  510. - Merged in some compiler fixes from paulharris's github repro.
  511. - Retested this build under Windows (VS 2010, including static analysis),
  512. tcc 0.9.26, gcc v4.6 and clang v3.3.
  513. - Added example6.c, which dumps an image of the mandelbrot set to a PNG
  514. file.
  515. - Modified example2 to help test the
  516. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  517. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
  518. possible src file fclose() leak if alignment bytes+local header file write
  519. faiiled
  520. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
  521. Was pushing the wrong central dir header offset, appears harmless in this
  522. release, but it became a problem in the zip64 branch
  523. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
  524. #include <time.h> (thanks fermtect).
  525. 5/19/12 v1.13 - From [email protected] and [email protected] - Fix
  526. mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  527. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
  528. re-ran a randomized regression test on ~500k files.
  529. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  530. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
  531. (static analysis) option and fixed all warnings (except for the silly
  532. "Use of the comma-operator in a tested expression.." analysis warning,
  533. which I purposely use to work around a MSVC compiler warning).
  534. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
  535. tested Linux executables. The codeblocks workspace is compatible with
  536. Linux+Win32/x64.
  537. - Added miniz_tester solution/project, which is a useful little app
  538. derived from LZHAM's tester app that I use as part of the regression test.
  539. - Ran miniz.c and tinfl.c through another series of regression testing on
  540. ~500,000 files and archives.
  541. - Modified example5.c so it purposely disables a bunch of high-level
  542. functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
  543. MINIZ_NO_STDIO bug report.)
  544. - Fix ftell() usage in examples so they exit with an error on files which
  545. are too large (a limitation of the examples, not miniz itself).
  546. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
  547. minor level_and_flags issues in the archive API's.
  548. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
  549. Dawson <[email protected]> for the feedback/bug report.
  550. 5/28/11 v1.11 - Added statement from unlicense.org
  551. 5/27/11 v1.10 - Substantial compressor optimizations:
  552. - Level 1 is now ~4x faster than before. The L1 compressor's throughput
  553. now varies between 70-110MB/sec. on a
  554. - Core i7 (actual throughput varies depending on the type of data, and x64
  555. vs. x86).
  556. - Improved baseline L2-L9 compression perf. Also, greatly improved
  557. compression perf. issues on some file types.
  558. - Refactored the compression code for better readability and
  559. maintainability.
  560. - Added level 10 compression level (L10 has slightly better ratio than
  561. level 9, but could have a potentially large
  562. drop in throughput on some files).
  563. 5/15/11 v1.09 - Initial stable release.
  564. * Low-level Deflate/Inflate implementation notes:
  565. Compression: Use the "tdefl" API's. The compressor supports raw, static,
  566. and dynamic blocks, lazy or
  567. greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
  568. It performs and compresses
  569. approximately as well as zlib.
  570. Decompression: Use the "tinfl" API's. The entire decompressor is
  571. implemented as a single function
  572. coroutine: see tinfl_decompress(). It supports decompression into a 32KB
  573. (or larger power of 2) wrapping buffer, or into a memory
  574. block large enough to hold the entire file.
  575. The low-level tdefl/tinfl API's do not make any use of dynamic memory
  576. allocation.
  577. * zlib-style API notes:
  578. miniz.c implements a fairly large subset of zlib. There's enough
  579. functionality present for it to be a drop-in
  580. zlib replacement in many apps:
  581. The z_stream struct, optional memory allocation callbacks
  582. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  583. inflateInit/inflateInit2/inflate/inflateEnd
  584. compress, compress2, compressBound, uncompress
  585. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
  586. routines.
  587. Supports raw deflate streams or standard zlib streams with adler-32
  588. checking.
  589. Limitations:
  590. The callback API's are not implemented yet. No support for gzip headers or
  591. zlib static dictionaries.
  592. I've tried to closely emulate zlib's various flavors of stream flushing
  593. and return status codes, but
  594. there are no guarantees that miniz.c pulls this off perfectly.
  595. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
  596. originally written by
  597. Alex Evans. Supports 1-4 bytes/pixel images.
  598. * ZIP archive API notes:
  599. The ZIP archive API's where designed with simplicity and efficiency in
  600. mind, with just enough abstraction to
  601. get the job done with minimal fuss. There are simple API's to retrieve file
  602. information, read files from
  603. existing archives, create new archives, append new files to existing
  604. archives, or clone archive data from
  605. one archive to another. It supports archives located in memory or the heap,
  606. on disk (using stdio.h),
  607. or you can specify custom file read/write callbacks.
  608. - Archive reading: Just call this function to read a single file from a
  609. disk archive:
  610. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
  611. char *pArchive_name,
  612. size_t *pSize, mz_uint zip_flags);
  613. For more complex cases, use the "mz_zip_reader" functions. Upon opening an
  614. archive, the entire central
  615. directory is located and read as-is into memory, and subsequent file access
  616. only occurs when reading individual files.
  617. - Archives file scanning: The simple way is to use this function to scan a
  618. loaded archive for a specific file:
  619. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  620. const char *pComment, mz_uint flags);
  621. The locate operation can optionally check file comments too, which (as one
  622. example) can be used to identify
  623. multiple versions of the same file in an archive. This function uses a
  624. simple linear search through the central
  625. directory, so it's not very fast.
  626. Alternately, you can iterate through all the files in an archive (using
  627. mz_zip_reader_get_num_files()) and
  628. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  629. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
  630. immediately writes compressed file data
  631. to disk and builds an exact image of the central directory in memory. The
  632. central directory image is written
  633. all at once at the end of the archive file when the archive is finalized.
  634. The archive writer can optionally align each file's local header and file
  635. data to any power of 2 alignment,
  636. which can be useful when the archive will be read from optical media. Also,
  637. the writer supports placing
  638. arbitrary data blobs at the very beginning of ZIP archives. Archives
  639. written using either feature are still
  640. readable by any ZIP tool.
  641. - Archive appending: The simple way to add a single file to an archive is
  642. to call this function:
  643. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
  644. const char *pArchive_name,
  645. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
  646. comment_size, mz_uint level_and_flags);
  647. The archive will be created if it doesn't already exist, otherwise it'll be
  648. appended to.
  649. Note the appending is done in-place and is not an atomic operation, so if
  650. something goes wrong
  651. during the operation it's possible the archive could be left without a
  652. central directory (although the local
  653. file headers and file data will be fine, so the archive will be
  654. recoverable).
  655. For more complex archive modification scenarios:
  656. 1. The safest way is to use a mz_zip_reader to read the existing archive,
  657. cloning only those bits you want to
  658. preserve into a new archive using using the
  659. mz_zip_writer_add_from_zip_reader() function (which compiles the
  660. compressed file data as-is). When you're done, delete the old archive and
  661. rename the newly written archive, and
  662. you're done. This is safe but requires a bunch of temporary disk space or
  663. heap memory.
  664. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
  665. mz_zip_writer_init_from_reader(),
  666. append new files as needed, then finalize the archive which will write an
  667. updated central directory to the
  668. original archive. (This is basically what
  669. mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  670. possibility that the archive's central directory could be lost with this
  671. method if anything goes wrong, though.
  672. - ZIP archive support limitations:
  673. No zip64 or spanning support. Extraction functions can only handle
  674. unencrypted, stored or deflated files.
  675. Requires streams capable of seeking.
  676. * This is a header file library, like stb_image.c. To get only a header file,
  677. either cut and paste the
  678. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
  679. include miniz.c from it.
  680. * Important: For best perf. be sure to customize the below macros for your
  681. target platform:
  682. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  683. #define MINIZ_LITTLE_ENDIAN 1
  684. #define MINIZ_HAS_64BIT_REGISTERS 1
  685. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
  686. including miniz.c to ensure miniz
  687. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
  688. able to process large files
  689. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  690. */
  691. #ifndef MINIZ_HEADER_INCLUDED
  692. #define MINIZ_HEADER_INCLUDED
  693. //#include <stdlib.h>
  694. // Defines to completely disable specific portions of miniz.c:
  695. // If all macros here are defined the only functionality remaining will be
  696. // CRC-32, adler-32, tinfl, and tdefl.
  697. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
  698. // stdio for file I/O.
  699. //#define MINIZ_NO_STDIO
  700. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
  701. // to get the current time, or
  702. // get/set file times, and the C run-time funcs that get/set times won't be
  703. // called.
  704. // The current downside is the times written to your archives will be from 1979.
  705. #define MINIZ_NO_TIME
  706. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  707. #define MINIZ_NO_ARCHIVE_APIS
  708. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
  709. // API's.
  710. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  711. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
  712. // API's.
  713. //#define MINIZ_NO_ZLIB_APIS
  714. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
  715. // conflicts against stock zlib.
  716. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  717. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  718. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
  719. // user alloc/free/realloc
  720. // callbacks to the zlib and archive API's, and a few stand-alone helper API's
  721. // which don't provide custom user
  722. // functions (such as tdefl_compress_mem_to_heap() and
  723. // tinfl_decompress_mem_to_heap()) won't work.
  724. //#define MINIZ_NO_MALLOC
  725. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  726. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
  727. // on Linux
  728. #define MINIZ_NO_TIME
  729. #endif
  730. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  731. //#include <time.h>
  732. #endif
  733. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
  734. defined(__i386) || defined(__i486__) || defined(__i486) || \
  735. defined(i386) || defined(__ia64__) || defined(__x86_64__)
  736. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  737. #define MINIZ_X86_OR_X64_CPU 1
  738. #endif
  739. #if defined(__sparcv9)
  740. // Big endian
  741. #else
  742. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  743. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  744. #define MINIZ_LITTLE_ENDIAN 1
  745. #endif
  746. #endif
  747. #if MINIZ_X86_OR_X64_CPU
  748. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
  749. // integer loads and stores from unaligned addresses.
  750. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  751. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
  752. 0 // disable to suppress compiler warnings
  753. #endif
  754. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
  755. defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
  756. defined(__x86_64__)
  757. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
  758. // reasonably fast (and don't involve compiler generated calls to helper
  759. // functions).
  760. #define MINIZ_HAS_64BIT_REGISTERS 1
  761. #endif
  762. #ifdef __cplusplus
  763. extern "C" {
  764. #endif
  765. // ------------------- zlib-style API Definitions.
  766. // For more compatibility with zlib, miniz.c uses unsigned long for some
  767. // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  768. typedef unsigned long mz_ulong;
  769. // mz_free() internally uses the MZ_FREE() macro (which by default calls free()
  770. // unless you've modified the MZ_MALLOC macro) to release a block allocated from
  771. // the heap.
  772. void mz_free(void *p);
  773. #define MZ_ADLER32_INIT (1)
  774. // mz_adler32() returns the initial adler-32 value to use when called with
  775. // ptr==NULL.
  776. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  777. #define MZ_CRC32_INIT (0)
  778. // mz_crc32() returns the initial CRC-32 value to use when called with
  779. // ptr==NULL.
  780. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  781. // Compression strategies.
  782. enum {
  783. MZ_DEFAULT_STRATEGY = 0,
  784. MZ_FILTERED = 1,
  785. MZ_HUFFMAN_ONLY = 2,
  786. MZ_RLE = 3,
  787. MZ_FIXED = 4
  788. };
  789. // Method
  790. #define MZ_DEFLATED 8
  791. #ifndef MINIZ_NO_ZLIB_APIS
  792. // Heap allocation callbacks.
  793. // Note that mz_alloc_func parameter types purpsosely differ from zlib's:
  794. // items/size is size_t, not unsigned long.
  795. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  796. typedef void (*mz_free_func)(void *opaque, void *address);
  797. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
  798. size_t size);
  799. #define MZ_VERSION "9.1.15"
  800. #define MZ_VERNUM 0x91F0
  801. #define MZ_VER_MAJOR 9
  802. #define MZ_VER_MINOR 1
  803. #define MZ_VER_REVISION 15
  804. #define MZ_VER_SUBREVISION 0
  805. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
  806. // other values are for advanced use (refer to the zlib docs).
  807. enum {
  808. MZ_NO_FLUSH = 0,
  809. MZ_PARTIAL_FLUSH = 1,
  810. MZ_SYNC_FLUSH = 2,
  811. MZ_FULL_FLUSH = 3,
  812. MZ_FINISH = 4,
  813. MZ_BLOCK = 5
  814. };
  815. // Return status codes. MZ_PARAM_ERROR is non-standard.
  816. enum {
  817. MZ_OK = 0,
  818. MZ_STREAM_END = 1,
  819. MZ_NEED_DICT = 2,
  820. MZ_ERRNO = -1,
  821. MZ_STREAM_ERROR = -2,
  822. MZ_DATA_ERROR = -3,
  823. MZ_MEM_ERROR = -4,
  824. MZ_BUF_ERROR = -5,
  825. MZ_VERSION_ERROR = -6,
  826. MZ_PARAM_ERROR = -10000
  827. };
  828. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best
  829. // possible compression (not zlib compatible, and may be very slow),
  830. // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  831. enum {
  832. MZ_NO_COMPRESSION = 0,
  833. MZ_BEST_SPEED = 1,
  834. MZ_BEST_COMPRESSION = 9,
  835. MZ_UBER_COMPRESSION = 10,
  836. MZ_DEFAULT_LEVEL = 6,
  837. MZ_DEFAULT_COMPRESSION = -1
  838. };
  839. // Window bits
  840. #define MZ_DEFAULT_WINDOW_BITS 15
  841. struct mz_internal_state;
  842. // Compression/decompression stream struct.
  843. typedef struct mz_stream_s {
  844. const unsigned char *next_in; // pointer to next byte to read
  845. unsigned int avail_in; // number of bytes available at next_in
  846. mz_ulong total_in; // total number of bytes consumed so far
  847. unsigned char *next_out; // pointer to next byte to write
  848. unsigned int avail_out; // number of bytes that can be written to next_out
  849. mz_ulong total_out; // total number of bytes produced so far
  850. char *msg; // error msg (unused)
  851. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  852. mz_alloc_func
  853. zalloc; // optional heap allocation function (defaults to malloc)
  854. mz_free_func zfree; // optional heap free function (defaults to free)
  855. void *opaque; // heap alloc function user pointer
  856. int data_type; // data_type (unused)
  857. mz_ulong adler; // adler32 of the source or uncompressed data
  858. mz_ulong reserved; // not used
  859. } mz_stream;
  860. typedef mz_stream *mz_streamp;
  861. // Returns the version string of miniz.c.
  862. const char *mz_version(void);
  863. // mz_deflateInit() initializes a compressor with default options:
  864. // Parameters:
  865. // pStream must point to an initialized mz_stream struct.
  866. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  867. // level 1 enables a specially optimized compression function that's been
  868. // optimized purely for performance, not ratio.
  869. // (This special func. is currently only enabled when
  870. // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  871. // Return values:
  872. // MZ_OK on success.
  873. // MZ_STREAM_ERROR if the stream is bogus.
  874. // MZ_PARAM_ERROR if the input parameters are bogus.
  875. // MZ_MEM_ERROR on out of memory.
  876. int mz_deflateInit(mz_streamp pStream, int level);
  877. // mz_deflateInit2() is like mz_deflate(), except with more control:
  878. // Additional parameters:
  879. // method must be MZ_DEFLATED
  880. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
  881. // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
  882. // header or footer)
  883. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  884. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  885. int mem_level, int strategy);
  886. // Quickly resets a compressor without having to reallocate anything. Same as
  887. // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  888. int mz_deflateReset(mz_streamp pStream);
  889. // mz_deflate() compresses the input to output, consuming as much of the input
  890. // and producing as much output as possible.
  891. // Parameters:
  892. // pStream is the stream to read from and write to. You must initialize/update
  893. // the next_in, avail_in, next_out, and avail_out members.
  894. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
  895. // MZ_FINISH.
  896. // Return values:
  897. // MZ_OK on success (when flushing, or if more input is needed but not
  898. // available, and/or there's more output to be written but the output buffer
  899. // is full).
  900. // MZ_STREAM_END if all input has been consumed and all output bytes have been
  901. // written. Don't call mz_deflate() on the stream anymore.
  902. // MZ_STREAM_ERROR if the stream is bogus.
  903. // MZ_PARAM_ERROR if one of the parameters is invalid.
  904. // MZ_BUF_ERROR if no forward progress is possible because the input and/or
  905. // output buffers are empty. (Fill up the input buffer or free up some output
  906. // space and try again.)
  907. int mz_deflate(mz_streamp pStream, int flush);
  908. // mz_deflateEnd() deinitializes a compressor:
  909. // Return values:
  910. // MZ_OK on success.
  911. // MZ_STREAM_ERROR if the stream is bogus.
  912. int mz_deflateEnd(mz_streamp pStream);
  913. // mz_deflateBound() returns a (very) conservative upper bound on the amount of
  914. // data that could be generated by deflate(), assuming flush is set to only
  915. // MZ_NO_FLUSH or MZ_FINISH.
  916. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  917. // Single-call compression functions mz_compress() and mz_compress2():
  918. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on
  919. // failure.
  920. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  921. const unsigned char *pSource, mz_ulong source_len);
  922. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  923. const unsigned char *pSource, mz_ulong source_len, int level);
  924. // mz_compressBound() returns a (very) conservative upper bound on the amount of
  925. // data that could be generated by calling mz_compress().
  926. mz_ulong mz_compressBound(mz_ulong source_len);
  927. // Initializes a decompressor.
  928. int mz_inflateInit(mz_streamp pStream);
  929. // mz_inflateInit2() is like mz_inflateInit() with an additional option that
  930. // controls the window size and whether or not the stream has been wrapped with
  931. // a zlib header/footer:
  932. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
  933. // -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  934. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  935. // Decompresses the input stream to the output, consuming only as much of the
  936. // input as needed, and writing as much to the output as possible.
  937. // Parameters:
  938. // pStream is the stream to read from and write to. You must initialize/update
  939. // the next_in, avail_in, next_out, and avail_out members.
  940. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  941. // On the first call, if flush is MZ_FINISH it's assumed the input and output
  942. // buffers are both sized large enough to decompress the entire stream in a
  943. // single call (this is slightly faster).
  944. // MZ_FINISH implies that there are no more source bytes available beside
  945. // what's already in the input buffer, and that the output buffer is large
  946. // enough to hold the rest of the decompressed data.
  947. // Return values:
  948. // MZ_OK on success. Either more input is needed but not available, and/or
  949. // there's more output to be written but the output buffer is full.
  950. // MZ_STREAM_END if all needed input has been consumed and all output bytes
  951. // have been written. For zlib streams, the adler-32 of the decompressed data
  952. // has also been verified.
  953. // MZ_STREAM_ERROR if the stream is bogus.
  954. // MZ_DATA_ERROR if the deflate stream is invalid.
  955. // MZ_PARAM_ERROR if one of the parameters is invalid.
  956. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is
  957. // empty but the inflater needs more input to continue, or if the output
  958. // buffer is not large enough. Call mz_inflate() again
  959. // with more input data, or with more room in the output buffer (except when
  960. // using single call decompression, described above).
  961. int mz_inflate(mz_streamp pStream, int flush);
  962. // Deinitializes a decompressor.
  963. int mz_inflateEnd(mz_streamp pStream);
  964. // Single-call decompression.
  965. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on
  966. // failure.
  967. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  968. const unsigned char *pSource, mz_ulong source_len);
  969. // Returns a string description of the specified error code, or NULL if the
  970. // error code is invalid.
  971. const char *mz_error(int err);
  972. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
  973. // as a drop-in replacement for the subset of zlib that miniz.c supports.
  974. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
  975. // use zlib in the same project.
  976. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  977. typedef unsigned char Byte;
  978. typedef unsigned int uInt;
  979. typedef mz_ulong uLong;
  980. typedef Byte Bytef;
  981. typedef uInt uIntf;
  982. typedef char charf;
  983. typedef int intf;
  984. typedef void *voidpf;
  985. typedef uLong uLongf;
  986. typedef void *voidp;
  987. typedef void *const voidpc;
  988. #define Z_NULL 0
  989. #define Z_NO_FLUSH MZ_NO_FLUSH
  990. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  991. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  992. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  993. #define Z_FINISH MZ_FINISH
  994. #define Z_BLOCK MZ_BLOCK
  995. #define Z_OK MZ_OK
  996. #define Z_STREAM_END MZ_STREAM_END
  997. #define Z_NEED_DICT MZ_NEED_DICT
  998. #define Z_ERRNO MZ_ERRNO
  999. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  1000. #define Z_DATA_ERROR MZ_DATA_ERROR
  1001. #define Z_MEM_ERROR MZ_MEM_ERROR
  1002. #define Z_BUF_ERROR MZ_BUF_ERROR
  1003. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  1004. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  1005. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  1006. #define Z_BEST_SPEED MZ_BEST_SPEED
  1007. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  1008. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  1009. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  1010. #define Z_FILTERED MZ_FILTERED
  1011. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  1012. #define Z_RLE MZ_RLE
  1013. #define Z_FIXED MZ_FIXED
  1014. #define Z_DEFLATED MZ_DEFLATED
  1015. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  1016. #define alloc_func mz_alloc_func
  1017. #define free_func mz_free_func
  1018. #define internal_state mz_internal_state
  1019. #define z_stream mz_stream
  1020. #define deflateInit mz_deflateInit
  1021. #define deflateInit2 mz_deflateInit2
  1022. #define deflateReset mz_deflateReset
  1023. #define deflate mz_deflate
  1024. #define deflateEnd mz_deflateEnd
  1025. #define deflateBound mz_deflateBound
  1026. #define compress mz_compress
  1027. #define compress2 mz_compress2
  1028. #define compressBound mz_compressBound
  1029. #define inflateInit mz_inflateInit
  1030. #define inflateInit2 mz_inflateInit2
  1031. #define inflate mz_inflate
  1032. #define inflateEnd mz_inflateEnd
  1033. #define uncompress mz_uncompress
  1034. #define crc32 mz_crc32
  1035. #define adler32 mz_adler32
  1036. #define MAX_WBITS 15
  1037. #define MAX_MEM_LEVEL 9
  1038. #define zError mz_error
  1039. #define ZLIB_VERSION MZ_VERSION
  1040. #define ZLIB_VERNUM MZ_VERNUM
  1041. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  1042. #define ZLIB_VER_MINOR MZ_VER_MINOR
  1043. #define ZLIB_VER_REVISION MZ_VER_REVISION
  1044. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  1045. #define zlibVersion mz_version
  1046. #define zlib_version mz_version()
  1047. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  1048. #endif // MINIZ_NO_ZLIB_APIS
  1049. // ------------------- Types and macros
  1050. typedef unsigned char mz_uint8;
  1051. typedef signed short mz_int16;
  1052. typedef unsigned short mz_uint16;
  1053. typedef unsigned int mz_uint32;
  1054. typedef unsigned int mz_uint;
  1055. typedef long long mz_int64;
  1056. typedef unsigned long long mz_uint64;
  1057. typedef int mz_bool;
  1058. #define MZ_FALSE (0)
  1059. #define MZ_TRUE (1)
  1060. // An attempt to work around MSVC's spammy "warning C4127: conditional
  1061. // expression is constant" message.
  1062. #ifdef _MSC_VER
  1063. #define MZ_MACRO_END while (0, 0)
  1064. #else
  1065. #define MZ_MACRO_END while (0)
  1066. #endif
  1067. // ------------------- ZIP archive reading/writing
  1068. #ifndef MINIZ_NO_ARCHIVE_APIS
  1069. enum {
  1070. MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
  1071. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  1072. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  1073. };
  1074. typedef struct {
  1075. mz_uint32 m_file_index;
  1076. mz_uint32 m_central_dir_ofs;
  1077. mz_uint16 m_version_made_by;
  1078. mz_uint16 m_version_needed;
  1079. mz_uint16 m_bit_flag;
  1080. mz_uint16 m_method;
  1081. #ifndef MINIZ_NO_TIME
  1082. time_t m_time;
  1083. #endif
  1084. mz_uint32 m_crc32;
  1085. mz_uint64 m_comp_size;
  1086. mz_uint64 m_uncomp_size;
  1087. mz_uint16 m_internal_attr;
  1088. mz_uint32 m_external_attr;
  1089. mz_uint64 m_local_header_ofs;
  1090. mz_uint32 m_comment_size;
  1091. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  1092. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  1093. } mz_zip_archive_file_stat;
  1094. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
  1095. void *pBuf, size_t n);
  1096. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
  1097. const void *pBuf, size_t n);
  1098. struct mz_zip_internal_state_tag;
  1099. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  1100. typedef enum {
  1101. MZ_ZIP_MODE_INVALID = 0,
  1102. MZ_ZIP_MODE_READING = 1,
  1103. MZ_ZIP_MODE_WRITING = 2,
  1104. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  1105. } mz_zip_mode;
  1106. typedef struct mz_zip_archive_tag {
  1107. mz_uint64 m_archive_size;
  1108. mz_uint64 m_central_directory_file_ofs;
  1109. mz_uint m_total_files;
  1110. mz_zip_mode m_zip_mode;
  1111. mz_uint m_file_offset_alignment;
  1112. mz_alloc_func m_pAlloc;
  1113. mz_free_func m_pFree;
  1114. mz_realloc_func m_pRealloc;
  1115. void *m_pAlloc_opaque;
  1116. mz_file_read_func m_pRead;
  1117. mz_file_write_func m_pWrite;
  1118. void *m_pIO_opaque;
  1119. mz_zip_internal_state *m_pState;
  1120. } mz_zip_archive;
  1121. typedef enum {
  1122. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  1123. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  1124. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  1125. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  1126. } mz_zip_flags;
  1127. // ZIP archive reading
  1128. // Inits a ZIP archive reader.
  1129. // These functions read and validate the archive's central directory.
  1130. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  1131. mz_uint32 flags);
  1132. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  1133. size_t size, mz_uint32 flags);
  1134. #ifndef MINIZ_NO_STDIO
  1135. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  1136. mz_uint32 flags);
  1137. #endif
  1138. // Returns the total number of files in the archive.
  1139. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  1140. // Returns detailed information about an archive file entry.
  1141. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  1142. mz_zip_archive_file_stat *pStat);
  1143. // Determines if an archive file entry is a directory entry.
  1144. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  1145. mz_uint file_index);
  1146. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  1147. mz_uint file_index);
  1148. // Retrieves the filename of an archive file entry.
  1149. // Returns the number of bytes written to pFilename, or if filename_buf_size is
  1150. // 0 this function returns the number of bytes needed to fully store the
  1151. // filename.
  1152. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  1153. char *pFilename, mz_uint filename_buf_size);
  1154. // Attempts to locates a file in the archive's central directory.
  1155. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  1156. // Returns -1 if the file cannot be found.
  1157. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  1158. const char *pComment, mz_uint flags);
  1159. // Extracts a archive file to a memory buffer using no memory allocation.
  1160. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  1161. mz_uint file_index, void *pBuf,
  1162. size_t buf_size, mz_uint flags,
  1163. void *pUser_read_buf,
  1164. size_t user_read_buf_size);
  1165. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  1166. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  1167. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  1168. // Extracts a archive file to a memory buffer.
  1169. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  1170. void *pBuf, size_t buf_size,
  1171. mz_uint flags);
  1172. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  1173. const char *pFilename, void *pBuf,
  1174. size_t buf_size, mz_uint flags);
  1175. // Extracts a archive file to a dynamically allocated heap buffer.
  1176. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  1177. size_t *pSize, mz_uint flags);
  1178. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  1179. const char *pFilename, size_t *pSize,
  1180. mz_uint flags);
  1181. // Extracts a archive file using a callback function to output the file's data.
  1182. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  1183. mz_uint file_index,
  1184. mz_file_write_func pCallback,
  1185. void *pOpaque, mz_uint flags);
  1186. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  1187. const char *pFilename,
  1188. mz_file_write_func pCallback,
  1189. void *pOpaque, mz_uint flags);
  1190. #ifndef MINIZ_NO_STDIO
  1191. // Extracts a archive file to a disk file and sets its last accessed and
  1192. // modified times.
  1193. // This function only extracts files, not archive directory records.
  1194. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  1195. const char *pDst_filename, mz_uint flags);
  1196. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  1197. const char *pArchive_filename,
  1198. const char *pDst_filename,
  1199. mz_uint flags);
  1200. #endif
  1201. // Ends archive reading, freeing all allocations, and closing the input archive
  1202. // file if mz_zip_reader_init_file() was used.
  1203. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  1204. // ZIP archive writing
  1205. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1206. // Inits a ZIP archive writer.
  1207. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  1208. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  1209. size_t size_to_reserve_at_beginning,
  1210. size_t initial_allocation_size);
  1211. #ifndef MINIZ_NO_STDIO
  1212. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  1213. mz_uint64 size_to_reserve_at_beginning);
  1214. #endif
  1215. // Converts a ZIP archive reader object into a writer object, to allow efficient
  1216. // in-place file appends to occur on an existing archive.
  1217. // For archives opened using mz_zip_reader_init_file, pFilename must be the
  1218. // archive's filename so it can be reopened for writing. If the file can't be
  1219. // reopened, mz_zip_reader_end() will be called.
  1220. // For archives opened using mz_zip_reader_init_mem, the memory block must be
  1221. // growable using the realloc callback (which defaults to realloc unless you've
  1222. // overridden it).
  1223. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
  1224. // user provided m_pWrite function cannot be NULL.
  1225. // Note: In-place archive modification is not recommended unless you know what
  1226. // you're doing, because if execution stops or something goes wrong before
  1227. // the archive is finalized the file's central directory will be hosed.
  1228. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  1229. const char *pFilename);
  1230. // Adds the contents of a memory buffer to an archive. These functions record
  1231. // the current local time into the archive.
  1232. // To add a directory entry, call this method with an archive name ending in a
  1233. // forwardslash with empty buffer.
  1234. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1235. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1236. // just set to MZ_DEFAULT_COMPRESSION.
  1237. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  1238. const void *pBuf, size_t buf_size,
  1239. mz_uint level_and_flags);
  1240. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  1241. const char *pArchive_name, const void *pBuf,
  1242. size_t buf_size, const void *pComment,
  1243. mz_uint16 comment_size,
  1244. mz_uint level_and_flags, mz_uint64 uncomp_size,
  1245. mz_uint32 uncomp_crc32);
  1246. #ifndef MINIZ_NO_STDIO
  1247. // Adds the contents of a disk file to an archive. This function also records
  1248. // the disk file's modified time into the archive.
  1249. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1250. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1251. // just set to MZ_DEFAULT_COMPRESSION.
  1252. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  1253. const char *pSrc_filename, const void *pComment,
  1254. mz_uint16 comment_size, mz_uint level_and_flags);
  1255. #endif
  1256. // Adds a file to an archive by fully cloning the data from another archive.
  1257. // This function fully clones the source file's compressed data (no
  1258. // recompression), along with its full filename, extra data, and comment fields.
  1259. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  1260. mz_zip_archive *pSource_zip,
  1261. mz_uint file_index);
  1262. // Finalizes the archive by writing the central directory records followed by
  1263. // the end of central directory record.
  1264. // After an archive is finalized, the only valid call on the mz_zip_archive
  1265. // struct is mz_zip_writer_end().
  1266. // An archive must be manually finalized by calling this function for it to be
  1267. // valid.
  1268. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  1269. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  1270. size_t *pSize);
  1271. // Ends archive writing, freeing all allocations, and closing the output file if
  1272. // mz_zip_writer_init_file() was used.
  1273. // Note for the archive to be valid, it must have been finalized before ending.
  1274. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  1275. // Misc. high-level helper functions:
  1276. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
  1277. // appends a memory blob to a ZIP archive.
  1278. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1279. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1280. // just set to MZ_DEFAULT_COMPRESSION.
  1281. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  1282. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  1283. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  1284. mz_uint level_and_flags);
  1285. // Reads a single file from an archive into a heap block.
  1286. // Returns NULL on failure.
  1287. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  1288. const char *pArchive_name,
  1289. size_t *pSize, mz_uint zip_flags);
  1290. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1291. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  1292. // ------------------- Low-level Decompression API Definitions
  1293. // Decompression flags used by tinfl_decompress().
  1294. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
  1295. // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
  1296. // input is a raw deflate stream.
  1297. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
  1298. // beyond the end of the supplied input buffer. If clear, the input buffer
  1299. // contains all remaining input.
  1300. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
  1301. // enough to hold the entire decompressed stream. If clear, the output buffer is
  1302. // at least the size of the dictionary (typically 32KB).
  1303. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
  1304. // decompressed bytes.
  1305. enum {
  1306. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  1307. TINFL_FLAG_HAS_MORE_INPUT = 2,
  1308. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  1309. TINFL_FLAG_COMPUTE_ADLER32 = 8
  1310. };
  1311. // High level decompression functions:
  1312. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
  1313. // allocated via malloc().
  1314. // On entry:
  1315. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
  1316. // to decompress.
  1317. // On return:
  1318. // Function returns a pointer to the decompressed data, or NULL on failure.
  1319. // *pOut_len will be set to the decompressed data's size, which could be larger
  1320. // than src_buf_len on uncompressible data.
  1321. // The caller must call mz_free() on the returned block when it's no longer
  1322. // needed.
  1323. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1324. size_t *pOut_len, int flags);
  1325. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
  1326. // in memory.
  1327. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
  1328. // written on success.
  1329. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  1330. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1331. const void *pSrc_buf, size_t src_buf_len,
  1332. int flags);
  1333. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an
  1334. // internal 32KB buffer, and a user provided callback function will be called to
  1335. // flush the buffer.
  1336. // Returns 1 on success or 0 on failure.
  1337. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
  1338. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  1339. tinfl_put_buf_func_ptr pPut_buf_func,
  1340. void *pPut_buf_user, int flags);
  1341. struct tinfl_decompressor_tag;
  1342. typedef struct tinfl_decompressor_tag tinfl_decompressor;
  1343. // Max size of LZ dictionary.
  1344. #define TINFL_LZ_DICT_SIZE 32768
  1345. // Return status.
  1346. typedef enum {
  1347. TINFL_STATUS_BAD_PARAM = -3,
  1348. TINFL_STATUS_ADLER32_MISMATCH = -2,
  1349. TINFL_STATUS_FAILED = -1,
  1350. TINFL_STATUS_DONE = 0,
  1351. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  1352. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  1353. } tinfl_status;
  1354. // Initializes the decompressor to its initial state.
  1355. #define tinfl_init(r) \
  1356. do { \
  1357. (r)->m_state = 0; \
  1358. } \
  1359. MZ_MACRO_END
  1360. #define tinfl_get_adler32(r) (r)->m_check_adler32
  1361. // Main low-level decompressor coroutine function. This is the only function
  1362. // actually needed for decompression. All the other functions are just
  1363. // high-level helpers for improved usability.
  1364. // This is a universal API, i.e. it can be used as a building block to build any
  1365. // desired higher level decompression API. In the limit case, it can be called
  1366. // once per every byte input or output.
  1367. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  1368. const mz_uint8 *pIn_buf_next,
  1369. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  1370. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  1371. const mz_uint32 decomp_flags);
  1372. // Internal/private bits follow.
  1373. enum {
  1374. TINFL_MAX_HUFF_TABLES = 3,
  1375. TINFL_MAX_HUFF_SYMBOLS_0 = 288,
  1376. TINFL_MAX_HUFF_SYMBOLS_1 = 32,
  1377. TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  1378. TINFL_FAST_LOOKUP_BITS = 10,
  1379. TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  1380. };
  1381. typedef struct {
  1382. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  1383. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
  1384. m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  1385. } tinfl_huff_table;
  1386. #if MINIZ_HAS_64BIT_REGISTERS
  1387. #define TINFL_USE_64BIT_BITBUF 1
  1388. #endif
  1389. #if TINFL_USE_64BIT_BITBUF
  1390. typedef mz_uint64 tinfl_bit_buf_t;
  1391. #define TINFL_BITBUF_SIZE (64)
  1392. #else
  1393. typedef mz_uint32 tinfl_bit_buf_t;
  1394. #define TINFL_BITBUF_SIZE (32)
  1395. #endif
  1396. struct tinfl_decompressor_tag {
  1397. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
  1398. m_check_adler32, m_dist, m_counter, m_num_extra,
  1399. m_table_sizes[TINFL_MAX_HUFF_TABLES];
  1400. tinfl_bit_buf_t m_bit_buf;
  1401. size_t m_dist_from_out_buf_start;
  1402. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  1403. mz_uint8 m_raw_header[4],
  1404. m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  1405. };
  1406. // ------------------- Low-level Compression API Definitions
  1407. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
  1408. // slower, and raw/dynamic blocks will be output more frequently).
  1409. #define TDEFL_LESS_MEMORY 0
  1410. // tdefl_init() compression flags logically OR'd together (low 12 bits contain
  1411. // the max. number of probes per dictionary search):
  1412. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
  1413. // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
  1414. // compression), 4095=Huffman+LZ (slowest/best compression).
  1415. enum {
  1416. TDEFL_HUFFMAN_ONLY = 0,
  1417. TDEFL_DEFAULT_MAX_PROBES = 128,
  1418. TDEFL_MAX_PROBES_MASK = 0xFFF
  1419. };
  1420. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
  1421. // the deflate data, and the Adler-32 of the source data at the end. Otherwise,
  1422. // you'll get raw deflate data.
  1423. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
  1424. // when not writing zlib headers).
  1425. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
  1426. // efficient lazy parsing.
  1427. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
  1428. // initialization time to the minimum, but the output may vary from run to run
  1429. // given the same input (depending on the contents of memory).
  1430. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  1431. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  1432. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  1433. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  1434. // The low 12 bits are reserved to control the max # of hash probes per
  1435. // dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  1436. enum {
  1437. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  1438. TDEFL_COMPUTE_ADLER32 = 0x02000,
  1439. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  1440. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  1441. TDEFL_RLE_MATCHES = 0x10000,
  1442. TDEFL_FILTER_MATCHES = 0x20000,
  1443. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  1444. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  1445. };
  1446. // High level compression functions:
  1447. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
  1448. // allocated via malloc().
  1449. // On entry:
  1450. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  1451. // flags: The max match finder probes (default is 128) logically OR'd against
  1452. // the above flags. Higher probes are slower but improve compression.
  1453. // On return:
  1454. // Function returns a pointer to the compressed data, or NULL on failure.
  1455. // *pOut_len will be set to the compressed data's size, which could be larger
  1456. // than src_buf_len on uncompressible data.
  1457. // The caller must free() the returned block when it's no longer needed.
  1458. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1459. size_t *pOut_len, int flags);
  1460. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in
  1461. // memory.
  1462. // Returns 0 on failure.
  1463. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1464. const void *pSrc_buf, size_t src_buf_len,
  1465. int flags);
  1466. // Compresses an image to a compressed PNG file in memory.
  1467. // On entry:
  1468. // pImage, w, h, and num_chans describe the image to compress. num_chans may be
  1469. // 1, 2, 3, or 4.
  1470. // The image pitch in bytes per scanline will be w*num_chans. The leftmost
  1471. // pixel on the top scanline is stored first in memory.
  1472. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
  1473. // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  1474. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL
  1475. // apps).
  1476. // On return:
  1477. // Function returns a pointer to the compressed data, or NULL on failure.
  1478. // *pLen_out will be set to the size of the PNG image file.
  1479. // The caller must mz_free() the returned heap block (which will typically be
  1480. // larger than *pLen_out) when it's no longer needed.
  1481. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  1482. int h, int num_chans,
  1483. size_t *pLen_out,
  1484. mz_uint level, mz_bool flip);
  1485. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  1486. int num_chans, size_t *pLen_out);
  1487. // Output stream interface. The compressor uses this interface to write
  1488. // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  1489. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
  1490. void *pUser);
  1491. // tdefl_compress_mem_to_output() compresses a block to an output stream. The
  1492. // above helpers use this function internally.
  1493. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  1494. tdefl_put_buf_func_ptr pPut_buf_func,
  1495. void *pPut_buf_user, int flags);
  1496. enum {
  1497. TDEFL_MAX_HUFF_TABLES = 3,
  1498. TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
  1499. TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
  1500. TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
  1501. TDEFL_LZ_DICT_SIZE = 32768,
  1502. TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
  1503. TDEFL_MIN_MATCH_LEN = 3,
  1504. TDEFL_MAX_MATCH_LEN = 258
  1505. };
  1506. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
  1507. // output block (using static/fixed Huffman codes).
  1508. #if TDEFL_LESS_MEMORY
  1509. enum {
  1510. TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
  1511. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1512. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1513. TDEFL_LZ_HASH_BITS = 12,
  1514. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1515. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1516. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1517. };
  1518. #else
  1519. enum {
  1520. TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
  1521. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1522. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1523. TDEFL_LZ_HASH_BITS = 15,
  1524. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1525. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1526. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1527. };
  1528. #endif
  1529. // The low-level tdefl functions below may be used directly if the above helper
  1530. // functions aren't flexible enough. The low-level functions don't make any heap
  1531. // allocations, unlike the above helper functions.
  1532. typedef enum {
  1533. TDEFL_STATUS_BAD_PARAM = -2,
  1534. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  1535. TDEFL_STATUS_OKAY = 0,
  1536. TDEFL_STATUS_DONE = 1
  1537. } tdefl_status;
  1538. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  1539. typedef enum {
  1540. TDEFL_NO_FLUSH = 0,
  1541. TDEFL_SYNC_FLUSH = 2,
  1542. TDEFL_FULL_FLUSH = 3,
  1543. TDEFL_FINISH = 4
  1544. } tdefl_flush;
  1545. // tdefl's compression state structure.
  1546. typedef struct {
  1547. tdefl_put_buf_func_ptr m_pPut_buf_func;
  1548. void *m_pPut_buf_user;
  1549. mz_uint m_flags, m_max_probes[2];
  1550. int m_greedy_parsing;
  1551. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  1552. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  1553. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
  1554. m_bit_buffer;
  1555. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
  1556. m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
  1557. m_wants_to_finish;
  1558. tdefl_status m_prev_return_status;
  1559. const void *m_pIn_buf;
  1560. void *m_pOut_buf;
  1561. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  1562. tdefl_flush m_flush;
  1563. const mz_uint8 *m_pSrc;
  1564. size_t m_src_buf_left, m_out_buf_ofs;
  1565. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  1566. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1567. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1568. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1569. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  1570. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  1571. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  1572. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  1573. } tdefl_compressor;
  1574. // Initializes the compressor.
  1575. // There is no corresponding deinit() function because the tdefl API's do not
  1576. // dynamically allocate memory.
  1577. // pBut_buf_func: If NULL, output data will be supplied to the specified
  1578. // callback. In this case, the user should call the tdefl_compress_buffer() API
  1579. // for compression.
  1580. // If pBut_buf_func is NULL the user should always call the tdefl_compress()
  1581. // API.
  1582. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
  1583. // etc.)
  1584. tdefl_status tdefl_init(tdefl_compressor *d,
  1585. tdefl_put_buf_func_ptr pPut_buf_func,
  1586. void *pPut_buf_user, int flags);
  1587. // Compresses a block of data, consuming as much of the specified input buffer
  1588. // as possible, and writing as much compressed data to the specified output
  1589. // buffer as possible.
  1590. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  1591. size_t *pIn_buf_size, void *pOut_buf,
  1592. size_t *pOut_buf_size, tdefl_flush flush);
  1593. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
  1594. // non-NULL tdefl_put_buf_func_ptr.
  1595. // tdefl_compress_buffer() always consumes the entire input buffer.
  1596. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  1597. size_t in_buf_size, tdefl_flush flush);
  1598. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  1599. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  1600. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
  1601. // defined, because it uses some of its macros.
  1602. #ifndef MINIZ_NO_ZLIB_APIS
  1603. // Create tdefl_compress() flags given zlib-style compression parameters.
  1604. // level may range from [0,10] (where 10 is absolute max compression, but may be
  1605. // much slower on some files)
  1606. // window_bits may be -15 (raw deflate) or 15 (zlib)
  1607. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
  1608. // MZ_RLE, or MZ_FIXED
  1609. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  1610. int strategy);
  1611. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  1612. #ifdef __cplusplus
  1613. }
  1614. #endif
  1615. #endif // MINIZ_HEADER_INCLUDED
  1616. // ------------------- End of Header: Implementation follows. (If you only want
  1617. // the header, define MINIZ_HEADER_FILE_ONLY.)
  1618. #ifndef MINIZ_HEADER_FILE_ONLY
  1619. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
  1620. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
  1621. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
  1622. //#include <assert.h>
  1623. //#include <string.h>
  1624. #define MZ_ASSERT(x) assert(x)
  1625. #ifdef MINIZ_NO_MALLOC
  1626. #define MZ_MALLOC(x) NULL
  1627. #define MZ_FREE(x) (void)x, ((void)0)
  1628. #define MZ_REALLOC(p, x) NULL
  1629. #else
  1630. #define MZ_MALLOC(x) malloc(x)
  1631. #define MZ_FREE(x) free(x)
  1632. #define MZ_REALLOC(p, x) realloc(p, x)
  1633. #endif
  1634. #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
  1635. #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
  1636. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  1637. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1638. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  1639. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  1640. #else
  1641. #define MZ_READ_LE16(p) \
  1642. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1643. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  1644. #define MZ_READ_LE32(p) \
  1645. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1646. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
  1647. ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
  1648. ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  1649. #endif
  1650. #ifdef _MSC_VER
  1651. #define MZ_FORCEINLINE __forceinline
  1652. #elif defined(__GNUC__)
  1653. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  1654. #else
  1655. #define MZ_FORCEINLINE inline
  1656. #endif
  1657. #ifdef __cplusplus
  1658. extern "C" {
  1659. #endif
  1660. // ------------------- zlib-style API's
  1661. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
  1662. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
  1663. size_t block_len = buf_len % 5552;
  1664. if (!ptr) return MZ_ADLER32_INIT;
  1665. while (buf_len) {
  1666. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  1667. s1 += ptr[0], s2 += s1;
  1668. s1 += ptr[1], s2 += s1;
  1669. s1 += ptr[2], s2 += s1;
  1670. s1 += ptr[3], s2 += s1;
  1671. s1 += ptr[4], s2 += s1;
  1672. s1 += ptr[5], s2 += s1;
  1673. s1 += ptr[6], s2 += s1;
  1674. s1 += ptr[7], s2 += s1;
  1675. }
  1676. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1677. s1 %= 65521U, s2 %= 65521U;
  1678. buf_len -= block_len;
  1679. block_len = 5552;
  1680. }
  1681. return (s2 << 16) + s1;
  1682. }
  1683. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
  1684. // implementation that balances processor cache usage against speed":
  1685. // http://www.geocities.com/malbrain/
  1686. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
  1687. static const mz_uint32 s_crc32[16] = {
  1688. 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
  1689. 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
  1690. 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
  1691. mz_uint32 crcu32 = (mz_uint32)crc;
  1692. if (!ptr) return MZ_CRC32_INIT;
  1693. crcu32 = ~crcu32;
  1694. while (buf_len--) {
  1695. mz_uint8 b = *ptr++;
  1696. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
  1697. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
  1698. }
  1699. return ~crcu32;
  1700. }
  1701. void mz_free(void *p) { MZ_FREE(p); }
  1702. #ifndef MINIZ_NO_ZLIB_APIS
  1703. static void *def_alloc_func(void *opaque, size_t items, size_t size) {
  1704. (void)opaque, (void)items, (void)size;
  1705. return MZ_MALLOC(items * size);
  1706. }
  1707. static void def_free_func(void *opaque, void *address) {
  1708. (void)opaque, (void)address;
  1709. MZ_FREE(address);
  1710. }
  1711. // static void *def_realloc_func(void *opaque, void *address, size_t items,
  1712. // size_t size) {
  1713. // (void)opaque, (void)address, (void)items, (void)size;
  1714. // return MZ_REALLOC(address, items * size);
  1715. //}
  1716. const char *mz_version(void) { return MZ_VERSION; }
  1717. int mz_deflateInit(mz_streamp pStream, int level) {
  1718. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
  1719. MZ_DEFAULT_STRATEGY);
  1720. }
  1721. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  1722. int mem_level, int strategy) {
  1723. tdefl_compressor *pComp;
  1724. mz_uint comp_flags =
  1725. TDEFL_COMPUTE_ADLER32 |
  1726. tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  1727. if (!pStream) return MZ_STREAM_ERROR;
  1728. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
  1729. ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1730. (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
  1731. return MZ_PARAM_ERROR;
  1732. pStream->data_type = 0;
  1733. pStream->adler = MZ_ADLER32_INIT;
  1734. pStream->msg = NULL;
  1735. pStream->reserved = 0;
  1736. pStream->total_in = 0;
  1737. pStream->total_out = 0;
  1738. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1739. if (!pStream->zfree) pStream->zfree = def_free_func;
  1740. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
  1741. sizeof(tdefl_compressor));
  1742. if (!pComp) return MZ_MEM_ERROR;
  1743. pStream->state = (struct mz_internal_state *)pComp;
  1744. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
  1745. mz_deflateEnd(pStream);
  1746. return MZ_PARAM_ERROR;
  1747. }
  1748. return MZ_OK;
  1749. }
  1750. int mz_deflateReset(mz_streamp pStream) {
  1751. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
  1752. (!pStream->zfree))
  1753. return MZ_STREAM_ERROR;
  1754. pStream->total_in = pStream->total_out = 0;
  1755. tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
  1756. ((tdefl_compressor *)pStream->state)->m_flags);
  1757. return MZ_OK;
  1758. }
  1759. int mz_deflate(mz_streamp pStream, int flush) {
  1760. size_t in_bytes, out_bytes;
  1761. mz_ulong orig_total_in, orig_total_out;
  1762. int mz_status = MZ_OK;
  1763. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
  1764. (!pStream->next_out))
  1765. return MZ_STREAM_ERROR;
  1766. if (!pStream->avail_out) return MZ_BUF_ERROR;
  1767. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1768. if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
  1769. TDEFL_STATUS_DONE)
  1770. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  1771. orig_total_in = pStream->total_in;
  1772. orig_total_out = pStream->total_out;
  1773. for (;;) {
  1774. tdefl_status defl_status;
  1775. in_bytes = pStream->avail_in;
  1776. out_bytes = pStream->avail_out;
  1777. defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
  1778. pStream->next_in, &in_bytes, pStream->next_out,
  1779. &out_bytes, (tdefl_flush)flush);
  1780. pStream->next_in += (mz_uint)in_bytes;
  1781. pStream->avail_in -= (mz_uint)in_bytes;
  1782. pStream->total_in += (mz_uint)in_bytes;
  1783. pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
  1784. pStream->next_out += (mz_uint)out_bytes;
  1785. pStream->avail_out -= (mz_uint)out_bytes;
  1786. pStream->total_out += (mz_uint)out_bytes;
  1787. if (defl_status < 0) {
  1788. mz_status = MZ_STREAM_ERROR;
  1789. break;
  1790. } else if (defl_status == TDEFL_STATUS_DONE) {
  1791. mz_status = MZ_STREAM_END;
  1792. break;
  1793. } else if (!pStream->avail_out)
  1794. break;
  1795. else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
  1796. if ((flush) || (pStream->total_in != orig_total_in) ||
  1797. (pStream->total_out != orig_total_out))
  1798. break;
  1799. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  1800. }
  1801. }
  1802. return mz_status;
  1803. }
  1804. int mz_deflateEnd(mz_streamp pStream) {
  1805. if (!pStream) return MZ_STREAM_ERROR;
  1806. if (pStream->state) {
  1807. pStream->zfree(pStream->opaque, pStream->state);
  1808. pStream->state = NULL;
  1809. }
  1810. return MZ_OK;
  1811. }
  1812. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
  1813. (void)pStream;
  1814. // This is really over conservative. (And lame, but it's actually pretty
  1815. // tricky to compute a true upper bound given the way tdefl's blocking works.)
  1816. return MZ_MAX(128 + (source_len * 110) / 100,
  1817. 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  1818. }
  1819. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  1820. const unsigned char *pSource, mz_ulong source_len, int level) {
  1821. int status;
  1822. mz_stream stream;
  1823. memset(&stream, 0, sizeof(stream));
  1824. // In case mz_ulong is 64-bits (argh I hate longs).
  1825. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1826. stream.next_in = pSource;
  1827. stream.avail_in = (mz_uint32)source_len;
  1828. stream.next_out = pDest;
  1829. stream.avail_out = (mz_uint32)*pDest_len;
  1830. status = mz_deflateInit(&stream, level);
  1831. if (status != MZ_OK) return status;
  1832. status = mz_deflate(&stream, MZ_FINISH);
  1833. if (status != MZ_STREAM_END) {
  1834. mz_deflateEnd(&stream);
  1835. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1836. }
  1837. *pDest_len = stream.total_out;
  1838. return mz_deflateEnd(&stream);
  1839. }
  1840. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  1841. const unsigned char *pSource, mz_ulong source_len) {
  1842. return mz_compress2(pDest, pDest_len, pSource, source_len,
  1843. MZ_DEFAULT_COMPRESSION);
  1844. }
  1845. mz_ulong mz_compressBound(mz_ulong source_len) {
  1846. return mz_deflateBound(NULL, source_len);
  1847. }
  1848. typedef struct {
  1849. tinfl_decompressor m_decomp;
  1850. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
  1851. int m_window_bits;
  1852. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1853. tinfl_status m_last_status;
  1854. } inflate_state;
  1855. int mz_inflateInit2(mz_streamp pStream, int window_bits) {
  1856. inflate_state *pDecomp;
  1857. if (!pStream) return MZ_STREAM_ERROR;
  1858. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1859. (-window_bits != MZ_DEFAULT_WINDOW_BITS))
  1860. return MZ_PARAM_ERROR;
  1861. pStream->data_type = 0;
  1862. pStream->adler = 0;
  1863. pStream->msg = NULL;
  1864. pStream->total_in = 0;
  1865. pStream->total_out = 0;
  1866. pStream->reserved = 0;
  1867. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1868. if (!pStream->zfree) pStream->zfree = def_free_func;
  1869. pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
  1870. sizeof(inflate_state));
  1871. if (!pDecomp) return MZ_MEM_ERROR;
  1872. pStream->state = (struct mz_internal_state *)pDecomp;
  1873. tinfl_init(&pDecomp->m_decomp);
  1874. pDecomp->m_dict_ofs = 0;
  1875. pDecomp->m_dict_avail = 0;
  1876. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1877. pDecomp->m_first_call = 1;
  1878. pDecomp->m_has_flushed = 0;
  1879. pDecomp->m_window_bits = window_bits;
  1880. return MZ_OK;
  1881. }
  1882. int mz_inflateInit(mz_streamp pStream) {
  1883. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1884. }
  1885. int mz_inflate(mz_streamp pStream, int flush) {
  1886. inflate_state *pState;
  1887. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1888. size_t in_bytes, out_bytes, orig_avail_in;
  1889. tinfl_status status;
  1890. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  1891. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1892. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
  1893. return MZ_STREAM_ERROR;
  1894. pState = (inflate_state *)pStream->state;
  1895. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1896. orig_avail_in = pStream->avail_in;
  1897. first_call = pState->m_first_call;
  1898. pState->m_first_call = 0;
  1899. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1900. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1901. pState->m_has_flushed |= (flush == MZ_FINISH);
  1902. if ((flush == MZ_FINISH) && (first_call)) {
  1903. // MZ_FINISH on the first call implies that the input and output buffers are
  1904. // large enough to hold the entire compressed/decompressed file.
  1905. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1906. in_bytes = pStream->avail_in;
  1907. out_bytes = pStream->avail_out;
  1908. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
  1909. pStream->next_out, pStream->next_out, &out_bytes,
  1910. decomp_flags);
  1911. pState->m_last_status = status;
  1912. pStream->next_in += (mz_uint)in_bytes;
  1913. pStream->avail_in -= (mz_uint)in_bytes;
  1914. pStream->total_in += (mz_uint)in_bytes;
  1915. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1916. pStream->next_out += (mz_uint)out_bytes;
  1917. pStream->avail_out -= (mz_uint)out_bytes;
  1918. pStream->total_out += (mz_uint)out_bytes;
  1919. if (status < 0)
  1920. return MZ_DATA_ERROR;
  1921. else if (status != TINFL_STATUS_DONE) {
  1922. pState->m_last_status = TINFL_STATUS_FAILED;
  1923. return MZ_BUF_ERROR;
  1924. }
  1925. return MZ_STREAM_END;
  1926. }
  1927. // flush != MZ_FINISH then we must assume there's more input.
  1928. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1929. if (pState->m_dict_avail) {
  1930. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1931. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1932. pStream->next_out += n;
  1933. pStream->avail_out -= n;
  1934. pStream->total_out += n;
  1935. pState->m_dict_avail -= n;
  1936. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1937. return ((pState->m_last_status == TINFL_STATUS_DONE) &&
  1938. (!pState->m_dict_avail))
  1939. ? MZ_STREAM_END
  1940. : MZ_OK;
  1941. }
  1942. for (;;) {
  1943. in_bytes = pStream->avail_in;
  1944. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1945. status = tinfl_decompress(
  1946. &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
  1947. pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1948. pState->m_last_status = status;
  1949. pStream->next_in += (mz_uint)in_bytes;
  1950. pStream->avail_in -= (mz_uint)in_bytes;
  1951. pStream->total_in += (mz_uint)in_bytes;
  1952. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1953. pState->m_dict_avail = (mz_uint)out_bytes;
  1954. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1955. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1956. pStream->next_out += n;
  1957. pStream->avail_out -= n;
  1958. pStream->total_out += n;
  1959. pState->m_dict_avail -= n;
  1960. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1961. if (status < 0)
  1962. return MZ_DATA_ERROR; // Stream is corrupted (there could be some
  1963. // uncompressed data left in the output dictionary -
  1964. // oh well).
  1965. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1966. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
  1967. // without supplying more input or by setting flush
  1968. // to MZ_FINISH.
  1969. else if (flush == MZ_FINISH) {
  1970. // The output buffer MUST be large to hold the remaining uncompressed data
  1971. // when flush==MZ_FINISH.
  1972. if (status == TINFL_STATUS_DONE)
  1973. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1974. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
  1975. // at least 1 more byte on the way. If there's no more room left in the
  1976. // output buffer then something is wrong.
  1977. else if (!pStream->avail_out)
  1978. return MZ_BUF_ERROR;
  1979. } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
  1980. (!pStream->avail_out) || (pState->m_dict_avail))
  1981. break;
  1982. }
  1983. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
  1984. ? MZ_STREAM_END
  1985. : MZ_OK;
  1986. }
  1987. int mz_inflateEnd(mz_streamp pStream) {
  1988. if (!pStream) return MZ_STREAM_ERROR;
  1989. if (pStream->state) {
  1990. pStream->zfree(pStream->opaque, pStream->state);
  1991. pStream->state = NULL;
  1992. }
  1993. return MZ_OK;
  1994. }
  1995. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  1996. const unsigned char *pSource, mz_ulong source_len) {
  1997. mz_stream stream;
  1998. int status;
  1999. memset(&stream, 0, sizeof(stream));
  2000. // In case mz_ulong is 64-bits (argh I hate longs).
  2001. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  2002. stream.next_in = pSource;
  2003. stream.avail_in = (mz_uint32)source_len;
  2004. stream.next_out = pDest;
  2005. stream.avail_out = (mz_uint32)*pDest_len;
  2006. status = mz_inflateInit(&stream);
  2007. if (status != MZ_OK) return status;
  2008. status = mz_inflate(&stream, MZ_FINISH);
  2009. if (status != MZ_STREAM_END) {
  2010. mz_inflateEnd(&stream);
  2011. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
  2012. : status;
  2013. }
  2014. *pDest_len = stream.total_out;
  2015. return mz_inflateEnd(&stream);
  2016. }
  2017. const char *mz_error(int err) {
  2018. static struct {
  2019. int m_err;
  2020. const char *m_pDesc;
  2021. } s_error_descs[] = {{MZ_OK, ""},
  2022. {MZ_STREAM_END, "stream end"},
  2023. {MZ_NEED_DICT, "need dictionary"},
  2024. {MZ_ERRNO, "file error"},
  2025. {MZ_STREAM_ERROR, "stream error"},
  2026. {MZ_DATA_ERROR, "data error"},
  2027. {MZ_MEM_ERROR, "out of memory"},
  2028. {MZ_BUF_ERROR, "buf error"},
  2029. {MZ_VERSION_ERROR, "version error"},
  2030. {MZ_PARAM_ERROR, "parameter error"}};
  2031. mz_uint i;
  2032. for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
  2033. if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  2034. return NULL;
  2035. }
  2036. #endif // MINIZ_NO_ZLIB_APIS
  2037. // ------------------- Low-level Decompression (completely independent from all
  2038. // compression API's)
  2039. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  2040. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  2041. #define TINFL_CR_BEGIN \
  2042. switch (r->m_state) { \
  2043. case 0:
  2044. #define TINFL_CR_RETURN(state_index, result) \
  2045. do { \
  2046. status = result; \
  2047. r->m_state = state_index; \
  2048. goto common_exit; \
  2049. case state_index:; \
  2050. } \
  2051. MZ_MACRO_END
  2052. #define TINFL_CR_RETURN_FOREVER(state_index, result) \
  2053. do { \
  2054. for (;;) { \
  2055. TINFL_CR_RETURN(state_index, result); \
  2056. } \
  2057. } \
  2058. MZ_MACRO_END
  2059. #define TINFL_CR_FINISH }
  2060. // TODO: If the caller has indicated that there's no more input, and we attempt
  2061. // to read beyond the input buf, then something is wrong with the input because
  2062. // the inflator never
  2063. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
  2064. // the stream with 0's in this scenario.
  2065. #define TINFL_GET_BYTE(state_index, c) \
  2066. do { \
  2067. if (pIn_buf_cur >= pIn_buf_end) { \
  2068. for (;;) { \
  2069. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  2070. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  2071. if (pIn_buf_cur < pIn_buf_end) { \
  2072. c = *pIn_buf_cur++; \
  2073. break; \
  2074. } \
  2075. } else { \
  2076. c = 0; \
  2077. break; \
  2078. } \
  2079. } \
  2080. } else \
  2081. c = *pIn_buf_cur++; \
  2082. } \
  2083. MZ_MACRO_END
  2084. #define TINFL_NEED_BITS(state_index, n) \
  2085. do { \
  2086. mz_uint c; \
  2087. TINFL_GET_BYTE(state_index, c); \
  2088. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2089. num_bits += 8; \
  2090. } while (num_bits < (mz_uint)(n))
  2091. #define TINFL_SKIP_BITS(state_index, n) \
  2092. do { \
  2093. if (num_bits < (mz_uint)(n)) { \
  2094. TINFL_NEED_BITS(state_index, n); \
  2095. } \
  2096. bit_buf >>= (n); \
  2097. num_bits -= (n); \
  2098. } \
  2099. MZ_MACRO_END
  2100. #define TINFL_GET_BITS(state_index, b, n) \
  2101. do { \
  2102. if (num_bits < (mz_uint)(n)) { \
  2103. TINFL_NEED_BITS(state_index, n); \
  2104. } \
  2105. b = bit_buf & ((1 << (n)) - 1); \
  2106. bit_buf >>= (n); \
  2107. num_bits -= (n); \
  2108. } \
  2109. MZ_MACRO_END
  2110. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
  2111. // remaining in the input buffer falls below 2.
  2112. // It reads just enough bytes from the input stream that are needed to decode
  2113. // the next Huffman code (and absolutely no more). It works by trying to fully
  2114. // decode a
  2115. // Huffman code by using whatever bits are currently present in the bit buffer.
  2116. // If this fails, it reads another byte, and tries again until it succeeds or
  2117. // until the
  2118. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  2119. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  2120. do { \
  2121. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  2122. if (temp >= 0) { \
  2123. code_len = temp >> 9; \
  2124. if ((code_len) && (num_bits >= code_len)) break; \
  2125. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  2126. code_len = TINFL_FAST_LOOKUP_BITS; \
  2127. do { \
  2128. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2129. } while ((temp < 0) && (num_bits >= (code_len + 1))); \
  2130. if (temp >= 0) break; \
  2131. } \
  2132. TINFL_GET_BYTE(state_index, c); \
  2133. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2134. num_bits += 8; \
  2135. } while (num_bits < 15);
  2136. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
  2137. // than you would initially expect because the zlib API expects the decompressor
  2138. // to never read
  2139. // beyond the final byte of the deflate stream. (In other words, when this macro
  2140. // wants to read another byte from the input, it REALLY needs another byte in
  2141. // order to fully
  2142. // decode the next Huffman code.) Handling this properly is particularly
  2143. // important on raw deflate (non-zlib) streams, which aren't followed by a byte
  2144. // aligned adler-32.
  2145. // The slow path is only executed at the very end of the input buffer.
  2146. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
  2147. do { \
  2148. int temp; \
  2149. mz_uint code_len, c; \
  2150. if (num_bits < 15) { \
  2151. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  2152. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  2153. } else { \
  2154. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
  2155. (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
  2156. pIn_buf_cur += 2; \
  2157. num_bits += 16; \
  2158. } \
  2159. } \
  2160. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
  2161. 0) \
  2162. code_len = temp >> 9, temp &= 511; \
  2163. else { \
  2164. code_len = TINFL_FAST_LOOKUP_BITS; \
  2165. do { \
  2166. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2167. } while (temp < 0); \
  2168. } \
  2169. sym = temp; \
  2170. bit_buf >>= code_len; \
  2171. num_bits -= code_len; \
  2172. } \
  2173. MZ_MACRO_END
  2174. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  2175. const mz_uint8 *pIn_buf_next,
  2176. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  2177. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  2178. const mz_uint32 decomp_flags) {
  2179. static const int s_length_base[31] = {
  2180. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  2181. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  2182. static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
  2183. 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  2184. 4, 4, 5, 5, 5, 5, 0, 0, 0};
  2185. static const int s_dist_base[32] = {
  2186. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
  2187. 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
  2188. 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
  2189. static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  2190. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  2191. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
  2192. static const mz_uint8 s_length_dezigzag[19] = {
  2193. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2194. static const int s_min_table_sizes[3] = {257, 1, 4};
  2195. tinfl_status status = TINFL_STATUS_FAILED;
  2196. mz_uint32 num_bits, dist, counter, num_extra;
  2197. tinfl_bit_buf_t bit_buf;
  2198. const mz_uint8 *pIn_buf_cur = pIn_buf_next,
  2199. *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  2200. mz_uint8 *pOut_buf_cur = pOut_buf_next,
  2201. *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  2202. size_t out_buf_size_mask =
  2203. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
  2204. ? (size_t)-1
  2205. : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
  2206. dist_from_out_buf_start;
  2207. // Ensure the output buffer's size is a power of 2, unless the output buffer
  2208. // is large enough to hold the entire output file (in which case it doesn't
  2209. // matter).
  2210. if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
  2211. (pOut_buf_next < pOut_buf_start)) {
  2212. *pIn_buf_size = *pOut_buf_size = 0;
  2213. return TINFL_STATUS_BAD_PARAM;
  2214. }
  2215. num_bits = r->m_num_bits;
  2216. bit_buf = r->m_bit_buf;
  2217. dist = r->m_dist;
  2218. counter = r->m_counter;
  2219. num_extra = r->m_num_extra;
  2220. dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  2221. TINFL_CR_BEGIN
  2222. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
  2223. r->m_z_adler32 = r->m_check_adler32 = 1;
  2224. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2225. TINFL_GET_BYTE(1, r->m_zhdr0);
  2226. TINFL_GET_BYTE(2, r->m_zhdr1);
  2227. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
  2228. (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  2229. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  2230. counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
  2231. ((out_buf_size_mask + 1) <
  2232. (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4)))));
  2233. if (counter) {
  2234. TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
  2235. }
  2236. }
  2237. do {
  2238. TINFL_GET_BITS(3, r->m_final, 3);
  2239. r->m_type = r->m_final >> 1;
  2240. if (r->m_type == 0) {
  2241. TINFL_SKIP_BITS(5, num_bits & 7);
  2242. for (counter = 0; counter < 4; ++counter) {
  2243. if (num_bits)
  2244. TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
  2245. else
  2246. TINFL_GET_BYTE(7, r->m_raw_header[counter]);
  2247. }
  2248. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
  2249. (mz_uint)(0xFFFF ^
  2250. (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
  2251. TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
  2252. }
  2253. while ((counter) && (num_bits)) {
  2254. TINFL_GET_BITS(51, dist, 8);
  2255. while (pOut_buf_cur >= pOut_buf_end) {
  2256. TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
  2257. }
  2258. *pOut_buf_cur++ = (mz_uint8)dist;
  2259. counter--;
  2260. }
  2261. while (counter) {
  2262. size_t n;
  2263. while (pOut_buf_cur >= pOut_buf_end) {
  2264. TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
  2265. }
  2266. while (pIn_buf_cur >= pIn_buf_end) {
  2267. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
  2268. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  2269. } else {
  2270. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  2271. }
  2272. }
  2273. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
  2274. (size_t)(pIn_buf_end - pIn_buf_cur)),
  2275. counter);
  2276. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
  2277. pIn_buf_cur += n;
  2278. pOut_buf_cur += n;
  2279. counter -= (mz_uint)n;
  2280. }
  2281. } else if (r->m_type == 3) {
  2282. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  2283. } else {
  2284. if (r->m_type == 1) {
  2285. mz_uint8 *p = r->m_tables[0].m_code_size;
  2286. mz_uint i;
  2287. r->m_table_sizes[0] = 288;
  2288. r->m_table_sizes[1] = 32;
  2289. TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  2290. for (i = 0; i <= 143; ++i) *p++ = 8;
  2291. for (; i <= 255; ++i) *p++ = 9;
  2292. for (; i <= 279; ++i) *p++ = 7;
  2293. for (; i <= 287; ++i) *p++ = 8;
  2294. } else {
  2295. for (counter = 0; counter < 3; counter++) {
  2296. TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
  2297. r->m_table_sizes[counter] += s_min_table_sizes[counter];
  2298. }
  2299. MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
  2300. for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
  2301. mz_uint s;
  2302. TINFL_GET_BITS(14, s, 3);
  2303. r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
  2304. }
  2305. r->m_table_sizes[2] = 19;
  2306. }
  2307. for (; (int)r->m_type >= 0; r->m_type--) {
  2308. int tree_next, tree_cur;
  2309. tinfl_huff_table *pTable;
  2310. mz_uint i, j, used_syms, total, sym_index, next_code[17],
  2311. total_syms[16];
  2312. pTable = &r->m_tables[r->m_type];
  2313. MZ_CLEAR_OBJ(total_syms);
  2314. MZ_CLEAR_OBJ(pTable->m_look_up);
  2315. MZ_CLEAR_OBJ(pTable->m_tree);
  2316. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
  2317. total_syms[pTable->m_code_size[i]]++;
  2318. used_syms = 0, total = 0;
  2319. next_code[0] = next_code[1] = 0;
  2320. for (i = 1; i <= 15; ++i) {
  2321. used_syms += total_syms[i];
  2322. next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
  2323. }
  2324. if ((65536 != total) && (used_syms > 1)) {
  2325. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  2326. }
  2327. for (tree_next = -1, sym_index = 0;
  2328. sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
  2329. mz_uint rev_code = 0, l, cur_code,
  2330. code_size = pTable->m_code_size[sym_index];
  2331. if (!code_size) continue;
  2332. cur_code = next_code[code_size]++;
  2333. for (l = code_size; l > 0; l--, cur_code >>= 1)
  2334. rev_code = (rev_code << 1) | (cur_code & 1);
  2335. if (code_size <= TINFL_FAST_LOOKUP_BITS) {
  2336. mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
  2337. while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
  2338. pTable->m_look_up[rev_code] = k;
  2339. rev_code += (1 << code_size);
  2340. }
  2341. continue;
  2342. }
  2343. if (0 ==
  2344. (tree_cur = pTable->m_look_up[rev_code &
  2345. (TINFL_FAST_LOOKUP_SIZE - 1)])) {
  2346. pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
  2347. (mz_int16)tree_next;
  2348. tree_cur = tree_next;
  2349. tree_next -= 2;
  2350. }
  2351. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  2352. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
  2353. tree_cur -= ((rev_code >>= 1) & 1);
  2354. if (!pTable->m_tree[-tree_cur - 1]) {
  2355. pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
  2356. tree_cur = tree_next;
  2357. tree_next -= 2;
  2358. } else
  2359. tree_cur = pTable->m_tree[-tree_cur - 1];
  2360. }
  2361. tree_cur -= ((rev_code >>= 1) & 1);
  2362. pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  2363. }
  2364. if (r->m_type == 2) {
  2365. for (counter = 0;
  2366. counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
  2367. mz_uint s;
  2368. TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
  2369. if (dist < 16) {
  2370. r->m_len_codes[counter++] = (mz_uint8)dist;
  2371. continue;
  2372. }
  2373. if ((dist == 16) && (!counter)) {
  2374. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  2375. }
  2376. num_extra = "\02\03\07"[dist - 16];
  2377. TINFL_GET_BITS(18, s, num_extra);
  2378. s += "\03\03\013"[dist - 16];
  2379. TINFL_MEMSET(r->m_len_codes + counter,
  2380. (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
  2381. counter += s;
  2382. }
  2383. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
  2384. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  2385. }
  2386. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
  2387. r->m_table_sizes[0]);
  2388. TINFL_MEMCPY(r->m_tables[1].m_code_size,
  2389. r->m_len_codes + r->m_table_sizes[0],
  2390. r->m_table_sizes[1]);
  2391. }
  2392. }
  2393. for (;;) {
  2394. mz_uint8 *pSrc;
  2395. for (;;) {
  2396. if (((pIn_buf_end - pIn_buf_cur) < 4) ||
  2397. ((pOut_buf_end - pOut_buf_cur) < 2)) {
  2398. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  2399. if (counter >= 256) break;
  2400. while (pOut_buf_cur >= pOut_buf_end) {
  2401. TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
  2402. }
  2403. *pOut_buf_cur++ = (mz_uint8)counter;
  2404. } else {
  2405. int sym2;
  2406. mz_uint code_len;
  2407. #if TINFL_USE_64BIT_BITBUF
  2408. if (num_bits < 30) {
  2409. bit_buf |=
  2410. (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
  2411. pIn_buf_cur += 4;
  2412. num_bits += 32;
  2413. }
  2414. #else
  2415. if (num_bits < 15) {
  2416. bit_buf |=
  2417. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2418. pIn_buf_cur += 2;
  2419. num_bits += 16;
  2420. }
  2421. #endif
  2422. if ((sym2 =
  2423. r->m_tables[0]
  2424. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2425. 0)
  2426. code_len = sym2 >> 9;
  2427. else {
  2428. code_len = TINFL_FAST_LOOKUP_BITS;
  2429. do {
  2430. sym2 = r->m_tables[0]
  2431. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2432. } while (sym2 < 0);
  2433. }
  2434. counter = sym2;
  2435. bit_buf >>= code_len;
  2436. num_bits -= code_len;
  2437. if (counter & 256) break;
  2438. #if !TINFL_USE_64BIT_BITBUF
  2439. if (num_bits < 15) {
  2440. bit_buf |=
  2441. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2442. pIn_buf_cur += 2;
  2443. num_bits += 16;
  2444. }
  2445. #endif
  2446. if ((sym2 =
  2447. r->m_tables[0]
  2448. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2449. 0)
  2450. code_len = sym2 >> 9;
  2451. else {
  2452. code_len = TINFL_FAST_LOOKUP_BITS;
  2453. do {
  2454. sym2 = r->m_tables[0]
  2455. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2456. } while (sym2 < 0);
  2457. }
  2458. bit_buf >>= code_len;
  2459. num_bits -= code_len;
  2460. pOut_buf_cur[0] = (mz_uint8)counter;
  2461. if (sym2 & 256) {
  2462. pOut_buf_cur++;
  2463. counter = sym2;
  2464. break;
  2465. }
  2466. pOut_buf_cur[1] = (mz_uint8)sym2;
  2467. pOut_buf_cur += 2;
  2468. }
  2469. }
  2470. if ((counter &= 511) == 256) break;
  2471. num_extra = s_length_extra[counter - 257];
  2472. counter = s_length_base[counter - 257];
  2473. if (num_extra) {
  2474. mz_uint extra_bits;
  2475. TINFL_GET_BITS(25, extra_bits, num_extra);
  2476. counter += extra_bits;
  2477. }
  2478. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  2479. num_extra = s_dist_extra[dist];
  2480. dist = s_dist_base[dist];
  2481. if (num_extra) {
  2482. mz_uint extra_bits;
  2483. TINFL_GET_BITS(27, extra_bits, num_extra);
  2484. dist += extra_bits;
  2485. }
  2486. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  2487. if ((dist > dist_from_out_buf_start) &&
  2488. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
  2489. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  2490. }
  2491. pSrc = pOut_buf_start +
  2492. ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  2493. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
  2494. while (counter--) {
  2495. while (pOut_buf_cur >= pOut_buf_end) {
  2496. TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
  2497. }
  2498. *pOut_buf_cur++ =
  2499. pOut_buf_start[(dist_from_out_buf_start++ - dist) &
  2500. out_buf_size_mask];
  2501. }
  2502. continue;
  2503. }
  2504. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2505. else if ((counter >= 9) && (counter <= dist)) {
  2506. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  2507. do {
  2508. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  2509. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  2510. pOut_buf_cur += 8;
  2511. } while ((pSrc += 8) < pSrc_end);
  2512. if ((counter &= 7) < 3) {
  2513. if (counter) {
  2514. pOut_buf_cur[0] = pSrc[0];
  2515. if (counter > 1) pOut_buf_cur[1] = pSrc[1];
  2516. pOut_buf_cur += counter;
  2517. }
  2518. continue;
  2519. }
  2520. }
  2521. #endif
  2522. do {
  2523. pOut_buf_cur[0] = pSrc[0];
  2524. pOut_buf_cur[1] = pSrc[1];
  2525. pOut_buf_cur[2] = pSrc[2];
  2526. pOut_buf_cur += 3;
  2527. pSrc += 3;
  2528. } while ((int)(counter -= 3) > 2);
  2529. if ((int)counter > 0) {
  2530. pOut_buf_cur[0] = pSrc[0];
  2531. if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1];
  2532. pOut_buf_cur += counter;
  2533. }
  2534. }
  2535. }
  2536. } while (!(r->m_final & 1));
  2537. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2538. TINFL_SKIP_BITS(32, num_bits & 7);
  2539. for (counter = 0; counter < 4; ++counter) {
  2540. mz_uint s;
  2541. if (num_bits)
  2542. TINFL_GET_BITS(41, s, 8);
  2543. else
  2544. TINFL_GET_BYTE(42, s);
  2545. r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
  2546. }
  2547. }
  2548. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  2549. TINFL_CR_FINISH
  2550. common_exit:
  2551. r->m_num_bits = num_bits;
  2552. r->m_bit_buf = bit_buf;
  2553. r->m_dist = dist;
  2554. r->m_counter = counter;
  2555. r->m_num_extra = num_extra;
  2556. r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  2557. *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
  2558. *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  2559. if ((decomp_flags &
  2560. (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
  2561. (status >= 0)) {
  2562. const mz_uint8 *ptr = pOut_buf_next;
  2563. size_t buf_len = *pOut_buf_size;
  2564. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
  2565. s2 = r->m_check_adler32 >> 16;
  2566. size_t block_len = buf_len % 5552;
  2567. while (buf_len) {
  2568. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  2569. s1 += ptr[0], s2 += s1;
  2570. s1 += ptr[1], s2 += s1;
  2571. s1 += ptr[2], s2 += s1;
  2572. s1 += ptr[3], s2 += s1;
  2573. s1 += ptr[4], s2 += s1;
  2574. s1 += ptr[5], s2 += s1;
  2575. s1 += ptr[6], s2 += s1;
  2576. s1 += ptr[7], s2 += s1;
  2577. }
  2578. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  2579. s1 %= 65521U, s2 %= 65521U;
  2580. buf_len -= block_len;
  2581. block_len = 5552;
  2582. }
  2583. r->m_check_adler32 = (s2 << 16) + s1;
  2584. if ((status == TINFL_STATUS_DONE) &&
  2585. (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
  2586. (r->m_check_adler32 != r->m_z_adler32))
  2587. status = TINFL_STATUS_ADLER32_MISMATCH;
  2588. }
  2589. return status;
  2590. }
  2591. // Higher level helper functions.
  2592. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  2593. size_t *pOut_len, int flags) {
  2594. tinfl_decompressor decomp;
  2595. void *pBuf = NULL, *pNew_buf;
  2596. size_t src_buf_ofs = 0, out_buf_capacity = 0;
  2597. *pOut_len = 0;
  2598. tinfl_init(&decomp);
  2599. for (;;) {
  2600. size_t src_buf_size = src_buf_len - src_buf_ofs,
  2601. dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  2602. tinfl_status status = tinfl_decompress(
  2603. &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
  2604. (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
  2605. &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2606. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2607. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
  2608. MZ_FREE(pBuf);
  2609. *pOut_len = 0;
  2610. return NULL;
  2611. }
  2612. src_buf_ofs += src_buf_size;
  2613. *pOut_len += dst_buf_size;
  2614. if (status == TINFL_STATUS_DONE) break;
  2615. new_out_buf_capacity = out_buf_capacity * 2;
  2616. if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  2617. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  2618. if (!pNew_buf) {
  2619. MZ_FREE(pBuf);
  2620. *pOut_len = 0;
  2621. return NULL;
  2622. }
  2623. pBuf = pNew_buf;
  2624. out_buf_capacity = new_out_buf_capacity;
  2625. }
  2626. return pBuf;
  2627. }
  2628. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  2629. const void *pSrc_buf, size_t src_buf_len,
  2630. int flags) {
  2631. tinfl_decompressor decomp;
  2632. tinfl_status status;
  2633. tinfl_init(&decomp);
  2634. status =
  2635. tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
  2636. (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
  2637. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2638. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2639. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
  2640. : out_buf_len;
  2641. }
  2642. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  2643. tinfl_put_buf_func_ptr pPut_buf_func,
  2644. void *pPut_buf_user, int flags) {
  2645. int result = 0;
  2646. tinfl_decompressor decomp;
  2647. mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
  2648. size_t in_buf_ofs = 0, dict_ofs = 0;
  2649. if (!pDict) return TINFL_STATUS_FAILED;
  2650. tinfl_init(&decomp);
  2651. for (;;) {
  2652. size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
  2653. dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  2654. tinfl_status status =
  2655. tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
  2656. &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  2657. (flags &
  2658. ~(TINFL_FLAG_HAS_MORE_INPUT |
  2659. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  2660. in_buf_ofs += in_buf_size;
  2661. if ((dst_buf_size) &&
  2662. (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  2663. break;
  2664. if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
  2665. result = (status == TINFL_STATUS_DONE);
  2666. break;
  2667. }
  2668. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  2669. }
  2670. MZ_FREE(pDict);
  2671. *pIn_buf_size = in_buf_ofs;
  2672. return result;
  2673. }
  2674. // ------------------- Low-level Compression (independent from all decompression
  2675. // API's)
  2676. // Purposely making these tables static for faster init and thread safety.
  2677. static const mz_uint16 s_tdefl_len_sym[256] = {
  2678. 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
  2679. 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
  2680. 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
  2681. 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
  2682. 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  2683. 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
  2684. 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
  2685. 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
  2686. 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
  2687. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
  2688. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
  2689. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
  2690. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
  2691. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  2692. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
  2693. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2694. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2695. 285};
  2696. static const mz_uint8 s_tdefl_len_extra[256] = {
  2697. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
  2698. 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  2699. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  2700. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2701. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2702. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2703. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2704. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2705. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2706. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2707. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
  2708. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  2709. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  2710. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
  2711. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2712. 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2713. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2714. 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2715. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
  2716. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2717. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2718. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2719. 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2720. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2721. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2722. 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2723. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2724. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2725. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2726. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2727. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2728. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2729. 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2730. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2731. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2732. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2733. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2734. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2735. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
  2736. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  2737. 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,
  2738. 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,
  2739. 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,
  2740. 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,
  2741. 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,
  2742. 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,
  2743. 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,
  2744. 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,
  2745. 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,
  2746. 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,
  2747. 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,
  2748. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2749. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2750. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2751. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2752. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2753. 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,
  2754. 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,
  2755. 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,
  2756. 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,
  2757. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
  2758. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  2759. 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
  2760. 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
  2761. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  2762. 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2763. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2764. 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  2765. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
  2766. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  2767. 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
  2768. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
  2769. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2770. 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2771. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2772. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2773. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
  2774. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
  2775. // values.
  2776. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  2777. static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
  2778. tdefl_sym_freq *pSyms0,
  2779. tdefl_sym_freq *pSyms1) {
  2780. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  2781. tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  2782. MZ_CLEAR_OBJ(hist);
  2783. for (i = 0; i < num_syms; i++) {
  2784. mz_uint freq = pSyms0[i].m_key;
  2785. hist[freq & 0xFF]++;
  2786. hist[256 + ((freq >> 8) & 0xFF)]++;
  2787. }
  2788. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  2789. total_passes--;
  2790. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
  2791. const mz_uint32 *pHist = &hist[pass << 8];
  2792. mz_uint offsets[256], cur_ofs = 0;
  2793. for (i = 0; i < 256; i++) {
  2794. offsets[i] = cur_ofs;
  2795. cur_ofs += pHist[i];
  2796. }
  2797. for (i = 0; i < num_syms; i++)
  2798. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
  2799. pCur_syms[i];
  2800. {
  2801. tdefl_sym_freq *t = pCur_syms;
  2802. pCur_syms = pNew_syms;
  2803. pNew_syms = t;
  2804. }
  2805. }
  2806. return pCur_syms;
  2807. }
  2808. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
  2809. // [email protected], Jyrki Katajainen, [email protected], November 1996.
  2810. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
  2811. int root, leaf, next, avbl, used, dpth;
  2812. if (n == 0)
  2813. return;
  2814. else if (n == 1) {
  2815. A[0].m_key = 1;
  2816. return;
  2817. }
  2818. A[0].m_key += A[1].m_key;
  2819. root = 0;
  2820. leaf = 2;
  2821. for (next = 1; next < n - 1; next++) {
  2822. if (leaf >= n || A[root].m_key < A[leaf].m_key) {
  2823. A[next].m_key = A[root].m_key;
  2824. A[root++].m_key = (mz_uint16)next;
  2825. } else
  2826. A[next].m_key = A[leaf++].m_key;
  2827. if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
  2828. A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
  2829. A[root++].m_key = (mz_uint16)next;
  2830. } else
  2831. A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  2832. }
  2833. A[n - 2].m_key = 0;
  2834. for (next = n - 3; next >= 0; next--)
  2835. A[next].m_key = A[A[next].m_key].m_key + 1;
  2836. avbl = 1;
  2837. used = dpth = 0;
  2838. root = n - 2;
  2839. next = n - 1;
  2840. while (avbl > 0) {
  2841. while (root >= 0 && (int)A[root].m_key == dpth) {
  2842. used++;
  2843. root--;
  2844. }
  2845. while (avbl > used) {
  2846. A[next--].m_key = (mz_uint16)(dpth);
  2847. avbl--;
  2848. }
  2849. avbl = 2 * used;
  2850. dpth++;
  2851. used = 0;
  2852. }
  2853. }
  2854. // Limits canonical Huffman code table's max code size.
  2855. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  2856. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
  2857. int code_list_len,
  2858. int max_code_size) {
  2859. int i;
  2860. mz_uint32 total = 0;
  2861. if (code_list_len <= 1) return;
  2862. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
  2863. pNum_codes[max_code_size] += pNum_codes[i];
  2864. for (i = max_code_size; i > 0; i--)
  2865. total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  2866. while (total != (1UL << max_code_size)) {
  2867. pNum_codes[max_code_size]--;
  2868. for (i = max_code_size - 1; i > 0; i--)
  2869. if (pNum_codes[i]) {
  2870. pNum_codes[i]--;
  2871. pNum_codes[i + 1] += 2;
  2872. break;
  2873. }
  2874. total--;
  2875. }
  2876. }
  2877. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
  2878. int table_len, int code_size_limit,
  2879. int static_table) {
  2880. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
  2881. mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
  2882. MZ_CLEAR_OBJ(num_codes);
  2883. if (static_table) {
  2884. for (i = 0; i < table_len; i++)
  2885. num_codes[d->m_huff_code_sizes[table_num][i]]++;
  2886. } else {
  2887. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
  2888. *pSyms;
  2889. int num_used_syms = 0;
  2890. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  2891. for (i = 0; i < table_len; i++)
  2892. if (pSym_count[i]) {
  2893. syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
  2894. syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
  2895. }
  2896. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
  2897. tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  2898. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  2899. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
  2900. code_size_limit);
  2901. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
  2902. MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  2903. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  2904. for (l = num_codes[i]; l > 0; l--)
  2905. d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  2906. }
  2907. next_code[1] = 0;
  2908. for (j = 0, i = 2; i <= code_size_limit; i++)
  2909. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  2910. for (i = 0; i < table_len; i++) {
  2911. mz_uint rev_code = 0, code, code_size;
  2912. if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  2913. code = next_code[code_size]++;
  2914. for (l = code_size; l > 0; l--, code >>= 1)
  2915. rev_code = (rev_code << 1) | (code & 1);
  2916. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  2917. }
  2918. }
  2919. #define TDEFL_PUT_BITS(b, l) \
  2920. do { \
  2921. mz_uint bits = b; \
  2922. mz_uint len = l; \
  2923. MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  2924. d->m_bit_buffer |= (bits << d->m_bits_in); \
  2925. d->m_bits_in += len; \
  2926. while (d->m_bits_in >= 8) { \
  2927. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  2928. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  2929. d->m_bit_buffer >>= 8; \
  2930. d->m_bits_in -= 8; \
  2931. } \
  2932. } \
  2933. MZ_MACRO_END
  2934. #define TDEFL_RLE_PREV_CODE_SIZE() \
  2935. { \
  2936. if (rle_repeat_count) { \
  2937. if (rle_repeat_count < 3) { \
  2938. d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
  2939. d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  2940. while (rle_repeat_count--) \
  2941. packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  2942. } else { \
  2943. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
  2944. packed_code_sizes[num_packed_code_sizes++] = 16; \
  2945. packed_code_sizes[num_packed_code_sizes++] = \
  2946. (mz_uint8)(rle_repeat_count - 3); \
  2947. } \
  2948. rle_repeat_count = 0; \
  2949. } \
  2950. }
  2951. #define TDEFL_RLE_ZERO_CODE_SIZE() \
  2952. { \
  2953. if (rle_z_count) { \
  2954. if (rle_z_count < 3) { \
  2955. d->m_huff_count[2][0] = \
  2956. (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
  2957. while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  2958. } else if (rle_z_count <= 10) { \
  2959. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
  2960. packed_code_sizes[num_packed_code_sizes++] = 17; \
  2961. packed_code_sizes[num_packed_code_sizes++] = \
  2962. (mz_uint8)(rle_z_count - 3); \
  2963. } else { \
  2964. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
  2965. packed_code_sizes[num_packed_code_sizes++] = 18; \
  2966. packed_code_sizes[num_packed_code_sizes++] = \
  2967. (mz_uint8)(rle_z_count - 11); \
  2968. } \
  2969. rle_z_count = 0; \
  2970. } \
  2971. }
  2972. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
  2973. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2974. static void tdefl_start_dynamic_block(tdefl_compressor *d) {
  2975. int num_lit_codes, num_dist_codes, num_bit_lengths;
  2976. mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
  2977. rle_repeat_count, packed_code_sizes_index;
  2978. mz_uint8
  2979. code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2980. packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2981. prev_code_size = 0xFF;
  2982. d->m_huff_count[0][256] = 1;
  2983. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  2984. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  2985. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
  2986. if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  2987. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
  2988. if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  2989. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  2990. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
  2991. num_dist_codes);
  2992. total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
  2993. num_packed_code_sizes = 0;
  2994. rle_z_count = 0;
  2995. rle_repeat_count = 0;
  2996. memset(&d->m_huff_count[2][0], 0,
  2997. sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  2998. for (i = 0; i < total_code_sizes_to_pack; i++) {
  2999. mz_uint8 code_size = code_sizes_to_pack[i];
  3000. if (!code_size) {
  3001. TDEFL_RLE_PREV_CODE_SIZE();
  3002. if (++rle_z_count == 138) {
  3003. TDEFL_RLE_ZERO_CODE_SIZE();
  3004. }
  3005. } else {
  3006. TDEFL_RLE_ZERO_CODE_SIZE();
  3007. if (code_size != prev_code_size) {
  3008. TDEFL_RLE_PREV_CODE_SIZE();
  3009. d->m_huff_count[2][code_size] =
  3010. (mz_uint16)(d->m_huff_count[2][code_size] + 1);
  3011. packed_code_sizes[num_packed_code_sizes++] = code_size;
  3012. } else if (++rle_repeat_count == 6) {
  3013. TDEFL_RLE_PREV_CODE_SIZE();
  3014. }
  3015. }
  3016. prev_code_size = code_size;
  3017. }
  3018. if (rle_repeat_count) {
  3019. TDEFL_RLE_PREV_CODE_SIZE();
  3020. } else {
  3021. TDEFL_RLE_ZERO_CODE_SIZE();
  3022. }
  3023. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  3024. TDEFL_PUT_BITS(2, 2);
  3025. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  3026. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  3027. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
  3028. if (d->m_huff_code_sizes
  3029. [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
  3030. break;
  3031. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
  3032. TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  3033. for (i = 0; (int)i < num_bit_lengths; i++)
  3034. TDEFL_PUT_BITS(
  3035. d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  3036. for (packed_code_sizes_index = 0;
  3037. packed_code_sizes_index < num_packed_code_sizes;) {
  3038. mz_uint code = packed_code_sizes[packed_code_sizes_index++];
  3039. MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  3040. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  3041. if (code >= 16)
  3042. TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
  3043. "\02\03\07"[code - 16]);
  3044. }
  3045. }
  3046. static void tdefl_start_static_block(tdefl_compressor *d) {
  3047. mz_uint i;
  3048. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  3049. for (i = 0; i <= 143; ++i) *p++ = 8;
  3050. for (; i <= 255; ++i) *p++ = 9;
  3051. for (; i <= 279; ++i) *p++ = 7;
  3052. for (; i <= 287; ++i) *p++ = 8;
  3053. memset(d->m_huff_code_sizes[1], 5, 32);
  3054. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  3055. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  3056. TDEFL_PUT_BITS(1, 2);
  3057. }
  3058. static const mz_uint mz_bitmasks[17] = {
  3059. 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  3060. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
  3061. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
  3062. MINIZ_HAS_64BIT_REGISTERS
  3063. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3064. mz_uint flags;
  3065. mz_uint8 *pLZ_codes;
  3066. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  3067. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  3068. mz_uint64 bit_buffer = d->m_bit_buffer;
  3069. mz_uint bits_in = d->m_bits_in;
  3070. #define TDEFL_PUT_BITS_FAST(b, l) \
  3071. { \
  3072. bit_buffer |= (((mz_uint64)(b)) << bits_in); \
  3073. bits_in += (l); \
  3074. }
  3075. flags = 1;
  3076. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
  3077. flags >>= 1) {
  3078. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3079. if (flags & 1) {
  3080. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  3081. mz_uint match_len = pLZ_codes[0],
  3082. match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
  3083. pLZ_codes += 3;
  3084. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3085. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3086. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3087. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3088. s_tdefl_len_extra[match_len]);
  3089. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  3090. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3091. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  3092. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  3093. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  3094. sym = (match_dist < 512) ? s0 : s1;
  3095. num_extra_bits = (match_dist < 512) ? n0 : n1;
  3096. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3097. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
  3098. d->m_huff_code_sizes[1][sym]);
  3099. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
  3100. num_extra_bits);
  3101. } else {
  3102. mz_uint lit = *pLZ_codes++;
  3103. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3104. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3105. d->m_huff_code_sizes[0][lit]);
  3106. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  3107. flags >>= 1;
  3108. lit = *pLZ_codes++;
  3109. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3110. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3111. d->m_huff_code_sizes[0][lit]);
  3112. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  3113. flags >>= 1;
  3114. lit = *pLZ_codes++;
  3115. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3116. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3117. d->m_huff_code_sizes[0][lit]);
  3118. }
  3119. }
  3120. }
  3121. if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE;
  3122. *(mz_uint64 *)pOutput_buf = bit_buffer;
  3123. pOutput_buf += (bits_in >> 3);
  3124. bit_buffer >>= (bits_in & ~7);
  3125. bits_in &= 7;
  3126. }
  3127. #undef TDEFL_PUT_BITS_FAST
  3128. d->m_pOutput_buf = pOutput_buf;
  3129. d->m_bits_in = 0;
  3130. d->m_bit_buffer = 0;
  3131. while (bits_in) {
  3132. mz_uint32 n = MZ_MIN(bits_in, 16);
  3133. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  3134. bit_buffer >>= n;
  3135. bits_in -= n;
  3136. }
  3137. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3138. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3139. }
  3140. #else
  3141. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3142. mz_uint flags;
  3143. mz_uint8 *pLZ_codes;
  3144. flags = 1;
  3145. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
  3146. flags >>= 1) {
  3147. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3148. if (flags & 1) {
  3149. mz_uint sym, num_extra_bits;
  3150. mz_uint match_len = pLZ_codes[0],
  3151. match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
  3152. pLZ_codes += 3;
  3153. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3154. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3155. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3156. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3157. s_tdefl_len_extra[match_len]);
  3158. if (match_dist < 512) {
  3159. sym = s_tdefl_small_dist_sym[match_dist];
  3160. num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  3161. } else {
  3162. sym = s_tdefl_large_dist_sym[match_dist >> 8];
  3163. num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  3164. }
  3165. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3166. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  3167. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  3168. } else {
  3169. mz_uint lit = *pLZ_codes++;
  3170. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3171. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  3172. }
  3173. }
  3174. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3175. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3176. }
  3177. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
  3178. // MINIZ_HAS_64BIT_REGISTERS
  3179. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
  3180. if (static_block)
  3181. tdefl_start_static_block(d);
  3182. else
  3183. tdefl_start_dynamic_block(d);
  3184. return tdefl_compress_lz_codes(d);
  3185. }
  3186. static int tdefl_flush_block(tdefl_compressor *d, int flush) {
  3187. mz_uint saved_bit_buf, saved_bits_in;
  3188. mz_uint8 *pSaved_output_buf;
  3189. mz_bool comp_block_succeeded = MZ_FALSE;
  3190. int n, use_raw_block =
  3191. ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
  3192. (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  3193. mz_uint8 *pOutput_buf_start =
  3194. ((d->m_pPut_buf_func == NULL) &&
  3195. ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
  3196. ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
  3197. : d->m_output_buf;
  3198. d->m_pOutput_buf = pOutput_buf_start;
  3199. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  3200. MZ_ASSERT(!d->m_output_flush_remaining);
  3201. d->m_output_flush_ofs = 0;
  3202. d->m_output_flush_remaining = 0;
  3203. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  3204. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  3205. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
  3206. TDEFL_PUT_BITS(0x78, 8);
  3207. TDEFL_PUT_BITS(0x01, 8);
  3208. }
  3209. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  3210. pSaved_output_buf = d->m_pOutput_buf;
  3211. saved_bit_buf = d->m_bit_buffer;
  3212. saved_bits_in = d->m_bits_in;
  3213. if (!use_raw_block)
  3214. comp_block_succeeded =
  3215. tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
  3216. (d->m_total_lz_bytes < 48));
  3217. // If the block gets expanded, forget the current contents of the output
  3218. // buffer and send a raw block instead.
  3219. if (((use_raw_block) ||
  3220. ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
  3221. d->m_total_lz_bytes))) &&
  3222. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
  3223. mz_uint i;
  3224. d->m_pOutput_buf = pSaved_output_buf;
  3225. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3226. TDEFL_PUT_BITS(0, 2);
  3227. if (d->m_bits_in) {
  3228. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3229. }
  3230. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
  3231. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  3232. }
  3233. for (i = 0; i < d->m_total_lz_bytes; ++i) {
  3234. TDEFL_PUT_BITS(
  3235. d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
  3236. 8);
  3237. }
  3238. }
  3239. // Check for the extremely unlikely (if not impossible) case of the compressed
  3240. // block not fitting into the output buffer when using dynamic codes.
  3241. else if (!comp_block_succeeded) {
  3242. d->m_pOutput_buf = pSaved_output_buf;
  3243. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3244. tdefl_compress_block(d, MZ_TRUE);
  3245. }
  3246. if (flush) {
  3247. if (flush == TDEFL_FINISH) {
  3248. if (d->m_bits_in) {
  3249. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3250. }
  3251. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
  3252. mz_uint i, a = d->m_adler32;
  3253. for (i = 0; i < 4; i++) {
  3254. TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
  3255. a <<= 8;
  3256. }
  3257. }
  3258. } else {
  3259. mz_uint i, z = 0;
  3260. TDEFL_PUT_BITS(0, 3);
  3261. if (d->m_bits_in) {
  3262. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3263. }
  3264. for (i = 2; i; --i, z ^= 0xFFFF) {
  3265. TDEFL_PUT_BITS(z & 0xFFFF, 16);
  3266. }
  3267. }
  3268. }
  3269. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  3270. memset(&d->m_huff_count[0][0], 0,
  3271. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3272. memset(&d->m_huff_count[1][0], 0,
  3273. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3274. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3275. d->m_pLZ_flags = d->m_lz_code_buf;
  3276. d->m_num_flags_left = 8;
  3277. d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
  3278. d->m_total_lz_bytes = 0;
  3279. d->m_block_index++;
  3280. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
  3281. if (d->m_pPut_buf_func) {
  3282. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3283. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  3284. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  3285. } else if (pOutput_buf_start == d->m_output_buf) {
  3286. int bytes_to_copy = (int)MZ_MIN(
  3287. (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  3288. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
  3289. bytes_to_copy);
  3290. d->m_out_buf_ofs += bytes_to_copy;
  3291. if ((n -= bytes_to_copy) != 0) {
  3292. d->m_output_flush_ofs = bytes_to_copy;
  3293. d->m_output_flush_remaining = n;
  3294. }
  3295. } else {
  3296. d->m_out_buf_ofs += n;
  3297. }
  3298. }
  3299. return d->m_output_flush_remaining;
  3300. }
  3301. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3302. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
  3303. static MZ_FORCEINLINE void tdefl_find_match(
  3304. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3305. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3306. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3307. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3308. probe_len;
  3309. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3310. const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
  3311. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
  3312. s01 = TDEFL_READ_UNALIGNED_WORD(s);
  3313. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3314. if (max_match_len <= match_len) return;
  3315. for (;;) {
  3316. for (;;) {
  3317. if (--num_probes_left == 0) return;
  3318. #define TDEFL_PROBE \
  3319. next_probe_pos = d->m_next[probe_pos]; \
  3320. if ((!next_probe_pos) || \
  3321. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3322. return; \
  3323. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3324. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
  3325. break;
  3326. TDEFL_PROBE;
  3327. TDEFL_PROBE;
  3328. TDEFL_PROBE;
  3329. }
  3330. if (!dist) break;
  3331. q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3332. if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue;
  3333. p = s;
  3334. probe_len = 32;
  3335. do {
  3336. } while (
  3337. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3338. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3339. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3340. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3341. (--probe_len > 0));
  3342. if (!probe_len) {
  3343. *pMatch_dist = dist;
  3344. *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
  3345. break;
  3346. } else if ((probe_len = ((mz_uint)(p - s) * 2) +
  3347. (mz_uint)(*(const mz_uint8 *)p ==
  3348. *(const mz_uint8 *)q)) > match_len) {
  3349. *pMatch_dist = dist;
  3350. if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
  3351. max_match_len)
  3352. break;
  3353. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  3354. }
  3355. }
  3356. }
  3357. #else
  3358. static MZ_FORCEINLINE void tdefl_find_match(
  3359. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3360. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3361. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3362. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3363. probe_len;
  3364. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3365. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  3366. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  3367. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3368. if (max_match_len <= match_len) return;
  3369. for (;;) {
  3370. for (;;) {
  3371. if (--num_probes_left == 0) return;
  3372. #define TDEFL_PROBE \
  3373. next_probe_pos = d->m_next[probe_pos]; \
  3374. if ((!next_probe_pos) || \
  3375. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3376. return; \
  3377. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3378. if ((d->m_dict[probe_pos + match_len] == c0) && \
  3379. (d->m_dict[probe_pos + match_len - 1] == c1)) \
  3380. break;
  3381. TDEFL_PROBE;
  3382. TDEFL_PROBE;
  3383. TDEFL_PROBE;
  3384. }
  3385. if (!dist) break;
  3386. p = s;
  3387. q = d->m_dict + probe_pos;
  3388. for (probe_len = 0; probe_len < max_match_len; probe_len++)
  3389. if (*p++ != *q++) break;
  3390. if (probe_len > match_len) {
  3391. *pMatch_dist = dist;
  3392. if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  3393. c0 = d->m_dict[pos + match_len];
  3394. c1 = d->m_dict[pos + match_len - 1];
  3395. }
  3396. }
  3397. }
  3398. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3399. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3400. static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
  3401. // Faster, minimally featured LZRW1-style match+parse loop with better
  3402. // register utilization. Intended for applications where raw throughput is
  3403. // valued more highly than ratio.
  3404. mz_uint lookahead_pos = d->m_lookahead_pos,
  3405. lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
  3406. total_lz_bytes = d->m_total_lz_bytes,
  3407. num_flags_left = d->m_num_flags_left;
  3408. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  3409. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3410. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
  3411. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  3412. mz_uint dst_pos =
  3413. (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  3414. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3415. d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  3416. d->m_src_buf_left -= num_bytes_to_process;
  3417. lookahead_size += num_bytes_to_process;
  3418. while (num_bytes_to_process) {
  3419. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  3420. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  3421. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3422. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
  3423. MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  3424. d->m_pSrc += n;
  3425. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  3426. num_bytes_to_process -= n;
  3427. }
  3428. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  3429. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
  3430. break;
  3431. while (lookahead_size >= 4) {
  3432. mz_uint cur_match_dist, cur_match_len = 1;
  3433. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  3434. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  3435. mz_uint hash =
  3436. (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
  3437. TDEFL_LEVEL1_HASH_SIZE_MASK;
  3438. mz_uint probe_pos = d->m_hash[hash];
  3439. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  3440. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
  3441. dict_size) &&
  3442. ((*(const mz_uint32 *)(d->m_dict +
  3443. (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
  3444. 0xFFFFFF) == first_trigram)) {
  3445. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  3446. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3447. mz_uint32 probe_len = 32;
  3448. do {
  3449. } while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
  3450. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3451. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3452. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3453. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3454. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3455. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3456. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3457. (--probe_len > 0));
  3458. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
  3459. (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  3460. if (!probe_len)
  3461. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  3462. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
  3463. ((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3464. (cur_match_dist >= 8U * 1024U))) {
  3465. cur_match_len = 1;
  3466. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3467. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3468. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3469. } else {
  3470. mz_uint32 s0, s1;
  3471. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  3472. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
  3473. (cur_match_dist >= 1) &&
  3474. (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  3475. cur_match_dist--;
  3476. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  3477. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  3478. pLZ_code_buf += 3;
  3479. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  3480. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  3481. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  3482. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  3483. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
  3484. TDEFL_MIN_MATCH_LEN]]++;
  3485. }
  3486. } else {
  3487. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3488. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3489. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3490. }
  3491. if (--num_flags_left == 0) {
  3492. num_flags_left = 8;
  3493. pLZ_flags = pLZ_code_buf++;
  3494. }
  3495. total_lz_bytes += cur_match_len;
  3496. lookahead_pos += cur_match_len;
  3497. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  3498. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  3499. MZ_ASSERT(lookahead_size >= cur_match_len);
  3500. lookahead_size -= cur_match_len;
  3501. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3502. int n;
  3503. d->m_lookahead_pos = lookahead_pos;
  3504. d->m_lookahead_size = lookahead_size;
  3505. d->m_dict_size = dict_size;
  3506. d->m_total_lz_bytes = total_lz_bytes;
  3507. d->m_pLZ_code_buf = pLZ_code_buf;
  3508. d->m_pLZ_flags = pLZ_flags;
  3509. d->m_num_flags_left = num_flags_left;
  3510. if ((n = tdefl_flush_block(d, 0)) != 0)
  3511. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3512. total_lz_bytes = d->m_total_lz_bytes;
  3513. pLZ_code_buf = d->m_pLZ_code_buf;
  3514. pLZ_flags = d->m_pLZ_flags;
  3515. num_flags_left = d->m_num_flags_left;
  3516. }
  3517. }
  3518. while (lookahead_size) {
  3519. mz_uint8 lit = d->m_dict[cur_pos];
  3520. total_lz_bytes++;
  3521. *pLZ_code_buf++ = lit;
  3522. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3523. if (--num_flags_left == 0) {
  3524. num_flags_left = 8;
  3525. pLZ_flags = pLZ_code_buf++;
  3526. }
  3527. d->m_huff_count[0][lit]++;
  3528. lookahead_pos++;
  3529. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  3530. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3531. lookahead_size--;
  3532. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3533. int n;
  3534. d->m_lookahead_pos = lookahead_pos;
  3535. d->m_lookahead_size = lookahead_size;
  3536. d->m_dict_size = dict_size;
  3537. d->m_total_lz_bytes = total_lz_bytes;
  3538. d->m_pLZ_code_buf = pLZ_code_buf;
  3539. d->m_pLZ_flags = pLZ_flags;
  3540. d->m_num_flags_left = num_flags_left;
  3541. if ((n = tdefl_flush_block(d, 0)) != 0)
  3542. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3543. total_lz_bytes = d->m_total_lz_bytes;
  3544. pLZ_code_buf = d->m_pLZ_code_buf;
  3545. pLZ_flags = d->m_pLZ_flags;
  3546. num_flags_left = d->m_num_flags_left;
  3547. }
  3548. }
  3549. }
  3550. d->m_lookahead_pos = lookahead_pos;
  3551. d->m_lookahead_size = lookahead_size;
  3552. d->m_dict_size = dict_size;
  3553. d->m_total_lz_bytes = total_lz_bytes;
  3554. d->m_pLZ_code_buf = pLZ_code_buf;
  3555. d->m_pLZ_flags = pLZ_flags;
  3556. d->m_num_flags_left = num_flags_left;
  3557. return MZ_TRUE;
  3558. }
  3559. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3560. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
  3561. mz_uint8 lit) {
  3562. d->m_total_lz_bytes++;
  3563. *d->m_pLZ_code_buf++ = lit;
  3564. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
  3565. if (--d->m_num_flags_left == 0) {
  3566. d->m_num_flags_left = 8;
  3567. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3568. }
  3569. d->m_huff_count[0][lit]++;
  3570. }
  3571. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d,
  3572. mz_uint match_len,
  3573. mz_uint match_dist) {
  3574. mz_uint32 s0, s1;
  3575. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
  3576. (match_dist <= TDEFL_LZ_DICT_SIZE));
  3577. d->m_total_lz_bytes += match_len;
  3578. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  3579. match_dist -= 1;
  3580. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  3581. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
  3582. d->m_pLZ_code_buf += 3;
  3583. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
  3584. if (--d->m_num_flags_left == 0) {
  3585. d->m_num_flags_left = 8;
  3586. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3587. }
  3588. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3589. s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  3590. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  3591. if (match_len >= TDEFL_MIN_MATCH_LEN)
  3592. d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  3593. }
  3594. static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
  3595. const mz_uint8 *pSrc = d->m_pSrc;
  3596. size_t src_buf_left = d->m_src_buf_left;
  3597. tdefl_flush flush = d->m_flush;
  3598. while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
  3599. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  3600. // Update dictionary and hash chains. Keeps the lookahead size equal to
  3601. // TDEFL_MAX_MATCH_LEN.
  3602. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
  3603. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3604. TDEFL_LZ_DICT_SIZE_MASK,
  3605. ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  3606. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3607. << TDEFL_LZ_HASH_SHIFT) ^
  3608. d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3609. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3610. src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  3611. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  3612. src_buf_left -= num_bytes_to_process;
  3613. d->m_lookahead_size += num_bytes_to_process;
  3614. while (pSrc != pSrc_end) {
  3615. mz_uint8 c = *pSrc++;
  3616. d->m_dict[dst_pos] = c;
  3617. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3618. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3619. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  3620. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3621. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3622. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3623. ins_pos++;
  3624. }
  3625. } else {
  3626. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
  3627. mz_uint8 c = *pSrc++;
  3628. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3629. TDEFL_LZ_DICT_SIZE_MASK;
  3630. src_buf_left--;
  3631. d->m_dict[dst_pos] = c;
  3632. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3633. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3634. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
  3635. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  3636. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3637. << (TDEFL_LZ_HASH_SHIFT * 2)) ^
  3638. (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
  3639. << TDEFL_LZ_HASH_SHIFT) ^
  3640. c) &
  3641. (TDEFL_LZ_HASH_SIZE - 1);
  3642. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3643. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3644. }
  3645. }
  3646. }
  3647. d->m_dict_size =
  3648. MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  3649. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break;
  3650. // Simple lazy/greedy parsing state machine.
  3651. len_to_move = 1;
  3652. cur_match_dist = 0;
  3653. cur_match_len =
  3654. d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
  3655. cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3656. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
  3657. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
  3658. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3659. cur_match_len = 0;
  3660. while (cur_match_len < d->m_lookahead_size) {
  3661. if (d->m_dict[cur_pos + cur_match_len] != c) break;
  3662. cur_match_len++;
  3663. }
  3664. if (cur_match_len < TDEFL_MIN_MATCH_LEN)
  3665. cur_match_len = 0;
  3666. else
  3667. cur_match_dist = 1;
  3668. }
  3669. } else {
  3670. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
  3671. d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  3672. }
  3673. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3674. (cur_match_dist >= 8U * 1024U)) ||
  3675. (cur_pos == cur_match_dist) ||
  3676. ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
  3677. cur_match_dist = cur_match_len = 0;
  3678. }
  3679. if (d->m_saved_match_len) {
  3680. if (cur_match_len > d->m_saved_match_len) {
  3681. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  3682. if (cur_match_len >= 128) {
  3683. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3684. d->m_saved_match_len = 0;
  3685. len_to_move = cur_match_len;
  3686. } else {
  3687. d->m_saved_lit = d->m_dict[cur_pos];
  3688. d->m_saved_match_dist = cur_match_dist;
  3689. d->m_saved_match_len = cur_match_len;
  3690. }
  3691. } else {
  3692. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  3693. len_to_move = d->m_saved_match_len - 1;
  3694. d->m_saved_match_len = 0;
  3695. }
  3696. } else if (!cur_match_dist)
  3697. tdefl_record_literal(d,
  3698. d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  3699. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
  3700. (cur_match_len >= 128)) {
  3701. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3702. len_to_move = cur_match_len;
  3703. } else {
  3704. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
  3705. d->m_saved_match_dist = cur_match_dist;
  3706. d->m_saved_match_len = cur_match_len;
  3707. }
  3708. // Move the lookahead forward by len_to_move bytes.
  3709. d->m_lookahead_pos += len_to_move;
  3710. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  3711. d->m_lookahead_size -= len_to_move;
  3712. d->m_dict_size =
  3713. MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
  3714. // Check if it's time to flush the current LZ codes to the internal output
  3715. // buffer.
  3716. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  3717. ((d->m_total_lz_bytes > 31 * 1024) &&
  3718. (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
  3719. d->m_total_lz_bytes) ||
  3720. (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
  3721. int n;
  3722. d->m_pSrc = pSrc;
  3723. d->m_src_buf_left = src_buf_left;
  3724. if ((n = tdefl_flush_block(d, 0)) != 0)
  3725. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3726. }
  3727. }
  3728. d->m_pSrc = pSrc;
  3729. d->m_src_buf_left = src_buf_left;
  3730. return MZ_TRUE;
  3731. }
  3732. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
  3733. if (d->m_pIn_buf_size) {
  3734. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3735. }
  3736. if (d->m_pOut_buf_size) {
  3737. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
  3738. d->m_output_flush_remaining);
  3739. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
  3740. d->m_output_buf + d->m_output_flush_ofs, n);
  3741. d->m_output_flush_ofs += (mz_uint)n;
  3742. d->m_output_flush_remaining -= (mz_uint)n;
  3743. d->m_out_buf_ofs += n;
  3744. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  3745. }
  3746. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
  3747. : TDEFL_STATUS_OKAY;
  3748. }
  3749. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  3750. size_t *pIn_buf_size, void *pOut_buf,
  3751. size_t *pOut_buf_size, tdefl_flush flush) {
  3752. if (!d) {
  3753. if (pIn_buf_size) *pIn_buf_size = 0;
  3754. if (pOut_buf_size) *pOut_buf_size = 0;
  3755. return TDEFL_STATUS_BAD_PARAM;
  3756. }
  3757. d->m_pIn_buf = pIn_buf;
  3758. d->m_pIn_buf_size = pIn_buf_size;
  3759. d->m_pOut_buf = pOut_buf;
  3760. d->m_pOut_buf_size = pOut_buf_size;
  3761. d->m_pSrc = (const mz_uint8 *)(pIn_buf);
  3762. d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  3763. d->m_out_buf_ofs = 0;
  3764. d->m_flush = flush;
  3765. if (((d->m_pPut_buf_func != NULL) ==
  3766. ((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
  3767. (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  3768. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
  3769. (pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
  3770. (pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
  3771. if (pIn_buf_size) *pIn_buf_size = 0;
  3772. if (pOut_buf_size) *pOut_buf_size = 0;
  3773. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  3774. }
  3775. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  3776. if ((d->m_output_flush_remaining) || (d->m_finished))
  3777. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3778. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3779. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  3780. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  3781. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
  3782. TDEFL_RLE_MATCHES)) == 0)) {
  3783. if (!tdefl_compress_fast(d)) return d->m_prev_return_status;
  3784. } else
  3785. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3786. {
  3787. if (!tdefl_compress_normal(d)) return d->m_prev_return_status;
  3788. }
  3789. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
  3790. (pIn_buf))
  3791. d->m_adler32 =
  3792. (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
  3793. d->m_pSrc - (const mz_uint8 *)pIn_buf);
  3794. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
  3795. (!d->m_output_flush_remaining)) {
  3796. if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status;
  3797. d->m_finished = (flush == TDEFL_FINISH);
  3798. if (flush == TDEFL_FULL_FLUSH) {
  3799. MZ_CLEAR_OBJ(d->m_hash);
  3800. MZ_CLEAR_OBJ(d->m_next);
  3801. d->m_dict_size = 0;
  3802. }
  3803. }
  3804. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3805. }
  3806. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  3807. size_t in_buf_size, tdefl_flush flush) {
  3808. MZ_ASSERT(d->m_pPut_buf_func);
  3809. return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  3810. }
  3811. tdefl_status tdefl_init(tdefl_compressor *d,
  3812. tdefl_put_buf_func_ptr pPut_buf_func,
  3813. void *pPut_buf_user, int flags) {
  3814. d->m_pPut_buf_func = pPut_buf_func;
  3815. d->m_pPut_buf_user = pPut_buf_user;
  3816. d->m_flags = (mz_uint)(flags);
  3817. d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
  3818. d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  3819. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  3820. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  3821. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
  3822. d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  3823. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
  3824. d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  3825. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3826. d->m_pLZ_flags = d->m_lz_code_buf;
  3827. d->m_num_flags_left = 8;
  3828. d->m_pOutput_buf = d->m_output_buf;
  3829. d->m_pOutput_buf_end = d->m_output_buf;
  3830. d->m_prev_return_status = TDEFL_STATUS_OKAY;
  3831. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
  3832. d->m_adler32 = 1;
  3833. d->m_pIn_buf = NULL;
  3834. d->m_pOut_buf = NULL;
  3835. d->m_pIn_buf_size = NULL;
  3836. d->m_pOut_buf_size = NULL;
  3837. d->m_flush = TDEFL_NO_FLUSH;
  3838. d->m_pSrc = NULL;
  3839. d->m_src_buf_left = 0;
  3840. d->m_out_buf_ofs = 0;
  3841. memset(&d->m_huff_count[0][0], 0,
  3842. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3843. memset(&d->m_huff_count[1][0], 0,
  3844. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3845. return TDEFL_STATUS_OKAY;
  3846. }
  3847. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
  3848. return d->m_prev_return_status;
  3849. }
  3850. mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
  3851. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  3852. tdefl_put_buf_func_ptr pPut_buf_func,
  3853. void *pPut_buf_user, int flags) {
  3854. tdefl_compressor *pComp;
  3855. mz_bool succeeded;
  3856. if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  3857. pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3858. if (!pComp) return MZ_FALSE;
  3859. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
  3860. TDEFL_STATUS_OKAY);
  3861. succeeded =
  3862. succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
  3863. TDEFL_STATUS_DONE);
  3864. MZ_FREE(pComp);
  3865. return succeeded;
  3866. }
  3867. typedef struct {
  3868. size_t m_size, m_capacity;
  3869. mz_uint8 *m_pBuf;
  3870. mz_bool m_expandable;
  3871. } tdefl_output_buffer;
  3872. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
  3873. void *pUser) {
  3874. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  3875. size_t new_size = p->m_size + len;
  3876. if (new_size > p->m_capacity) {
  3877. size_t new_capacity = p->m_capacity;
  3878. mz_uint8 *pNew_buf;
  3879. if (!p->m_expandable) return MZ_FALSE;
  3880. do {
  3881. new_capacity = MZ_MAX(128U, new_capacity << 1U);
  3882. } while (new_size > new_capacity);
  3883. pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
  3884. if (!pNew_buf) return MZ_FALSE;
  3885. p->m_pBuf = pNew_buf;
  3886. p->m_capacity = new_capacity;
  3887. }
  3888. memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
  3889. p->m_size = new_size;
  3890. return MZ_TRUE;
  3891. }
  3892. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  3893. size_t *pOut_len, int flags) {
  3894. tdefl_output_buffer out_buf;
  3895. MZ_CLEAR_OBJ(out_buf);
  3896. if (!pOut_len)
  3897. return MZ_FALSE;
  3898. else
  3899. *pOut_len = 0;
  3900. out_buf.m_expandable = MZ_TRUE;
  3901. if (!tdefl_compress_mem_to_output(
  3902. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3903. return NULL;
  3904. *pOut_len = out_buf.m_size;
  3905. return out_buf.m_pBuf;
  3906. }
  3907. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  3908. const void *pSrc_buf, size_t src_buf_len,
  3909. int flags) {
  3910. tdefl_output_buffer out_buf;
  3911. MZ_CLEAR_OBJ(out_buf);
  3912. if (!pOut_buf) return 0;
  3913. out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
  3914. out_buf.m_capacity = out_buf_len;
  3915. if (!tdefl_compress_mem_to_output(
  3916. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3917. return 0;
  3918. return out_buf.m_size;
  3919. }
  3920. #ifndef MINIZ_NO_ZLIB_APIS
  3921. static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
  3922. 128, 256, 512, 768, 1500};
  3923. // level may actually range from [0,10] (10 is a "hidden" max level, where we
  3924. // want a bit more compression and it's fine if throughput to fall off a cliff
  3925. // on some files).
  3926. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  3927. int strategy) {
  3928. mz_uint comp_flags =
  3929. s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
  3930. ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  3931. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  3932. if (!level)
  3933. comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  3934. else if (strategy == MZ_FILTERED)
  3935. comp_flags |= TDEFL_FILTER_MATCHES;
  3936. else if (strategy == MZ_HUFFMAN_ONLY)
  3937. comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  3938. else if (strategy == MZ_FIXED)
  3939. comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  3940. else if (strategy == MZ_RLE)
  3941. comp_flags |= TDEFL_RLE_MATCHES;
  3942. return comp_flags;
  3943. }
  3944. #endif // MINIZ_NO_ZLIB_APIS
  3945. #ifdef _MSC_VER
  3946. #pragma warning(push)
  3947. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  3948. // aggregate initializer (also supported by GNU
  3949. // C and C99, so no big deal)
  3950. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  3951. // 'int', possible loss of data
  3952. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  3953. // 'int', possible loss of data
  3954. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  3955. // deprecated. Instead, use the ISO C and C++
  3956. // conformant name: _strdup.
  3957. #endif
  3958. // Simple PNG writer function by Alex Evans, 2011. Released into the public
  3959. // domain: https://gist.github.com/908299, more context at
  3960. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  3961. // This is actually a modification of Alex's original code so PNG files
  3962. // generated by this function pass pngcheck.
  3963. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  3964. int h, int num_chans,
  3965. size_t *pLen_out,
  3966. mz_uint level, mz_bool flip) {
  3967. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
  3968. // defined.
  3969. static const mz_uint s_tdefl_png_num_probes[11] = {
  3970. 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
  3971. tdefl_compressor *pComp =
  3972. (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3973. tdefl_output_buffer out_buf;
  3974. int i, bpl = w * num_chans, y, z;
  3975. mz_uint32 c;
  3976. *pLen_out = 0;
  3977. if (!pComp) return NULL;
  3978. MZ_CLEAR_OBJ(out_buf);
  3979. out_buf.m_expandable = MZ_TRUE;
  3980. out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
  3981. if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
  3982. MZ_FREE(pComp);
  3983. return NULL;
  3984. }
  3985. // write dummy header
  3986. for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  3987. // compress image data
  3988. tdefl_init(
  3989. pComp, tdefl_output_buffer_putter, &out_buf,
  3990. s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  3991. for (y = 0; y < h; ++y) {
  3992. tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
  3993. tdefl_compress_buffer(pComp,
  3994. (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
  3995. bpl, TDEFL_NO_FLUSH);
  3996. }
  3997. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
  3998. TDEFL_STATUS_DONE) {
  3999. MZ_FREE(pComp);
  4000. MZ_FREE(out_buf.m_pBuf);
  4001. return NULL;
  4002. }
  4003. // write real header
  4004. *pLen_out = out_buf.m_size - 41;
  4005. {
  4006. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  4007. mz_uint8 pnghdr[41] = {0x89,
  4008. 0x50,
  4009. 0x4e,
  4010. 0x47,
  4011. 0x0d,
  4012. 0x0a,
  4013. 0x1a,
  4014. 0x0a,
  4015. 0x00,
  4016. 0x00,
  4017. 0x00,
  4018. 0x0d,
  4019. 0x49,
  4020. 0x48,
  4021. 0x44,
  4022. 0x52,
  4023. 0,
  4024. 0,
  4025. (mz_uint8)(w >> 8),
  4026. (mz_uint8)w,
  4027. 0,
  4028. 0,
  4029. (mz_uint8)(h >> 8),
  4030. (mz_uint8)h,
  4031. 8,
  4032. chans[num_chans],
  4033. 0,
  4034. 0,
  4035. 0,
  4036. 0,
  4037. 0,
  4038. 0,
  4039. 0,
  4040. (mz_uint8)(*pLen_out >> 24),
  4041. (mz_uint8)(*pLen_out >> 16),
  4042. (mz_uint8)(*pLen_out >> 8),
  4043. (mz_uint8)*pLen_out,
  4044. 0x49,
  4045. 0x44,
  4046. 0x41,
  4047. 0x54};
  4048. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
  4049. for (i = 0; i < 4; ++i, c <<= 8)
  4050. ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
  4051. memcpy(out_buf.m_pBuf, pnghdr, 41);
  4052. }
  4053. // write footer (IDAT CRC-32, followed by IEND chunk)
  4054. if (!tdefl_output_buffer_putter(
  4055. "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
  4056. *pLen_out = 0;
  4057. MZ_FREE(pComp);
  4058. MZ_FREE(out_buf.m_pBuf);
  4059. return NULL;
  4060. }
  4061. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
  4062. *pLen_out + 4);
  4063. for (i = 0; i < 4; ++i, c <<= 8)
  4064. (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
  4065. // compute final size of file, grab compressed data buffer and return
  4066. *pLen_out += 57;
  4067. MZ_FREE(pComp);
  4068. return out_buf.m_pBuf;
  4069. }
  4070. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  4071. int num_chans, size_t *pLen_out) {
  4072. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
  4073. // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
  4074. // where #defined out)
  4075. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
  4076. pLen_out, 6, MZ_FALSE);
  4077. }
  4078. // ------------------- .ZIP archive reading
  4079. #ifndef MINIZ_NO_ARCHIVE_APIS
  4080. #error "No arvhive APIs"
  4081. #ifdef MINIZ_NO_STDIO
  4082. #define MZ_FILE void *
  4083. #else
  4084. #include <stdio.h>
  4085. #include <sys/stat.h>
  4086. #if defined(_MSC_VER) || defined(__MINGW64__)
  4087. static FILE *mz_fopen(const char *pFilename, const char *pMode) {
  4088. FILE *pFile = NULL;
  4089. fopen_s(&pFile, pFilename, pMode);
  4090. return pFile;
  4091. }
  4092. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
  4093. FILE *pFile = NULL;
  4094. if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL;
  4095. return pFile;
  4096. }
  4097. #ifndef MINIZ_NO_TIME
  4098. #include <sys/utime.h>
  4099. #endif
  4100. #define MZ_FILE FILE
  4101. #define MZ_FOPEN mz_fopen
  4102. #define MZ_FCLOSE fclose
  4103. #define MZ_FREAD fread
  4104. #define MZ_FWRITE fwrite
  4105. #define MZ_FTELL64 _ftelli64
  4106. #define MZ_FSEEK64 _fseeki64
  4107. #define MZ_FILE_STAT_STRUCT _stat
  4108. #define MZ_FILE_STAT _stat
  4109. #define MZ_FFLUSH fflush
  4110. #define MZ_FREOPEN mz_freopen
  4111. #define MZ_DELETE_FILE remove
  4112. #elif defined(__MINGW32__)
  4113. #ifndef MINIZ_NO_TIME
  4114. #include <sys/utime.h>
  4115. #endif
  4116. #define MZ_FILE FILE
  4117. #define MZ_FOPEN(f, m) fopen(f, m)
  4118. #define MZ_FCLOSE fclose
  4119. #define MZ_FREAD fread
  4120. #define MZ_FWRITE fwrite
  4121. #define MZ_FTELL64 ftello64
  4122. #define MZ_FSEEK64 fseeko64
  4123. #define MZ_FILE_STAT_STRUCT _stat
  4124. #define MZ_FILE_STAT _stat
  4125. #define MZ_FFLUSH fflush
  4126. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4127. #define MZ_DELETE_FILE remove
  4128. #elif defined(__TINYC__)
  4129. #ifndef MINIZ_NO_TIME
  4130. #include <sys/utime.h>
  4131. #endif
  4132. #define MZ_FILE FILE
  4133. #define MZ_FOPEN(f, m) fopen(f, m)
  4134. #define MZ_FCLOSE fclose
  4135. #define MZ_FREAD fread
  4136. #define MZ_FWRITE fwrite
  4137. #define MZ_FTELL64 ftell
  4138. #define MZ_FSEEK64 fseek
  4139. #define MZ_FILE_STAT_STRUCT stat
  4140. #define MZ_FILE_STAT stat
  4141. #define MZ_FFLUSH fflush
  4142. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4143. #define MZ_DELETE_FILE remove
  4144. #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
  4145. #ifndef MINIZ_NO_TIME
  4146. #include <utime.h>
  4147. #endif
  4148. #define MZ_FILE FILE
  4149. #define MZ_FOPEN(f, m) fopen64(f, m)
  4150. #define MZ_FCLOSE fclose
  4151. #define MZ_FREAD fread
  4152. #define MZ_FWRITE fwrite
  4153. #define MZ_FTELL64 ftello64
  4154. #define MZ_FSEEK64 fseeko64
  4155. #define MZ_FILE_STAT_STRUCT stat64
  4156. #define MZ_FILE_STAT stat64
  4157. #define MZ_FFLUSH fflush
  4158. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  4159. #define MZ_DELETE_FILE remove
  4160. #else
  4161. #ifndef MINIZ_NO_TIME
  4162. #include <utime.h>
  4163. #endif
  4164. #define MZ_FILE FILE
  4165. #define MZ_FOPEN(f, m) fopen(f, m)
  4166. #define MZ_FCLOSE fclose
  4167. #define MZ_FREAD fread
  4168. #define MZ_FWRITE fwrite
  4169. #define MZ_FTELL64 ftello
  4170. #define MZ_FSEEK64 fseeko
  4171. #define MZ_FILE_STAT_STRUCT stat
  4172. #define MZ_FILE_STAT stat
  4173. #define MZ_FFLUSH fflush
  4174. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4175. #define MZ_DELETE_FILE remove
  4176. #endif // #ifdef _MSC_VER
  4177. #endif // #ifdef MINIZ_NO_STDIO
  4178. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  4179. // Various ZIP archive enums. To completely avoid cross platform compiler
  4180. // alignment and platform endian issues, miniz.c doesn't use structs for any of
  4181. // this stuff.
  4182. enum {
  4183. // ZIP archive identifiers and record sizes
  4184. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
  4185. MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
  4186. MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  4187. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
  4188. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
  4189. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  4190. // Central directory header record offsets
  4191. MZ_ZIP_CDH_SIG_OFS = 0,
  4192. MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
  4193. MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
  4194. MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  4195. MZ_ZIP_CDH_METHOD_OFS = 10,
  4196. MZ_ZIP_CDH_FILE_TIME_OFS = 12,
  4197. MZ_ZIP_CDH_FILE_DATE_OFS = 14,
  4198. MZ_ZIP_CDH_CRC32_OFS = 16,
  4199. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
  4200. MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
  4201. MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
  4202. MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  4203. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
  4204. MZ_ZIP_CDH_DISK_START_OFS = 34,
  4205. MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
  4206. MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
  4207. MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  4208. // Local directory header offsets
  4209. MZ_ZIP_LDH_SIG_OFS = 0,
  4210. MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
  4211. MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
  4212. MZ_ZIP_LDH_METHOD_OFS = 8,
  4213. MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  4214. MZ_ZIP_LDH_FILE_DATE_OFS = 12,
  4215. MZ_ZIP_LDH_CRC32_OFS = 14,
  4216. MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
  4217. MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  4218. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
  4219. MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  4220. // End of central directory offsets
  4221. MZ_ZIP_ECDH_SIG_OFS = 0,
  4222. MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
  4223. MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
  4224. MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  4225. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
  4226. MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
  4227. MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
  4228. MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  4229. };
  4230. typedef struct {
  4231. void *m_p;
  4232. size_t m_size, m_capacity;
  4233. mz_uint m_element_size;
  4234. } mz_zip_array;
  4235. struct mz_zip_internal_state_tag {
  4236. mz_zip_array m_central_dir;
  4237. mz_zip_array m_central_dir_offsets;
  4238. mz_zip_array m_sorted_central_dir_offsets;
  4239. MZ_FILE *m_pFile;
  4240. void *m_pMem;
  4241. size_t m_mem_size;
  4242. size_t m_mem_capacity;
  4243. };
  4244. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
  4245. (array_ptr)->m_element_size = element_size
  4246. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
  4247. ((element_type *)((array_ptr)->m_p))[index]
  4248. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
  4249. mz_zip_array *pArray) {
  4250. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  4251. memset(pArray, 0, sizeof(mz_zip_array));
  4252. }
  4253. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
  4254. mz_zip_array *pArray,
  4255. size_t min_new_capacity,
  4256. mz_uint growing) {
  4257. void *pNew_p;
  4258. size_t new_capacity = min_new_capacity;
  4259. MZ_ASSERT(pArray->m_element_size);
  4260. if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  4261. if (growing) {
  4262. new_capacity = MZ_MAX(1, pArray->m_capacity);
  4263. while (new_capacity < min_new_capacity) new_capacity *= 2;
  4264. }
  4265. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
  4266. pArray->m_element_size, new_capacity)))
  4267. return MZ_FALSE;
  4268. pArray->m_p = pNew_p;
  4269. pArray->m_capacity = new_capacity;
  4270. return MZ_TRUE;
  4271. }
  4272. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip,
  4273. mz_zip_array *pArray,
  4274. size_t new_capacity,
  4275. mz_uint growing) {
  4276. if (new_capacity > pArray->m_capacity) {
  4277. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
  4278. return MZ_FALSE;
  4279. }
  4280. return MZ_TRUE;
  4281. }
  4282. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip,
  4283. mz_zip_array *pArray,
  4284. size_t new_size,
  4285. mz_uint growing) {
  4286. if (new_size > pArray->m_capacity) {
  4287. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
  4288. return MZ_FALSE;
  4289. }
  4290. pArray->m_size = new_size;
  4291. return MZ_TRUE;
  4292. }
  4293. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip,
  4294. mz_zip_array *pArray,
  4295. size_t n) {
  4296. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  4297. }
  4298. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip,
  4299. mz_zip_array *pArray,
  4300. const void *pElements,
  4301. size_t n) {
  4302. size_t orig_size = pArray->m_size;
  4303. if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
  4304. return MZ_FALSE;
  4305. memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
  4306. pElements, n * pArray->m_element_size);
  4307. return MZ_TRUE;
  4308. }
  4309. #ifndef MINIZ_NO_TIME
  4310. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
  4311. struct tm tm;
  4312. memset(&tm, 0, sizeof(tm));
  4313. tm.tm_isdst = -1;
  4314. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
  4315. tm.tm_mon = ((dos_date >> 5) & 15) - 1;
  4316. tm.tm_mday = dos_date & 31;
  4317. tm.tm_hour = (dos_time >> 11) & 31;
  4318. tm.tm_min = (dos_time >> 5) & 63;
  4319. tm.tm_sec = (dos_time << 1) & 62;
  4320. return mktime(&tm);
  4321. }
  4322. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
  4323. mz_uint16 *pDOS_date) {
  4324. #ifdef _MSC_VER
  4325. struct tm tm_struct;
  4326. struct tm *tm = &tm_struct;
  4327. errno_t err = localtime_s(tm, &time);
  4328. if (err) {
  4329. *pDOS_date = 0;
  4330. *pDOS_time = 0;
  4331. return;
  4332. }
  4333. #else
  4334. struct tm *tm = localtime(&time);
  4335. #endif
  4336. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
  4337. ((tm->tm_sec) >> 1));
  4338. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
  4339. ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  4340. }
  4341. #endif
  4342. #ifndef MINIZ_NO_STDIO
  4343. static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
  4344. mz_uint16 *pDOS_time,
  4345. mz_uint16 *pDOS_date) {
  4346. #ifdef MINIZ_NO_TIME
  4347. (void)pFilename;
  4348. *pDOS_date = *pDOS_time = 0;
  4349. #else
  4350. struct MZ_FILE_STAT_STRUCT file_stat;
  4351. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
  4352. // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  4353. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE;
  4354. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  4355. #endif // #ifdef MINIZ_NO_TIME
  4356. return MZ_TRUE;
  4357. }
  4358. #ifndef MINIZ_NO_TIME
  4359. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
  4360. time_t modified_time) {
  4361. struct utimbuf t;
  4362. t.actime = access_time;
  4363. t.modtime = modified_time;
  4364. return !utime(pFilename, &t);
  4365. }
  4366. #endif // #ifndef MINIZ_NO_TIME
  4367. #endif // #ifndef MINIZ_NO_STDIO
  4368. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
  4369. mz_uint32 flags) {
  4370. (void)flags;
  4371. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  4372. return MZ_FALSE;
  4373. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  4374. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  4375. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  4376. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  4377. pZip->m_archive_size = 0;
  4378. pZip->m_central_directory_file_ofs = 0;
  4379. pZip->m_total_files = 0;
  4380. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  4381. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  4382. return MZ_FALSE;
  4383. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  4384. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  4385. sizeof(mz_uint8));
  4386. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  4387. sizeof(mz_uint32));
  4388. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  4389. sizeof(mz_uint32));
  4390. return MZ_TRUE;
  4391. }
  4392. static MZ_FORCEINLINE mz_bool
  4393. mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
  4394. const mz_zip_array *pCentral_dir_offsets,
  4395. mz_uint l_index, mz_uint r_index) {
  4396. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4397. pCentral_dir_array, mz_uint8,
  4398. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4399. l_index)),
  4400. *pE;
  4401. const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(
  4402. pCentral_dir_array, mz_uint8,
  4403. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  4404. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
  4405. r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4406. mz_uint8 l = 0, r = 0;
  4407. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4408. pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4409. pE = pL + MZ_MIN(l_len, r_len);
  4410. while (pL < pE) {
  4411. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4412. pL++;
  4413. pR++;
  4414. }
  4415. return (pL == pE) ? (l_len < r_len) : (l < r);
  4416. }
  4417. #define MZ_SWAP_UINT32(a, b) \
  4418. do { \
  4419. mz_uint32 t = a; \
  4420. a = b; \
  4421. b = t; \
  4422. } \
  4423. MZ_MACRO_END
  4424. // Heap sort of lowercased filenames, used to help accelerate plain central
  4425. // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
  4426. // but it could allocate memory.)
  4427. static void mz_zip_reader_sort_central_dir_offsets_by_filename(
  4428. mz_zip_archive *pZip) {
  4429. mz_zip_internal_state *pState = pZip->m_pState;
  4430. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4431. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4432. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4433. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4434. const int size = pZip->m_total_files;
  4435. int start = (size - 2) >> 1, end;
  4436. while (start >= 0) {
  4437. int child, root = start;
  4438. for (;;) {
  4439. if ((child = (root << 1) + 1) >= size) break;
  4440. child +=
  4441. (((child + 1) < size) &&
  4442. (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4443. pIndices[child], pIndices[child + 1])));
  4444. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4445. pIndices[root], pIndices[child]))
  4446. break;
  4447. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4448. root = child;
  4449. }
  4450. start--;
  4451. }
  4452. end = size - 1;
  4453. while (end > 0) {
  4454. int child, root = 0;
  4455. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  4456. for (;;) {
  4457. if ((child = (root << 1) + 1) >= end) break;
  4458. child +=
  4459. (((child + 1) < end) &&
  4460. mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4461. pIndices[child], pIndices[child + 1]));
  4462. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4463. pIndices[root], pIndices[child]))
  4464. break;
  4465. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4466. root = child;
  4467. }
  4468. end--;
  4469. }
  4470. }
  4471. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
  4472. mz_uint32 flags) {
  4473. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  4474. mz_uint64 cdir_ofs;
  4475. mz_int64 cur_file_ofs;
  4476. const mz_uint8 *p;
  4477. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
  4478. mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  4479. mz_bool sort_central_dir =
  4480. ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  4481. // Basic sanity checks - reject files which are too small, and check the first
  4482. // 4 bytes of the file to make sure a local header is there.
  4483. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4484. return MZ_FALSE;
  4485. // Find the end of central directory record by scanning the file from the end
  4486. // towards the beginning.
  4487. cur_file_ofs =
  4488. MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  4489. for (;;) {
  4490. int i,
  4491. n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  4492. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  4493. return MZ_FALSE;
  4494. for (i = n - 4; i >= 0; --i)
  4495. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break;
  4496. if (i >= 0) {
  4497. cur_file_ofs += i;
  4498. break;
  4499. }
  4500. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
  4501. (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  4502. return MZ_FALSE;
  4503. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  4504. }
  4505. // Read and verify the end of central directory record.
  4506. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4507. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
  4508. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4509. return MZ_FALSE;
  4510. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
  4511. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  4512. ((pZip->m_total_files =
  4513. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
  4514. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  4515. return MZ_FALSE;
  4516. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  4517. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  4518. if (((num_this_disk | cdir_disk_index) != 0) &&
  4519. ((num_this_disk != 1) || (cdir_disk_index != 1)))
  4520. return MZ_FALSE;
  4521. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
  4522. pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  4523. return MZ_FALSE;
  4524. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  4525. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE;
  4526. pZip->m_central_directory_file_ofs = cdir_ofs;
  4527. if (pZip->m_total_files) {
  4528. mz_uint i, n;
  4529. // Read the entire central directory into a heap block, and allocate another
  4530. // heap block to hold the unsorted central dir file record offsets, and
  4531. // another to hold the sorted indices.
  4532. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
  4533. MZ_FALSE)) ||
  4534. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
  4535. pZip->m_total_files, MZ_FALSE)))
  4536. return MZ_FALSE;
  4537. if (sort_central_dir) {
  4538. if (!mz_zip_array_resize(pZip,
  4539. &pZip->m_pState->m_sorted_central_dir_offsets,
  4540. pZip->m_total_files, MZ_FALSE))
  4541. return MZ_FALSE;
  4542. }
  4543. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
  4544. pZip->m_pState->m_central_dir.m_p,
  4545. cdir_size) != cdir_size)
  4546. return MZ_FALSE;
  4547. // Now create an index into the central directory file records, do some
  4548. // basic sanity checking on each record, and check for zip64 entries (which
  4549. // are not yet supported).
  4550. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  4551. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
  4552. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  4553. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
  4554. (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  4555. return MZ_FALSE;
  4556. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4557. i) =
  4558. (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  4559. if (sort_central_dir)
  4560. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
  4561. mz_uint32, i) = i;
  4562. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4563. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4564. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
  4565. (decomp_size != comp_size)) ||
  4566. (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
  4567. (comp_size == 0xFFFFFFFF))
  4568. return MZ_FALSE;
  4569. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  4570. if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE;
  4571. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
  4572. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  4573. return MZ_FALSE;
  4574. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4575. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4576. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  4577. MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
  4578. n)
  4579. return MZ_FALSE;
  4580. n -= total_header_size;
  4581. p += total_header_size;
  4582. }
  4583. }
  4584. if (sort_central_dir)
  4585. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  4586. return MZ_TRUE;
  4587. }
  4588. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  4589. mz_uint32 flags) {
  4590. if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE;
  4591. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4592. pZip->m_archive_size = size;
  4593. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4594. mz_zip_reader_end(pZip);
  4595. return MZ_FALSE;
  4596. }
  4597. return MZ_TRUE;
  4598. }
  4599. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
  4600. void *pBuf, size_t n) {
  4601. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4602. size_t s = (file_ofs >= pZip->m_archive_size)
  4603. ? 0
  4604. : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  4605. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  4606. return s;
  4607. }
  4608. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  4609. size_t size, mz_uint32 flags) {
  4610. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4611. pZip->m_archive_size = size;
  4612. pZip->m_pRead = mz_zip_mem_read_func;
  4613. pZip->m_pIO_opaque = pZip;
  4614. #ifdef __cplusplus
  4615. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  4616. #else
  4617. pZip->m_pState->m_pMem = (void *)pMem;
  4618. #endif
  4619. pZip->m_pState->m_mem_size = size;
  4620. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4621. mz_zip_reader_end(pZip);
  4622. return MZ_FALSE;
  4623. }
  4624. return MZ_TRUE;
  4625. }
  4626. #ifndef MINIZ_NO_STDIO
  4627. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
  4628. void *pBuf, size_t n) {
  4629. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4630. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  4631. if (((mz_int64)file_ofs < 0) ||
  4632. (((cur_ofs != (mz_int64)file_ofs)) &&
  4633. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  4634. return 0;
  4635. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  4636. }
  4637. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  4638. mz_uint32 flags) {
  4639. mz_uint64 file_size;
  4640. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  4641. if (!pFile) return MZ_FALSE;
  4642. if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
  4643. MZ_FCLOSE(pFile);
  4644. return MZ_FALSE;
  4645. }
  4646. file_size = MZ_FTELL64(pFile);
  4647. if (!mz_zip_reader_init_internal(pZip, flags)) {
  4648. MZ_FCLOSE(pFile);
  4649. return MZ_FALSE;
  4650. }
  4651. pZip->m_pRead = mz_zip_file_read_func;
  4652. pZip->m_pIO_opaque = pZip;
  4653. pZip->m_pState->m_pFile = pFile;
  4654. pZip->m_archive_size = file_size;
  4655. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4656. mz_zip_reader_end(pZip);
  4657. return MZ_FALSE;
  4658. }
  4659. return MZ_TRUE;
  4660. }
  4661. #endif // #ifndef MINIZ_NO_STDIO
  4662. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
  4663. return pZip ? pZip->m_total_files : 0;
  4664. }
  4665. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(
  4666. mz_zip_archive *pZip, mz_uint file_index) {
  4667. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
  4668. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4669. return NULL;
  4670. return &MZ_ZIP_ARRAY_ELEMENT(
  4671. &pZip->m_pState->m_central_dir, mz_uint8,
  4672. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4673. file_index));
  4674. }
  4675. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  4676. mz_uint file_index) {
  4677. mz_uint m_bit_flag;
  4678. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4679. if (!p) return MZ_FALSE;
  4680. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4681. return (m_bit_flag & 1);
  4682. }
  4683. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  4684. mz_uint file_index) {
  4685. mz_uint filename_len, external_attr;
  4686. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4687. if (!p) return MZ_FALSE;
  4688. // First see if the filename ends with a '/' character.
  4689. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4690. if (filename_len) {
  4691. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  4692. return MZ_TRUE;
  4693. }
  4694. // Bugfix: This code was also checking if the internal attribute was non-zero,
  4695. // which wasn't correct.
  4696. // Most/all zip writers (hopefully) set DOS file/directory attributes in the
  4697. // low 16-bits, so check for the DOS directory flag and ignore the source OS
  4698. // ID in the created by field.
  4699. // FIXME: Remove this check? Is it necessary - we already check the filename.
  4700. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4701. if ((external_attr & 0x10) != 0) return MZ_TRUE;
  4702. return MZ_FALSE;
  4703. }
  4704. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  4705. mz_zip_archive_file_stat *pStat) {
  4706. mz_uint n;
  4707. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4708. if ((!p) || (!pStat)) return MZ_FALSE;
  4709. // Unpack the central directory record.
  4710. pStat->m_file_index = file_index;
  4711. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
  4712. &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  4713. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  4714. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  4715. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4716. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  4717. #ifndef MINIZ_NO_TIME
  4718. pStat->m_time =
  4719. mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
  4720. MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  4721. #endif
  4722. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  4723. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4724. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4725. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  4726. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4727. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4728. // Copy as much of the filename and comment as possible.
  4729. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4730. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  4731. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4732. pStat->m_filename[n] = '\0';
  4733. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4734. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  4735. pStat->m_comment_size = n;
  4736. memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4737. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4738. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4739. n);
  4740. pStat->m_comment[n] = '\0';
  4741. return MZ_TRUE;
  4742. }
  4743. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  4744. char *pFilename, mz_uint filename_buf_size) {
  4745. mz_uint n;
  4746. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4747. if (!p) {
  4748. if (filename_buf_size) pFilename[0] = '\0';
  4749. return 0;
  4750. }
  4751. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4752. if (filename_buf_size) {
  4753. n = MZ_MIN(n, filename_buf_size - 1);
  4754. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4755. pFilename[n] = '\0';
  4756. }
  4757. return n + 1;
  4758. }
  4759. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA,
  4760. const char *pB,
  4761. mz_uint len,
  4762. mz_uint flags) {
  4763. mz_uint i;
  4764. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len);
  4765. for (i = 0; i < len; ++i)
  4766. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE;
  4767. return MZ_TRUE;
  4768. }
  4769. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(
  4770. const mz_zip_array *pCentral_dir_array,
  4771. const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR,
  4772. mz_uint r_len) {
  4773. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4774. pCentral_dir_array, mz_uint8,
  4775. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4776. l_index)),
  4777. *pE;
  4778. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4779. mz_uint8 l = 0, r = 0;
  4780. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4781. pE = pL + MZ_MIN(l_len, r_len);
  4782. while (pL < pE) {
  4783. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4784. pL++;
  4785. pR++;
  4786. }
  4787. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  4788. }
  4789. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
  4790. const char *pFilename) {
  4791. mz_zip_internal_state *pState = pZip->m_pState;
  4792. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4793. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4794. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4795. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4796. const int size = pZip->m_total_files;
  4797. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  4798. int l = 0, h = size - 1;
  4799. while (l <= h) {
  4800. int m = (l + h) >> 1, file_index = pIndices[m],
  4801. comp =
  4802. mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
  4803. file_index, pFilename, filename_len);
  4804. if (!comp)
  4805. return file_index;
  4806. else if (comp < 0)
  4807. l = m + 1;
  4808. else
  4809. h = m - 1;
  4810. }
  4811. return -1;
  4812. }
  4813. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  4814. const char *pComment, mz_uint flags) {
  4815. mz_uint file_index;
  4816. size_t name_len, comment_len;
  4817. if ((!pZip) || (!pZip->m_pState) || (!pName) ||
  4818. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4819. return -1;
  4820. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
  4821. (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  4822. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  4823. name_len = strlen(pName);
  4824. if (name_len > 0xFFFF) return -1;
  4825. comment_len = pComment ? strlen(pComment) : 0;
  4826. if (comment_len > 0xFFFF) return -1;
  4827. for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
  4828. const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(
  4829. &pZip->m_pState->m_central_dir, mz_uint8,
  4830. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4831. file_index));
  4832. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4833. const char *pFilename =
  4834. (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4835. if (filename_len < name_len) continue;
  4836. if (comment_len) {
  4837. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4838. file_comment_len =
  4839. MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4840. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  4841. if ((file_comment_len != comment_len) ||
  4842. (!mz_zip_reader_string_equal(pComment, pFile_comment,
  4843. file_comment_len, flags)))
  4844. continue;
  4845. }
  4846. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
  4847. int ofs = filename_len - 1;
  4848. do {
  4849. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
  4850. (pFilename[ofs] == ':'))
  4851. break;
  4852. } while (--ofs >= 0);
  4853. ofs++;
  4854. pFilename += ofs;
  4855. filename_len -= ofs;
  4856. }
  4857. if ((filename_len == name_len) &&
  4858. (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  4859. return file_index;
  4860. }
  4861. return -1;
  4862. }
  4863. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  4864. mz_uint file_index, void *pBuf,
  4865. size_t buf_size, mz_uint flags,
  4866. void *pUser_read_buf,
  4867. size_t user_read_buf_size) {
  4868. int status = TINFL_STATUS_DONE;
  4869. mz_uint64 needed_size, cur_file_ofs, comp_remaining,
  4870. out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  4871. mz_zip_archive_file_stat file_stat;
  4872. void *pRead_buf;
  4873. mz_uint32
  4874. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  4875. sizeof(mz_uint32)];
  4876. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4877. tinfl_decompressor inflator;
  4878. if ((buf_size) && (!pBuf)) return MZ_FALSE;
  4879. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  4880. // Empty file, or a directory (but not always a directory - I've seen odd zips
  4881. // with directories that have compressed data which inflates to 0 bytes)
  4882. if (!file_stat.m_comp_size) return MZ_TRUE;
  4883. // Entry is a subdirectory (I've seen old zips with dir entries which have
  4884. // compressed deflate data which inflates to 0 bytes, but these entries claim
  4885. // to uncompress to 512 bytes in the headers).
  4886. // I'm torn how to handle this case - should it fail instead?
  4887. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  4888. // Encryption and patch files are not supported.
  4889. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  4890. // This function only supports stored and deflate.
  4891. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  4892. (file_stat.m_method != MZ_DEFLATED))
  4893. return MZ_FALSE;
  4894. // Ensure supplied output buffer is large enough.
  4895. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
  4896. : file_stat.m_uncomp_size;
  4897. if (buf_size < needed_size) return MZ_FALSE;
  4898. // Read and parse the local directory entry.
  4899. cur_file_ofs = file_stat.m_local_header_ofs;
  4900. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  4901. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  4902. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4903. return MZ_FALSE;
  4904. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4905. return MZ_FALSE;
  4906. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  4907. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  4908. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4909. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  4910. return MZ_FALSE;
  4911. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  4912. // The file is stored or the caller has requested the compressed data.
  4913. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4914. (size_t)needed_size) != needed_size)
  4915. return MZ_FALSE;
  4916. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
  4917. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4918. (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  4919. }
  4920. // Decompress the file either directly from memory or from a file input
  4921. // buffer.
  4922. tinfl_init(&inflator);
  4923. if (pZip->m_pState->m_pMem) {
  4924. // Read directly from the archive in memory.
  4925. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  4926. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  4927. comp_remaining = 0;
  4928. } else if (pUser_read_buf) {
  4929. // Use a user provided read buffer.
  4930. if (!user_read_buf_size) return MZ_FALSE;
  4931. pRead_buf = (mz_uint8 *)pUser_read_buf;
  4932. read_buf_size = user_read_buf_size;
  4933. read_buf_avail = 0;
  4934. comp_remaining = file_stat.m_comp_size;
  4935. } else {
  4936. // Temporarily allocate a read buffer.
  4937. read_buf_size =
  4938. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  4939. #ifdef _MSC_VER
  4940. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  4941. (read_buf_size > 0x7FFFFFFF))
  4942. #else
  4943. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  4944. #endif
  4945. return MZ_FALSE;
  4946. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4947. (size_t)read_buf_size)))
  4948. return MZ_FALSE;
  4949. read_buf_avail = 0;
  4950. comp_remaining = file_stat.m_comp_size;
  4951. }
  4952. do {
  4953. size_t in_buf_size,
  4954. out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  4955. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  4956. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4957. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4958. (size_t)read_buf_avail) != read_buf_avail) {
  4959. status = TINFL_STATUS_FAILED;
  4960. break;
  4961. }
  4962. cur_file_ofs += read_buf_avail;
  4963. comp_remaining -= read_buf_avail;
  4964. read_buf_ofs = 0;
  4965. }
  4966. in_buf_size = (size_t)read_buf_avail;
  4967. status = tinfl_decompress(
  4968. &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  4969. (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
  4970. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
  4971. (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  4972. read_buf_avail -= in_buf_size;
  4973. read_buf_ofs += in_buf_size;
  4974. out_buf_ofs += out_buf_size;
  4975. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  4976. if (status == TINFL_STATUS_DONE) {
  4977. // Make sure the entire file was decompressed, and check its CRC.
  4978. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  4979. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4980. (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  4981. status = TINFL_STATUS_FAILED;
  4982. }
  4983. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  4984. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4985. return status == TINFL_STATUS_DONE;
  4986. }
  4987. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  4988. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  4989. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
  4990. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  4991. if (file_index < 0) return MZ_FALSE;
  4992. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  4993. flags, pUser_read_buf,
  4994. user_read_buf_size);
  4995. }
  4996. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  4997. void *pBuf, size_t buf_size,
  4998. mz_uint flags) {
  4999. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  5000. flags, NULL, 0);
  5001. }
  5002. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  5003. const char *pFilename, void *pBuf,
  5004. size_t buf_size, mz_uint flags) {
  5005. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
  5006. buf_size, flags, NULL, 0);
  5007. }
  5008. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  5009. size_t *pSize, mz_uint flags) {
  5010. mz_uint64 comp_size, uncomp_size, alloc_size;
  5011. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  5012. void *pBuf;
  5013. if (pSize) *pSize = 0;
  5014. if (!p) return NULL;
  5015. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5016. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  5017. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  5018. #ifdef _MSC_VER
  5019. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5020. #else
  5021. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5022. #endif
  5023. return NULL;
  5024. if (NULL ==
  5025. (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  5026. return NULL;
  5027. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
  5028. flags)) {
  5029. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5030. return NULL;
  5031. }
  5032. if (pSize) *pSize = (size_t)alloc_size;
  5033. return pBuf;
  5034. }
  5035. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  5036. const char *pFilename, size_t *pSize,
  5037. mz_uint flags) {
  5038. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5039. if (file_index < 0) {
  5040. if (pSize) *pSize = 0;
  5041. return MZ_FALSE;
  5042. }
  5043. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  5044. }
  5045. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  5046. mz_uint file_index,
  5047. mz_file_write_func pCallback,
  5048. void *pOpaque, mz_uint flags) {
  5049. int status = TINFL_STATUS_DONE;
  5050. mz_uint file_crc32 = MZ_CRC32_INIT;
  5051. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
  5052. out_buf_ofs = 0, cur_file_ofs;
  5053. mz_zip_archive_file_stat file_stat;
  5054. void *pRead_buf = NULL;
  5055. void *pWrite_buf = NULL;
  5056. mz_uint32
  5057. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5058. sizeof(mz_uint32)];
  5059. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5060. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5061. // Empty file, or a directory (but not always a directory - I've seen odd zips
  5062. // with directories that have compressed data which inflates to 0 bytes)
  5063. if (!file_stat.m_comp_size) return MZ_TRUE;
  5064. // Entry is a subdirectory (I've seen old zips with dir entries which have
  5065. // compressed deflate data which inflates to 0 bytes, but these entries claim
  5066. // to uncompress to 512 bytes in the headers).
  5067. // I'm torn how to handle this case - should it fail instead?
  5068. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  5069. // Encryption and patch files are not supported.
  5070. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  5071. // This function only supports stored and deflate.
  5072. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  5073. (file_stat.m_method != MZ_DEFLATED))
  5074. return MZ_FALSE;
  5075. // Read and parse the local directory entry.
  5076. cur_file_ofs = file_stat.m_local_header_ofs;
  5077. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  5078. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5079. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5080. return MZ_FALSE;
  5081. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5082. return MZ_FALSE;
  5083. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  5084. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5085. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5086. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  5087. return MZ_FALSE;
  5088. // Decompress the file either directly from memory or from a file input
  5089. // buffer.
  5090. if (pZip->m_pState->m_pMem) {
  5091. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  5092. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  5093. comp_remaining = 0;
  5094. } else {
  5095. read_buf_size =
  5096. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5097. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5098. (size_t)read_buf_size)))
  5099. return MZ_FALSE;
  5100. read_buf_avail = 0;
  5101. comp_remaining = file_stat.m_comp_size;
  5102. }
  5103. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  5104. // The file is stored or the caller has requested the compressed data.
  5105. if (pZip->m_pState->m_pMem) {
  5106. #ifdef _MSC_VER
  5107. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  5108. (file_stat.m_comp_size > 0xFFFFFFFF))
  5109. #else
  5110. if (((sizeof(size_t) == sizeof(mz_uint32))) &&
  5111. (file_stat.m_comp_size > 0xFFFFFFFF))
  5112. #endif
  5113. return MZ_FALSE;
  5114. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5115. (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  5116. status = TINFL_STATUS_FAILED;
  5117. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5118. file_crc32 =
  5119. (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
  5120. (size_t)file_stat.m_comp_size);
  5121. cur_file_ofs += file_stat.m_comp_size;
  5122. out_buf_ofs += file_stat.m_comp_size;
  5123. comp_remaining = 0;
  5124. } else {
  5125. while (comp_remaining) {
  5126. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5127. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5128. (size_t)read_buf_avail) != read_buf_avail) {
  5129. status = TINFL_STATUS_FAILED;
  5130. break;
  5131. }
  5132. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5133. file_crc32 = (mz_uint32)mz_crc32(
  5134. file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  5135. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5136. (size_t)read_buf_avail) != read_buf_avail) {
  5137. status = TINFL_STATUS_FAILED;
  5138. break;
  5139. }
  5140. cur_file_ofs += read_buf_avail;
  5141. out_buf_ofs += read_buf_avail;
  5142. comp_remaining -= read_buf_avail;
  5143. }
  5144. }
  5145. } else {
  5146. tinfl_decompressor inflator;
  5147. tinfl_init(&inflator);
  5148. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5149. TINFL_LZ_DICT_SIZE)))
  5150. status = TINFL_STATUS_FAILED;
  5151. else {
  5152. do {
  5153. mz_uint8 *pWrite_buf_cur =
  5154. (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5155. size_t in_buf_size,
  5156. out_buf_size =
  5157. TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5158. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  5159. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5160. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5161. (size_t)read_buf_avail) != read_buf_avail) {
  5162. status = TINFL_STATUS_FAILED;
  5163. break;
  5164. }
  5165. cur_file_ofs += read_buf_avail;
  5166. comp_remaining -= read_buf_avail;
  5167. read_buf_ofs = 0;
  5168. }
  5169. in_buf_size = (size_t)read_buf_avail;
  5170. status = tinfl_decompress(
  5171. &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  5172. (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
  5173. comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  5174. read_buf_avail -= in_buf_size;
  5175. read_buf_ofs += in_buf_size;
  5176. if (out_buf_size) {
  5177. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
  5178. out_buf_size) {
  5179. status = TINFL_STATUS_FAILED;
  5180. break;
  5181. }
  5182. file_crc32 =
  5183. (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  5184. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
  5185. status = TINFL_STATUS_FAILED;
  5186. break;
  5187. }
  5188. }
  5189. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
  5190. (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  5191. }
  5192. }
  5193. if ((status == TINFL_STATUS_DONE) &&
  5194. (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
  5195. // Make sure the entire file was decompressed, and check its CRC.
  5196. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  5197. (file_crc32 != file_stat.m_crc32))
  5198. status = TINFL_STATUS_FAILED;
  5199. }
  5200. if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5201. if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  5202. return status == TINFL_STATUS_DONE;
  5203. }
  5204. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  5205. const char *pFilename,
  5206. mz_file_write_func pCallback,
  5207. void *pOpaque, mz_uint flags) {
  5208. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5209. if (file_index < 0) return MZ_FALSE;
  5210. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
  5211. flags);
  5212. }
  5213. #ifndef MINIZ_NO_STDIO
  5214. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
  5215. const void *pBuf, size_t n) {
  5216. (void)ofs;
  5217. return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
  5218. }
  5219. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  5220. const char *pDst_filename,
  5221. mz_uint flags) {
  5222. mz_bool status;
  5223. mz_zip_archive_file_stat file_stat;
  5224. MZ_FILE *pFile;
  5225. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5226. pFile = MZ_FOPEN(pDst_filename, "wb");
  5227. if (!pFile) return MZ_FALSE;
  5228. status = mz_zip_reader_extract_to_callback(
  5229. pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  5230. if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE;
  5231. #ifndef MINIZ_NO_TIME
  5232. if (status)
  5233. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  5234. #endif
  5235. return status;
  5236. }
  5237. #endif // #ifndef MINIZ_NO_STDIO
  5238. mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
  5239. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  5240. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5241. return MZ_FALSE;
  5242. if (pZip->m_pState) {
  5243. mz_zip_internal_state *pState = pZip->m_pState;
  5244. pZip->m_pState = NULL;
  5245. mz_zip_array_clear(pZip, &pState->m_central_dir);
  5246. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  5247. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  5248. #ifndef MINIZ_NO_STDIO
  5249. if (pState->m_pFile) {
  5250. MZ_FCLOSE(pState->m_pFile);
  5251. pState->m_pFile = NULL;
  5252. }
  5253. #endif // #ifndef MINIZ_NO_STDIO
  5254. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  5255. }
  5256. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  5257. return MZ_TRUE;
  5258. }
  5259. #ifndef MINIZ_NO_STDIO
  5260. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  5261. const char *pArchive_filename,
  5262. const char *pDst_filename,
  5263. mz_uint flags) {
  5264. int file_index =
  5265. mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  5266. if (file_index < 0) return MZ_FALSE;
  5267. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  5268. }
  5269. #endif
  5270. // ------------------- .ZIP archive writing
  5271. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  5272. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
  5273. p[0] = (mz_uint8)v;
  5274. p[1] = (mz_uint8)(v >> 8);
  5275. }
  5276. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
  5277. p[0] = (mz_uint8)v;
  5278. p[1] = (mz_uint8)(v >> 8);
  5279. p[2] = (mz_uint8)(v >> 16);
  5280. p[3] = (mz_uint8)(v >> 24);
  5281. }
  5282. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  5283. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  5284. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
  5285. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
  5286. (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  5287. return MZ_FALSE;
  5288. if (pZip->m_file_offset_alignment) {
  5289. // Ensure user specified file offset alignment is a power of 2.
  5290. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  5291. return MZ_FALSE;
  5292. }
  5293. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  5294. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  5295. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  5296. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5297. pZip->m_archive_size = existing_size;
  5298. pZip->m_central_directory_file_ofs = 0;
  5299. pZip->m_total_files = 0;
  5300. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  5301. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  5302. return MZ_FALSE;
  5303. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  5304. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  5305. sizeof(mz_uint8));
  5306. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  5307. sizeof(mz_uint32));
  5308. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  5309. sizeof(mz_uint32));
  5310. return MZ_TRUE;
  5311. }
  5312. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
  5313. const void *pBuf, size_t n) {
  5314. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5315. mz_zip_internal_state *pState = pZip->m_pState;
  5316. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  5317. #ifdef _MSC_VER
  5318. if ((!n) ||
  5319. ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5320. #else
  5321. if ((!n) ||
  5322. ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5323. #endif
  5324. return 0;
  5325. if (new_size > pState->m_mem_capacity) {
  5326. void *pNew_block;
  5327. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
  5328. while (new_capacity < new_size) new_capacity *= 2;
  5329. if (NULL == (pNew_block = pZip->m_pRealloc(
  5330. pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  5331. return 0;
  5332. pState->m_pMem = pNew_block;
  5333. pState->m_mem_capacity = new_capacity;
  5334. }
  5335. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  5336. pState->m_mem_size = (size_t)new_size;
  5337. return n;
  5338. }
  5339. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  5340. size_t size_to_reserve_at_beginning,
  5341. size_t initial_allocation_size) {
  5342. pZip->m_pWrite = mz_zip_heap_write_func;
  5343. pZip->m_pIO_opaque = pZip;
  5344. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5345. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
  5346. size_to_reserve_at_beginning))) {
  5347. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
  5348. pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
  5349. mz_zip_writer_end(pZip);
  5350. return MZ_FALSE;
  5351. }
  5352. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  5353. }
  5354. return MZ_TRUE;
  5355. }
  5356. #ifndef MINIZ_NO_STDIO
  5357. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
  5358. const void *pBuf, size_t n) {
  5359. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5360. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  5361. if (((mz_int64)file_ofs < 0) ||
  5362. (((cur_ofs != (mz_int64)file_ofs)) &&
  5363. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  5364. return 0;
  5365. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  5366. }
  5367. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  5368. mz_uint64 size_to_reserve_at_beginning) {
  5369. MZ_FILE *pFile;
  5370. pZip->m_pWrite = mz_zip_file_write_func;
  5371. pZip->m_pIO_opaque = pZip;
  5372. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5373. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
  5374. mz_zip_writer_end(pZip);
  5375. return MZ_FALSE;
  5376. }
  5377. pZip->m_pState->m_pFile = pFile;
  5378. if (size_to_reserve_at_beginning) {
  5379. mz_uint64 cur_ofs = 0;
  5380. char buf[4096];
  5381. MZ_CLEAR_OBJ(buf);
  5382. do {
  5383. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  5384. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
  5385. mz_zip_writer_end(pZip);
  5386. return MZ_FALSE;
  5387. }
  5388. cur_ofs += n;
  5389. size_to_reserve_at_beginning -= n;
  5390. } while (size_to_reserve_at_beginning);
  5391. }
  5392. return MZ_TRUE;
  5393. }
  5394. #endif // #ifndef MINIZ_NO_STDIO
  5395. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  5396. const char *pFilename) {
  5397. mz_zip_internal_state *pState;
  5398. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5399. return MZ_FALSE;
  5400. // No sense in trying to write to an archive that's already at the support max
  5401. // size
  5402. if ((pZip->m_total_files == 0xFFFF) ||
  5403. ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5404. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  5405. return MZ_FALSE;
  5406. pState = pZip->m_pState;
  5407. if (pState->m_pFile) {
  5408. #ifdef MINIZ_NO_STDIO
  5409. pFilename;
  5410. return MZ_FALSE;
  5411. #else
  5412. // Archive is being read from stdio - try to reopen as writable.
  5413. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5414. if (!pFilename) return MZ_FALSE;
  5415. pZip->m_pWrite = mz_zip_file_write_func;
  5416. if (NULL ==
  5417. (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
  5418. // The mz_zip_archive is now in a bogus state because pState->m_pFile is
  5419. // NULL, so just close it.
  5420. mz_zip_reader_end(pZip);
  5421. return MZ_FALSE;
  5422. }
  5423. #endif // #ifdef MINIZ_NO_STDIO
  5424. } else if (pState->m_pMem) {
  5425. // Archive lives in a memory block. Assume it's from the heap that we can
  5426. // resize using the realloc callback.
  5427. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5428. pState->m_mem_capacity = pState->m_mem_size;
  5429. pZip->m_pWrite = mz_zip_heap_write_func;
  5430. }
  5431. // Archive is being read via a user provided read function - make sure the
  5432. // user has specified a write function too.
  5433. else if (!pZip->m_pWrite)
  5434. return MZ_FALSE;
  5435. // Start writing new files at the archive's current central directory
  5436. // location.
  5437. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  5438. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5439. pZip->m_central_directory_file_ofs = 0;
  5440. return MZ_TRUE;
  5441. }
  5442. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  5443. const void *pBuf, size_t buf_size,
  5444. mz_uint level_and_flags) {
  5445. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
  5446. level_and_flags, 0, 0);
  5447. }
  5448. typedef struct {
  5449. mz_zip_archive *m_pZip;
  5450. mz_uint64 m_cur_archive_file_ofs;
  5451. mz_uint64 m_comp_size;
  5452. } mz_zip_writer_add_state;
  5453. static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
  5454. void *pUser) {
  5455. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  5456. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
  5457. pState->m_cur_archive_file_ofs, pBuf,
  5458. len) != len)
  5459. return MZ_FALSE;
  5460. pState->m_cur_archive_file_ofs += len;
  5461. pState->m_comp_size += len;
  5462. return MZ_TRUE;
  5463. }
  5464. static mz_bool mz_zip_writer_create_local_dir_header(
  5465. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5466. mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5467. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5468. mz_uint16 dos_time, mz_uint16 dos_date) {
  5469. (void)pZip;
  5470. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  5471. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  5472. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5473. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  5474. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  5475. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  5476. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  5477. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  5478. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  5479. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5480. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  5481. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  5482. return MZ_TRUE;
  5483. }
  5484. static mz_bool mz_zip_writer_create_central_dir_header(
  5485. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5486. mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
  5487. mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
  5488. mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
  5489. mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
  5490. (void)pZip;
  5491. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5492. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  5493. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5494. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  5495. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  5496. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  5497. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  5498. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  5499. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  5500. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5501. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  5502. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  5503. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  5504. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  5505. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  5506. return MZ_TRUE;
  5507. }
  5508. static mz_bool mz_zip_writer_add_to_central_dir(
  5509. mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
  5510. const void *pExtra, mz_uint16 extra_size, const void *pComment,
  5511. mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5512. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5513. mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
  5514. mz_uint32 ext_attributes) {
  5515. mz_zip_internal_state *pState = pZip->m_pState;
  5516. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  5517. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  5518. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5519. // No zip64 support yet
  5520. if ((local_header_ofs > 0xFFFFFFFF) ||
  5521. (((mz_uint64)pState->m_central_dir.m_size +
  5522. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
  5523. comment_size) > 0xFFFFFFFF))
  5524. return MZ_FALSE;
  5525. if (!mz_zip_writer_create_central_dir_header(
  5526. pZip, central_dir_header, filename_size, extra_size, comment_size,
  5527. uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
  5528. dos_date, local_header_ofs, ext_attributes))
  5529. return MZ_FALSE;
  5530. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
  5531. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  5532. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
  5533. filename_size)) ||
  5534. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
  5535. extra_size)) ||
  5536. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
  5537. comment_size)) ||
  5538. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
  5539. &central_dir_ofs, 1))) {
  5540. // Try to push the central directory array back into its original state.
  5541. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5542. MZ_FALSE);
  5543. return MZ_FALSE;
  5544. }
  5545. return MZ_TRUE;
  5546. }
  5547. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
  5548. // Basic ZIP archive filename validity checks: Valid filenames cannot start
  5549. // with a forward slash, cannot contain a drive letter, and cannot use
  5550. // DOS-style backward slashes.
  5551. if (*pArchive_name == '/') return MZ_FALSE;
  5552. while (*pArchive_name) {
  5553. if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE;
  5554. pArchive_name++;
  5555. }
  5556. return MZ_TRUE;
  5557. }
  5558. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(
  5559. mz_zip_archive *pZip) {
  5560. mz_uint32 n;
  5561. if (!pZip->m_file_offset_alignment) return 0;
  5562. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  5563. return (pZip->m_file_offset_alignment - n) &
  5564. (pZip->m_file_offset_alignment - 1);
  5565. }
  5566. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
  5567. mz_uint64 cur_file_ofs, mz_uint32 n) {
  5568. char buf[4096];
  5569. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  5570. while (n) {
  5571. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  5572. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  5573. return MZ_FALSE;
  5574. cur_file_ofs += s;
  5575. n -= s;
  5576. }
  5577. return MZ_TRUE;
  5578. }
  5579. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  5580. const char *pArchive_name, const void *pBuf,
  5581. size_t buf_size, const void *pComment,
  5582. mz_uint16 comment_size,
  5583. mz_uint level_and_flags, mz_uint64 uncomp_size,
  5584. mz_uint32 uncomp_crc32) {
  5585. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  5586. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  5587. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5588. cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  5589. size_t archive_name_size;
  5590. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5591. tdefl_compressor *pComp = NULL;
  5592. mz_bool store_data_uncompressed;
  5593. mz_zip_internal_state *pState;
  5594. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5595. level = level_and_flags & 0xF;
  5596. store_data_uncompressed =
  5597. ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  5598. if ((!pZip) || (!pZip->m_pState) ||
  5599. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
  5600. (!pArchive_name) || ((comment_size) && (!pComment)) ||
  5601. (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  5602. return MZ_FALSE;
  5603. pState = pZip->m_pState;
  5604. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  5605. return MZ_FALSE;
  5606. // No zip64 support yet
  5607. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE;
  5608. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5609. #ifndef MINIZ_NO_TIME
  5610. {
  5611. time_t cur_time;
  5612. time(&cur_time);
  5613. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  5614. }
  5615. #endif // #ifndef MINIZ_NO_TIME
  5616. archive_name_size = strlen(pArchive_name);
  5617. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5618. num_alignment_padding_bytes =
  5619. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5620. // no zip64 support yet
  5621. if ((pZip->m_total_files == 0xFFFF) ||
  5622. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5623. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5624. comment_size + archive_name_size) > 0xFFFFFFFF))
  5625. return MZ_FALSE;
  5626. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
  5627. // Set DOS Subdirectory attribute bit.
  5628. ext_attributes |= 0x10;
  5629. // Subdirectories cannot contain data.
  5630. if ((buf_size) || (uncomp_size)) return MZ_FALSE;
  5631. }
  5632. // Try to do any allocations before writing to the archive, so if an
  5633. // allocation fails the file remains unmodified. (A good idea if we're doing
  5634. // an in-place modification.)
  5635. if ((!mz_zip_array_ensure_room(
  5636. pZip, &pState->m_central_dir,
  5637. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) ||
  5638. (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  5639. return MZ_FALSE;
  5640. if ((!store_data_uncompressed) && (buf_size)) {
  5641. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5642. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  5643. return MZ_FALSE;
  5644. }
  5645. if (!mz_zip_writer_write_zeros(
  5646. pZip, cur_archive_file_ofs,
  5647. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5648. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5649. return MZ_FALSE;
  5650. }
  5651. local_dir_header_ofs += num_alignment_padding_bytes;
  5652. if (pZip->m_file_offset_alignment) {
  5653. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5654. 0);
  5655. }
  5656. cur_archive_file_ofs +=
  5657. num_alignment_padding_bytes + sizeof(local_dir_header);
  5658. MZ_CLEAR_OBJ(local_dir_header);
  5659. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5660. archive_name_size) != archive_name_size) {
  5661. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5662. return MZ_FALSE;
  5663. }
  5664. cur_archive_file_ofs += archive_name_size;
  5665. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
  5666. uncomp_crc32 =
  5667. (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
  5668. uncomp_size = buf_size;
  5669. if (uncomp_size <= 3) {
  5670. level = 0;
  5671. store_data_uncompressed = MZ_TRUE;
  5672. }
  5673. }
  5674. if (store_data_uncompressed) {
  5675. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
  5676. buf_size) != buf_size) {
  5677. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5678. return MZ_FALSE;
  5679. }
  5680. cur_archive_file_ofs += buf_size;
  5681. comp_size = buf_size;
  5682. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED;
  5683. } else if (buf_size) {
  5684. mz_zip_writer_add_state state;
  5685. state.m_pZip = pZip;
  5686. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5687. state.m_comp_size = 0;
  5688. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5689. tdefl_create_comp_flags_from_zip_params(
  5690. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5691. TDEFL_STATUS_OKAY) ||
  5692. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
  5693. TDEFL_STATUS_DONE)) {
  5694. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5695. return MZ_FALSE;
  5696. }
  5697. comp_size = state.m_comp_size;
  5698. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5699. method = MZ_DEFLATED;
  5700. }
  5701. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5702. pComp = NULL;
  5703. // no zip64 support yet
  5704. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5705. return MZ_FALSE;
  5706. if (!mz_zip_writer_create_local_dir_header(
  5707. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5708. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5709. return MZ_FALSE;
  5710. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5711. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5712. return MZ_FALSE;
  5713. if (!mz_zip_writer_add_to_central_dir(
  5714. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5715. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5716. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5717. return MZ_FALSE;
  5718. pZip->m_total_files++;
  5719. pZip->m_archive_size = cur_archive_file_ofs;
  5720. return MZ_TRUE;
  5721. }
  5722. #ifndef MINIZ_NO_STDIO
  5723. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  5724. const char *pSrc_filename, const void *pComment,
  5725. mz_uint16 comment_size,
  5726. mz_uint level_and_flags) {
  5727. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  5728. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  5729. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5730. cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
  5731. comp_size = 0;
  5732. size_t archive_name_size;
  5733. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5734. MZ_FILE *pSrc_file = NULL;
  5735. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5736. level = level_and_flags & 0xF;
  5737. if ((!pZip) || (!pZip->m_pState) ||
  5738. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
  5739. ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  5740. return MZ_FALSE;
  5741. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE;
  5742. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5743. archive_name_size = strlen(pArchive_name);
  5744. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5745. num_alignment_padding_bytes =
  5746. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5747. // no zip64 support yet
  5748. if ((pZip->m_total_files == 0xFFFF) ||
  5749. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5750. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5751. comment_size + archive_name_size) > 0xFFFFFFFF))
  5752. return MZ_FALSE;
  5753. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  5754. return MZ_FALSE;
  5755. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  5756. if (!pSrc_file) return MZ_FALSE;
  5757. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  5758. uncomp_size = MZ_FTELL64(pSrc_file);
  5759. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  5760. if (uncomp_size > 0xFFFFFFFF) {
  5761. // No zip64 support yet
  5762. MZ_FCLOSE(pSrc_file);
  5763. return MZ_FALSE;
  5764. }
  5765. if (uncomp_size <= 3) level = 0;
  5766. if (!mz_zip_writer_write_zeros(
  5767. pZip, cur_archive_file_ofs,
  5768. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5769. MZ_FCLOSE(pSrc_file);
  5770. return MZ_FALSE;
  5771. }
  5772. local_dir_header_ofs += num_alignment_padding_bytes;
  5773. if (pZip->m_file_offset_alignment) {
  5774. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5775. 0);
  5776. }
  5777. cur_archive_file_ofs +=
  5778. num_alignment_padding_bytes + sizeof(local_dir_header);
  5779. MZ_CLEAR_OBJ(local_dir_header);
  5780. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5781. archive_name_size) != archive_name_size) {
  5782. MZ_FCLOSE(pSrc_file);
  5783. return MZ_FALSE;
  5784. }
  5785. cur_archive_file_ofs += archive_name_size;
  5786. if (uncomp_size) {
  5787. mz_uint64 uncomp_remaining = uncomp_size;
  5788. void *pRead_buf =
  5789. pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  5790. if (!pRead_buf) {
  5791. MZ_FCLOSE(pSrc_file);
  5792. return MZ_FALSE;
  5793. }
  5794. if (!level) {
  5795. while (uncomp_remaining) {
  5796. mz_uint n =
  5797. (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  5798. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
  5799. (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
  5800. n) != n)) {
  5801. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5802. MZ_FCLOSE(pSrc_file);
  5803. return MZ_FALSE;
  5804. }
  5805. uncomp_crc32 =
  5806. (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  5807. uncomp_remaining -= n;
  5808. cur_archive_file_ofs += n;
  5809. }
  5810. comp_size = uncomp_size;
  5811. } else {
  5812. mz_bool result = MZ_FALSE;
  5813. mz_zip_writer_add_state state;
  5814. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5815. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  5816. if (!pComp) {
  5817. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5818. MZ_FCLOSE(pSrc_file);
  5819. return MZ_FALSE;
  5820. }
  5821. state.m_pZip = pZip;
  5822. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5823. state.m_comp_size = 0;
  5824. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5825. tdefl_create_comp_flags_from_zip_params(
  5826. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5827. TDEFL_STATUS_OKAY) {
  5828. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5829. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5830. MZ_FCLOSE(pSrc_file);
  5831. return MZ_FALSE;
  5832. }
  5833. for (;;) {
  5834. size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining,
  5835. (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5836. tdefl_status status;
  5837. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  5838. break;
  5839. uncomp_crc32 = (mz_uint32)mz_crc32(
  5840. uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  5841. uncomp_remaining -= in_buf_size;
  5842. status = tdefl_compress_buffer(
  5843. pComp, pRead_buf, in_buf_size,
  5844. uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  5845. if (status == TDEFL_STATUS_DONE) {
  5846. result = MZ_TRUE;
  5847. break;
  5848. } else if (status != TDEFL_STATUS_OKAY)
  5849. break;
  5850. }
  5851. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5852. if (!result) {
  5853. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5854. MZ_FCLOSE(pSrc_file);
  5855. return MZ_FALSE;
  5856. }
  5857. comp_size = state.m_comp_size;
  5858. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5859. method = MZ_DEFLATED;
  5860. }
  5861. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5862. }
  5863. MZ_FCLOSE(pSrc_file);
  5864. pSrc_file = NULL;
  5865. // no zip64 support yet
  5866. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5867. return MZ_FALSE;
  5868. if (!mz_zip_writer_create_local_dir_header(
  5869. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5870. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5871. return MZ_FALSE;
  5872. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5873. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5874. return MZ_FALSE;
  5875. if (!mz_zip_writer_add_to_central_dir(
  5876. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5877. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5878. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5879. return MZ_FALSE;
  5880. pZip->m_total_files++;
  5881. pZip->m_archive_size = cur_archive_file_ofs;
  5882. return MZ_TRUE;
  5883. }
  5884. #endif // #ifndef MINIZ_NO_STDIO
  5885. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  5886. mz_zip_archive *pSource_zip,
  5887. mz_uint file_index) {
  5888. mz_uint n, bit_flags, num_alignment_padding_bytes;
  5889. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  5890. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  5891. mz_uint32
  5892. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5893. sizeof(mz_uint32)];
  5894. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5895. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5896. size_t orig_central_dir_size;
  5897. mz_zip_internal_state *pState;
  5898. void *pBuf;
  5899. const mz_uint8 *pSrc_central_header;
  5900. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  5901. return MZ_FALSE;
  5902. if (NULL ==
  5903. (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  5904. return MZ_FALSE;
  5905. pState = pZip->m_pState;
  5906. num_alignment_padding_bytes =
  5907. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5908. // no zip64 support yet
  5909. if ((pZip->m_total_files == 0xFFFF) ||
  5910. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5911. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
  5912. 0xFFFFFFFF))
  5913. return MZ_FALSE;
  5914. cur_src_file_ofs =
  5915. MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  5916. cur_dst_file_ofs = pZip->m_archive_size;
  5917. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
  5918. pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5919. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5920. return MZ_FALSE;
  5921. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5922. return MZ_FALSE;
  5923. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5924. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
  5925. num_alignment_padding_bytes))
  5926. return MZ_FALSE;
  5927. cur_dst_file_ofs += num_alignment_padding_bytes;
  5928. local_dir_header_ofs = cur_dst_file_ofs;
  5929. if (pZip->m_file_offset_alignment) {
  5930. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5931. 0);
  5932. }
  5933. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
  5934. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5935. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5936. return MZ_FALSE;
  5937. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5938. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5939. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5940. comp_bytes_remaining =
  5941. n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5942. if (NULL == (pBuf = pZip->m_pAlloc(
  5943. pZip->m_pAlloc_opaque, 1,
  5944. (size_t)MZ_MAX(sizeof(mz_uint32) * 4,
  5945. MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
  5946. comp_bytes_remaining)))))
  5947. return MZ_FALSE;
  5948. while (comp_bytes_remaining) {
  5949. n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  5950. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5951. n) != n) {
  5952. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5953. return MZ_FALSE;
  5954. }
  5955. cur_src_file_ofs += n;
  5956. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5957. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5958. return MZ_FALSE;
  5959. }
  5960. cur_dst_file_ofs += n;
  5961. comp_bytes_remaining -= n;
  5962. }
  5963. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  5964. if (bit_flags & 8) {
  5965. // Copy data descriptor
  5966. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5967. sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
  5968. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5969. return MZ_FALSE;
  5970. }
  5971. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  5972. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5973. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5974. return MZ_FALSE;
  5975. }
  5976. cur_src_file_ofs += n;
  5977. cur_dst_file_ofs += n;
  5978. }
  5979. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5980. // no zip64 support yet
  5981. if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE;
  5982. orig_central_dir_size = pState->m_central_dir.m_size;
  5983. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5984. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
  5985. local_dir_header_ofs);
  5986. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
  5987. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  5988. return MZ_FALSE;
  5989. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  5990. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  5991. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  5992. if (!mz_zip_array_push_back(
  5993. pZip, &pState->m_central_dir,
  5994. pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
  5995. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5996. MZ_FALSE);
  5997. return MZ_FALSE;
  5998. }
  5999. if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE;
  6000. n = (mz_uint32)orig_central_dir_size;
  6001. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
  6002. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  6003. MZ_FALSE);
  6004. return MZ_FALSE;
  6005. }
  6006. pZip->m_total_files++;
  6007. pZip->m_archive_size = cur_dst_file_ofs;
  6008. return MZ_TRUE;
  6009. }
  6010. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
  6011. mz_zip_internal_state *pState;
  6012. mz_uint64 central_dir_ofs, central_dir_size;
  6013. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  6014. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  6015. return MZ_FALSE;
  6016. pState = pZip->m_pState;
  6017. // no zip64 support yet
  6018. if ((pZip->m_total_files > 0xFFFF) ||
  6019. ((pZip->m_archive_size + pState->m_central_dir.m_size +
  6020. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  6021. return MZ_FALSE;
  6022. central_dir_ofs = 0;
  6023. central_dir_size = 0;
  6024. if (pZip->m_total_files) {
  6025. // Write central directory
  6026. central_dir_ofs = pZip->m_archive_size;
  6027. central_dir_size = pState->m_central_dir.m_size;
  6028. pZip->m_central_directory_file_ofs = central_dir_ofs;
  6029. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
  6030. pState->m_central_dir.m_p,
  6031. (size_t)central_dir_size) != central_dir_size)
  6032. return MZ_FALSE;
  6033. pZip->m_archive_size += central_dir_size;
  6034. }
  6035. // Write end of central directory record
  6036. MZ_CLEAR_OBJ(hdr);
  6037. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
  6038. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  6039. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
  6040. pZip->m_total_files);
  6041. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  6042. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  6043. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  6044. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
  6045. sizeof(hdr)) != sizeof(hdr))
  6046. return MZ_FALSE;
  6047. #ifndef MINIZ_NO_STDIO
  6048. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE;
  6049. #endif // #ifndef MINIZ_NO_STDIO
  6050. pZip->m_archive_size += sizeof(hdr);
  6051. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  6052. return MZ_TRUE;
  6053. }
  6054. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  6055. size_t *pSize) {
  6056. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE;
  6057. if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE;
  6058. if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE;
  6059. *pBuf = pZip->m_pState->m_pMem;
  6060. *pSize = pZip->m_pState->m_mem_size;
  6061. pZip->m_pState->m_pMem = NULL;
  6062. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  6063. return MZ_TRUE;
  6064. }
  6065. mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
  6066. mz_zip_internal_state *pState;
  6067. mz_bool status = MZ_TRUE;
  6068. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  6069. ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
  6070. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  6071. return MZ_FALSE;
  6072. pState = pZip->m_pState;
  6073. pZip->m_pState = NULL;
  6074. mz_zip_array_clear(pZip, &pState->m_central_dir);
  6075. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  6076. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  6077. #ifndef MINIZ_NO_STDIO
  6078. if (pState->m_pFile) {
  6079. MZ_FCLOSE(pState->m_pFile);
  6080. pState->m_pFile = NULL;
  6081. }
  6082. #endif // #ifndef MINIZ_NO_STDIO
  6083. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
  6084. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  6085. pState->m_pMem = NULL;
  6086. }
  6087. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  6088. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  6089. return status;
  6090. }
  6091. #ifndef MINIZ_NO_STDIO
  6092. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  6093. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  6094. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  6095. mz_uint level_and_flags) {
  6096. mz_bool status, created_new_archive = MZ_FALSE;
  6097. mz_zip_archive zip_archive;
  6098. struct MZ_FILE_STAT_STRUCT file_stat;
  6099. MZ_CLEAR_OBJ(zip_archive);
  6100. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  6101. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
  6102. ((comment_size) && (!pComment)) ||
  6103. ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  6104. return MZ_FALSE;
  6105. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  6106. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
  6107. // Create a new archive.
  6108. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  6109. return MZ_FALSE;
  6110. created_new_archive = MZ_TRUE;
  6111. } else {
  6112. // Append to an existing archive.
  6113. if (!mz_zip_reader_init_file(
  6114. &zip_archive, pZip_filename,
  6115. level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6116. return MZ_FALSE;
  6117. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
  6118. mz_zip_reader_end(&zip_archive);
  6119. return MZ_FALSE;
  6120. }
  6121. }
  6122. status =
  6123. mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
  6124. pComment, comment_size, level_and_flags, 0, 0);
  6125. // Always finalize, even if adding failed for some reason, so we have a valid
  6126. // central directory. (This may not always succeed, but we can try.)
  6127. if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE;
  6128. if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE;
  6129. if ((!status) && (created_new_archive)) {
  6130. // It's a new archive and something went wrong, so just delete it.
  6131. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  6132. (void)ignoredStatus;
  6133. }
  6134. return status;
  6135. }
  6136. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  6137. const char *pArchive_name,
  6138. size_t *pSize, mz_uint flags) {
  6139. int file_index;
  6140. mz_zip_archive zip_archive;
  6141. void *p = NULL;
  6142. if (pSize) *pSize = 0;
  6143. if ((!pZip_filename) || (!pArchive_name)) return NULL;
  6144. MZ_CLEAR_OBJ(zip_archive);
  6145. if (!mz_zip_reader_init_file(
  6146. &zip_archive, pZip_filename,
  6147. flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6148. return NULL;
  6149. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
  6150. flags)) >= 0)
  6151. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  6152. mz_zip_reader_end(&zip_archive);
  6153. return p;
  6154. }
  6155. #endif // #ifndef MINIZ_NO_STDIO
  6156. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  6157. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  6158. #ifdef __cplusplus
  6159. }
  6160. #endif
  6161. #endif // MINIZ_HEADER_FILE_ONLY
  6162. /*
  6163. This is free and unencumbered software released into the public domain.
  6164. Anyone is free to copy, modify, publish, use, compile, sell, or
  6165. distribute this software, either in source code form or as a compiled
  6166. binary, for any purpose, commercial or non-commercial, and by any
  6167. means.
  6168. In jurisdictions that recognize copyright laws, the author or authors
  6169. of this software dedicate any and all copyright interest in the
  6170. software to the public domain. We make this dedication for the benefit
  6171. of the public at large and to the detriment of our heirs and
  6172. successors. We intend this dedication to be an overt act of
  6173. relinquishment in perpetuity of all present and future rights to this
  6174. software under copyright law.
  6175. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6176. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6177. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  6178. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6179. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6180. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  6181. OTHER DEALINGS IN THE SOFTWARE.
  6182. For more information, please refer to <http://unlicense.org/>
  6183. */
  6184. // ---------------------- end of miniz ----------------------------------------
  6185. #ifdef __clang__
  6186. #pragma clang diagnostic pop
  6187. #endif
  6188. #ifdef _MSC_VER
  6189. #pragma warning(pop)
  6190. #endif
  6191. } // namespace miniz
  6192. #else
  6193. // Reuse MINIZ_LITTE_ENDIAN macro
  6194. #if defined(__sparcv9)
  6195. // Big endian
  6196. #else
  6197. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  6198. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  6199. #define MINIZ_LITTLE_ENDIAN 1
  6200. #endif
  6201. #endif
  6202. #endif // TINYEXR_USE_MINIZ
  6203. // static bool IsBigEndian(void) {
  6204. // union {
  6205. // unsigned int i;
  6206. // char c[4];
  6207. // } bint = {0x01020304};
  6208. //
  6209. // return bint.c[0] == 1;
  6210. //}
  6211. static void SetErrorMessage(const std::string &msg, const char **err) {
  6212. if (err) {
  6213. #ifdef _WIN32
  6214. (*err) = _strdup(msg.c_str());
  6215. #else
  6216. (*err) = strdup(msg.c_str());
  6217. #endif
  6218. }
  6219. }
  6220. static const int kEXRVersionSize = 8;
  6221. static void cpy2(unsigned short *dst_val, const unsigned short *src_val) {
  6222. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6223. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6224. dst[0] = src[0];
  6225. dst[1] = src[1];
  6226. }
  6227. static void swap2(unsigned short *val) {
  6228. #ifdef MINIZ_LITTLE_ENDIAN
  6229. (void)val;
  6230. #else
  6231. unsigned short tmp = *val;
  6232. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6233. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6234. dst[0] = src[1];
  6235. dst[1] = src[0];
  6236. #endif
  6237. }
  6238. #ifdef __clang__
  6239. #pragma clang diagnostic push
  6240. #pragma clang diagnostic ignored "-Wunused-function"
  6241. #endif
  6242. static void cpy4(int *dst_val, const int *src_val) {
  6243. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6244. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6245. dst[0] = src[0];
  6246. dst[1] = src[1];
  6247. dst[2] = src[2];
  6248. dst[3] = src[3];
  6249. }
  6250. static void cpy4(unsigned int *dst_val, const unsigned int *src_val) {
  6251. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6252. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6253. dst[0] = src[0];
  6254. dst[1] = src[1];
  6255. dst[2] = src[2];
  6256. dst[3] = src[3];
  6257. }
  6258. static void cpy4(float *dst_val, const float *src_val) {
  6259. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6260. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6261. dst[0] = src[0];
  6262. dst[1] = src[1];
  6263. dst[2] = src[2];
  6264. dst[3] = src[3];
  6265. }
  6266. #ifdef __clang__
  6267. #pragma clang diagnostic pop
  6268. #endif
  6269. static void swap4(unsigned int *val) {
  6270. #ifdef MINIZ_LITTLE_ENDIAN
  6271. (void)val;
  6272. #else
  6273. unsigned int tmp = *val;
  6274. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6275. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6276. dst[0] = src[3];
  6277. dst[1] = src[2];
  6278. dst[2] = src[1];
  6279. dst[3] = src[0];
  6280. #endif
  6281. }
  6282. #if 0
  6283. static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
  6284. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6285. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6286. dst[0] = src[0];
  6287. dst[1] = src[1];
  6288. dst[2] = src[2];
  6289. dst[3] = src[3];
  6290. dst[4] = src[4];
  6291. dst[5] = src[5];
  6292. dst[6] = src[6];
  6293. dst[7] = src[7];
  6294. }
  6295. #endif
  6296. static void swap8(tinyexr::tinyexr_uint64 *val) {
  6297. #ifdef MINIZ_LITTLE_ENDIAN
  6298. (void)val;
  6299. #else
  6300. tinyexr::tinyexr_uint64 tmp = (*val);
  6301. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6302. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6303. dst[0] = src[7];
  6304. dst[1] = src[6];
  6305. dst[2] = src[5];
  6306. dst[3] = src[4];
  6307. dst[4] = src[3];
  6308. dst[5] = src[2];
  6309. dst[6] = src[1];
  6310. dst[7] = src[0];
  6311. #endif
  6312. }
  6313. // https://gist.github.com/rygorous/2156668
  6314. // Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
  6315. union FP32 {
  6316. unsigned int u;
  6317. float f;
  6318. struct {
  6319. #if MINIZ_LITTLE_ENDIAN
  6320. unsigned int Mantissa : 23;
  6321. unsigned int Exponent : 8;
  6322. unsigned int Sign : 1;
  6323. #else
  6324. unsigned int Sign : 1;
  6325. unsigned int Exponent : 8;
  6326. unsigned int Mantissa : 23;
  6327. #endif
  6328. } s;
  6329. };
  6330. #ifdef __clang__
  6331. #pragma clang diagnostic push
  6332. #pragma clang diagnostic ignored "-Wpadded"
  6333. #endif
  6334. union FP16 {
  6335. unsigned short u;
  6336. struct {
  6337. #if MINIZ_LITTLE_ENDIAN
  6338. unsigned int Mantissa : 10;
  6339. unsigned int Exponent : 5;
  6340. unsigned int Sign : 1;
  6341. #else
  6342. unsigned int Sign : 1;
  6343. unsigned int Exponent : 5;
  6344. unsigned int Mantissa : 10;
  6345. #endif
  6346. } s;
  6347. };
  6348. #ifdef __clang__
  6349. #pragma clang diagnostic pop
  6350. #endif
  6351. static FP32 half_to_float(FP16 h) {
  6352. static const FP32 magic = {113 << 23};
  6353. static const unsigned int shifted_exp = 0x7c00
  6354. << 13; // exponent mask after shift
  6355. FP32 o;
  6356. o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
  6357. unsigned int exp_ = shifted_exp & o.u; // just the exponent
  6358. o.u += (127 - 15) << 23; // exponent adjust
  6359. // handle exponent special cases
  6360. if (exp_ == shifted_exp) // Inf/NaN?
  6361. o.u += (128 - 16) << 23; // extra exp adjust
  6362. else if (exp_ == 0) // Zero/Denormal?
  6363. {
  6364. o.u += 1 << 23; // extra exp adjust
  6365. o.f -= magic.f; // renormalize
  6366. }
  6367. o.u |= (h.u & 0x8000U) << 16U; // sign bit
  6368. return o;
  6369. }
  6370. static FP16 float_to_half_full(FP32 f) {
  6371. FP16 o = {0};
  6372. // Based on ISPC reference code (with minor modifications)
  6373. if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
  6374. o.s.Exponent = 0;
  6375. else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
  6376. {
  6377. o.s.Exponent = 31;
  6378. o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
  6379. } else // Normalized number
  6380. {
  6381. // Exponent unbias the single, then bias the halfp
  6382. int newexp = f.s.Exponent - 127 + 15;
  6383. if (newexp >= 31) // Overflow, return signed infinity
  6384. o.s.Exponent = 31;
  6385. else if (newexp <= 0) // Underflow
  6386. {
  6387. if ((14 - newexp) <= 24) // Mantissa might be non-zero
  6388. {
  6389. unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
  6390. o.s.Mantissa = mant >> (14 - newexp);
  6391. if ((mant >> (13 - newexp)) & 1) // Check for rounding
  6392. o.u++; // Round, might overflow into exp bit, but this is OK
  6393. }
  6394. } else {
  6395. o.s.Exponent = static_cast<unsigned int>(newexp);
  6396. o.s.Mantissa = f.s.Mantissa >> 13;
  6397. if (f.s.Mantissa & 0x1000) // Check for rounding
  6398. o.u++; // Round, might overflow to inf, this is OK
  6399. }
  6400. }
  6401. o.s.Sign = f.s.Sign;
  6402. return o;
  6403. }
  6404. // NOTE: From OpenEXR code
  6405. // #define IMF_INCREASING_Y 0
  6406. // #define IMF_DECREASING_Y 1
  6407. // #define IMF_RAMDOM_Y 2
  6408. //
  6409. // #define IMF_NO_COMPRESSION 0
  6410. // #define IMF_RLE_COMPRESSION 1
  6411. // #define IMF_ZIPS_COMPRESSION 2
  6412. // #define IMF_ZIP_COMPRESSION 3
  6413. // #define IMF_PIZ_COMPRESSION 4
  6414. // #define IMF_PXR24_COMPRESSION 5
  6415. // #define IMF_B44_COMPRESSION 6
  6416. // #define IMF_B44A_COMPRESSION 7
  6417. #ifdef __clang__
  6418. #pragma clang diagnostic push
  6419. #if __has_warning("-Wzero-as-null-pointer-constant")
  6420. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  6421. #endif
  6422. #endif
  6423. static const char *ReadString(std::string *s, const char *ptr, size_t len) {
  6424. // Read untile NULL(\0).
  6425. const char *p = ptr;
  6426. const char *q = ptr;
  6427. while ((size_t(q - ptr) < len) && (*q) != 0) {
  6428. q++;
  6429. }
  6430. if (size_t(q - ptr) >= len) {
  6431. (*s) = std::string();
  6432. return NULL;
  6433. }
  6434. (*s) = std::string(p, q);
  6435. return q + 1; // skip '\0'
  6436. }
  6437. static bool ReadAttribute(std::string *name, std::string *type,
  6438. std::vector<unsigned char> *data, size_t *marker_size,
  6439. const char *marker, size_t size) {
  6440. size_t name_len = strnlen(marker, size);
  6441. if (name_len == size) {
  6442. // String does not have a terminating character.
  6443. return false;
  6444. }
  6445. *name = std::string(marker, name_len);
  6446. marker += name_len + 1;
  6447. size -= name_len + 1;
  6448. size_t type_len = strnlen(marker, size);
  6449. if (type_len == size) {
  6450. return false;
  6451. }
  6452. *type = std::string(marker, type_len);
  6453. marker += type_len + 1;
  6454. size -= type_len + 1;
  6455. if (size < sizeof(uint32_t)) {
  6456. return false;
  6457. }
  6458. uint32_t data_len;
  6459. memcpy(&data_len, marker, sizeof(uint32_t));
  6460. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  6461. if (data_len == 0) {
  6462. if ((*type).compare("string") == 0) {
  6463. // Accept empty string attribute.
  6464. marker += sizeof(uint32_t);
  6465. size -= sizeof(uint32_t);
  6466. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
  6467. data->resize(1);
  6468. (*data)[0] = '\0';
  6469. return true;
  6470. } else {
  6471. return false;
  6472. }
  6473. }
  6474. marker += sizeof(uint32_t);
  6475. size -= sizeof(uint32_t);
  6476. if (size < data_len) {
  6477. return false;
  6478. }
  6479. data->resize(static_cast<size_t>(data_len));
  6480. memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
  6481. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
  6482. return true;
  6483. }
  6484. static void WriteAttributeToMemory(std::vector<unsigned char> *out,
  6485. const char *name, const char *type,
  6486. const unsigned char *data, int len) {
  6487. out->insert(out->end(), name, name + strlen(name) + 1);
  6488. out->insert(out->end(), type, type + strlen(type) + 1);
  6489. int outLen = len;
  6490. tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen));
  6491. out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),
  6492. reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
  6493. out->insert(out->end(), data, data + len);
  6494. }
  6495. typedef struct {
  6496. std::string name; // less than 255 bytes long
  6497. int pixel_type;
  6498. int x_sampling;
  6499. int y_sampling;
  6500. unsigned char p_linear;
  6501. unsigned char pad[3];
  6502. } ChannelInfo;
  6503. typedef struct {
  6504. std::vector<tinyexr::ChannelInfo> channels;
  6505. std::vector<EXRAttribute> attributes;
  6506. int data_window[4];
  6507. int line_order;
  6508. int display_window[4];
  6509. float screen_window_center[2];
  6510. float screen_window_width;
  6511. float pixel_aspect_ratio;
  6512. int chunk_count;
  6513. // Tiled format
  6514. int tile_size_x;
  6515. int tile_size_y;
  6516. int tile_level_mode;
  6517. int tile_rounding_mode;
  6518. unsigned int header_len;
  6519. int compression_type;
  6520. void clear() {
  6521. channels.clear();
  6522. attributes.clear();
  6523. data_window[0] = 0;
  6524. data_window[1] = 0;
  6525. data_window[2] = 0;
  6526. data_window[3] = 0;
  6527. line_order = 0;
  6528. display_window[0] = 0;
  6529. display_window[1] = 0;
  6530. display_window[2] = 0;
  6531. display_window[3] = 0;
  6532. screen_window_center[0] = 0.0f;
  6533. screen_window_center[1] = 0.0f;
  6534. screen_window_width = 0.0f;
  6535. pixel_aspect_ratio = 0.0f;
  6536. chunk_count = 0;
  6537. // Tiled format
  6538. tile_size_x = 0;
  6539. tile_size_y = 0;
  6540. tile_level_mode = 0;
  6541. tile_rounding_mode = 0;
  6542. header_len = 0;
  6543. compression_type = 0;
  6544. }
  6545. } HeaderInfo;
  6546. static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,
  6547. const std::vector<unsigned char> &data) {
  6548. const char *p = reinterpret_cast<const char *>(&data.at(0));
  6549. for (;;) {
  6550. if ((*p) == 0) {
  6551. break;
  6552. }
  6553. ChannelInfo info;
  6554. tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -
  6555. (p - reinterpret_cast<const char *>(data.data()));
  6556. if (data_len < 0) {
  6557. return false;
  6558. }
  6559. p = ReadString(&info.name, p, size_t(data_len));
  6560. if ((p == NULL) && (info.name.empty())) {
  6561. // Buffer overrun. Issue #51.
  6562. return false;
  6563. }
  6564. const unsigned char *data_end =
  6565. reinterpret_cast<const unsigned char *>(p) + 16;
  6566. if (data_end >= (data.data() + data.size())) {
  6567. return false;
  6568. }
  6569. memcpy(&info.pixel_type, p, sizeof(int));
  6570. p += 4;
  6571. info.p_linear = static_cast<unsigned char>(p[0]); // uchar
  6572. p += 1 + 3; // reserved: uchar[3]
  6573. memcpy(&info.x_sampling, p, sizeof(int)); // int
  6574. p += 4;
  6575. memcpy(&info.y_sampling, p, sizeof(int)); // int
  6576. p += 4;
  6577. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type));
  6578. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling));
  6579. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling));
  6580. channels.push_back(info);
  6581. }
  6582. return true;
  6583. }
  6584. static void WriteChannelInfo(std::vector<unsigned char> &data,
  6585. const std::vector<ChannelInfo> &channels) {
  6586. size_t sz = 0;
  6587. // Calculate total size.
  6588. for (size_t c = 0; c < channels.size(); c++) {
  6589. sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
  6590. sz += 16; // 4 * int
  6591. }
  6592. data.resize(sz + 1);
  6593. unsigned char *p = &data.at(0);
  6594. for (size_t c = 0; c < channels.size(); c++) {
  6595. memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
  6596. p += strlen(channels[c].name.c_str());
  6597. (*p) = '\0';
  6598. p++;
  6599. int pixel_type = channels[c].pixel_type;
  6600. int x_sampling = channels[c].x_sampling;
  6601. int y_sampling = channels[c].y_sampling;
  6602. tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type));
  6603. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling));
  6604. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling));
  6605. memcpy(p, &pixel_type, sizeof(int));
  6606. p += sizeof(int);
  6607. (*p) = channels[c].p_linear;
  6608. p += 4;
  6609. memcpy(p, &x_sampling, sizeof(int));
  6610. p += sizeof(int);
  6611. memcpy(p, &y_sampling, sizeof(int));
  6612. p += sizeof(int);
  6613. }
  6614. (*p) = '\0';
  6615. }
  6616. static void CompressZip(unsigned char *dst,
  6617. tinyexr::tinyexr_uint64 &compressedSize,
  6618. const unsigned char *src, unsigned long src_size) {
  6619. std::vector<unsigned char> tmpBuf(src_size);
  6620. //
  6621. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6622. // ImfZipCompressor.cpp
  6623. //
  6624. //
  6625. // Reorder the pixel data.
  6626. //
  6627. const char *srcPtr = reinterpret_cast<const char *>(src);
  6628. {
  6629. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6630. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6631. const char *stop = srcPtr + src_size;
  6632. for (;;) {
  6633. if (srcPtr < stop)
  6634. *(t1++) = *(srcPtr++);
  6635. else
  6636. break;
  6637. if (srcPtr < stop)
  6638. *(t2++) = *(srcPtr++);
  6639. else
  6640. break;
  6641. }
  6642. }
  6643. //
  6644. // Predictor.
  6645. //
  6646. {
  6647. unsigned char *t = &tmpBuf.at(0) + 1;
  6648. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6649. int p = t[-1];
  6650. while (t < stop) {
  6651. int d = int(t[0]) - p + (128 + 256);
  6652. p = t[0];
  6653. t[0] = static_cast<unsigned char>(d);
  6654. ++t;
  6655. }
  6656. }
  6657. #if TINYEXR_USE_MINIZ
  6658. //
  6659. // Compress the data using miniz
  6660. //
  6661. miniz::mz_ulong outSize = miniz::mz_compressBound(src_size);
  6662. int ret = miniz::mz_compress(
  6663. dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),
  6664. src_size);
  6665. assert(ret == miniz::MZ_OK);
  6666. (void)ret;
  6667. compressedSize = outSize;
  6668. #else
  6669. uLong outSize = compressBound(static_cast<uLong>(src_size));
  6670. int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),
  6671. src_size);
  6672. assert(ret == Z_OK);
  6673. compressedSize = outSize;
  6674. #endif
  6675. // Use uncompressed data when compressed data is larger than uncompressed.
  6676. // (Issue 40)
  6677. if (compressedSize >= src_size) {
  6678. compressedSize = src_size;
  6679. memcpy(dst, src, src_size);
  6680. }
  6681. }
  6682. static bool DecompressZip(unsigned char *dst,
  6683. unsigned long *uncompressed_size /* inout */,
  6684. const unsigned char *src, unsigned long src_size) {
  6685. if ((*uncompressed_size) == src_size) {
  6686. // Data is not compressed(Issue 40).
  6687. memcpy(dst, src, src_size);
  6688. return true;
  6689. }
  6690. std::vector<unsigned char> tmpBuf(*uncompressed_size);
  6691. #if TINYEXR_USE_MINIZ
  6692. int ret =
  6693. miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6694. if (miniz::MZ_OK != ret) {
  6695. return false;
  6696. }
  6697. #else
  6698. int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6699. if (Z_OK != ret) {
  6700. return false;
  6701. }
  6702. #endif
  6703. //
  6704. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6705. // ImfZipCompressor.cpp
  6706. //
  6707. // Predictor.
  6708. {
  6709. unsigned char *t = &tmpBuf.at(0) + 1;
  6710. unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);
  6711. while (t < stop) {
  6712. int d = int(t[-1]) + int(t[0]) - 128;
  6713. t[0] = static_cast<unsigned char>(d);
  6714. ++t;
  6715. }
  6716. }
  6717. // Reorder the pixel data.
  6718. {
  6719. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6720. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6721. (*uncompressed_size + 1) / 2;
  6722. char *s = reinterpret_cast<char *>(dst);
  6723. char *stop = s + (*uncompressed_size);
  6724. for (;;) {
  6725. if (s < stop)
  6726. *(s++) = *(t1++);
  6727. else
  6728. break;
  6729. if (s < stop)
  6730. *(s++) = *(t2++);
  6731. else
  6732. break;
  6733. }
  6734. }
  6735. return true;
  6736. }
  6737. // RLE code from OpenEXR --------------------------------------
  6738. #ifdef __clang__
  6739. #pragma clang diagnostic push
  6740. #pragma clang diagnostic ignored "-Wsign-conversion"
  6741. #endif
  6742. #ifdef _MSC_VER
  6743. #pragma warning(push)
  6744. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  6745. // aggregate initializer (also supported by GNU
  6746. // C and C99, so no big deal)
  6747. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  6748. // 'int', possible loss of data
  6749. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  6750. // 'int', possible loss of data
  6751. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  6752. // deprecated. Instead, use the ISO C and C++
  6753. // conformant name: _strdup.
  6754. #endif
  6755. const int MIN_RUN_LENGTH = 3;
  6756. const int MAX_RUN_LENGTH = 127;
  6757. //
  6758. // Compress an array of bytes, using run-length encoding,
  6759. // and return the length of the compressed data.
  6760. //
  6761. static int rleCompress(int inLength, const char in[], signed char out[]) {
  6762. const char *inEnd = in + inLength;
  6763. const char *runStart = in;
  6764. const char *runEnd = in + 1;
  6765. signed char *outWrite = out;
  6766. while (runStart < inEnd) {
  6767. while (runEnd < inEnd && *runStart == *runEnd &&
  6768. runEnd - runStart - 1 < MAX_RUN_LENGTH) {
  6769. ++runEnd;
  6770. }
  6771. if (runEnd - runStart >= MIN_RUN_LENGTH) {
  6772. //
  6773. // Compressable run
  6774. //
  6775. *outWrite++ = static_cast<char>(runEnd - runStart) - 1;
  6776. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart));
  6777. runStart = runEnd;
  6778. } else {
  6779. //
  6780. // Uncompressable run
  6781. //
  6782. while (runEnd < inEnd &&
  6783. ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||
  6784. (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&
  6785. runEnd - runStart < MAX_RUN_LENGTH) {
  6786. ++runEnd;
  6787. }
  6788. *outWrite++ = static_cast<char>(runStart - runEnd);
  6789. while (runStart < runEnd) {
  6790. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));
  6791. }
  6792. }
  6793. ++runEnd;
  6794. }
  6795. return static_cast<int>(outWrite - out);
  6796. }
  6797. //
  6798. // Uncompress an array of bytes compressed with rleCompress().
  6799. // Returns the length of the oncompressed data, or 0 if the
  6800. // length of the uncompressed data would be more than maxLength.
  6801. //
  6802. static int rleUncompress(int inLength, int maxLength, const signed char in[],
  6803. char out[]) {
  6804. char *outStart = out;
  6805. while (inLength > 0) {
  6806. if (*in < 0) {
  6807. int count = -(static_cast<int>(*in++));
  6808. inLength -= count + 1;
  6809. if (0 > (maxLength -= count)) return 0;
  6810. memcpy(out, in, count);
  6811. out += count;
  6812. in += count;
  6813. } else {
  6814. int count = *in++;
  6815. inLength -= 2;
  6816. if (0 > (maxLength -= count + 1)) return 0;
  6817. memset(out, *reinterpret_cast<const char *>(in), count + 1);
  6818. out += count + 1;
  6819. in++;
  6820. }
  6821. }
  6822. return static_cast<int>(out - outStart);
  6823. }
  6824. #ifdef __clang__
  6825. #pragma clang diagnostic pop
  6826. #endif
  6827. // End of RLE code from OpenEXR -----------------------------------
  6828. static void CompressRle(unsigned char *dst,
  6829. tinyexr::tinyexr_uint64 &compressedSize,
  6830. const unsigned char *src, unsigned long src_size) {
  6831. std::vector<unsigned char> tmpBuf(src_size);
  6832. //
  6833. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6834. // ImfRleCompressor.cpp
  6835. //
  6836. //
  6837. // Reorder the pixel data.
  6838. //
  6839. const char *srcPtr = reinterpret_cast<const char *>(src);
  6840. {
  6841. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6842. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6843. const char *stop = srcPtr + src_size;
  6844. for (;;) {
  6845. if (srcPtr < stop)
  6846. *(t1++) = *(srcPtr++);
  6847. else
  6848. break;
  6849. if (srcPtr < stop)
  6850. *(t2++) = *(srcPtr++);
  6851. else
  6852. break;
  6853. }
  6854. }
  6855. //
  6856. // Predictor.
  6857. //
  6858. {
  6859. unsigned char *t = &tmpBuf.at(0) + 1;
  6860. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6861. int p = t[-1];
  6862. while (t < stop) {
  6863. int d = int(t[0]) - p + (128 + 256);
  6864. p = t[0];
  6865. t[0] = static_cast<unsigned char>(d);
  6866. ++t;
  6867. }
  6868. }
  6869. // outSize will be (srcSiz * 3) / 2 at max.
  6870. int outSize = rleCompress(static_cast<int>(src_size),
  6871. reinterpret_cast<const char *>(&tmpBuf.at(0)),
  6872. reinterpret_cast<signed char *>(dst));
  6873. assert(outSize > 0);
  6874. compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
  6875. // Use uncompressed data when compressed data is larger than uncompressed.
  6876. // (Issue 40)
  6877. if (compressedSize >= src_size) {
  6878. compressedSize = src_size;
  6879. memcpy(dst, src, src_size);
  6880. }
  6881. }
  6882. static void DecompressRle(unsigned char *dst,
  6883. const unsigned long uncompressed_size,
  6884. const unsigned char *src, unsigned long src_size) {
  6885. if (uncompressed_size == src_size) {
  6886. // Data is not compressed(Issue 40).
  6887. memcpy(dst, src, src_size);
  6888. return;
  6889. }
  6890. std::vector<unsigned char> tmpBuf(uncompressed_size);
  6891. int ret = rleUncompress(static_cast<int>(src_size),
  6892. static_cast<int>(uncompressed_size),
  6893. reinterpret_cast<const signed char *>(src),
  6894. reinterpret_cast<char *>(&tmpBuf.at(0)));
  6895. assert(ret == static_cast<int>(uncompressed_size));
  6896. (void)ret;
  6897. //
  6898. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6899. // ImfRleCompressor.cpp
  6900. //
  6901. // Predictor.
  6902. {
  6903. unsigned char *t = &tmpBuf.at(0) + 1;
  6904. unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;
  6905. while (t < stop) {
  6906. int d = int(t[-1]) + int(t[0]) - 128;
  6907. t[0] = static_cast<unsigned char>(d);
  6908. ++t;
  6909. }
  6910. }
  6911. // Reorder the pixel data.
  6912. {
  6913. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6914. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6915. (uncompressed_size + 1) / 2;
  6916. char *s = reinterpret_cast<char *>(dst);
  6917. char *stop = s + uncompressed_size;
  6918. for (;;) {
  6919. if (s < stop)
  6920. *(s++) = *(t1++);
  6921. else
  6922. break;
  6923. if (s < stop)
  6924. *(s++) = *(t2++);
  6925. else
  6926. break;
  6927. }
  6928. }
  6929. }
  6930. #if TINYEXR_USE_PIZ
  6931. #ifdef __clang__
  6932. #pragma clang diagnostic push
  6933. #pragma clang diagnostic ignored "-Wc++11-long-long"
  6934. #pragma clang diagnostic ignored "-Wold-style-cast"
  6935. #pragma clang diagnostic ignored "-Wpadded"
  6936. #pragma clang diagnostic ignored "-Wsign-conversion"
  6937. #pragma clang diagnostic ignored "-Wc++11-extensions"
  6938. #pragma clang diagnostic ignored "-Wconversion"
  6939. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  6940. #if __has_warning("-Wcast-qual")
  6941. #pragma clang diagnostic ignored "-Wcast-qual"
  6942. #endif
  6943. #endif
  6944. //
  6945. // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
  6946. //
  6947. // -----------------------------------------------------------------
  6948. // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
  6949. // Digital Ltd. LLC)
  6950. // (3 clause BSD license)
  6951. //
  6952. struct PIZChannelData {
  6953. unsigned short *start;
  6954. unsigned short *end;
  6955. int nx;
  6956. int ny;
  6957. int ys;
  6958. int size;
  6959. };
  6960. //-----------------------------------------------------------------------------
  6961. //
  6962. // 16-bit Haar Wavelet encoding and decoding
  6963. //
  6964. // The source code in this file is derived from the encoding
  6965. // and decoding routines written by Christian Rouet for his
  6966. // PIZ image file format.
  6967. //
  6968. //-----------------------------------------------------------------------------
  6969. //
  6970. // Wavelet basis functions without modulo arithmetic; they produce
  6971. // the best compression ratios when the wavelet-transformed data are
  6972. // Huffman-encoded, but the wavelet transform works only for 14-bit
  6973. // data (untransformed data values must be less than (1 << 14)).
  6974. //
  6975. inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
  6976. unsigned short &h) {
  6977. short as = static_cast<short>(a);
  6978. short bs = static_cast<short>(b);
  6979. short ms = (as + bs) >> 1;
  6980. short ds = as - bs;
  6981. l = static_cast<unsigned short>(ms);
  6982. h = static_cast<unsigned short>(ds);
  6983. }
  6984. inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
  6985. unsigned short &b) {
  6986. short ls = static_cast<short>(l);
  6987. short hs = static_cast<short>(h);
  6988. int hi = hs;
  6989. int ai = ls + (hi & 1) + (hi >> 1);
  6990. short as = static_cast<short>(ai);
  6991. short bs = static_cast<short>(ai - hi);
  6992. a = static_cast<unsigned short>(as);
  6993. b = static_cast<unsigned short>(bs);
  6994. }
  6995. //
  6996. // Wavelet basis functions with modulo arithmetic; they work with full
  6997. // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
  6998. // compress the data quite as well.
  6999. //
  7000. const int NBITS = 16;
  7001. const int A_OFFSET = 1 << (NBITS - 1);
  7002. const int M_OFFSET = 1 << (NBITS - 1);
  7003. const int MOD_MASK = (1 << NBITS) - 1;
  7004. inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
  7005. unsigned short &h) {
  7006. int ao = (a + A_OFFSET) & MOD_MASK;
  7007. int m = ((ao + b) >> 1);
  7008. int d = ao - b;
  7009. if (d < 0) m = (m + M_OFFSET) & MOD_MASK;
  7010. d &= MOD_MASK;
  7011. l = static_cast<unsigned short>(m);
  7012. h = static_cast<unsigned short>(d);
  7013. }
  7014. inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
  7015. unsigned short &b) {
  7016. int m = l;
  7017. int d = h;
  7018. int bb = (m - (d >> 1)) & MOD_MASK;
  7019. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  7020. b = static_cast<unsigned short>(bb);
  7021. a = static_cast<unsigned short>(aa);
  7022. }
  7023. //
  7024. // 2D Wavelet encoding:
  7025. //
  7026. static void wav2Encode(
  7027. unsigned short *in, // io: values are transformed in place
  7028. int nx, // i : x size
  7029. int ox, // i : x offset
  7030. int ny, // i : y size
  7031. int oy, // i : y offset
  7032. unsigned short mx) // i : maximum in[x][y] value
  7033. {
  7034. bool w14 = (mx < (1 << 14));
  7035. int n = (nx > ny) ? ny : nx;
  7036. int p = 1; // == 1 << level
  7037. int p2 = 2; // == 1 << (level+1)
  7038. //
  7039. // Hierachical loop on smaller dimension n
  7040. //
  7041. while (p2 <= n) {
  7042. unsigned short *py = in;
  7043. unsigned short *ey = in + oy * (ny - p2);
  7044. int oy1 = oy * p;
  7045. int oy2 = oy * p2;
  7046. int ox1 = ox * p;
  7047. int ox2 = ox * p2;
  7048. unsigned short i00, i01, i10, i11;
  7049. //
  7050. // Y loop
  7051. //
  7052. for (; py <= ey; py += oy2) {
  7053. unsigned short *px = py;
  7054. unsigned short *ex = py + ox * (nx - p2);
  7055. //
  7056. // X loop
  7057. //
  7058. for (; px <= ex; px += ox2) {
  7059. unsigned short *p01 = px + ox1;
  7060. unsigned short *p10 = px + oy1;
  7061. unsigned short *p11 = p10 + ox1;
  7062. //
  7063. // 2D wavelet encoding
  7064. //
  7065. if (w14) {
  7066. wenc14(*px, *p01, i00, i01);
  7067. wenc14(*p10, *p11, i10, i11);
  7068. wenc14(i00, i10, *px, *p10);
  7069. wenc14(i01, i11, *p01, *p11);
  7070. } else {
  7071. wenc16(*px, *p01, i00, i01);
  7072. wenc16(*p10, *p11, i10, i11);
  7073. wenc16(i00, i10, *px, *p10);
  7074. wenc16(i01, i11, *p01, *p11);
  7075. }
  7076. }
  7077. //
  7078. // Encode (1D) odd column (still in Y loop)
  7079. //
  7080. if (nx & p) {
  7081. unsigned short *p10 = px + oy1;
  7082. if (w14)
  7083. wenc14(*px, *p10, i00, *p10);
  7084. else
  7085. wenc16(*px, *p10, i00, *p10);
  7086. *px = i00;
  7087. }
  7088. }
  7089. //
  7090. // Encode (1D) odd line (must loop in X)
  7091. //
  7092. if (ny & p) {
  7093. unsigned short *px = py;
  7094. unsigned short *ex = py + ox * (nx - p2);
  7095. for (; px <= ex; px += ox2) {
  7096. unsigned short *p01 = px + ox1;
  7097. if (w14)
  7098. wenc14(*px, *p01, i00, *p01);
  7099. else
  7100. wenc16(*px, *p01, i00, *p01);
  7101. *px = i00;
  7102. }
  7103. }
  7104. //
  7105. // Next level
  7106. //
  7107. p = p2;
  7108. p2 <<= 1;
  7109. }
  7110. }
  7111. //
  7112. // 2D Wavelet decoding:
  7113. //
  7114. static void wav2Decode(
  7115. unsigned short *in, // io: values are transformed in place
  7116. int nx, // i : x size
  7117. int ox, // i : x offset
  7118. int ny, // i : y size
  7119. int oy, // i : y offset
  7120. unsigned short mx) // i : maximum in[x][y] value
  7121. {
  7122. bool w14 = (mx < (1 << 14));
  7123. int n = (nx > ny) ? ny : nx;
  7124. int p = 1;
  7125. int p2;
  7126. //
  7127. // Search max level
  7128. //
  7129. while (p <= n) p <<= 1;
  7130. p >>= 1;
  7131. p2 = p;
  7132. p >>= 1;
  7133. //
  7134. // Hierarchical loop on smaller dimension n
  7135. //
  7136. while (p >= 1) {
  7137. unsigned short *py = in;
  7138. unsigned short *ey = in + oy * (ny - p2);
  7139. int oy1 = oy * p;
  7140. int oy2 = oy * p2;
  7141. int ox1 = ox * p;
  7142. int ox2 = ox * p2;
  7143. unsigned short i00, i01, i10, i11;
  7144. //
  7145. // Y loop
  7146. //
  7147. for (; py <= ey; py += oy2) {
  7148. unsigned short *px = py;
  7149. unsigned short *ex = py + ox * (nx - p2);
  7150. //
  7151. // X loop
  7152. //
  7153. for (; px <= ex; px += ox2) {
  7154. unsigned short *p01 = px + ox1;
  7155. unsigned short *p10 = px + oy1;
  7156. unsigned short *p11 = p10 + ox1;
  7157. //
  7158. // 2D wavelet decoding
  7159. //
  7160. if (w14) {
  7161. wdec14(*px, *p10, i00, i10);
  7162. wdec14(*p01, *p11, i01, i11);
  7163. wdec14(i00, i01, *px, *p01);
  7164. wdec14(i10, i11, *p10, *p11);
  7165. } else {
  7166. wdec16(*px, *p10, i00, i10);
  7167. wdec16(*p01, *p11, i01, i11);
  7168. wdec16(i00, i01, *px, *p01);
  7169. wdec16(i10, i11, *p10, *p11);
  7170. }
  7171. }
  7172. //
  7173. // Decode (1D) odd column (still in Y loop)
  7174. //
  7175. if (nx & p) {
  7176. unsigned short *p10 = px + oy1;
  7177. if (w14)
  7178. wdec14(*px, *p10, i00, *p10);
  7179. else
  7180. wdec16(*px, *p10, i00, *p10);
  7181. *px = i00;
  7182. }
  7183. }
  7184. //
  7185. // Decode (1D) odd line (must loop in X)
  7186. //
  7187. if (ny & p) {
  7188. unsigned short *px = py;
  7189. unsigned short *ex = py + ox * (nx - p2);
  7190. for (; px <= ex; px += ox2) {
  7191. unsigned short *p01 = px + ox1;
  7192. if (w14)
  7193. wdec14(*px, *p01, i00, *p01);
  7194. else
  7195. wdec16(*px, *p01, i00, *p01);
  7196. *px = i00;
  7197. }
  7198. }
  7199. //
  7200. // Next level
  7201. //
  7202. p2 = p;
  7203. p >>= 1;
  7204. }
  7205. }
  7206. //-----------------------------------------------------------------------------
  7207. //
  7208. // 16-bit Huffman compression and decompression.
  7209. //
  7210. // The source code in this file is derived from the 8-bit
  7211. // Huffman compression and decompression routines written
  7212. // by Christian Rouet for his PIZ image file format.
  7213. //
  7214. //-----------------------------------------------------------------------------
  7215. // Adds some modification for tinyexr.
  7216. const int HUF_ENCBITS = 16; // literal (value) bit length
  7217. const int HUF_DECBITS = 14; // decoding bit size (>= 8)
  7218. const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
  7219. const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  7220. const int HUF_DECMASK = HUF_DECSIZE - 1;
  7221. struct HufDec { // short code long code
  7222. //-------------------------------
  7223. int len : 8; // code length 0
  7224. int lit : 24; // lit p size
  7225. int *p; // 0 lits
  7226. };
  7227. inline long long hufLength(long long code) { return code & 63; }
  7228. inline long long hufCode(long long code) { return code >> 6; }
  7229. inline void outputBits(int nBits, long long bits, long long &c, int &lc,
  7230. char *&out) {
  7231. c <<= nBits;
  7232. lc += nBits;
  7233. c |= bits;
  7234. while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));
  7235. }
  7236. inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
  7237. while (lc < nBits) {
  7238. c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));
  7239. lc += 8;
  7240. }
  7241. lc -= nBits;
  7242. return (c >> lc) & ((1 << nBits) - 1);
  7243. }
  7244. //
  7245. // ENCODING TABLE BUILDING & (UN)PACKING
  7246. //
  7247. //
  7248. // Build a "canonical" Huffman code table:
  7249. // - for each (uncompressed) symbol, hcode contains the length
  7250. // of the corresponding code (in the compressed data)
  7251. // - canonical codes are computed and stored in hcode
  7252. // - the rules for constructing canonical codes are as follows:
  7253. // * shorter codes (if filled with zeroes to the right)
  7254. // have a numerically higher value than longer codes
  7255. // * for codes with the same length, numerical values
  7256. // increase with numerical symbol values
  7257. // - because the canonical code table can be constructed from
  7258. // symbol lengths alone, the code table can be transmitted
  7259. // without sending the actual code values
  7260. // - see http://www.compressconsult.com/huffman/
  7261. //
  7262. static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
  7263. long long n[59];
  7264. //
  7265. // For each i from 0 through 58, count the
  7266. // number of different codes of length i, and
  7267. // store the count in n[i].
  7268. //
  7269. for (int i = 0; i <= 58; ++i) n[i] = 0;
  7270. for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;
  7271. //
  7272. // For each i from 58 through 1, compute the
  7273. // numerically lowest code with length i, and
  7274. // store that code in n[i].
  7275. //
  7276. long long c = 0;
  7277. for (int i = 58; i > 0; --i) {
  7278. long long nc = ((c + n[i]) >> 1);
  7279. n[i] = c;
  7280. c = nc;
  7281. }
  7282. //
  7283. // hcode[i] contains the length, l, of the
  7284. // code for symbol i. Assign the next available
  7285. // code of length l to the symbol and store both
  7286. // l and the code in hcode[i].
  7287. //
  7288. for (int i = 0; i < HUF_ENCSIZE; ++i) {
  7289. int l = static_cast<int>(hcode[i]);
  7290. if (l > 0) hcode[i] = l | (n[l]++ << 6);
  7291. }
  7292. }
  7293. //
  7294. // Compute Huffman codes (based on frq input) and store them in frq:
  7295. // - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
  7296. // - max code length is 58 bits;
  7297. // - codes outside the range [im-iM] have a null length (unused values);
  7298. // - original frequencies are destroyed;
  7299. // - encoding tables are used by hufEncode() and hufBuildDecTable();
  7300. //
  7301. struct FHeapCompare {
  7302. bool operator()(long long *a, long long *b) { return *a > *b; }
  7303. };
  7304. static void hufBuildEncTable(
  7305. long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
  7306. int *im, // o: min frq index
  7307. int *iM) // o: max frq index
  7308. {
  7309. //
  7310. // This function assumes that when it is called, array frq
  7311. // indicates the frequency of all possible symbols in the data
  7312. // that are to be Huffman-encoded. (frq[i] contains the number
  7313. // of occurrences of symbol i in the data.)
  7314. //
  7315. // The loop below does three things:
  7316. //
  7317. // 1) Finds the minimum and maximum indices that point
  7318. // to non-zero entries in frq:
  7319. //
  7320. // frq[im] != 0, and frq[i] == 0 for all i < im
  7321. // frq[iM] != 0, and frq[i] == 0 for all i > iM
  7322. //
  7323. // 2) Fills array fHeap with pointers to all non-zero
  7324. // entries in frq.
  7325. //
  7326. // 3) Initializes array hlink such that hlink[i] == i
  7327. // for all array entries.
  7328. //
  7329. std::vector<int> hlink(HUF_ENCSIZE);
  7330. std::vector<long long *> fHeap(HUF_ENCSIZE);
  7331. *im = 0;
  7332. while (!frq[*im]) (*im)++;
  7333. int nf = 0;
  7334. for (int i = *im; i < HUF_ENCSIZE; i++) {
  7335. hlink[i] = i;
  7336. if (frq[i]) {
  7337. fHeap[nf] = &frq[i];
  7338. nf++;
  7339. *iM = i;
  7340. }
  7341. }
  7342. //
  7343. // Add a pseudo-symbol, with a frequency count of 1, to frq;
  7344. // adjust the fHeap and hlink array accordingly. Function
  7345. // hufEncode() uses the pseudo-symbol for run-length encoding.
  7346. //
  7347. (*iM)++;
  7348. frq[*iM] = 1;
  7349. fHeap[nf] = &frq[*iM];
  7350. nf++;
  7351. //
  7352. // Build an array, scode, such that scode[i] contains the number
  7353. // of bits assigned to symbol i. Conceptually this is done by
  7354. // constructing a tree whose leaves are the symbols with non-zero
  7355. // frequency:
  7356. //
  7357. // Make a heap that contains all symbols with a non-zero frequency,
  7358. // with the least frequent symbol on top.
  7359. //
  7360. // Repeat until only one symbol is left on the heap:
  7361. //
  7362. // Take the two least frequent symbols off the top of the heap.
  7363. // Create a new node that has first two nodes as children, and
  7364. // whose frequency is the sum of the frequencies of the first
  7365. // two nodes. Put the new node back into the heap.
  7366. //
  7367. // The last node left on the heap is the root of the tree. For each
  7368. // leaf node, the distance between the root and the leaf is the length
  7369. // of the code for the corresponding symbol.
  7370. //
  7371. // The loop below doesn't actually build the tree; instead we compute
  7372. // the distances of the leaves from the root on the fly. When a new
  7373. // node is added to the heap, then that node's descendants are linked
  7374. // into a single linear list that starts at the new node, and the code
  7375. // lengths of the descendants (that is, their distance from the root
  7376. // of the tree) are incremented by one.
  7377. //
  7378. std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7379. std::vector<long long> scode(HUF_ENCSIZE);
  7380. memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
  7381. while (nf > 1) {
  7382. //
  7383. // Find the indices, mm and m, of the two smallest non-zero frq
  7384. // values in fHeap, add the smallest frq to the second-smallest
  7385. // frq, and remove the smallest frq value from fHeap.
  7386. //
  7387. int mm = fHeap[0] - frq;
  7388. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7389. --nf;
  7390. int m = fHeap[0] - frq;
  7391. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7392. frq[m] += frq[mm];
  7393. std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7394. //
  7395. // The entries in scode are linked into lists with the
  7396. // entries in hlink serving as "next" pointers and with
  7397. // the end of a list marked by hlink[j] == j.
  7398. //
  7399. // Traverse the lists that start at scode[m] and scode[mm].
  7400. // For each element visited, increment the length of the
  7401. // corresponding code by one bit. (If we visit scode[j]
  7402. // during the traversal, then the code for symbol j becomes
  7403. // one bit longer.)
  7404. //
  7405. // Merge the lists that start at scode[m] and scode[mm]
  7406. // into a single list that starts at scode[m].
  7407. //
  7408. //
  7409. // Add a bit to all codes in the first list.
  7410. //
  7411. for (int j = m;; j = hlink[j]) {
  7412. scode[j]++;
  7413. assert(scode[j] <= 58);
  7414. if (hlink[j] == j) {
  7415. //
  7416. // Merge the two lists.
  7417. //
  7418. hlink[j] = mm;
  7419. break;
  7420. }
  7421. }
  7422. //
  7423. // Add a bit to all codes in the second list
  7424. //
  7425. for (int j = mm;; j = hlink[j]) {
  7426. scode[j]++;
  7427. assert(scode[j] <= 58);
  7428. if (hlink[j] == j) break;
  7429. }
  7430. }
  7431. //
  7432. // Build a canonical Huffman code table, replacing the code
  7433. // lengths in scode with (code, code length) pairs. Copy the
  7434. // code table from scode into frq.
  7435. //
  7436. hufCanonicalCodeTable(scode.data());
  7437. memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
  7438. }
  7439. //
  7440. // Pack an encoding table:
  7441. // - only code lengths, not actual codes, are stored
  7442. // - runs of zeroes are compressed as follows:
  7443. //
  7444. // unpacked packed
  7445. // --------------------------------
  7446. // 1 zero 0 (6 bits)
  7447. // 2 zeroes 59
  7448. // 3 zeroes 60
  7449. // 4 zeroes 61
  7450. // 5 zeroes 62
  7451. // n zeroes (6 or more) 63 n-6 (6 + 8 bits)
  7452. //
  7453. const int SHORT_ZEROCODE_RUN = 59;
  7454. const int LONG_ZEROCODE_RUN = 63;
  7455. const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  7456. const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
  7457. static void hufPackEncTable(
  7458. const long long *hcode, // i : encoding table [HUF_ENCSIZE]
  7459. int im, // i : min hcode index
  7460. int iM, // i : max hcode index
  7461. char **pcode) // o: ptr to packed table (updated)
  7462. {
  7463. char *p = *pcode;
  7464. long long c = 0;
  7465. int lc = 0;
  7466. for (; im <= iM; im++) {
  7467. int l = hufLength(hcode[im]);
  7468. if (l == 0) {
  7469. int zerun = 1;
  7470. while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
  7471. if (hufLength(hcode[im + 1]) > 0) break;
  7472. im++;
  7473. zerun++;
  7474. }
  7475. if (zerun >= 2) {
  7476. if (zerun >= SHORTEST_LONG_RUN) {
  7477. outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
  7478. outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
  7479. } else {
  7480. outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
  7481. }
  7482. continue;
  7483. }
  7484. }
  7485. outputBits(6, l, c, lc, p);
  7486. }
  7487. if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));
  7488. *pcode = p;
  7489. }
  7490. //
  7491. // Unpack an encoding table packed by hufPackEncTable():
  7492. //
  7493. static bool hufUnpackEncTable(
  7494. const char **pcode, // io: ptr to packed table (updated)
  7495. int ni, // i : input size (in bytes)
  7496. int im, // i : min hcode index
  7497. int iM, // i : max hcode index
  7498. long long *hcode) // o: encoding table [HUF_ENCSIZE]
  7499. {
  7500. memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
  7501. const char *p = *pcode;
  7502. long long c = 0;
  7503. int lc = 0;
  7504. for (; im <= iM; im++) {
  7505. if (p - *pcode > ni) {
  7506. return false;
  7507. }
  7508. long long l = hcode[im] = getBits(6, c, lc, p); // code length
  7509. if (l == (long long)LONG_ZEROCODE_RUN) {
  7510. if (p - *pcode > ni) {
  7511. return false;
  7512. }
  7513. int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
  7514. if (im + zerun > iM + 1) {
  7515. return false;
  7516. }
  7517. while (zerun--) hcode[im++] = 0;
  7518. im--;
  7519. } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
  7520. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  7521. if (im + zerun > iM + 1) {
  7522. return false;
  7523. }
  7524. while (zerun--) hcode[im++] = 0;
  7525. im--;
  7526. }
  7527. }
  7528. *pcode = const_cast<char *>(p);
  7529. hufCanonicalCodeTable(hcode);
  7530. return true;
  7531. }
  7532. //
  7533. // DECODING TABLE BUILDING
  7534. //
  7535. //
  7536. // Clear a newly allocated decoding table so that it contains only zeroes.
  7537. //
  7538. static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
  7539. // decoding table [HUF_DECSIZE]
  7540. {
  7541. for (int i = 0; i < HUF_DECSIZE; i++) {
  7542. hdecod[i].len = 0;
  7543. hdecod[i].lit = 0;
  7544. hdecod[i].p = NULL;
  7545. }
  7546. // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
  7547. }
  7548. //
  7549. // Build a decoding hash table based on the encoding table hcode:
  7550. // - short codes (<= HUF_DECBITS) are resolved with a single table access;
  7551. // - long code entry allocations are not optimized, because long codes are
  7552. // unfrequent;
  7553. // - decoding tables are used by hufDecode();
  7554. //
  7555. static bool hufBuildDecTable(const long long *hcode, // i : encoding table
  7556. int im, // i : min index in hcode
  7557. int iM, // i : max index in hcode
  7558. HufDec *hdecod) // o: (allocated by caller)
  7559. // decoding table [HUF_DECSIZE]
  7560. {
  7561. //
  7562. // Init hashtable & loop on all codes.
  7563. // Assumes that hufClearDecTable(hdecod) has already been called.
  7564. //
  7565. for (; im <= iM; im++) {
  7566. long long c = hufCode(hcode[im]);
  7567. int l = hufLength(hcode[im]);
  7568. if (c >> l) {
  7569. //
  7570. // Error: c is supposed to be an l-bit code,
  7571. // but c contains a value that is greater
  7572. // than the largest l-bit number.
  7573. //
  7574. // invalidTableEntry();
  7575. return false;
  7576. }
  7577. if (l > HUF_DECBITS) {
  7578. //
  7579. // Long code: add a secondary entry
  7580. //
  7581. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  7582. if (pl->len) {
  7583. //
  7584. // Error: a short code has already
  7585. // been stored in table entry *pl.
  7586. //
  7587. // invalidTableEntry();
  7588. return false;
  7589. }
  7590. pl->lit++;
  7591. if (pl->p) {
  7592. int *p = pl->p;
  7593. pl->p = new int[pl->lit];
  7594. for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i];
  7595. delete[] p;
  7596. } else {
  7597. pl->p = new int[1];
  7598. }
  7599. pl->p[pl->lit - 1] = im;
  7600. } else if (l) {
  7601. //
  7602. // Short code: init all primary entries
  7603. //
  7604. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  7605. for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
  7606. if (pl->len || pl->p) {
  7607. //
  7608. // Error: a short code or a long code has
  7609. // already been stored in table entry *pl.
  7610. //
  7611. // invalidTableEntry();
  7612. return false;
  7613. }
  7614. pl->len = l;
  7615. pl->lit = im;
  7616. }
  7617. }
  7618. }
  7619. return true;
  7620. }
  7621. //
  7622. // Free the long code entries of a decoding table built by hufBuildDecTable()
  7623. //
  7624. static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
  7625. {
  7626. for (int i = 0; i < HUF_DECSIZE; i++) {
  7627. if (hdecod[i].p) {
  7628. delete[] hdecod[i].p;
  7629. hdecod[i].p = 0;
  7630. }
  7631. }
  7632. }
  7633. //
  7634. // ENCODING
  7635. //
  7636. inline void outputCode(long long code, long long &c, int &lc, char *&out) {
  7637. outputBits(hufLength(code), hufCode(code), c, lc, out);
  7638. }
  7639. inline void sendCode(long long sCode, int runCount, long long runCode,
  7640. long long &c, int &lc, char *&out) {
  7641. //
  7642. // Output a run of runCount instances of the symbol sCount.
  7643. // Output the symbols explicitly, or if that is shorter, output
  7644. // the sCode symbol once followed by a runCode symbol and runCount
  7645. // expressed as an 8-bit number.
  7646. //
  7647. if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
  7648. outputCode(sCode, c, lc, out);
  7649. outputCode(runCode, c, lc, out);
  7650. outputBits(8, runCount, c, lc, out);
  7651. } else {
  7652. while (runCount-- >= 0) outputCode(sCode, c, lc, out);
  7653. }
  7654. }
  7655. //
  7656. // Encode (compress) ni values based on the Huffman encoding table hcode:
  7657. //
  7658. static int hufEncode // return: output size (in bits)
  7659. (const long long *hcode, // i : encoding table
  7660. const unsigned short *in, // i : uncompressed input buffer
  7661. const int ni, // i : input buffer size (in bytes)
  7662. int rlc, // i : rl code
  7663. char *out) // o: compressed output buffer
  7664. {
  7665. char *outStart = out;
  7666. long long c = 0; // bits not yet written to out
  7667. int lc = 0; // number of valid bits in c (LSB)
  7668. int s = in[0];
  7669. int cs = 0;
  7670. //
  7671. // Loop on input values
  7672. //
  7673. for (int i = 1; i < ni; i++) {
  7674. //
  7675. // Count same values or send code
  7676. //
  7677. if (s == in[i] && cs < 255) {
  7678. cs++;
  7679. } else {
  7680. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7681. cs = 0;
  7682. }
  7683. s = in[i];
  7684. }
  7685. //
  7686. // Send remaining code
  7687. //
  7688. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7689. if (lc) *out = (c << (8 - lc)) & 0xff;
  7690. return (out - outStart) * 8 + lc;
  7691. }
  7692. //
  7693. // DECODING
  7694. //
  7695. //
  7696. // In order to force the compiler to inline them,
  7697. // getChar() and getCode() are implemented as macros
  7698. // instead of "inline" functions.
  7699. //
  7700. #define getChar(c, lc, in) \
  7701. { \
  7702. c = (c << 8) | *(unsigned char *)(in++); \
  7703. lc += 8; \
  7704. }
  7705. #if 0
  7706. #define getCode(po, rlc, c, lc, in, out, ob, oe) \
  7707. { \
  7708. if (po == rlc) { \
  7709. if (lc < 8) getChar(c, lc, in); \
  7710. \
  7711. lc -= 8; \
  7712. \
  7713. unsigned char cs = (c >> lc); \
  7714. \
  7715. if (out + cs > oe) return false; \
  7716. \
  7717. /* TinyEXR issue 78 */ \
  7718. unsigned short s = out[-1]; \
  7719. \
  7720. while (cs-- > 0) *out++ = s; \
  7721. } else if (out < oe) { \
  7722. *out++ = po; \
  7723. } else { \
  7724. return false; \
  7725. } \
  7726. }
  7727. #else
  7728. static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,
  7729. const char *in_end, unsigned short *&out,
  7730. const unsigned short *ob, const unsigned short *oe) {
  7731. (void)ob;
  7732. if (po == rlc) {
  7733. if (lc < 8) {
  7734. /* TinyEXR issue 78 */
  7735. if ((in + 1) >= in_end) {
  7736. return false;
  7737. }
  7738. getChar(c, lc, in);
  7739. }
  7740. lc -= 8;
  7741. unsigned char cs = (c >> lc);
  7742. if (out + cs > oe) return false;
  7743. // Bounds check for safety
  7744. // Issue 100.
  7745. if ((out - 1) < ob) return false;
  7746. unsigned short s = out[-1];
  7747. while (cs-- > 0) *out++ = s;
  7748. } else if (out < oe) {
  7749. *out++ = po;
  7750. } else {
  7751. return false;
  7752. }
  7753. return true;
  7754. }
  7755. #endif
  7756. //
  7757. // Decode (uncompress) ni bits based on encoding & decoding tables:
  7758. //
  7759. static bool hufDecode(const long long *hcode, // i : encoding table
  7760. const HufDec *hdecod, // i : decoding table
  7761. const char *in, // i : compressed input buffer
  7762. int ni, // i : input size (in bits)
  7763. int rlc, // i : run-length code
  7764. int no, // i : expected output size (in bytes)
  7765. unsigned short *out) // o: uncompressed output buffer
  7766. {
  7767. long long c = 0;
  7768. int lc = 0;
  7769. unsigned short *outb = out; // begin
  7770. unsigned short *oe = out + no; // end
  7771. const char *ie = in + (ni + 7) / 8; // input byte size
  7772. //
  7773. // Loop on input bytes
  7774. //
  7775. while (in < ie) {
  7776. getChar(c, lc, in);
  7777. //
  7778. // Access decoding table
  7779. //
  7780. while (lc >= HUF_DECBITS) {
  7781. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  7782. if (pl.len) {
  7783. //
  7784. // Get short code
  7785. //
  7786. lc -= pl.len;
  7787. // std::cout << "lit = " << pl.lit << std::endl;
  7788. // std::cout << "rlc = " << rlc << std::endl;
  7789. // std::cout << "c = " << c << std::endl;
  7790. // std::cout << "lc = " << lc << std::endl;
  7791. // std::cout << "in = " << in << std::endl;
  7792. // std::cout << "out = " << out << std::endl;
  7793. // std::cout << "oe = " << oe << std::endl;
  7794. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7795. return false;
  7796. }
  7797. } else {
  7798. if (!pl.p) {
  7799. return false;
  7800. }
  7801. // invalidCode(); // wrong code
  7802. //
  7803. // Search long code
  7804. //
  7805. int j;
  7806. for (j = 0; j < pl.lit; j++) {
  7807. int l = hufLength(hcode[pl.p[j]]);
  7808. while (lc < l && in < ie) // get more bits
  7809. getChar(c, lc, in);
  7810. if (lc >= l) {
  7811. if (hufCode(hcode[pl.p[j]]) ==
  7812. ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
  7813. //
  7814. // Found : get long code
  7815. //
  7816. lc -= l;
  7817. if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
  7818. return false;
  7819. }
  7820. break;
  7821. }
  7822. }
  7823. }
  7824. if (j == pl.lit) {
  7825. return false;
  7826. // invalidCode(); // Not found
  7827. }
  7828. }
  7829. }
  7830. }
  7831. //
  7832. // Get remaining (short) codes
  7833. //
  7834. int i = (8 - ni) & 7;
  7835. c >>= i;
  7836. lc -= i;
  7837. while (lc > 0) {
  7838. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  7839. if (pl.len) {
  7840. lc -= pl.len;
  7841. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7842. return false;
  7843. }
  7844. } else {
  7845. return false;
  7846. // invalidCode(); // wrong (long) code
  7847. }
  7848. }
  7849. if (out - outb != no) {
  7850. return false;
  7851. }
  7852. // notEnoughData ();
  7853. return true;
  7854. }
  7855. static void countFrequencies(std::vector<long long> &freq,
  7856. const unsigned short data[/*n*/], int n) {
  7857. for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;
  7858. for (int i = 0; i < n; ++i) ++freq[data[i]];
  7859. }
  7860. static void writeUInt(char buf[4], unsigned int i) {
  7861. unsigned char *b = (unsigned char *)buf;
  7862. b[0] = i;
  7863. b[1] = i >> 8;
  7864. b[2] = i >> 16;
  7865. b[3] = i >> 24;
  7866. }
  7867. static unsigned int readUInt(const char buf[4]) {
  7868. const unsigned char *b = (const unsigned char *)buf;
  7869. return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
  7870. ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
  7871. }
  7872. //
  7873. // EXTERNAL INTERFACE
  7874. //
  7875. static int hufCompress(const unsigned short raw[], int nRaw,
  7876. char compressed[]) {
  7877. if (nRaw == 0) return 0;
  7878. std::vector<long long> freq(HUF_ENCSIZE);
  7879. countFrequencies(freq, raw, nRaw);
  7880. int im = 0;
  7881. int iM = 0;
  7882. hufBuildEncTable(freq.data(), &im, &iM);
  7883. char *tableStart = compressed + 20;
  7884. char *tableEnd = tableStart;
  7885. hufPackEncTable(freq.data(), im, iM, &tableEnd);
  7886. int tableLength = tableEnd - tableStart;
  7887. char *dataStart = tableEnd;
  7888. int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
  7889. int data_length = (nBits + 7) / 8;
  7890. writeUInt(compressed, im);
  7891. writeUInt(compressed + 4, iM);
  7892. writeUInt(compressed + 8, tableLength);
  7893. writeUInt(compressed + 12, nBits);
  7894. writeUInt(compressed + 16, 0); // room for future extensions
  7895. return dataStart + data_length - compressed;
  7896. }
  7897. static bool hufUncompress(const char compressed[], int nCompressed,
  7898. std::vector<unsigned short> *raw) {
  7899. if (nCompressed == 0) {
  7900. if (raw->size() != 0) return false;
  7901. return false;
  7902. }
  7903. int im = readUInt(compressed);
  7904. int iM = readUInt(compressed + 4);
  7905. // int tableLength = readUInt (compressed + 8);
  7906. int nBits = readUInt(compressed + 12);
  7907. if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;
  7908. const char *ptr = compressed + 20;
  7909. //
  7910. // Fast decoder needs at least 2x64-bits of compressed data, and
  7911. // needs to be run-able on this platform. Otherwise, fall back
  7912. // to the original decoder
  7913. //
  7914. // if (FastHufDecoder::enabled() && nBits > 128)
  7915. //{
  7916. // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
  7917. // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
  7918. //}
  7919. // else
  7920. {
  7921. std::vector<long long> freq(HUF_ENCSIZE);
  7922. std::vector<HufDec> hdec(HUF_DECSIZE);
  7923. hufClearDecTable(&hdec.at(0));
  7924. hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
  7925. &freq.at(0));
  7926. {
  7927. if (nBits > 8 * (nCompressed - (ptr - compressed))) {
  7928. return false;
  7929. }
  7930. hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
  7931. hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
  7932. raw->data());
  7933. }
  7934. // catch (...)
  7935. //{
  7936. // hufFreeDecTable (hdec);
  7937. // throw;
  7938. //}
  7939. hufFreeDecTable(&hdec.at(0));
  7940. }
  7941. return true;
  7942. }
  7943. //
  7944. // Functions to compress the range of values in the pixel data
  7945. //
  7946. const int USHORT_RANGE = (1 << 16);
  7947. const int BITMAP_SIZE = (USHORT_RANGE >> 3);
  7948. static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
  7949. unsigned char bitmap[BITMAP_SIZE],
  7950. unsigned short &minNonZero,
  7951. unsigned short &maxNonZero) {
  7952. for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;
  7953. for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
  7954. bitmap[0] &= ~1; // zero is not explicitly stored in
  7955. // the bitmap; we assume that the
  7956. // data always contain zeroes
  7957. minNonZero = BITMAP_SIZE - 1;
  7958. maxNonZero = 0;
  7959. for (int i = 0; i < BITMAP_SIZE; ++i) {
  7960. if (bitmap[i]) {
  7961. if (minNonZero > i) minNonZero = i;
  7962. if (maxNonZero < i) maxNonZero = i;
  7963. }
  7964. }
  7965. }
  7966. static unsigned short forwardLutFromBitmap(
  7967. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  7968. int k = 0;
  7969. for (int i = 0; i < USHORT_RANGE; ++i) {
  7970. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  7971. lut[i] = k++;
  7972. else
  7973. lut[i] = 0;
  7974. }
  7975. return k - 1; // maximum value stored in lut[],
  7976. } // i.e. number of ones in bitmap minus 1
  7977. static unsigned short reverseLutFromBitmap(
  7978. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  7979. int k = 0;
  7980. for (int i = 0; i < USHORT_RANGE; ++i) {
  7981. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;
  7982. }
  7983. int n = k - 1;
  7984. while (k < USHORT_RANGE) lut[k++] = 0;
  7985. return n; // maximum k where lut[k] is non-zero,
  7986. } // i.e. number of ones in bitmap minus 1
  7987. static void applyLut(const unsigned short lut[USHORT_RANGE],
  7988. unsigned short data[/*nData*/], int nData) {
  7989. for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];
  7990. }
  7991. #ifdef __clang__
  7992. #pragma clang diagnostic pop
  7993. #endif // __clang__
  7994. #ifdef _MSC_VER
  7995. #pragma warning(pop)
  7996. #endif
  7997. static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,
  7998. const unsigned char *inPtr, size_t inSize,
  7999. const std::vector<ChannelInfo> &channelInfo,
  8000. int data_width, int num_lines) {
  8001. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  8002. unsigned short minNonZero;
  8003. unsigned short maxNonZero;
  8004. #if !MINIZ_LITTLE_ENDIAN
  8005. // @todo { PIZ compression on BigEndian architecture. }
  8006. assert(0);
  8007. return false;
  8008. #endif
  8009. // Assume `inSize` is multiple of 2 or 4.
  8010. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
  8011. std::vector<PIZChannelData> channelData(channelInfo.size());
  8012. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8013. for (size_t c = 0; c < channelData.size(); c++) {
  8014. PIZChannelData &cd = channelData[c];
  8015. cd.start = tmpBufferEnd;
  8016. cd.end = cd.start;
  8017. cd.nx = data_width;
  8018. cd.ny = num_lines;
  8019. // cd.ys = c.channel().ySampling;
  8020. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8021. if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8022. pixelSize = sizeof(short);
  8023. }
  8024. cd.size = static_cast<int>(pixelSize / sizeof(short));
  8025. tmpBufferEnd += cd.nx * cd.ny * cd.size;
  8026. }
  8027. const unsigned char *ptr = inPtr;
  8028. for (int y = 0; y < num_lines; ++y) {
  8029. for (size_t i = 0; i < channelData.size(); ++i) {
  8030. PIZChannelData &cd = channelData[i];
  8031. // if (modp (y, cd.ys) != 0)
  8032. // continue;
  8033. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8034. memcpy(cd.end, ptr, n * sizeof(unsigned short));
  8035. ptr += n * sizeof(unsigned short);
  8036. cd.end += n;
  8037. }
  8038. }
  8039. bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
  8040. bitmap.data(), minNonZero, maxNonZero);
  8041. std::vector<unsigned short> lut(USHORT_RANGE);
  8042. unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
  8043. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
  8044. //
  8045. // Store range compression info in _outBuffer
  8046. //
  8047. char *buf = reinterpret_cast<char *>(outPtr);
  8048. memcpy(buf, &minNonZero, sizeof(unsigned short));
  8049. buf += sizeof(unsigned short);
  8050. memcpy(buf, &maxNonZero, sizeof(unsigned short));
  8051. buf += sizeof(unsigned short);
  8052. if (minNonZero <= maxNonZero) {
  8053. memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),
  8054. maxNonZero - minNonZero + 1);
  8055. buf += maxNonZero - minNonZero + 1;
  8056. }
  8057. //
  8058. // Apply wavelet encoding
  8059. //
  8060. for (size_t i = 0; i < channelData.size(); ++i) {
  8061. PIZChannelData &cd = channelData[i];
  8062. for (int j = 0; j < cd.size; ++j) {
  8063. wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8064. maxValue);
  8065. }
  8066. }
  8067. //
  8068. // Apply Huffman encoding; append the result to _outBuffer
  8069. //
  8070. // length header(4byte), then huff data. Initialize length header with zero,
  8071. // then later fill it by `length`.
  8072. char *lengthPtr = buf;
  8073. int zero = 0;
  8074. memcpy(buf, &zero, sizeof(int));
  8075. buf += sizeof(int);
  8076. int length =
  8077. hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
  8078. memcpy(lengthPtr, &length, sizeof(int));
  8079. (*outSize) = static_cast<unsigned int>(
  8080. (reinterpret_cast<unsigned char *>(buf) - outPtr) +
  8081. static_cast<unsigned int>(length));
  8082. // Use uncompressed data when compressed data is larger than uncompressed.
  8083. // (Issue 40)
  8084. if ((*outSize) >= inSize) {
  8085. (*outSize) = static_cast<unsigned int>(inSize);
  8086. memcpy(outPtr, inPtr, inSize);
  8087. }
  8088. return true;
  8089. }
  8090. static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,
  8091. size_t tmpBufSize, size_t inLen, int num_channels,
  8092. const EXRChannelInfo *channels, int data_width,
  8093. int num_lines) {
  8094. if (inLen == tmpBufSize) {
  8095. // Data is not compressed(Issue 40).
  8096. memcpy(outPtr, inPtr, inLen);
  8097. return true;
  8098. }
  8099. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  8100. unsigned short minNonZero;
  8101. unsigned short maxNonZero;
  8102. #if !MINIZ_LITTLE_ENDIAN
  8103. // @todo { PIZ compression on BigEndian architecture. }
  8104. assert(0);
  8105. return false;
  8106. #endif
  8107. memset(bitmap.data(), 0, BITMAP_SIZE);
  8108. const unsigned char *ptr = inPtr;
  8109. // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
  8110. tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));
  8111. // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
  8112. tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));
  8113. ptr += 4;
  8114. if (maxNonZero >= BITMAP_SIZE) {
  8115. return false;
  8116. }
  8117. if (minNonZero <= maxNonZero) {
  8118. memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,
  8119. maxNonZero - minNonZero + 1);
  8120. ptr += maxNonZero - minNonZero + 1;
  8121. }
  8122. std::vector<unsigned short> lut(USHORT_RANGE);
  8123. memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
  8124. unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
  8125. //
  8126. // Huffman decoding
  8127. //
  8128. int length;
  8129. // length = *(reinterpret_cast<const int *>(ptr));
  8130. tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));
  8131. ptr += sizeof(int);
  8132. std::vector<unsigned short> tmpBuffer(tmpBufSize);
  8133. hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);
  8134. //
  8135. // Wavelet decoding
  8136. //
  8137. std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
  8138. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8139. for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
  8140. const EXRChannelInfo &chan = channels[i];
  8141. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8142. if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8143. pixelSize = sizeof(short);
  8144. }
  8145. channelData[i].start = tmpBufferEnd;
  8146. channelData[i].end = channelData[i].start;
  8147. channelData[i].nx = data_width;
  8148. channelData[i].ny = num_lines;
  8149. // channelData[i].ys = 1;
  8150. channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
  8151. tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
  8152. }
  8153. for (size_t i = 0; i < channelData.size(); ++i) {
  8154. PIZChannelData &cd = channelData[i];
  8155. for (int j = 0; j < cd.size; ++j) {
  8156. wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8157. maxValue);
  8158. }
  8159. }
  8160. //
  8161. // Expand the pixel data to their original range
  8162. //
  8163. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize));
  8164. for (int y = 0; y < num_lines; y++) {
  8165. for (size_t i = 0; i < channelData.size(); ++i) {
  8166. PIZChannelData &cd = channelData[i];
  8167. // if (modp (y, cd.ys) != 0)
  8168. // continue;
  8169. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8170. memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
  8171. outPtr += n * sizeof(unsigned short);
  8172. cd.end += n;
  8173. }
  8174. }
  8175. return true;
  8176. }
  8177. #endif // TINYEXR_USE_PIZ
  8178. #if TINYEXR_USE_ZFP
  8179. struct ZFPCompressionParam {
  8180. double rate;
  8181. int precision;
  8182. double tolerance;
  8183. int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
  8184. ZFPCompressionParam() {
  8185. type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;
  8186. rate = 2.0;
  8187. precision = 0;
  8188. tolerance = 0.0f;
  8189. }
  8190. };
  8191. bool FindZFPCompressionParam(ZFPCompressionParam *param,
  8192. const EXRAttribute *attributes,
  8193. int num_attributes) {
  8194. bool foundType = false;
  8195. for (int i = 0; i < num_attributes; i++) {
  8196. if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) &&
  8197. (attributes[i].size == 1)) {
  8198. param->type = static_cast<int>(attributes[i].value[0]);
  8199. foundType = true;
  8200. }
  8201. }
  8202. if (!foundType) {
  8203. return false;
  8204. }
  8205. if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8206. for (int i = 0; i < num_attributes; i++) {
  8207. if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&
  8208. (attributes[i].size == 8)) {
  8209. param->rate = *(reinterpret_cast<double *>(attributes[i].value));
  8210. return true;
  8211. }
  8212. }
  8213. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8214. for (int i = 0; i < num_attributes; i++) {
  8215. if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&
  8216. (attributes[i].size == 4)) {
  8217. param->rate = *(reinterpret_cast<int *>(attributes[i].value));
  8218. return true;
  8219. }
  8220. }
  8221. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8222. for (int i = 0; i < num_attributes; i++) {
  8223. if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&
  8224. (attributes[i].size == 8)) {
  8225. param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));
  8226. return true;
  8227. }
  8228. }
  8229. } else {
  8230. assert(0);
  8231. }
  8232. return false;
  8233. }
  8234. // Assume pixel format is FLOAT for all channels.
  8235. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,
  8236. int num_channels, const unsigned char *src,
  8237. unsigned long src_size,
  8238. const ZFPCompressionParam &param) {
  8239. size_t uncompressed_size = dst_width * dst_num_lines * num_channels;
  8240. if (uncompressed_size == src_size) {
  8241. // Data is not compressed(Issue 40).
  8242. memcpy(dst, src, src_size);
  8243. }
  8244. zfp_stream *zfp = NULL;
  8245. zfp_field *field = NULL;
  8246. assert((dst_width % 4) == 0);
  8247. assert((dst_num_lines % 4) == 0);
  8248. if ((dst_width & 3U) || (dst_num_lines & 3U)) {
  8249. return false;
  8250. }
  8251. field =
  8252. zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),
  8253. zfp_type_float, dst_width, dst_num_lines * num_channels);
  8254. zfp = zfp_stream_open(NULL);
  8255. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8256. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2,
  8257. /* write random access */ 0);
  8258. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8259. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8260. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8261. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8262. } else {
  8263. assert(0);
  8264. }
  8265. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8266. std::vector<unsigned char> buf(buf_size);
  8267. memcpy(&buf.at(0), src, src_size);
  8268. bitstream *stream = stream_open(&buf.at(0), buf_size);
  8269. zfp_stream_set_bit_stream(zfp, stream);
  8270. zfp_stream_rewind(zfp);
  8271. size_t image_size = dst_width * dst_num_lines;
  8272. for (int c = 0; c < num_channels; c++) {
  8273. // decompress 4x4 pixel block.
  8274. for (int y = 0; y < dst_num_lines; y += 4) {
  8275. for (int x = 0; x < dst_width; x += 4) {
  8276. float fblock[16];
  8277. zfp_decode_block_float_2(zfp, fblock);
  8278. for (int j = 0; j < 4; j++) {
  8279. for (int i = 0; i < 4; i++) {
  8280. dst[c * image_size + ((y + j) * dst_width + (x + i))] =
  8281. fblock[j * 4 + i];
  8282. }
  8283. }
  8284. }
  8285. }
  8286. }
  8287. zfp_field_free(field);
  8288. zfp_stream_close(zfp);
  8289. stream_close(stream);
  8290. return true;
  8291. }
  8292. // Assume pixel format is FLOAT for all channels.
  8293. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize,
  8294. const float *inPtr, int width, int num_lines, int num_channels,
  8295. const ZFPCompressionParam &param) {
  8296. zfp_stream *zfp = NULL;
  8297. zfp_field *field = NULL;
  8298. assert((width % 4) == 0);
  8299. assert((num_lines % 4) == 0);
  8300. if ((width & 3U) || (num_lines & 3U)) {
  8301. return false;
  8302. }
  8303. // create input array.
  8304. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),
  8305. zfp_type_float, width, num_lines * num_channels);
  8306. zfp = zfp_stream_open(NULL);
  8307. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8308. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
  8309. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8310. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8311. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8312. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8313. } else {
  8314. assert(0);
  8315. }
  8316. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8317. outBuf->resize(buf_size);
  8318. bitstream *stream = stream_open(&outBuf->at(0), buf_size);
  8319. zfp_stream_set_bit_stream(zfp, stream);
  8320. zfp_field_free(field);
  8321. size_t image_size = width * num_lines;
  8322. for (int c = 0; c < num_channels; c++) {
  8323. // compress 4x4 pixel block.
  8324. for (int y = 0; y < num_lines; y += 4) {
  8325. for (int x = 0; x < width; x += 4) {
  8326. float fblock[16];
  8327. for (int j = 0; j < 4; j++) {
  8328. for (int i = 0; i < 4; i++) {
  8329. fblock[j * 4 + i] =
  8330. inPtr[c * image_size + ((y + j) * width + (x + i))];
  8331. }
  8332. }
  8333. zfp_encode_block_float_2(zfp, fblock);
  8334. }
  8335. }
  8336. }
  8337. zfp_stream_flush(zfp);
  8338. (*outSize) = zfp_stream_compressed_size(zfp);
  8339. zfp_stream_close(zfp);
  8340. return true;
  8341. }
  8342. #endif
  8343. //
  8344. // -----------------------------------------------------------------
  8345. //
  8346. // TODO(syoyo): Refactor function arguments.
  8347. static bool DecodePixelData(/* out */ unsigned char **out_images,
  8348. const int *requested_pixel_types,
  8349. const unsigned char *data_ptr, size_t data_len,
  8350. int compression_type, int line_order, int width,
  8351. int height, int x_stride, int y, int line_no,
  8352. int num_lines, size_t pixel_data_size,
  8353. size_t num_attributes,
  8354. const EXRAttribute *attributes, size_t num_channels,
  8355. const EXRChannelInfo *channels,
  8356. const std::vector<size_t> &channel_offset_list) {
  8357. if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
  8358. #if TINYEXR_USE_PIZ
  8359. if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
  8360. // Invalid input #90
  8361. return false;
  8362. }
  8363. // Allocate original data size.
  8364. std::vector<unsigned char> outBuf(static_cast<size_t>(
  8365. static_cast<size_t>(width * num_lines) * pixel_data_size));
  8366. size_t tmpBufLen = outBuf.size();
  8367. bool ret = tinyexr::DecompressPiz(
  8368. reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,
  8369. data_len, static_cast<int>(num_channels), channels, width, num_lines);
  8370. assert(ret);
  8371. (void)ret;
  8372. // For PIZ_COMPRESSION:
  8373. // pixel sample data for channel 0 for scanline 0
  8374. // pixel sample data for channel 1 for scanline 0
  8375. // pixel sample data for channel ... for scanline 0
  8376. // pixel sample data for channel n for scanline 0
  8377. // pixel sample data for channel 0 for scanline 1
  8378. // pixel sample data for channel 1 for scanline 1
  8379. // pixel sample data for channel ... for scanline 1
  8380. // pixel sample data for channel n for scanline 1
  8381. // ...
  8382. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8383. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8384. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8385. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8386. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8387. channel_offset_list[c] * static_cast<size_t>(width)));
  8388. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8389. FP16 hf;
  8390. // hf.u = line_ptr[u];
  8391. // use `cpy` to avoid unaligned memory access when compiler's
  8392. // optimization is on.
  8393. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8394. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8395. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8396. unsigned short *image =
  8397. reinterpret_cast<unsigned short **>(out_images)[c];
  8398. if (line_order == 0) {
  8399. image += (static_cast<size_t>(line_no) + v) *
  8400. static_cast<size_t>(x_stride) +
  8401. u;
  8402. } else {
  8403. image += static_cast<size_t>(
  8404. (height - 1 - (line_no + static_cast<int>(v)))) *
  8405. static_cast<size_t>(x_stride) +
  8406. u;
  8407. }
  8408. *image = hf.u;
  8409. } else { // HALF -> FLOAT
  8410. FP32 f32 = half_to_float(hf);
  8411. float *image = reinterpret_cast<float **>(out_images)[c];
  8412. if (line_order == 0) {
  8413. image += (static_cast<size_t>(line_no) + v) *
  8414. static_cast<size_t>(x_stride) +
  8415. u;
  8416. } else {
  8417. image += static_cast<size_t>(
  8418. (height - 1 - (line_no + static_cast<int>(v)))) *
  8419. static_cast<size_t>(x_stride) +
  8420. u;
  8421. }
  8422. *image = f32.f;
  8423. }
  8424. }
  8425. }
  8426. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8427. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8428. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8429. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8430. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8431. channel_offset_list[c] * static_cast<size_t>(width)));
  8432. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8433. unsigned int val;
  8434. // val = line_ptr[u];
  8435. tinyexr::cpy4(&val, line_ptr + u);
  8436. tinyexr::swap4(&val);
  8437. unsigned int *image =
  8438. reinterpret_cast<unsigned int **>(out_images)[c];
  8439. if (line_order == 0) {
  8440. image += (static_cast<size_t>(line_no) + v) *
  8441. static_cast<size_t>(x_stride) +
  8442. u;
  8443. } else {
  8444. image += static_cast<size_t>(
  8445. (height - 1 - (line_no + static_cast<int>(v)))) *
  8446. static_cast<size_t>(x_stride) +
  8447. u;
  8448. }
  8449. *image = val;
  8450. }
  8451. }
  8452. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8453. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8454. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8455. const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(
  8456. v * pixel_data_size * static_cast<size_t>(x_stride) +
  8457. channel_offset_list[c] * static_cast<size_t>(x_stride)));
  8458. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8459. float val;
  8460. // val = line_ptr[u];
  8461. tinyexr::cpy4(&val, line_ptr + u);
  8462. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8463. float *image = reinterpret_cast<float **>(out_images)[c];
  8464. if (line_order == 0) {
  8465. image += (static_cast<size_t>(line_no) + v) *
  8466. static_cast<size_t>(x_stride) +
  8467. u;
  8468. } else {
  8469. image += static_cast<size_t>(
  8470. (height - 1 - (line_no + static_cast<int>(v)))) *
  8471. static_cast<size_t>(x_stride) +
  8472. u;
  8473. }
  8474. *image = val;
  8475. }
  8476. }
  8477. } else {
  8478. assert(0);
  8479. }
  8480. }
  8481. #else
  8482. assert(0 && "PIZ is enabled in this build");
  8483. return false;
  8484. #endif
  8485. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||
  8486. compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  8487. // Allocate original data size.
  8488. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8489. static_cast<size_t>(num_lines) *
  8490. pixel_data_size);
  8491. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8492. assert(dstLen > 0);
  8493. if (!tinyexr::DecompressZip(
  8494. reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,
  8495. static_cast<unsigned long>(data_len))) {
  8496. return false;
  8497. }
  8498. // For ZIP_COMPRESSION:
  8499. // pixel sample data for channel 0 for scanline 0
  8500. // pixel sample data for channel 1 for scanline 0
  8501. // pixel sample data for channel ... for scanline 0
  8502. // pixel sample data for channel n for scanline 0
  8503. // pixel sample data for channel 0 for scanline 1
  8504. // pixel sample data for channel 1 for scanline 1
  8505. // pixel sample data for channel ... for scanline 1
  8506. // pixel sample data for channel n for scanline 1
  8507. // ...
  8508. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8509. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8510. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8511. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8512. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8513. static_cast<size_t>(width) +
  8514. channel_offset_list[c] * static_cast<size_t>(width)));
  8515. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8516. tinyexr::FP16 hf;
  8517. // hf.u = line_ptr[u];
  8518. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8519. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8520. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8521. unsigned short *image =
  8522. reinterpret_cast<unsigned short **>(out_images)[c];
  8523. if (line_order == 0) {
  8524. image += (static_cast<size_t>(line_no) + v) *
  8525. static_cast<size_t>(x_stride) +
  8526. u;
  8527. } else {
  8528. image += (static_cast<size_t>(height) - 1U -
  8529. (static_cast<size_t>(line_no) + v)) *
  8530. static_cast<size_t>(x_stride) +
  8531. u;
  8532. }
  8533. *image = hf.u;
  8534. } else { // HALF -> FLOAT
  8535. tinyexr::FP32 f32 = half_to_float(hf);
  8536. float *image = reinterpret_cast<float **>(out_images)[c];
  8537. if (line_order == 0) {
  8538. image += (static_cast<size_t>(line_no) + v) *
  8539. static_cast<size_t>(x_stride) +
  8540. u;
  8541. } else {
  8542. image += (static_cast<size_t>(height) - 1U -
  8543. (static_cast<size_t>(line_no) + v)) *
  8544. static_cast<size_t>(x_stride) +
  8545. u;
  8546. }
  8547. *image = f32.f;
  8548. }
  8549. }
  8550. }
  8551. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8552. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8553. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8554. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8555. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8556. channel_offset_list[c] * static_cast<size_t>(width)));
  8557. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8558. unsigned int val;
  8559. // val = line_ptr[u];
  8560. tinyexr::cpy4(&val, line_ptr + u);
  8561. tinyexr::swap4(&val);
  8562. unsigned int *image =
  8563. reinterpret_cast<unsigned int **>(out_images)[c];
  8564. if (line_order == 0) {
  8565. image += (static_cast<size_t>(line_no) + v) *
  8566. static_cast<size_t>(x_stride) +
  8567. u;
  8568. } else {
  8569. image += (static_cast<size_t>(height) - 1U -
  8570. (static_cast<size_t>(line_no) + v)) *
  8571. static_cast<size_t>(x_stride) +
  8572. u;
  8573. }
  8574. *image = val;
  8575. }
  8576. }
  8577. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8578. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8579. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8580. const float *line_ptr = reinterpret_cast<float *>(
  8581. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8582. channel_offset_list[c] * static_cast<size_t>(width)));
  8583. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8584. float val;
  8585. // val = line_ptr[u];
  8586. tinyexr::cpy4(&val, line_ptr + u);
  8587. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8588. float *image = reinterpret_cast<float **>(out_images)[c];
  8589. if (line_order == 0) {
  8590. image += (static_cast<size_t>(line_no) + v) *
  8591. static_cast<size_t>(x_stride) +
  8592. u;
  8593. } else {
  8594. image += (static_cast<size_t>(height) - 1U -
  8595. (static_cast<size_t>(line_no) + v)) *
  8596. static_cast<size_t>(x_stride) +
  8597. u;
  8598. }
  8599. *image = val;
  8600. }
  8601. }
  8602. } else {
  8603. assert(0);
  8604. return false;
  8605. }
  8606. }
  8607. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  8608. // Allocate original data size.
  8609. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8610. static_cast<size_t>(num_lines) *
  8611. pixel_data_size);
  8612. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8613. assert(dstLen > 0);
  8614. tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)),
  8615. dstLen, data_ptr,
  8616. static_cast<unsigned long>(data_len));
  8617. // For RLE_COMPRESSION:
  8618. // pixel sample data for channel 0 for scanline 0
  8619. // pixel sample data for channel 1 for scanline 0
  8620. // pixel sample data for channel ... for scanline 0
  8621. // pixel sample data for channel n for scanline 0
  8622. // pixel sample data for channel 0 for scanline 1
  8623. // pixel sample data for channel 1 for scanline 1
  8624. // pixel sample data for channel ... for scanline 1
  8625. // pixel sample data for channel n for scanline 1
  8626. // ...
  8627. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8628. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8629. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8630. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8631. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8632. static_cast<size_t>(width) +
  8633. channel_offset_list[c] * static_cast<size_t>(width)));
  8634. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8635. tinyexr::FP16 hf;
  8636. // hf.u = line_ptr[u];
  8637. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8638. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8639. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8640. unsigned short *image =
  8641. reinterpret_cast<unsigned short **>(out_images)[c];
  8642. if (line_order == 0) {
  8643. image += (static_cast<size_t>(line_no) + v) *
  8644. static_cast<size_t>(x_stride) +
  8645. u;
  8646. } else {
  8647. image += (static_cast<size_t>(height) - 1U -
  8648. (static_cast<size_t>(line_no) + v)) *
  8649. static_cast<size_t>(x_stride) +
  8650. u;
  8651. }
  8652. *image = hf.u;
  8653. } else { // HALF -> FLOAT
  8654. tinyexr::FP32 f32 = half_to_float(hf);
  8655. float *image = reinterpret_cast<float **>(out_images)[c];
  8656. if (line_order == 0) {
  8657. image += (static_cast<size_t>(line_no) + v) *
  8658. static_cast<size_t>(x_stride) +
  8659. u;
  8660. } else {
  8661. image += (static_cast<size_t>(height) - 1U -
  8662. (static_cast<size_t>(line_no) + v)) *
  8663. static_cast<size_t>(x_stride) +
  8664. u;
  8665. }
  8666. *image = f32.f;
  8667. }
  8668. }
  8669. }
  8670. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8671. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8672. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8673. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8674. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8675. channel_offset_list[c] * static_cast<size_t>(width)));
  8676. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8677. unsigned int val;
  8678. // val = line_ptr[u];
  8679. tinyexr::cpy4(&val, line_ptr + u);
  8680. tinyexr::swap4(&val);
  8681. unsigned int *image =
  8682. reinterpret_cast<unsigned int **>(out_images)[c];
  8683. if (line_order == 0) {
  8684. image += (static_cast<size_t>(line_no) + v) *
  8685. static_cast<size_t>(x_stride) +
  8686. u;
  8687. } else {
  8688. image += (static_cast<size_t>(height) - 1U -
  8689. (static_cast<size_t>(line_no) + v)) *
  8690. static_cast<size_t>(x_stride) +
  8691. u;
  8692. }
  8693. *image = val;
  8694. }
  8695. }
  8696. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8697. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8698. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8699. const float *line_ptr = reinterpret_cast<float *>(
  8700. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8701. channel_offset_list[c] * static_cast<size_t>(width)));
  8702. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8703. float val;
  8704. // val = line_ptr[u];
  8705. tinyexr::cpy4(&val, line_ptr + u);
  8706. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8707. float *image = reinterpret_cast<float **>(out_images)[c];
  8708. if (line_order == 0) {
  8709. image += (static_cast<size_t>(line_no) + v) *
  8710. static_cast<size_t>(x_stride) +
  8711. u;
  8712. } else {
  8713. image += (static_cast<size_t>(height) - 1U -
  8714. (static_cast<size_t>(line_no) + v)) *
  8715. static_cast<size_t>(x_stride) +
  8716. u;
  8717. }
  8718. *image = val;
  8719. }
  8720. }
  8721. } else {
  8722. assert(0);
  8723. return false;
  8724. }
  8725. }
  8726. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  8727. #if TINYEXR_USE_ZFP
  8728. tinyexr::ZFPCompressionParam zfp_compression_param;
  8729. if (!FindZFPCompressionParam(&zfp_compression_param, attributes,
  8730. num_attributes)) {
  8731. assert(0);
  8732. return false;
  8733. }
  8734. // Allocate original data size.
  8735. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8736. static_cast<size_t>(num_lines) *
  8737. pixel_data_size);
  8738. unsigned long dstLen = outBuf.size();
  8739. assert(dstLen > 0);
  8740. tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,
  8741. num_lines, num_channels, data_ptr,
  8742. static_cast<unsigned long>(data_len),
  8743. zfp_compression_param);
  8744. // For ZFP_COMPRESSION:
  8745. // pixel sample data for channel 0 for scanline 0
  8746. // pixel sample data for channel 1 for scanline 0
  8747. // pixel sample data for channel ... for scanline 0
  8748. // pixel sample data for channel n for scanline 0
  8749. // pixel sample data for channel 0 for scanline 1
  8750. // pixel sample data for channel 1 for scanline 1
  8751. // pixel sample data for channel ... for scanline 1
  8752. // pixel sample data for channel n for scanline 1
  8753. // ...
  8754. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8755. assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT);
  8756. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8757. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8758. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8759. const float *line_ptr = reinterpret_cast<float *>(
  8760. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8761. channel_offset_list[c] * static_cast<size_t>(width)));
  8762. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8763. float val;
  8764. tinyexr::cpy4(&val, line_ptr + u);
  8765. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8766. float *image = reinterpret_cast<float **>(out_images)[c];
  8767. if (line_order == 0) {
  8768. image += (static_cast<size_t>(line_no) + v) *
  8769. static_cast<size_t>(x_stride) +
  8770. u;
  8771. } else {
  8772. image += (static_cast<size_t>(height) - 1U -
  8773. (static_cast<size_t>(line_no) + v)) *
  8774. static_cast<size_t>(x_stride) +
  8775. u;
  8776. }
  8777. *image = val;
  8778. }
  8779. }
  8780. } else {
  8781. assert(0);
  8782. return false;
  8783. }
  8784. }
  8785. #else
  8786. (void)attributes;
  8787. (void)num_attributes;
  8788. (void)num_channels;
  8789. assert(0);
  8790. return false;
  8791. #endif
  8792. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  8793. for (size_t c = 0; c < num_channels; c++) {
  8794. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8795. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8796. const unsigned short *line_ptr =
  8797. reinterpret_cast<const unsigned short *>(
  8798. data_ptr + v * pixel_data_size * size_t(width) +
  8799. channel_offset_list[c] * static_cast<size_t>(width));
  8800. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8801. unsigned short *outLine =
  8802. reinterpret_cast<unsigned short *>(out_images[c]);
  8803. if (line_order == 0) {
  8804. outLine += (size_t(y) + v) * size_t(x_stride);
  8805. } else {
  8806. outLine +=
  8807. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8808. }
  8809. for (int u = 0; u < width; u++) {
  8810. tinyexr::FP16 hf;
  8811. // hf.u = line_ptr[u];
  8812. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8813. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8814. outLine[u] = hf.u;
  8815. }
  8816. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8817. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8818. if (line_order == 0) {
  8819. outLine += (size_t(y) + v) * size_t(x_stride);
  8820. } else {
  8821. outLine +=
  8822. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8823. }
  8824. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8825. (data_ptr + data_len)) {
  8826. // Insufficient data size
  8827. return false;
  8828. }
  8829. for (int u = 0; u < width; u++) {
  8830. tinyexr::FP16 hf;
  8831. // address may not be aliged. use byte-wise copy for safety.#76
  8832. // hf.u = line_ptr[u];
  8833. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8834. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8835. tinyexr::FP32 f32 = half_to_float(hf);
  8836. outLine[u] = f32.f;
  8837. }
  8838. } else {
  8839. assert(0);
  8840. return false;
  8841. }
  8842. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8843. const float *line_ptr = reinterpret_cast<const float *>(
  8844. data_ptr + v * pixel_data_size * size_t(width) +
  8845. channel_offset_list[c] * static_cast<size_t>(width));
  8846. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8847. if (line_order == 0) {
  8848. outLine += (size_t(y) + v) * size_t(x_stride);
  8849. } else {
  8850. outLine +=
  8851. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8852. }
  8853. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8854. (data_ptr + data_len)) {
  8855. // Insufficient data size
  8856. return false;
  8857. }
  8858. for (int u = 0; u < width; u++) {
  8859. float val;
  8860. tinyexr::cpy4(&val, line_ptr + u);
  8861. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8862. outLine[u] = val;
  8863. }
  8864. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8865. const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(
  8866. data_ptr + v * pixel_data_size * size_t(width) +
  8867. channel_offset_list[c] * static_cast<size_t>(width));
  8868. unsigned int *outLine =
  8869. reinterpret_cast<unsigned int *>(out_images[c]);
  8870. if (line_order == 0) {
  8871. outLine += (size_t(y) + v) * size_t(x_stride);
  8872. } else {
  8873. outLine +=
  8874. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8875. }
  8876. for (int u = 0; u < width; u++) {
  8877. if (reinterpret_cast<const unsigned char *>(line_ptr + u) >=
  8878. (data_ptr + data_len)) {
  8879. // Corrupsed data?
  8880. return false;
  8881. }
  8882. unsigned int val;
  8883. tinyexr::cpy4(&val, line_ptr + u);
  8884. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8885. outLine[u] = val;
  8886. }
  8887. }
  8888. }
  8889. }
  8890. }
  8891. return true;
  8892. }
  8893. static void DecodeTiledPixelData(
  8894. unsigned char **out_images, int *width, int *height,
  8895. const int *requested_pixel_types, const unsigned char *data_ptr,
  8896. size_t data_len, int compression_type, int line_order, int data_width,
  8897. int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
  8898. int tile_size_y, size_t pixel_data_size, size_t num_attributes,
  8899. const EXRAttribute *attributes, size_t num_channels,
  8900. const EXRChannelInfo *channels,
  8901. const std::vector<size_t> &channel_offset_list) {
  8902. assert(tile_offset_x * tile_size_x < data_width);
  8903. assert(tile_offset_y * tile_size_y < data_height);
  8904. // Compute actual image size in a tile.
  8905. if ((tile_offset_x + 1) * tile_size_x >= data_width) {
  8906. (*width) = data_width - (tile_offset_x * tile_size_x);
  8907. } else {
  8908. (*width) = tile_size_x;
  8909. }
  8910. if ((tile_offset_y + 1) * tile_size_y >= data_height) {
  8911. (*height) = data_height - (tile_offset_y * tile_size_y);
  8912. } else {
  8913. (*height) = tile_size_y;
  8914. }
  8915. // Image size = tile size.
  8916. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
  8917. compression_type, line_order, (*width), tile_size_y,
  8918. /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
  8919. (*height), pixel_data_size, num_attributes, attributes,
  8920. num_channels, channels, channel_offset_list);
  8921. }
  8922. static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,
  8923. int *pixel_data_size, size_t *channel_offset,
  8924. int num_channels,
  8925. const EXRChannelInfo *channels) {
  8926. channel_offset_list->resize(static_cast<size_t>(num_channels));
  8927. (*pixel_data_size) = 0;
  8928. (*channel_offset) = 0;
  8929. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8930. (*channel_offset_list)[c] = (*channel_offset);
  8931. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8932. (*pixel_data_size) += sizeof(unsigned short);
  8933. (*channel_offset) += sizeof(unsigned short);
  8934. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8935. (*pixel_data_size) += sizeof(float);
  8936. (*channel_offset) += sizeof(float);
  8937. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8938. (*pixel_data_size) += sizeof(unsigned int);
  8939. (*channel_offset) += sizeof(unsigned int);
  8940. } else {
  8941. // ???
  8942. return false;
  8943. }
  8944. }
  8945. return true;
  8946. }
  8947. static unsigned char **AllocateImage(int num_channels,
  8948. const EXRChannelInfo *channels,
  8949. const int *requested_pixel_types,
  8950. int data_width, int data_height) {
  8951. unsigned char **images =
  8952. reinterpret_cast<unsigned char **>(static_cast<float **>(
  8953. malloc(sizeof(float *) * static_cast<size_t>(num_channels))));
  8954. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8955. size_t data_len =
  8956. static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
  8957. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8958. // pixel_data_size += sizeof(unsigned short);
  8959. // channel_offset += sizeof(unsigned short);
  8960. // Alloc internal image for half type.
  8961. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8962. images[c] =
  8963. reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(
  8964. malloc(sizeof(unsigned short) * data_len)));
  8965. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8966. images[c] = reinterpret_cast<unsigned char *>(
  8967. static_cast<float *>(malloc(sizeof(float) * data_len)));
  8968. } else {
  8969. assert(0);
  8970. }
  8971. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8972. // pixel_data_size += sizeof(float);
  8973. // channel_offset += sizeof(float);
  8974. images[c] = reinterpret_cast<unsigned char *>(
  8975. static_cast<float *>(malloc(sizeof(float) * data_len)));
  8976. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8977. // pixel_data_size += sizeof(unsigned int);
  8978. // channel_offset += sizeof(unsigned int);
  8979. images[c] = reinterpret_cast<unsigned char *>(
  8980. static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));
  8981. } else {
  8982. assert(0);
  8983. }
  8984. }
  8985. return images;
  8986. }
  8987. static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,
  8988. const EXRVersion *version, std::string *err,
  8989. const unsigned char *buf, size_t size) {
  8990. const char *marker = reinterpret_cast<const char *>(&buf[0]);
  8991. if (empty_header) {
  8992. (*empty_header) = false;
  8993. }
  8994. if (version->multipart) {
  8995. if (size > 0 && marker[0] == '\0') {
  8996. // End of header list.
  8997. if (empty_header) {
  8998. (*empty_header) = true;
  8999. }
  9000. return TINYEXR_SUCCESS;
  9001. }
  9002. }
  9003. // According to the spec, the header of every OpenEXR file must contain at
  9004. // least the following attributes:
  9005. //
  9006. // channels chlist
  9007. // compression compression
  9008. // dataWindow box2i
  9009. // displayWindow box2i
  9010. // lineOrder lineOrder
  9011. // pixelAspectRatio float
  9012. // screenWindowCenter v2f
  9013. // screenWindowWidth float
  9014. bool has_channels = false;
  9015. bool has_compression = false;
  9016. bool has_data_window = false;
  9017. bool has_display_window = false;
  9018. bool has_line_order = false;
  9019. bool has_pixel_aspect_ratio = false;
  9020. bool has_screen_window_center = false;
  9021. bool has_screen_window_width = false;
  9022. info->data_window[0] = 0;
  9023. info->data_window[1] = 0;
  9024. info->data_window[2] = 0;
  9025. info->data_window[3] = 0;
  9026. info->line_order = 0; // @fixme
  9027. info->display_window[0] = 0;
  9028. info->display_window[1] = 0;
  9029. info->display_window[2] = 0;
  9030. info->display_window[3] = 0;
  9031. info->screen_window_center[0] = 0.0f;
  9032. info->screen_window_center[1] = 0.0f;
  9033. info->screen_window_width = -1.0f;
  9034. info->pixel_aspect_ratio = -1.0f;
  9035. info->tile_size_x = -1;
  9036. info->tile_size_y = -1;
  9037. info->tile_level_mode = -1;
  9038. info->tile_rounding_mode = -1;
  9039. info->attributes.clear();
  9040. // Read attributes
  9041. size_t orig_size = size;
  9042. for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
  9043. if (0 == size) {
  9044. if (err) {
  9045. (*err) += "Insufficient data size for attributes.\n";
  9046. }
  9047. return TINYEXR_ERROR_INVALID_DATA;
  9048. } else if (marker[0] == '\0') {
  9049. size--;
  9050. break;
  9051. }
  9052. std::string attr_name;
  9053. std::string attr_type;
  9054. std::vector<unsigned char> data;
  9055. size_t marker_size;
  9056. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  9057. marker, size)) {
  9058. if (err) {
  9059. (*err) += "Failed to read attribute.\n";
  9060. }
  9061. return TINYEXR_ERROR_INVALID_DATA;
  9062. }
  9063. marker += marker_size;
  9064. size -= marker_size;
  9065. if (version->tiled && attr_name.compare("tiles") == 0) {
  9066. unsigned int x_size, y_size;
  9067. unsigned char tile_mode;
  9068. assert(data.size() == 9);
  9069. memcpy(&x_size, &data.at(0), sizeof(int));
  9070. memcpy(&y_size, &data.at(4), sizeof(int));
  9071. tile_mode = data[8];
  9072. tinyexr::swap4(&x_size);
  9073. tinyexr::swap4(&y_size);
  9074. info->tile_size_x = static_cast<int>(x_size);
  9075. info->tile_size_y = static_cast<int>(y_size);
  9076. // mode = levelMode + roundingMode * 16
  9077. info->tile_level_mode = tile_mode & 0x3;
  9078. info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
  9079. } else if (attr_name.compare("compression") == 0) {
  9080. bool ok = false;
  9081. if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
  9082. ok = true;
  9083. }
  9084. if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9085. #if TINYEXR_USE_PIZ
  9086. ok = true;
  9087. #else
  9088. if (err) {
  9089. (*err) = "PIZ compression is not supported.";
  9090. }
  9091. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9092. #endif
  9093. }
  9094. if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9095. #if TINYEXR_USE_ZFP
  9096. ok = true;
  9097. #else
  9098. if (err) {
  9099. (*err) = "ZFP compression is not supported.";
  9100. }
  9101. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9102. #endif
  9103. }
  9104. if (!ok) {
  9105. if (err) {
  9106. (*err) = "Unknown compression type.";
  9107. }
  9108. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9109. }
  9110. info->compression_type = static_cast<int>(data[0]);
  9111. has_compression = true;
  9112. } else if (attr_name.compare("channels") == 0) {
  9113. // name: zero-terminated string, from 1 to 255 bytes long
  9114. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  9115. // pLinear: unsigned char, possible values are 0 and 1
  9116. // reserved: three chars, should be zero
  9117. // xSampling: int
  9118. // ySampling: int
  9119. if (!ReadChannelInfo(info->channels, data)) {
  9120. if (err) {
  9121. (*err) += "Failed to parse channel info.\n";
  9122. }
  9123. return TINYEXR_ERROR_INVALID_DATA;
  9124. }
  9125. if (info->channels.size() < 1) {
  9126. if (err) {
  9127. (*err) += "# of channels is zero.\n";
  9128. }
  9129. return TINYEXR_ERROR_INVALID_DATA;
  9130. }
  9131. has_channels = true;
  9132. } else if (attr_name.compare("dataWindow") == 0) {
  9133. if (data.size() >= 16) {
  9134. memcpy(&info->data_window[0], &data.at(0), sizeof(int));
  9135. memcpy(&info->data_window[1], &data.at(4), sizeof(int));
  9136. memcpy(&info->data_window[2], &data.at(8), sizeof(int));
  9137. memcpy(&info->data_window[3], &data.at(12), sizeof(int));
  9138. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0]));
  9139. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1]));
  9140. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2]));
  9141. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3]));
  9142. has_data_window = true;
  9143. }
  9144. } else if (attr_name.compare("displayWindow") == 0) {
  9145. if (data.size() >= 16) {
  9146. memcpy(&info->display_window[0], &data.at(0), sizeof(int));
  9147. memcpy(&info->display_window[1], &data.at(4), sizeof(int));
  9148. memcpy(&info->display_window[2], &data.at(8), sizeof(int));
  9149. memcpy(&info->display_window[3], &data.at(12), sizeof(int));
  9150. tinyexr::swap4(
  9151. reinterpret_cast<unsigned int *>(&info->display_window[0]));
  9152. tinyexr::swap4(
  9153. reinterpret_cast<unsigned int *>(&info->display_window[1]));
  9154. tinyexr::swap4(
  9155. reinterpret_cast<unsigned int *>(&info->display_window[2]));
  9156. tinyexr::swap4(
  9157. reinterpret_cast<unsigned int *>(&info->display_window[3]));
  9158. has_display_window = true;
  9159. }
  9160. } else if (attr_name.compare("lineOrder") == 0) {
  9161. if (data.size() >= 1) {
  9162. info->line_order = static_cast<int>(data[0]);
  9163. has_line_order = true;
  9164. }
  9165. } else if (attr_name.compare("pixelAspectRatio") == 0) {
  9166. if (data.size() >= sizeof(float)) {
  9167. memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
  9168. tinyexr::swap4(
  9169. reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio));
  9170. has_pixel_aspect_ratio = true;
  9171. }
  9172. } else if (attr_name.compare("screenWindowCenter") == 0) {
  9173. if (data.size() >= 8) {
  9174. memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
  9175. memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
  9176. tinyexr::swap4(
  9177. reinterpret_cast<unsigned int *>(&info->screen_window_center[0]));
  9178. tinyexr::swap4(
  9179. reinterpret_cast<unsigned int *>(&info->screen_window_center[1]));
  9180. has_screen_window_center = true;
  9181. }
  9182. } else if (attr_name.compare("screenWindowWidth") == 0) {
  9183. if (data.size() >= sizeof(float)) {
  9184. memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
  9185. tinyexr::swap4(
  9186. reinterpret_cast<unsigned int *>(&info->screen_window_width));
  9187. has_screen_window_width = true;
  9188. }
  9189. } else if (attr_name.compare("chunkCount") == 0) {
  9190. if (data.size() >= sizeof(int)) {
  9191. memcpy(&info->chunk_count, &data.at(0), sizeof(int));
  9192. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count));
  9193. }
  9194. } else {
  9195. // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
  9196. if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9197. EXRAttribute attrib;
  9198. #ifdef _MSC_VER
  9199. strncpy_s(attrib.name, attr_name.c_str(), 255);
  9200. strncpy_s(attrib.type, attr_type.c_str(), 255);
  9201. #else
  9202. strncpy(attrib.name, attr_name.c_str(), 255);
  9203. strncpy(attrib.type, attr_type.c_str(), 255);
  9204. #endif
  9205. attrib.name[255] = '\0';
  9206. attrib.type[255] = '\0';
  9207. attrib.size = static_cast<int>(data.size());
  9208. attrib.value = static_cast<unsigned char *>(malloc(data.size()));
  9209. memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),
  9210. data.size());
  9211. info->attributes.push_back(attrib);
  9212. }
  9213. }
  9214. }
  9215. // Check if required attributes exist
  9216. {
  9217. std::stringstream ss_err;
  9218. if (!has_compression) {
  9219. ss_err << "\"compression\" attribute not found in the header."
  9220. << std::endl;
  9221. }
  9222. if (!has_channels) {
  9223. ss_err << "\"channels\" attribute not found in the header." << std::endl;
  9224. }
  9225. if (!has_line_order) {
  9226. ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
  9227. }
  9228. if (!has_display_window) {
  9229. ss_err << "\"displayWindow\" attribute not found in the header."
  9230. << std::endl;
  9231. }
  9232. if (!has_data_window) {
  9233. ss_err << "\"dataWindow\" attribute not found in the header or invalid."
  9234. << std::endl;
  9235. }
  9236. if (!has_pixel_aspect_ratio) {
  9237. ss_err << "\"pixelAspectRatio\" attribute not found in the header."
  9238. << std::endl;
  9239. }
  9240. if (!has_screen_window_width) {
  9241. ss_err << "\"screenWindowWidth\" attribute not found in the header."
  9242. << std::endl;
  9243. }
  9244. if (!has_screen_window_center) {
  9245. ss_err << "\"screenWindowCenter\" attribute not found in the header."
  9246. << std::endl;
  9247. }
  9248. if (!(ss_err.str().empty())) {
  9249. if (err) {
  9250. (*err) += ss_err.str();
  9251. }
  9252. return TINYEXR_ERROR_INVALID_HEADER;
  9253. }
  9254. }
  9255. info->header_len = static_cast<unsigned int>(orig_size - size);
  9256. return TINYEXR_SUCCESS;
  9257. }
  9258. // C++ HeaderInfo to C EXRHeader conversion.
  9259. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) {
  9260. exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
  9261. exr_header->screen_window_center[0] = info.screen_window_center[0];
  9262. exr_header->screen_window_center[1] = info.screen_window_center[1];
  9263. exr_header->screen_window_width = info.screen_window_width;
  9264. exr_header->chunk_count = info.chunk_count;
  9265. exr_header->display_window[0] = info.display_window[0];
  9266. exr_header->display_window[1] = info.display_window[1];
  9267. exr_header->display_window[2] = info.display_window[2];
  9268. exr_header->display_window[3] = info.display_window[3];
  9269. exr_header->data_window[0] = info.data_window[0];
  9270. exr_header->data_window[1] = info.data_window[1];
  9271. exr_header->data_window[2] = info.data_window[2];
  9272. exr_header->data_window[3] = info.data_window[3];
  9273. exr_header->line_order = info.line_order;
  9274. exr_header->compression_type = info.compression_type;
  9275. exr_header->tile_size_x = info.tile_size_x;
  9276. exr_header->tile_size_y = info.tile_size_y;
  9277. exr_header->tile_level_mode = info.tile_level_mode;
  9278. exr_header->tile_rounding_mode = info.tile_rounding_mode;
  9279. exr_header->num_channels = static_cast<int>(info.channels.size());
  9280. exr_header->channels = static_cast<EXRChannelInfo *>(malloc(
  9281. sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
  9282. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9283. #ifdef _MSC_VER
  9284. strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9285. #else
  9286. strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9287. #endif
  9288. // manually add '\0' for safety.
  9289. exr_header->channels[c].name[255] = '\0';
  9290. exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
  9291. exr_header->channels[c].p_linear = info.channels[c].p_linear;
  9292. exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
  9293. exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
  9294. }
  9295. exr_header->pixel_types = static_cast<int *>(
  9296. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9297. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9298. exr_header->pixel_types[c] = info.channels[c].pixel_type;
  9299. }
  9300. // Initially fill with values of `pixel_types`
  9301. exr_header->requested_pixel_types = static_cast<int *>(
  9302. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9303. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9304. exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
  9305. }
  9306. exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
  9307. if (exr_header->num_custom_attributes > 0) {
  9308. // TODO(syoyo): Report warning when # of attributes exceeds
  9309. // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
  9310. if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9311. exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;
  9312. }
  9313. exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(
  9314. sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
  9315. for (size_t i = 0; i < info.attributes.size(); i++) {
  9316. memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
  9317. 256);
  9318. memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
  9319. 256);
  9320. exr_header->custom_attributes[i].size = info.attributes[i].size;
  9321. // Just copy poiner
  9322. exr_header->custom_attributes[i].value = info.attributes[i].value;
  9323. }
  9324. } else {
  9325. exr_header->custom_attributes = NULL;
  9326. }
  9327. exr_header->header_len = info.header_len;
  9328. }
  9329. static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
  9330. const std::vector<tinyexr::tinyexr_uint64> &offsets,
  9331. const unsigned char *head, const size_t size,
  9332. std::string *err) {
  9333. int num_channels = exr_header->num_channels;
  9334. int num_scanline_blocks = 1;
  9335. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9336. num_scanline_blocks = 16;
  9337. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9338. num_scanline_blocks = 32;
  9339. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9340. num_scanline_blocks = 16;
  9341. }
  9342. int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;
  9343. int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;
  9344. if ((data_width < 0) || (data_height < 0)) {
  9345. if (err) {
  9346. std::stringstream ss;
  9347. ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl;
  9348. (*err) += ss.str();
  9349. }
  9350. return TINYEXR_ERROR_INVALID_DATA;
  9351. }
  9352. size_t num_blocks = offsets.size();
  9353. std::vector<size_t> channel_offset_list;
  9354. int pixel_data_size = 0;
  9355. size_t channel_offset = 0;
  9356. if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
  9357. &channel_offset, num_channels,
  9358. exr_header->channels)) {
  9359. if (err) {
  9360. (*err) += "Failed to compute channel layout.\n";
  9361. }
  9362. return TINYEXR_ERROR_INVALID_DATA;
  9363. }
  9364. bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety.
  9365. if (exr_header->tiled) {
  9366. size_t num_tiles = offsets.size(); // = # of blocks
  9367. exr_image->tiles = static_cast<EXRTile *>(
  9368. calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles)));
  9369. for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
  9370. // Allocate memory for each tile.
  9371. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
  9372. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9373. exr_header->tile_size_x, exr_header->tile_size_y);
  9374. // 16 byte: tile coordinates
  9375. // 4 byte : data size
  9376. // ~ : data(uncompressed or compressed)
  9377. if (offsets[tile_idx] + sizeof(int) * 5 > size) {
  9378. if (err) {
  9379. (*err) += "Insufficient data size.\n";
  9380. }
  9381. return TINYEXR_ERROR_INVALID_DATA;
  9382. }
  9383. size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));
  9384. const unsigned char *data_ptr =
  9385. reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]);
  9386. int tile_coordinates[4];
  9387. memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
  9388. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0]));
  9389. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1]));
  9390. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2]));
  9391. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3]));
  9392. // @todo{ LoD }
  9393. if (tile_coordinates[2] != 0) {
  9394. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9395. }
  9396. if (tile_coordinates[3] != 0) {
  9397. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9398. }
  9399. int data_len;
  9400. memcpy(&data_len, data_ptr + 16,
  9401. sizeof(int)); // 16 = sizeof(tile_coordinates)
  9402. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9403. if (data_len < 4 || size_t(data_len) > data_size) {
  9404. if (err) {
  9405. (*err) += "Insufficient data length.\n";
  9406. }
  9407. return TINYEXR_ERROR_INVALID_DATA;
  9408. }
  9409. // Move to data addr: 20 = 16 + 4;
  9410. data_ptr += 20;
  9411. tinyexr::DecodeTiledPixelData(
  9412. exr_image->tiles[tile_idx].images,
  9413. &(exr_image->tiles[tile_idx].width),
  9414. &(exr_image->tiles[tile_idx].height),
  9415. exr_header->requested_pixel_types, data_ptr,
  9416. static_cast<size_t>(data_len), exr_header->compression_type,
  9417. exr_header->line_order, data_width, data_height, tile_coordinates[0],
  9418. tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,
  9419. static_cast<size_t>(pixel_data_size),
  9420. static_cast<size_t>(exr_header->num_custom_attributes),
  9421. exr_header->custom_attributes,
  9422. static_cast<size_t>(exr_header->num_channels), exr_header->channels,
  9423. channel_offset_list);
  9424. exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
  9425. exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
  9426. exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
  9427. exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
  9428. exr_image->num_tiles = static_cast<int>(num_tiles);
  9429. }
  9430. } else { // scanline format
  9431. // Don't allow too large image(256GB * pixel_data_size or more). Workaround for #104.
  9432. size_t data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels);
  9433. if ((data_len == 0) || (data_len >= 0x4000000000)) {
  9434. if (err) {
  9435. std::stringstream ss;
  9436. ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl;
  9437. (*err) += ss.str();
  9438. }
  9439. return TINYEXR_ERROR_INVALID_DATA;
  9440. }
  9441. exr_image->images = tinyexr::AllocateImage(
  9442. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9443. data_width, data_height);
  9444. #ifdef _OPENMP
  9445. #pragma omp parallel for
  9446. #endif
  9447. for (int y = 0; y < static_cast<int>(num_blocks); y++) {
  9448. size_t y_idx = static_cast<size_t>(y);
  9449. if (offsets[y_idx] + sizeof(int) * 2 > size) {
  9450. invalid_data = true;
  9451. } else {
  9452. // 4 byte: scan line
  9453. // 4 byte: data size
  9454. // ~ : pixel data(uncompressed or compressed)
  9455. size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));
  9456. const unsigned char *data_ptr =
  9457. reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);
  9458. int line_no;
  9459. memcpy(&line_no, data_ptr, sizeof(int));
  9460. int data_len;
  9461. memcpy(&data_len, data_ptr + 4, sizeof(int));
  9462. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  9463. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9464. if (size_t(data_len) > data_size) {
  9465. invalid_data = true;
  9466. } else {
  9467. int end_line_no = (std::min)(line_no + num_scanline_blocks,
  9468. (exr_header->data_window[3] + 1));
  9469. int num_lines = end_line_no - line_no;
  9470. // assert(num_lines > 0);
  9471. if (num_lines <= 0) {
  9472. invalid_data = true;
  9473. } else {
  9474. // Move to data addr: 8 = 4 + 4;
  9475. data_ptr += 8;
  9476. // Adjust line_no with data_window.bmin.y
  9477. line_no -= exr_header->data_window[1];
  9478. if (line_no < 0) {
  9479. invalid_data = true;
  9480. } else {
  9481. if (!tinyexr::DecodePixelData(
  9482. exr_image->images, exr_header->requested_pixel_types,
  9483. data_ptr, static_cast<size_t>(data_len),
  9484. exr_header->compression_type, exr_header->line_order,
  9485. data_width, data_height, data_width, y, line_no,
  9486. num_lines, static_cast<size_t>(pixel_data_size),
  9487. static_cast<size_t>(exr_header->num_custom_attributes),
  9488. exr_header->custom_attributes,
  9489. static_cast<size_t>(exr_header->num_channels),
  9490. exr_header->channels, channel_offset_list)) {
  9491. invalid_data = true;
  9492. }
  9493. }
  9494. }
  9495. }
  9496. }
  9497. } // omp parallel
  9498. }
  9499. if (invalid_data) {
  9500. return TINYEXR_ERROR_INVALID_DATA;
  9501. }
  9502. // Overwrite `pixel_type` with `requested_pixel_type`.
  9503. {
  9504. for (int c = 0; c < exr_header->num_channels; c++) {
  9505. exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
  9506. }
  9507. }
  9508. {
  9509. exr_image->num_channels = num_channels;
  9510. exr_image->width = data_width;
  9511. exr_image->height = data_height;
  9512. }
  9513. return TINYEXR_SUCCESS;
  9514. }
  9515. static bool ReconstructLineOffsets(
  9516. std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,
  9517. const unsigned char *head, const unsigned char *marker, const size_t size) {
  9518. assert(head < marker);
  9519. assert(offsets->size() == n);
  9520. for (size_t i = 0; i < n; i++) {
  9521. size_t offset = static_cast<size_t>(marker - head);
  9522. // Offset should not exceed whole EXR file/data size.
  9523. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
  9524. return false;
  9525. }
  9526. int y;
  9527. unsigned int data_len;
  9528. memcpy(&y, marker, sizeof(int));
  9529. memcpy(&data_len, marker + 4, sizeof(unsigned int));
  9530. if (data_len >= size) {
  9531. return false;
  9532. }
  9533. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  9534. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9535. (*offsets)[i] = offset;
  9536. marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
  9537. }
  9538. return true;
  9539. }
  9540. static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,
  9541. const unsigned char *head,
  9542. const unsigned char *marker, const size_t size,
  9543. const char **err) {
  9544. if (exr_image == NULL || exr_header == NULL || head == NULL ||
  9545. marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
  9546. tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
  9547. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9548. }
  9549. int num_scanline_blocks = 1;
  9550. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9551. num_scanline_blocks = 16;
  9552. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9553. num_scanline_blocks = 32;
  9554. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9555. num_scanline_blocks = 16;
  9556. }
  9557. int data_width = exr_header->data_window[2] - exr_header->data_window[0];
  9558. if (data_width >= std::numeric_limits<int>::max()) {
  9559. // Issue 63
  9560. tinyexr::SetErrorMessage("Invalid data window value", err);
  9561. return TINYEXR_ERROR_INVALID_DATA;
  9562. }
  9563. data_width++;
  9564. int data_height = exr_header->data_window[3] - exr_header->data_window[1];
  9565. if (data_height >= std::numeric_limits<int>::max()) {
  9566. tinyexr::SetErrorMessage("Invalid data height value", err);
  9567. return TINYEXR_ERROR_INVALID_DATA;
  9568. }
  9569. data_height++;
  9570. if ((data_width < 0) || (data_height < 0)) {
  9571. tinyexr::SetErrorMessage("data window or data height is negative.", err);
  9572. return TINYEXR_ERROR_INVALID_DATA;
  9573. }
  9574. // Read offset tables.
  9575. size_t num_blocks = 0;
  9576. if (exr_header->chunk_count > 0) {
  9577. // Use `chunkCount` attribute.
  9578. num_blocks = static_cast<size_t>(exr_header->chunk_count);
  9579. } else if (exr_header->tiled) {
  9580. // @todo { LoD }
  9581. size_t num_x_tiles = static_cast<size_t>(data_width) /
  9582. static_cast<size_t>(exr_header->tile_size_x);
  9583. if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) <
  9584. static_cast<size_t>(data_width)) {
  9585. num_x_tiles++;
  9586. }
  9587. size_t num_y_tiles = static_cast<size_t>(data_height) /
  9588. static_cast<size_t>(exr_header->tile_size_y);
  9589. if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) <
  9590. static_cast<size_t>(data_height)) {
  9591. num_y_tiles++;
  9592. }
  9593. num_blocks = num_x_tiles * num_y_tiles;
  9594. } else {
  9595. num_blocks = static_cast<size_t>(data_height) /
  9596. static_cast<size_t>(num_scanline_blocks);
  9597. if (num_blocks * static_cast<size_t>(num_scanline_blocks) <
  9598. static_cast<size_t>(data_height)) {
  9599. num_blocks++;
  9600. }
  9601. }
  9602. std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks);
  9603. for (size_t y = 0; y < num_blocks; y++) {
  9604. tinyexr::tinyexr_uint64 offset;
  9605. // Issue #81
  9606. if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
  9607. tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
  9608. return TINYEXR_ERROR_INVALID_DATA;
  9609. }
  9610. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  9611. tinyexr::swap8(&offset);
  9612. if (offset >= size) {
  9613. tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
  9614. return TINYEXR_ERROR_INVALID_DATA;
  9615. }
  9616. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  9617. offsets[y] = offset;
  9618. }
  9619. // If line offsets are invalid, we try to reconstruct it.
  9620. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
  9621. for (size_t y = 0; y < num_blocks; y++) {
  9622. if (offsets[y] <= 0) {
  9623. // TODO(syoyo) Report as warning?
  9624. // if (err) {
  9625. // stringstream ss;
  9626. // ss << "Incomplete lineOffsets." << std::endl;
  9627. // (*err) += ss.str();
  9628. //}
  9629. bool ret =
  9630. ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
  9631. if (ret) {
  9632. // OK
  9633. break;
  9634. } else {
  9635. tinyexr::SetErrorMessage(
  9636. "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
  9637. return TINYEXR_ERROR_INVALID_DATA;
  9638. }
  9639. }
  9640. }
  9641. {
  9642. std::string e;
  9643. int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e);
  9644. if (ret != TINYEXR_SUCCESS) {
  9645. if (!e.empty()) {
  9646. tinyexr::SetErrorMessage(e, err);
  9647. }
  9648. // release memory(if exists)
  9649. if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
  9650. for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
  9651. if (exr_image->images[c]) {
  9652. free(exr_image->images[c]);
  9653. exr_image->images[c] = NULL;
  9654. }
  9655. }
  9656. free(exr_image->images);
  9657. exr_image->images = NULL;
  9658. }
  9659. }
  9660. return ret;
  9661. }
  9662. }
  9663. } // namespace tinyexr
  9664. int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
  9665. const char **err) {
  9666. if (out_rgba == NULL) {
  9667. tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
  9668. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9669. }
  9670. EXRVersion exr_version;
  9671. EXRImage exr_image;
  9672. EXRHeader exr_header;
  9673. InitEXRHeader(&exr_header);
  9674. InitEXRImage(&exr_image);
  9675. {
  9676. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  9677. if (ret != TINYEXR_SUCCESS) {
  9678. tinyexr::SetErrorMessage("Invalid EXR header.", err);
  9679. return ret;
  9680. }
  9681. if (exr_version.multipart || exr_version.non_image) {
  9682. tinyexr::SetErrorMessage(
  9683. "Loading multipart or DeepImage is not supported in LoadEXR() API",
  9684. err);
  9685. return TINYEXR_ERROR_INVALID_DATA; // @fixme.
  9686. }
  9687. }
  9688. {
  9689. int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
  9690. if (ret != TINYEXR_SUCCESS) {
  9691. FreeEXRHeader(&exr_header);
  9692. return ret;
  9693. }
  9694. }
  9695. // Read HALF channel as FLOAT.
  9696. for (int i = 0; i < exr_header.num_channels; i++) {
  9697. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  9698. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  9699. }
  9700. }
  9701. {
  9702. int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
  9703. if (ret != TINYEXR_SUCCESS) {
  9704. FreeEXRHeader(&exr_header);
  9705. return ret;
  9706. }
  9707. }
  9708. // RGBA
  9709. int idxR = -1;
  9710. int idxG = -1;
  9711. int idxB = -1;
  9712. int idxA = -1;
  9713. for (int c = 0; c < exr_header.num_channels; c++) {
  9714. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  9715. idxR = c;
  9716. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  9717. idxG = c;
  9718. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  9719. idxB = c;
  9720. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  9721. idxA = c;
  9722. }
  9723. }
  9724. if (exr_header.num_channels == 1) {
  9725. // Grayscale channel only.
  9726. (*out_rgba) = reinterpret_cast<float *>(
  9727. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9728. static_cast<size_t>(exr_image.height)));
  9729. if (exr_header.tiled) {
  9730. for (int it = 0; it < exr_image.num_tiles; it++) {
  9731. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9732. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9733. const int ii =
  9734. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9735. const int jj =
  9736. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9737. const int idx = ii + jj * exr_image.width;
  9738. // out of region check.
  9739. if (ii >= exr_image.width) {
  9740. continue;
  9741. }
  9742. if (jj >= exr_image.height) {
  9743. continue;
  9744. }
  9745. const int srcIdx = i + j * exr_header.tile_size_x;
  9746. unsigned char **src = exr_image.tiles[it].images;
  9747. (*out_rgba)[4 * idx + 0] =
  9748. reinterpret_cast<float **>(src)[0][srcIdx];
  9749. (*out_rgba)[4 * idx + 1] =
  9750. reinterpret_cast<float **>(src)[0][srcIdx];
  9751. (*out_rgba)[4 * idx + 2] =
  9752. reinterpret_cast<float **>(src)[0][srcIdx];
  9753. (*out_rgba)[4 * idx + 3] =
  9754. reinterpret_cast<float **>(src)[0][srcIdx];
  9755. }
  9756. }
  9757. }
  9758. } else {
  9759. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9760. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  9761. (*out_rgba)[4 * i + 0] = val;
  9762. (*out_rgba)[4 * i + 1] = val;
  9763. (*out_rgba)[4 * i + 2] = val;
  9764. (*out_rgba)[4 * i + 3] = val;
  9765. }
  9766. }
  9767. } else {
  9768. // Assume RGB(A)
  9769. if (idxR == -1) {
  9770. tinyexr::SetErrorMessage("R channel not found", err);
  9771. // @todo { free exr_image }
  9772. FreeEXRHeader(&exr_header);
  9773. return TINYEXR_ERROR_INVALID_DATA;
  9774. }
  9775. if (idxG == -1) {
  9776. tinyexr::SetErrorMessage("G channel not found", err);
  9777. // @todo { free exr_image }
  9778. FreeEXRHeader(&exr_header);
  9779. return TINYEXR_ERROR_INVALID_DATA;
  9780. }
  9781. if (idxB == -1) {
  9782. tinyexr::SetErrorMessage("B channel not found", err);
  9783. // @todo { free exr_image }
  9784. FreeEXRHeader(&exr_header);
  9785. return TINYEXR_ERROR_INVALID_DATA;
  9786. }
  9787. (*out_rgba) = reinterpret_cast<float *>(
  9788. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9789. static_cast<size_t>(exr_image.height)));
  9790. if (exr_header.tiled) {
  9791. for (int it = 0; it < exr_image.num_tiles; it++) {
  9792. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9793. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9794. const int ii =
  9795. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9796. const int jj =
  9797. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9798. const int idx = ii + jj * exr_image.width;
  9799. // out of region check.
  9800. if (ii >= exr_image.width) {
  9801. continue;
  9802. }
  9803. if (jj >= exr_image.height) {
  9804. continue;
  9805. }
  9806. const int srcIdx = i + j * exr_header.tile_size_x;
  9807. unsigned char **src = exr_image.tiles[it].images;
  9808. (*out_rgba)[4 * idx + 0] =
  9809. reinterpret_cast<float **>(src)[idxR][srcIdx];
  9810. (*out_rgba)[4 * idx + 1] =
  9811. reinterpret_cast<float **>(src)[idxG][srcIdx];
  9812. (*out_rgba)[4 * idx + 2] =
  9813. reinterpret_cast<float **>(src)[idxB][srcIdx];
  9814. if (idxA != -1) {
  9815. (*out_rgba)[4 * idx + 3] =
  9816. reinterpret_cast<float **>(src)[idxA][srcIdx];
  9817. } else {
  9818. (*out_rgba)[4 * idx + 3] = 1.0;
  9819. }
  9820. }
  9821. }
  9822. }
  9823. } else {
  9824. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9825. (*out_rgba)[4 * i + 0] =
  9826. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  9827. (*out_rgba)[4 * i + 1] =
  9828. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  9829. (*out_rgba)[4 * i + 2] =
  9830. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  9831. if (idxA != -1) {
  9832. (*out_rgba)[4 * i + 3] =
  9833. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  9834. } else {
  9835. (*out_rgba)[4 * i + 3] = 1.0;
  9836. }
  9837. }
  9838. }
  9839. }
  9840. (*width) = exr_image.width;
  9841. (*height) = exr_image.height;
  9842. FreeEXRHeader(&exr_header);
  9843. FreeEXRImage(&exr_image);
  9844. return TINYEXR_SUCCESS;
  9845. }
  9846. int IsEXR(const char *filename) {
  9847. EXRVersion exr_version;
  9848. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  9849. if (ret != TINYEXR_SUCCESS) {
  9850. return TINYEXR_ERROR_INVALID_HEADER;
  9851. }
  9852. return TINYEXR_SUCCESS;
  9853. }
  9854. int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,
  9855. const unsigned char *memory, size_t size,
  9856. const char **err) {
  9857. if (memory == NULL || exr_header == NULL) {
  9858. tinyexr::SetErrorMessage(
  9859. "Invalid argument. `memory` or `exr_header` argument is null in "
  9860. "ParseEXRHeaderFromMemory()",
  9861. err);
  9862. // Invalid argument
  9863. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9864. }
  9865. if (size < tinyexr::kEXRVersionSize) {
  9866. tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
  9867. return TINYEXR_ERROR_INVALID_DATA;
  9868. }
  9869. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  9870. size_t marker_size = size - tinyexr::kEXRVersionSize;
  9871. tinyexr::HeaderInfo info;
  9872. info.clear();
  9873. std::string err_str;
  9874. int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
  9875. if (ret != TINYEXR_SUCCESS) {
  9876. if (err && !err_str.empty()) {
  9877. tinyexr::SetErrorMessage(err_str, err);
  9878. }
  9879. }
  9880. ConvertHeader(exr_header, info);
  9881. // transfoer `tiled` from version.
  9882. exr_header->tiled = version->tiled;
  9883. return ret;
  9884. }
  9885. int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  9886. const unsigned char *memory, size_t size,
  9887. const char **err) {
  9888. if (out_rgba == NULL || memory == NULL) {
  9889. tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
  9890. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9891. }
  9892. EXRVersion exr_version;
  9893. EXRImage exr_image;
  9894. EXRHeader exr_header;
  9895. InitEXRHeader(&exr_header);
  9896. int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
  9897. if (ret != TINYEXR_SUCCESS) {
  9898. tinyexr::SetErrorMessage("Failed to parse EXR version", err);
  9899. return ret;
  9900. }
  9901. ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
  9902. if (ret != TINYEXR_SUCCESS) {
  9903. return ret;
  9904. }
  9905. // Read HALF channel as FLOAT.
  9906. for (int i = 0; i < exr_header.num_channels; i++) {
  9907. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  9908. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  9909. }
  9910. }
  9911. InitEXRImage(&exr_image);
  9912. ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
  9913. if (ret != TINYEXR_SUCCESS) {
  9914. return ret;
  9915. }
  9916. // RGBA
  9917. int idxR = -1;
  9918. int idxG = -1;
  9919. int idxB = -1;
  9920. int idxA = -1;
  9921. for (int c = 0; c < exr_header.num_channels; c++) {
  9922. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  9923. idxR = c;
  9924. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  9925. idxG = c;
  9926. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  9927. idxB = c;
  9928. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  9929. idxA = c;
  9930. }
  9931. }
  9932. // TODO(syoyo): Refactor removing same code as used in LoadEXR().
  9933. if (exr_header.num_channels == 1) {
  9934. // Grayscale channel only.
  9935. (*out_rgba) = reinterpret_cast<float *>(
  9936. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9937. static_cast<size_t>(exr_image.height)));
  9938. if (exr_header.tiled) {
  9939. for (int it = 0; it < exr_image.num_tiles; it++) {
  9940. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9941. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9942. const int ii =
  9943. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9944. const int jj =
  9945. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9946. const int idx = ii + jj * exr_image.width;
  9947. // out of region check.
  9948. if (ii >= exr_image.width) {
  9949. continue;
  9950. }
  9951. if (jj >= exr_image.height) {
  9952. continue;
  9953. }
  9954. const int srcIdx = i + j * exr_header.tile_size_x;
  9955. unsigned char **src = exr_image.tiles[it].images;
  9956. (*out_rgba)[4 * idx + 0] =
  9957. reinterpret_cast<float **>(src)[0][srcIdx];
  9958. (*out_rgba)[4 * idx + 1] =
  9959. reinterpret_cast<float **>(src)[0][srcIdx];
  9960. (*out_rgba)[4 * idx + 2] =
  9961. reinterpret_cast<float **>(src)[0][srcIdx];
  9962. (*out_rgba)[4 * idx + 3] =
  9963. reinterpret_cast<float **>(src)[0][srcIdx];
  9964. }
  9965. }
  9966. }
  9967. } else {
  9968. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9969. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  9970. (*out_rgba)[4 * i + 0] = val;
  9971. (*out_rgba)[4 * i + 1] = val;
  9972. (*out_rgba)[4 * i + 2] = val;
  9973. (*out_rgba)[4 * i + 3] = val;
  9974. }
  9975. }
  9976. } else {
  9977. // TODO(syoyo): Support non RGBA image.
  9978. if (idxR == -1) {
  9979. tinyexr::SetErrorMessage("R channel not found", err);
  9980. // @todo { free exr_image }
  9981. return TINYEXR_ERROR_INVALID_DATA;
  9982. }
  9983. if (idxG == -1) {
  9984. tinyexr::SetErrorMessage("G channel not found", err);
  9985. // @todo { free exr_image }
  9986. return TINYEXR_ERROR_INVALID_DATA;
  9987. }
  9988. if (idxB == -1) {
  9989. tinyexr::SetErrorMessage("B channel not found", err);
  9990. // @todo { free exr_image }
  9991. return TINYEXR_ERROR_INVALID_DATA;
  9992. }
  9993. (*out_rgba) = reinterpret_cast<float *>(
  9994. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9995. static_cast<size_t>(exr_image.height)));
  9996. if (exr_header.tiled) {
  9997. for (int it = 0; it < exr_image.num_tiles; it++) {
  9998. for (int j = 0; j < exr_header.tile_size_y; j++)
  9999. for (int i = 0; i < exr_header.tile_size_x; i++) {
  10000. const int ii =
  10001. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  10002. const int jj =
  10003. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  10004. const int idx = ii + jj * exr_image.width;
  10005. // out of region check.
  10006. if (ii >= exr_image.width) {
  10007. continue;
  10008. }
  10009. if (jj >= exr_image.height) {
  10010. continue;
  10011. }
  10012. const int srcIdx = i + j * exr_header.tile_size_x;
  10013. unsigned char **src = exr_image.tiles[it].images;
  10014. (*out_rgba)[4 * idx + 0] =
  10015. reinterpret_cast<float **>(src)[idxR][srcIdx];
  10016. (*out_rgba)[4 * idx + 1] =
  10017. reinterpret_cast<float **>(src)[idxG][srcIdx];
  10018. (*out_rgba)[4 * idx + 2] =
  10019. reinterpret_cast<float **>(src)[idxB][srcIdx];
  10020. if (idxA != -1) {
  10021. (*out_rgba)[4 * idx + 3] =
  10022. reinterpret_cast<float **>(src)[idxA][srcIdx];
  10023. } else {
  10024. (*out_rgba)[4 * idx + 3] = 1.0;
  10025. }
  10026. }
  10027. }
  10028. } else {
  10029. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  10030. (*out_rgba)[4 * i + 0] =
  10031. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  10032. (*out_rgba)[4 * i + 1] =
  10033. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  10034. (*out_rgba)[4 * i + 2] =
  10035. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  10036. if (idxA != -1) {
  10037. (*out_rgba)[4 * i + 3] =
  10038. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  10039. } else {
  10040. (*out_rgba)[4 * i + 3] = 1.0;
  10041. }
  10042. }
  10043. }
  10044. }
  10045. (*width) = exr_image.width;
  10046. (*height) = exr_image.height;
  10047. FreeEXRHeader(&exr_header);
  10048. FreeEXRImage(&exr_image);
  10049. return TINYEXR_SUCCESS;
  10050. }
  10051. int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,
  10052. const char *filename, const char **err) {
  10053. if (exr_image == NULL) {
  10054. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
  10055. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10056. }
  10057. #ifdef _WIN32
  10058. FILE *fp = NULL;
  10059. fopen_s(&fp, filename, "rb");
  10060. #else
  10061. FILE *fp = fopen(filename, "rb");
  10062. #endif
  10063. if (!fp) {
  10064. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  10065. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10066. }
  10067. size_t filesize;
  10068. // Compute size
  10069. fseek(fp, 0, SEEK_END);
  10070. filesize = static_cast<size_t>(ftell(fp));
  10071. fseek(fp, 0, SEEK_SET);
  10072. if (filesize < 16) {
  10073. tinyexr::SetErrorMessage("File size too short " + std::string(filename),
  10074. err);
  10075. return TINYEXR_ERROR_INVALID_FILE;
  10076. }
  10077. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  10078. {
  10079. size_t ret;
  10080. ret = fread(&buf[0], 1, filesize, fp);
  10081. assert(ret == filesize);
  10082. fclose(fp);
  10083. (void)ret;
  10084. }
  10085. return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize,
  10086. err);
  10087. }
  10088. int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,
  10089. const unsigned char *memory, const size_t size,
  10090. const char **err) {
  10091. if (exr_image == NULL || memory == NULL ||
  10092. (size < tinyexr::kEXRVersionSize)) {
  10093. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
  10094. err);
  10095. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10096. }
  10097. if (exr_header->header_len == 0) {
  10098. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  10099. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10100. }
  10101. const unsigned char *head = memory;
  10102. const unsigned char *marker = reinterpret_cast<const unsigned char *>(
  10103. memory + exr_header->header_len +
  10104. 8); // +8 for magic number + version header.
  10105. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
  10106. err);
  10107. }
  10108. size_t SaveEXRImageToMemory(const EXRImage *exr_image,
  10109. const EXRHeader *exr_header,
  10110. unsigned char **memory_out, const char **err) {
  10111. if (exr_image == NULL || memory_out == NULL ||
  10112. exr_header->compression_type < 0) {
  10113. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err);
  10114. return 0;
  10115. }
  10116. #if !TINYEXR_USE_PIZ
  10117. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10118. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10119. err);
  10120. return 0;
  10121. }
  10122. #endif
  10123. #if !TINYEXR_USE_ZFP
  10124. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10125. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10126. err);
  10127. return 0;
  10128. }
  10129. #endif
  10130. #if TINYEXR_USE_ZFP
  10131. for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) {
  10132. if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) {
  10133. tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
  10134. err);
  10135. return 0;
  10136. }
  10137. }
  10138. #endif
  10139. std::vector<unsigned char> memory;
  10140. // Header
  10141. {
  10142. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10143. memory.insert(memory.end(), header, header + 4);
  10144. }
  10145. // Version, scanline.
  10146. {
  10147. char marker[] = {2, 0, 0, 0};
  10148. /* @todo
  10149. if (exr_header->tiled) {
  10150. marker[1] |= 0x2;
  10151. }
  10152. if (exr_header->long_name) {
  10153. marker[1] |= 0x4;
  10154. }
  10155. if (exr_header->non_image) {
  10156. marker[1] |= 0x8;
  10157. }
  10158. if (exr_header->multipart) {
  10159. marker[1] |= 0x10;
  10160. }
  10161. */
  10162. memory.insert(memory.end(), marker, marker + 4);
  10163. }
  10164. int num_scanlines = 1;
  10165. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10166. num_scanlines = 16;
  10167. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10168. num_scanlines = 32;
  10169. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10170. num_scanlines = 16;
  10171. }
  10172. // Write attributes.
  10173. std::vector<tinyexr::ChannelInfo> channels;
  10174. {
  10175. std::vector<unsigned char> data;
  10176. for (int c = 0; c < exr_header->num_channels; c++) {
  10177. tinyexr::ChannelInfo info;
  10178. info.p_linear = 0;
  10179. info.pixel_type = exr_header->requested_pixel_types[c];
  10180. info.x_sampling = 1;
  10181. info.y_sampling = 1;
  10182. info.name = std::string(exr_header->channels[c].name);
  10183. channels.push_back(info);
  10184. }
  10185. tinyexr::WriteChannelInfo(data, channels);
  10186. tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
  10187. static_cast<int>(data.size()));
  10188. }
  10189. {
  10190. int comp = exr_header->compression_type;
  10191. tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp));
  10192. tinyexr::WriteAttributeToMemory(
  10193. &memory, "compression", "compression",
  10194. reinterpret_cast<const unsigned char *>(&comp), 1);
  10195. }
  10196. {
  10197. int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1};
  10198. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0]));
  10199. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1]));
  10200. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2]));
  10201. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3]));
  10202. tinyexr::WriteAttributeToMemory(
  10203. &memory, "dataWindow", "box2i",
  10204. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10205. tinyexr::WriteAttributeToMemory(
  10206. &memory, "displayWindow", "box2i",
  10207. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10208. }
  10209. {
  10210. unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
  10211. tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
  10212. &line_order, 1);
  10213. }
  10214. {
  10215. float aspectRatio = 1.0f;
  10216. tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
  10217. tinyexr::WriteAttributeToMemory(
  10218. &memory, "pixelAspectRatio", "float",
  10219. reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
  10220. }
  10221. {
  10222. float center[2] = {0.0f, 0.0f};
  10223. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0]));
  10224. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1]));
  10225. tinyexr::WriteAttributeToMemory(
  10226. &memory, "screenWindowCenter", "v2f",
  10227. reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float));
  10228. }
  10229. {
  10230. float w = static_cast<float>(exr_image->width);
  10231. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10232. tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
  10233. reinterpret_cast<const unsigned char *>(&w),
  10234. sizeof(float));
  10235. }
  10236. // Custom attributes
  10237. if (exr_header->num_custom_attributes > 0) {
  10238. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  10239. tinyexr::WriteAttributeToMemory(
  10240. &memory, exr_header->custom_attributes[i].name,
  10241. exr_header->custom_attributes[i].type,
  10242. reinterpret_cast<const unsigned char *>(
  10243. exr_header->custom_attributes[i].value),
  10244. exr_header->custom_attributes[i].size);
  10245. }
  10246. }
  10247. { // end of header
  10248. unsigned char e = 0;
  10249. memory.push_back(e);
  10250. }
  10251. int num_blocks = exr_image->height / num_scanlines;
  10252. if (num_blocks * num_scanlines < exr_image->height) {
  10253. num_blocks++;
  10254. }
  10255. std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks));
  10256. size_t headerSize = memory.size();
  10257. tinyexr::tinyexr_uint64 offset =
  10258. headerSize +
  10259. static_cast<size_t>(num_blocks) *
  10260. sizeof(
  10261. tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable)
  10262. std::vector<std::vector<unsigned char> > data_list(
  10263. static_cast<size_t>(num_blocks));
  10264. std::vector<size_t> channel_offset_list(
  10265. static_cast<size_t>(exr_header->num_channels));
  10266. int pixel_data_size = 0;
  10267. size_t channel_offset = 0;
  10268. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10269. channel_offset_list[c] = channel_offset;
  10270. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10271. pixel_data_size += sizeof(unsigned short);
  10272. channel_offset += sizeof(unsigned short);
  10273. } else if (exr_header->requested_pixel_types[c] ==
  10274. TINYEXR_PIXELTYPE_FLOAT) {
  10275. pixel_data_size += sizeof(float);
  10276. channel_offset += sizeof(float);
  10277. } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10278. pixel_data_size += sizeof(unsigned int);
  10279. channel_offset += sizeof(unsigned int);
  10280. } else {
  10281. assert(0);
  10282. }
  10283. }
  10284. #if TINYEXR_USE_ZFP
  10285. tinyexr::ZFPCompressionParam zfp_compression_param;
  10286. // Use ZFP compression parameter from custom attributes(if such a parameter
  10287. // exists)
  10288. {
  10289. bool ret = tinyexr::FindZFPCompressionParam(
  10290. &zfp_compression_param, exr_header->custom_attributes,
  10291. exr_header->num_custom_attributes);
  10292. if (!ret) {
  10293. // Use predefined compression parameter.
  10294. zfp_compression_param.type = 0;
  10295. zfp_compression_param.rate = 2;
  10296. }
  10297. }
  10298. #endif
  10299. // Use signed int since some OpenMP compiler doesn't allow unsigned type for
  10300. // `parallel for`
  10301. #ifdef _OPENMP
  10302. #pragma omp parallel for
  10303. #endif
  10304. for (int i = 0; i < num_blocks; i++) {
  10305. size_t ii = static_cast<size_t>(i);
  10306. int start_y = num_scanlines * i;
  10307. int endY = (std::min)(num_scanlines * (i + 1), exr_image->height);
  10308. int h = endY - start_y;
  10309. std::vector<unsigned char> buf(
  10310. static_cast<size_t>(exr_image->width * h * pixel_data_size));
  10311. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10312. if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10313. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10314. for (int y = 0; y < h; y++) {
  10315. // Assume increasing Y
  10316. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10317. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10318. channel_offset_list[c] *
  10319. static_cast<size_t>(exr_image->width)));
  10320. for (int x = 0; x < exr_image->width; x++) {
  10321. tinyexr::FP16 h16;
  10322. h16.u = reinterpret_cast<unsigned short **>(
  10323. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10324. tinyexr::FP32 f32 = half_to_float(h16);
  10325. tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f));
  10326. // line_ptr[x] = f32.f;
  10327. tinyexr::cpy4(line_ptr + x, &(f32.f));
  10328. }
  10329. }
  10330. } else if (exr_header->requested_pixel_types[c] ==
  10331. TINYEXR_PIXELTYPE_HALF) {
  10332. for (int y = 0; y < h; y++) {
  10333. // Assume increasing Y
  10334. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10335. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10336. exr_image->width) +
  10337. channel_offset_list[c] *
  10338. static_cast<size_t>(exr_image->width)));
  10339. for (int x = 0; x < exr_image->width; x++) {
  10340. unsigned short val = reinterpret_cast<unsigned short **>(
  10341. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10342. tinyexr::swap2(&val);
  10343. // line_ptr[x] = val;
  10344. tinyexr::cpy2(line_ptr + x, &val);
  10345. }
  10346. }
  10347. } else {
  10348. assert(0);
  10349. }
  10350. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10351. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10352. for (int y = 0; y < h; y++) {
  10353. // Assume increasing Y
  10354. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10355. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10356. exr_image->width) +
  10357. channel_offset_list[c] *
  10358. static_cast<size_t>(exr_image->width)));
  10359. for (int x = 0; x < exr_image->width; x++) {
  10360. tinyexr::FP32 f32;
  10361. f32.f = reinterpret_cast<float **>(
  10362. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10363. tinyexr::FP16 h16;
  10364. h16 = float_to_half_full(f32);
  10365. tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));
  10366. // line_ptr[x] = h16.u;
  10367. tinyexr::cpy2(line_ptr + x, &(h16.u));
  10368. }
  10369. }
  10370. } else if (exr_header->requested_pixel_types[c] ==
  10371. TINYEXR_PIXELTYPE_FLOAT) {
  10372. for (int y = 0; y < h; y++) {
  10373. // Assume increasing Y
  10374. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10375. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10376. channel_offset_list[c] *
  10377. static_cast<size_t>(exr_image->width)));
  10378. for (int x = 0; x < exr_image->width; x++) {
  10379. float val = reinterpret_cast<float **>(
  10380. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10381. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  10382. // line_ptr[x] = val;
  10383. tinyexr::cpy4(line_ptr + x, &val);
  10384. }
  10385. }
  10386. } else {
  10387. assert(0);
  10388. }
  10389. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10390. for (int y = 0; y < h; y++) {
  10391. // Assume increasing Y
  10392. unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(
  10393. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10394. channel_offset_list[c] * static_cast<size_t>(exr_image->width)));
  10395. for (int x = 0; x < exr_image->width; x++) {
  10396. unsigned int val = reinterpret_cast<unsigned int **>(
  10397. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10398. tinyexr::swap4(&val);
  10399. // line_ptr[x] = val;
  10400. tinyexr::cpy4(line_ptr + x, &val);
  10401. }
  10402. }
  10403. }
  10404. }
  10405. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  10406. // 4 byte: scan line
  10407. // 4 byte: data size
  10408. // ~ : pixel data(uncompressed)
  10409. std::vector<unsigned char> header(8);
  10410. unsigned int data_len = static_cast<unsigned int>(buf.size());
  10411. memcpy(&header.at(0), &start_y, sizeof(int));
  10412. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10413. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10414. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10415. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10416. data_list[ii].insert(data_list[ii].end(), buf.begin(),
  10417. buf.begin() + data_len);
  10418. } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10419. (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10420. #if TINYEXR_USE_MINIZ
  10421. std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound(
  10422. static_cast<unsigned long>(buf.size())));
  10423. #else
  10424. std::vector<unsigned char> block(
  10425. compressBound(static_cast<uLong>(buf.size())));
  10426. #endif
  10427. tinyexr::tinyexr_uint64 outSize = block.size();
  10428. tinyexr::CompressZip(&block.at(0), outSize,
  10429. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10430. static_cast<unsigned long>(buf.size()));
  10431. // 4 byte: scan line
  10432. // 4 byte: data size
  10433. // ~ : pixel data(compressed)
  10434. std::vector<unsigned char> header(8);
  10435. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10436. memcpy(&header.at(0), &start_y, sizeof(int));
  10437. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10438. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10439. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10440. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10441. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10442. block.begin() + data_len);
  10443. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  10444. // (buf.size() * 3) / 2 would be enough.
  10445. std::vector<unsigned char> block((buf.size() * 3) / 2);
  10446. tinyexr::tinyexr_uint64 outSize = block.size();
  10447. tinyexr::CompressRle(&block.at(0), outSize,
  10448. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10449. static_cast<unsigned long>(buf.size()));
  10450. // 4 byte: scan line
  10451. // 4 byte: data size
  10452. // ~ : pixel data(compressed)
  10453. std::vector<unsigned char> header(8);
  10454. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10455. memcpy(&header.at(0), &start_y, sizeof(int));
  10456. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10457. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10458. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10459. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10460. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10461. block.begin() + data_len);
  10462. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10463. #if TINYEXR_USE_PIZ
  10464. unsigned int bufLen =
  10465. 8192 + static_cast<unsigned int>(
  10466. 2 * static_cast<unsigned int>(
  10467. buf.size())); // @fixme { compute good bound. }
  10468. std::vector<unsigned char> block(bufLen);
  10469. unsigned int outSize = static_cast<unsigned int>(block.size());
  10470. CompressPiz(&block.at(0), &outSize,
  10471. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10472. buf.size(), channels, exr_image->width, h);
  10473. // 4 byte: scan line
  10474. // 4 byte: data size
  10475. // ~ : pixel data(compressed)
  10476. std::vector<unsigned char> header(8);
  10477. unsigned int data_len = outSize;
  10478. memcpy(&header.at(0), &start_y, sizeof(int));
  10479. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10480. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10481. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10482. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10483. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10484. block.begin() + data_len);
  10485. #else
  10486. assert(0);
  10487. #endif
  10488. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10489. #if TINYEXR_USE_ZFP
  10490. std::vector<unsigned char> block;
  10491. unsigned int outSize;
  10492. tinyexr::CompressZfp(
  10493. &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),
  10494. exr_image->width, h, exr_header->num_channels, zfp_compression_param);
  10495. // 4 byte: scan line
  10496. // 4 byte: data size
  10497. // ~ : pixel data(compressed)
  10498. std::vector<unsigned char> header(8);
  10499. unsigned int data_len = outSize;
  10500. memcpy(&header.at(0), &start_y, sizeof(int));
  10501. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10502. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10503. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10504. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10505. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10506. block.begin() + data_len);
  10507. #else
  10508. assert(0);
  10509. #endif
  10510. } else {
  10511. assert(0);
  10512. }
  10513. } // omp parallel
  10514. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10515. offsets[i] = offset;
  10516. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));
  10517. offset += data_list[i].size();
  10518. }
  10519. size_t totalSize = static_cast<size_t>(offset);
  10520. {
  10521. memory.insert(
  10522. memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)),
  10523. reinterpret_cast<unsigned char *>(&offsets.at(0)) +
  10524. sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks));
  10525. }
  10526. if ( memory.size() == 0 ) {
  10527. tinyexr::SetErrorMessage("Output memory size is zero", err);
  10528. return 0;
  10529. }
  10530. (*memory_out) = static_cast<unsigned char *>(malloc(totalSize));
  10531. memcpy((*memory_out), &memory.at(0), memory.size());
  10532. unsigned char *memory_ptr = *memory_out + memory.size();
  10533. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10534. memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size());
  10535. memory_ptr += data_list[i].size();
  10536. }
  10537. return totalSize; // OK
  10538. }
  10539. int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,
  10540. const char *filename, const char **err) {
  10541. if (exr_image == NULL || filename == NULL ||
  10542. exr_header->compression_type < 0) {
  10543. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
  10544. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10545. }
  10546. #if !TINYEXR_USE_PIZ
  10547. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10548. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10549. err);
  10550. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10551. }
  10552. #endif
  10553. #if !TINYEXR_USE_ZFP
  10554. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10555. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10556. err);
  10557. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10558. }
  10559. #endif
  10560. #ifdef _WIN32
  10561. FILE *fp = NULL;
  10562. fopen_s(&fp, filename, "wb");
  10563. #else
  10564. FILE *fp = fopen(filename, "wb");
  10565. #endif
  10566. if (!fp) {
  10567. tinyexr::SetErrorMessage("Cannot write a file", err);
  10568. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10569. }
  10570. unsigned char *mem = NULL;
  10571. size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
  10572. if (mem_size == 0) {
  10573. return TINYEXR_ERROR_SERIALZATION_FAILED;
  10574. }
  10575. size_t written_size = 0;
  10576. if ((mem_size > 0) && mem) {
  10577. written_size = fwrite(mem, 1, mem_size, fp);
  10578. }
  10579. free(mem);
  10580. fclose(fp);
  10581. if (written_size != mem_size) {
  10582. tinyexr::SetErrorMessage("Cannot write a file", err);
  10583. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10584. }
  10585. return TINYEXR_SUCCESS;
  10586. }
  10587. int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {
  10588. if (deep_image == NULL) {
  10589. tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
  10590. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10591. }
  10592. #ifdef _MSC_VER
  10593. FILE *fp = NULL;
  10594. errno_t errcode = fopen_s(&fp, filename, "rb");
  10595. if ((0 != errcode) || (!fp)) {
  10596. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10597. err);
  10598. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10599. }
  10600. #else
  10601. FILE *fp = fopen(filename, "rb");
  10602. if (!fp) {
  10603. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10604. err);
  10605. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10606. }
  10607. #endif
  10608. size_t filesize;
  10609. // Compute size
  10610. fseek(fp, 0, SEEK_END);
  10611. filesize = static_cast<size_t>(ftell(fp));
  10612. fseek(fp, 0, SEEK_SET);
  10613. if (filesize == 0) {
  10614. fclose(fp);
  10615. tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
  10616. err);
  10617. return TINYEXR_ERROR_INVALID_FILE;
  10618. }
  10619. std::vector<char> buf(filesize); // @todo { use mmap }
  10620. {
  10621. size_t ret;
  10622. ret = fread(&buf[0], 1, filesize, fp);
  10623. assert(ret == filesize);
  10624. (void)ret;
  10625. }
  10626. fclose(fp);
  10627. const char *head = &buf[0];
  10628. const char *marker = &buf[0];
  10629. // Header check.
  10630. {
  10631. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10632. if (memcmp(marker, header, 4) != 0) {
  10633. tinyexr::SetErrorMessage("Invalid magic number", err);
  10634. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  10635. }
  10636. marker += 4;
  10637. }
  10638. // Version, scanline.
  10639. {
  10640. // ver 2.0, scanline, deep bit on(0x800)
  10641. // must be [2, 0, 0, 0]
  10642. if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
  10643. tinyexr::SetErrorMessage("Unsupported version or scanline", err);
  10644. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10645. }
  10646. marker += 4;
  10647. }
  10648. int dx = -1;
  10649. int dy = -1;
  10650. int dw = -1;
  10651. int dh = -1;
  10652. int num_scanline_blocks = 1; // 16 for ZIP compression.
  10653. int compression_type = -1;
  10654. int num_channels = -1;
  10655. std::vector<tinyexr::ChannelInfo> channels;
  10656. // Read attributes
  10657. size_t size = filesize - tinyexr::kEXRVersionSize;
  10658. for (;;) {
  10659. if (0 == size) {
  10660. return TINYEXR_ERROR_INVALID_DATA;
  10661. } else if (marker[0] == '\0') {
  10662. marker++;
  10663. size--;
  10664. break;
  10665. }
  10666. std::string attr_name;
  10667. std::string attr_type;
  10668. std::vector<unsigned char> data;
  10669. size_t marker_size;
  10670. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  10671. marker, size)) {
  10672. return TINYEXR_ERROR_INVALID_DATA;
  10673. }
  10674. marker += marker_size;
  10675. size -= marker_size;
  10676. if (attr_name.compare("compression") == 0) {
  10677. compression_type = data[0];
  10678. if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
  10679. std::stringstream ss;
  10680. ss << "Unsupported compression type : " << compression_type;
  10681. tinyexr::SetErrorMessage(ss.str(), err);
  10682. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10683. }
  10684. if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10685. num_scanline_blocks = 16;
  10686. }
  10687. } else if (attr_name.compare("channels") == 0) {
  10688. // name: zero-terminated string, from 1 to 255 bytes long
  10689. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  10690. // pLinear: unsigned char, possible values are 0 and 1
  10691. // reserved: three chars, should be zero
  10692. // xSampling: int
  10693. // ySampling: int
  10694. if (!tinyexr::ReadChannelInfo(channels, data)) {
  10695. tinyexr::SetErrorMessage("Failed to parse channel info", err);
  10696. return TINYEXR_ERROR_INVALID_DATA;
  10697. }
  10698. num_channels = static_cast<int>(channels.size());
  10699. if (num_channels < 1) {
  10700. tinyexr::SetErrorMessage("Invalid channels format", err);
  10701. return TINYEXR_ERROR_INVALID_DATA;
  10702. }
  10703. } else if (attr_name.compare("dataWindow") == 0) {
  10704. memcpy(&dx, &data.at(0), sizeof(int));
  10705. memcpy(&dy, &data.at(4), sizeof(int));
  10706. memcpy(&dw, &data.at(8), sizeof(int));
  10707. memcpy(&dh, &data.at(12), sizeof(int));
  10708. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx));
  10709. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy));
  10710. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw));
  10711. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh));
  10712. } else if (attr_name.compare("displayWindow") == 0) {
  10713. int x;
  10714. int y;
  10715. int w;
  10716. int h;
  10717. memcpy(&x, &data.at(0), sizeof(int));
  10718. memcpy(&y, &data.at(4), sizeof(int));
  10719. memcpy(&w, &data.at(8), sizeof(int));
  10720. memcpy(&h, &data.at(12), sizeof(int));
  10721. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x));
  10722. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  10723. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10724. tinyexr::swap4(reinterpret_cast<unsigned int *>(&h));
  10725. }
  10726. }
  10727. assert(dx >= 0);
  10728. assert(dy >= 0);
  10729. assert(dw >= 0);
  10730. assert(dh >= 0);
  10731. assert(num_channels >= 1);
  10732. int data_width = dw - dx + 1;
  10733. int data_height = dh - dy + 1;
  10734. std::vector<float> image(
  10735. static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA
  10736. // Read offset tables.
  10737. int num_blocks = data_height / num_scanline_blocks;
  10738. if (num_blocks * num_scanline_blocks < data_height) {
  10739. num_blocks++;
  10740. }
  10741. std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
  10742. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10743. tinyexr::tinyexr_int64 offset;
  10744. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
  10745. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));
  10746. marker += sizeof(tinyexr::tinyexr_int64); // = 8
  10747. offsets[y] = offset;
  10748. }
  10749. #if TINYEXR_USE_PIZ
  10750. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10751. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10752. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10753. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||
  10754. (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
  10755. #else
  10756. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10757. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10758. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10759. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10760. #endif
  10761. // OK
  10762. } else {
  10763. tinyexr::SetErrorMessage("Unsupported compression format", err);
  10764. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10765. }
  10766. deep_image->image = static_cast<float ***>(
  10767. malloc(sizeof(float **) * static_cast<size_t>(num_channels)));
  10768. for (int c = 0; c < num_channels; c++) {
  10769. deep_image->image[c] = static_cast<float **>(
  10770. malloc(sizeof(float *) * static_cast<size_t>(data_height)));
  10771. for (int y = 0; y < data_height; y++) {
  10772. }
  10773. }
  10774. deep_image->offset_table = static_cast<int **>(
  10775. malloc(sizeof(int *) * static_cast<size_t>(data_height)));
  10776. for (int y = 0; y < data_height; y++) {
  10777. deep_image->offset_table[y] = static_cast<int *>(
  10778. malloc(sizeof(int) * static_cast<size_t>(data_width)));
  10779. }
  10780. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10781. const unsigned char *data_ptr =
  10782. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  10783. // int: y coordinate
  10784. // int64: packed size of pixel offset table
  10785. // int64: packed size of sample data
  10786. // int64: unpacked size of sample data
  10787. // compressed pixel offset table
  10788. // compressed sample data
  10789. int line_no;
  10790. tinyexr::tinyexr_int64 packedOffsetTableSize;
  10791. tinyexr::tinyexr_int64 packedSampleDataSize;
  10792. tinyexr::tinyexr_int64 unpackedSampleDataSize;
  10793. memcpy(&line_no, data_ptr, sizeof(int));
  10794. memcpy(&packedOffsetTableSize, data_ptr + 4,
  10795. sizeof(tinyexr::tinyexr_int64));
  10796. memcpy(&packedSampleDataSize, data_ptr + 12,
  10797. sizeof(tinyexr::tinyexr_int64));
  10798. memcpy(&unpackedSampleDataSize, data_ptr + 20,
  10799. sizeof(tinyexr::tinyexr_int64));
  10800. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  10801. tinyexr::swap8(
  10802. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));
  10803. tinyexr::swap8(
  10804. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));
  10805. tinyexr::swap8(
  10806. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));
  10807. std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
  10808. // decode pixel offset table.
  10809. {
  10810. unsigned long dstLen =
  10811. static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
  10812. if (!tinyexr::DecompressZip(
  10813. reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  10814. &dstLen, data_ptr + 28,
  10815. static_cast<unsigned long>(packedOffsetTableSize))) {
  10816. return false;
  10817. }
  10818. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  10819. for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
  10820. deep_image->offset_table[y][i] = pixelOffsetTable[i];
  10821. }
  10822. }
  10823. std::vector<unsigned char> sample_data(
  10824. static_cast<size_t>(unpackedSampleDataSize));
  10825. // decode sample data.
  10826. {
  10827. unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
  10828. if (dstLen) {
  10829. if (!tinyexr::DecompressZip(
  10830. reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,
  10831. data_ptr + 28 + packedOffsetTableSize,
  10832. static_cast<unsigned long>(packedSampleDataSize))) {
  10833. return false;
  10834. }
  10835. assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize));
  10836. }
  10837. }
  10838. // decode sample
  10839. int sampleSize = -1;
  10840. std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
  10841. {
  10842. int channel_offset = 0;
  10843. for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
  10844. channel_offset_list[i] = channel_offset;
  10845. if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
  10846. channel_offset += 4;
  10847. } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
  10848. channel_offset += 2;
  10849. } else if (channels[i].pixel_type ==
  10850. TINYEXR_PIXELTYPE_FLOAT) { // float
  10851. channel_offset += 4;
  10852. } else {
  10853. assert(0);
  10854. }
  10855. }
  10856. sampleSize = channel_offset;
  10857. }
  10858. assert(sampleSize >= 2);
  10859. assert(static_cast<size_t>(
  10860. pixelOffsetTable[static_cast<size_t>(data_width - 1)] *
  10861. sampleSize) == sample_data.size());
  10862. int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
  10863. //
  10864. // Alloc memory
  10865. //
  10866. //
  10867. // pixel data is stored as image[channels][pixel_samples]
  10868. //
  10869. {
  10870. tinyexr::tinyexr_uint64 data_offset = 0;
  10871. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  10872. deep_image->image[c][y] = static_cast<float *>(
  10873. malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
  10874. if (channels[c].pixel_type == 0) { // UINT
  10875. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10876. unsigned int ui;
  10877. unsigned int *src_ptr = reinterpret_cast<unsigned int *>(
  10878. &sample_data.at(size_t(data_offset) + x * sizeof(int)));
  10879. tinyexr::cpy4(&ui, src_ptr);
  10880. deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
  10881. }
  10882. data_offset +=
  10883. sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
  10884. } else if (channels[c].pixel_type == 1) { // half
  10885. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10886. tinyexr::FP16 f16;
  10887. const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(
  10888. &sample_data.at(size_t(data_offset) + x * sizeof(short)));
  10889. tinyexr::cpy2(&(f16.u), src_ptr);
  10890. tinyexr::FP32 f32 = half_to_float(f16);
  10891. deep_image->image[c][y][x] = f32.f;
  10892. }
  10893. data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
  10894. } else { // float
  10895. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10896. float f;
  10897. const float *src_ptr = reinterpret_cast<float *>(
  10898. &sample_data.at(size_t(data_offset) + x * sizeof(float)));
  10899. tinyexr::cpy4(&f, src_ptr);
  10900. deep_image->image[c][y][x] = f;
  10901. }
  10902. data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
  10903. }
  10904. }
  10905. }
  10906. } // y
  10907. deep_image->width = data_width;
  10908. deep_image->height = data_height;
  10909. deep_image->channel_names = static_cast<const char **>(
  10910. malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));
  10911. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  10912. #ifdef _WIN32
  10913. deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
  10914. #else
  10915. deep_image->channel_names[c] = strdup(channels[c].name.c_str());
  10916. #endif
  10917. }
  10918. deep_image->num_channels = num_channels;
  10919. return TINYEXR_SUCCESS;
  10920. }
  10921. void InitEXRImage(EXRImage *exr_image) {
  10922. if (exr_image == NULL) {
  10923. return;
  10924. }
  10925. exr_image->width = 0;
  10926. exr_image->height = 0;
  10927. exr_image->num_channels = 0;
  10928. exr_image->images = NULL;
  10929. exr_image->tiles = NULL;
  10930. exr_image->num_tiles = 0;
  10931. }
  10932. void FreeEXRErrorMessage(const char *msg) {
  10933. if (msg) {
  10934. free(reinterpret_cast<void *>(const_cast<char *>(msg)));
  10935. }
  10936. return;
  10937. }
  10938. void InitEXRHeader(EXRHeader *exr_header) {
  10939. if (exr_header == NULL) {
  10940. return;
  10941. }
  10942. memset(exr_header, 0, sizeof(EXRHeader));
  10943. }
  10944. int FreeEXRHeader(EXRHeader *exr_header) {
  10945. if (exr_header == NULL) {
  10946. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10947. }
  10948. if (exr_header->channels) {
  10949. free(exr_header->channels);
  10950. }
  10951. if (exr_header->pixel_types) {
  10952. free(exr_header->pixel_types);
  10953. }
  10954. if (exr_header->requested_pixel_types) {
  10955. free(exr_header->requested_pixel_types);
  10956. }
  10957. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  10958. if (exr_header->custom_attributes[i].value) {
  10959. free(exr_header->custom_attributes[i].value);
  10960. }
  10961. }
  10962. if (exr_header->custom_attributes) {
  10963. free(exr_header->custom_attributes);
  10964. }
  10965. return TINYEXR_SUCCESS;
  10966. }
  10967. int FreeEXRImage(EXRImage *exr_image) {
  10968. if (exr_image == NULL) {
  10969. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10970. }
  10971. for (int i = 0; i < exr_image->num_channels; i++) {
  10972. if (exr_image->images && exr_image->images[i]) {
  10973. free(exr_image->images[i]);
  10974. }
  10975. }
  10976. if (exr_image->images) {
  10977. free(exr_image->images);
  10978. }
  10979. if (exr_image->tiles) {
  10980. for (int tid = 0; tid < exr_image->num_tiles; tid++) {
  10981. for (int i = 0; i < exr_image->num_channels; i++) {
  10982. if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
  10983. free(exr_image->tiles[tid].images[i]);
  10984. }
  10985. }
  10986. if (exr_image->tiles[tid].images) {
  10987. free(exr_image->tiles[tid].images);
  10988. }
  10989. }
  10990. free(exr_image->tiles);
  10991. }
  10992. return TINYEXR_SUCCESS;
  10993. }
  10994. int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,
  10995. const char *filename, const char **err) {
  10996. if (exr_header == NULL || exr_version == NULL || filename == NULL) {
  10997. tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
  10998. err);
  10999. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11000. }
  11001. #ifdef _WIN32
  11002. FILE *fp = NULL;
  11003. fopen_s(&fp, filename, "rb");
  11004. #else
  11005. FILE *fp = fopen(filename, "rb");
  11006. #endif
  11007. if (!fp) {
  11008. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11009. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11010. }
  11011. size_t filesize;
  11012. // Compute size
  11013. fseek(fp, 0, SEEK_END);
  11014. filesize = static_cast<size_t>(ftell(fp));
  11015. fseek(fp, 0, SEEK_SET);
  11016. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11017. {
  11018. size_t ret;
  11019. ret = fread(&buf[0], 1, filesize, fp);
  11020. assert(ret == filesize);
  11021. fclose(fp);
  11022. if (ret != filesize) {
  11023. tinyexr::SetErrorMessage("fread() error on " + std::string(filename),
  11024. err);
  11025. return TINYEXR_ERROR_INVALID_FILE;
  11026. }
  11027. }
  11028. return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize,
  11029. err);
  11030. }
  11031. int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,
  11032. int *num_headers,
  11033. const EXRVersion *exr_version,
  11034. const unsigned char *memory, size_t size,
  11035. const char **err) {
  11036. if (memory == NULL || exr_headers == NULL || num_headers == NULL ||
  11037. exr_version == NULL) {
  11038. // Invalid argument
  11039. tinyexr::SetErrorMessage(
  11040. "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
  11041. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11042. }
  11043. if (size < tinyexr::kEXRVersionSize) {
  11044. tinyexr::SetErrorMessage("Data size too short", err);
  11045. return TINYEXR_ERROR_INVALID_DATA;
  11046. }
  11047. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  11048. size_t marker_size = size - tinyexr::kEXRVersionSize;
  11049. std::vector<tinyexr::HeaderInfo> infos;
  11050. for (;;) {
  11051. tinyexr::HeaderInfo info;
  11052. info.clear();
  11053. std::string err_str;
  11054. bool empty_header = false;
  11055. int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
  11056. marker, marker_size);
  11057. if (ret != TINYEXR_SUCCESS) {
  11058. tinyexr::SetErrorMessage(err_str, err);
  11059. return ret;
  11060. }
  11061. if (empty_header) {
  11062. marker += 1; // skip '\0'
  11063. break;
  11064. }
  11065. // `chunkCount` must exist in the header.
  11066. if (info.chunk_count == 0) {
  11067. tinyexr::SetErrorMessage(
  11068. "`chunkCount' attribute is not found in the header.", err);
  11069. return TINYEXR_ERROR_INVALID_DATA;
  11070. }
  11071. infos.push_back(info);
  11072. // move to next header.
  11073. marker += info.header_len;
  11074. size -= info.header_len;
  11075. }
  11076. // allocate memory for EXRHeader and create array of EXRHeader pointers.
  11077. (*exr_headers) =
  11078. static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));
  11079. for (size_t i = 0; i < infos.size(); i++) {
  11080. EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));
  11081. ConvertHeader(exr_header, infos[i]);
  11082. // transfoer `tiled` from version.
  11083. exr_header->tiled = exr_version->tiled;
  11084. (*exr_headers)[i] = exr_header;
  11085. }
  11086. (*num_headers) = static_cast<int>(infos.size());
  11087. return TINYEXR_SUCCESS;
  11088. }
  11089. int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,
  11090. const EXRVersion *exr_version,
  11091. const char *filename, const char **err) {
  11092. if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||
  11093. filename == NULL) {
  11094. tinyexr::SetErrorMessage(
  11095. "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
  11096. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11097. }
  11098. #ifdef _WIN32
  11099. FILE *fp = NULL;
  11100. fopen_s(&fp, filename, "rb");
  11101. #else
  11102. FILE *fp = fopen(filename, "rb");
  11103. #endif
  11104. if (!fp) {
  11105. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11106. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11107. }
  11108. size_t filesize;
  11109. // Compute size
  11110. fseek(fp, 0, SEEK_END);
  11111. filesize = static_cast<size_t>(ftell(fp));
  11112. fseek(fp, 0, SEEK_SET);
  11113. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11114. {
  11115. size_t ret;
  11116. ret = fread(&buf[0], 1, filesize, fp);
  11117. assert(ret == filesize);
  11118. fclose(fp);
  11119. if (ret != filesize) {
  11120. tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err);
  11121. return TINYEXR_ERROR_INVALID_FILE;
  11122. }
  11123. }
  11124. return ParseEXRMultipartHeaderFromMemory(
  11125. exr_headers, num_headers, exr_version, &buf.at(0), filesize, err);
  11126. }
  11127. int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,
  11128. size_t size) {
  11129. if (version == NULL || memory == NULL) {
  11130. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11131. }
  11132. if (size < tinyexr::kEXRVersionSize) {
  11133. return TINYEXR_ERROR_INVALID_DATA;
  11134. }
  11135. const unsigned char *marker = memory;
  11136. // Header check.
  11137. {
  11138. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  11139. if (memcmp(marker, header, 4) != 0) {
  11140. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  11141. }
  11142. marker += 4;
  11143. }
  11144. version->tiled = false;
  11145. version->long_name = false;
  11146. version->non_image = false;
  11147. version->multipart = false;
  11148. // Parse version header.
  11149. {
  11150. // must be 2
  11151. if (marker[0] != 2) {
  11152. return TINYEXR_ERROR_INVALID_EXR_VERSION;
  11153. }
  11154. if (version == NULL) {
  11155. return TINYEXR_SUCCESS; // May OK
  11156. }
  11157. version->version = 2;
  11158. if (marker[1] & 0x2) { // 9th bit
  11159. version->tiled = true;
  11160. }
  11161. if (marker[1] & 0x4) { // 10th bit
  11162. version->long_name = true;
  11163. }
  11164. if (marker[1] & 0x8) { // 11th bit
  11165. version->non_image = true; // (deep image)
  11166. }
  11167. if (marker[1] & 0x10) { // 12th bit
  11168. version->multipart = true;
  11169. }
  11170. }
  11171. return TINYEXR_SUCCESS;
  11172. }
  11173. int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {
  11174. if (filename == NULL) {
  11175. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11176. }
  11177. #ifdef _WIN32
  11178. FILE *fp = NULL;
  11179. fopen_s(&fp, filename, "rb");
  11180. #else
  11181. FILE *fp = fopen(filename, "rb");
  11182. #endif
  11183. if (!fp) {
  11184. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11185. }
  11186. size_t file_size;
  11187. // Compute size
  11188. fseek(fp, 0, SEEK_END);
  11189. file_size = static_cast<size_t>(ftell(fp));
  11190. fseek(fp, 0, SEEK_SET);
  11191. if (file_size < tinyexr::kEXRVersionSize) {
  11192. return TINYEXR_ERROR_INVALID_FILE;
  11193. }
  11194. unsigned char buf[tinyexr::kEXRVersionSize];
  11195. size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
  11196. fclose(fp);
  11197. if (ret != tinyexr::kEXRVersionSize) {
  11198. return TINYEXR_ERROR_INVALID_FILE;
  11199. }
  11200. return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
  11201. }
  11202. int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,
  11203. const EXRHeader **exr_headers,
  11204. unsigned int num_parts,
  11205. const unsigned char *memory,
  11206. const size_t size, const char **err) {
  11207. if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
  11208. memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
  11209. tinyexr::SetErrorMessage(
  11210. "Invalid argument for LoadEXRMultipartImageFromMemory()", err);
  11211. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11212. }
  11213. // compute total header size.
  11214. size_t total_header_size = 0;
  11215. for (unsigned int i = 0; i < num_parts; i++) {
  11216. if (exr_headers[i]->header_len == 0) {
  11217. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  11218. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11219. }
  11220. total_header_size += exr_headers[i]->header_len;
  11221. }
  11222. const char *marker = reinterpret_cast<const char *>(
  11223. memory + total_header_size + 4 +
  11224. 4); // +8 for magic number and version header.
  11225. marker += 1; // Skip empty header.
  11226. // NOTE 1:
  11227. // In multipart image, There is 'part number' before chunk data.
  11228. // 4 byte : part number
  11229. // 4+ : chunk
  11230. //
  11231. // NOTE 2:
  11232. // EXR spec says 'part number' is 'unsigned long' but actually this is
  11233. // 'unsigned int(4 bytes)' in OpenEXR implementation...
  11234. // http://www.openexr.com/openexrfilelayout.pdf
  11235. // Load chunk offset table.
  11236. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list;
  11237. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11238. std::vector<tinyexr::tinyexr_uint64> offset_table(
  11239. static_cast<size_t>(exr_headers[i]->chunk_count));
  11240. for (size_t c = 0; c < offset_table.size(); c++) {
  11241. tinyexr::tinyexr_uint64 offset;
  11242. memcpy(&offset, marker, 8);
  11243. tinyexr::swap8(&offset);
  11244. if (offset >= size) {
  11245. tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
  11246. err);
  11247. return TINYEXR_ERROR_INVALID_DATA;
  11248. }
  11249. offset_table[c] = offset + 4; // +4 to skip 'part number'
  11250. marker += 8;
  11251. }
  11252. chunk_offset_table_list.push_back(offset_table);
  11253. }
  11254. // Decode image.
  11255. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11256. std::vector<tinyexr::tinyexr_uint64> &offset_table =
  11257. chunk_offset_table_list[i];
  11258. // First check 'part number' is identitical to 'i'
  11259. for (size_t c = 0; c < offset_table.size(); c++) {
  11260. const unsigned char *part_number_addr =
  11261. memory + offset_table[c] - 4; // -4 to move to 'part number' field.
  11262. unsigned int part_no;
  11263. memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
  11264. tinyexr::swap4(&part_no);
  11265. if (part_no != i) {
  11266. tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
  11267. err);
  11268. return TINYEXR_ERROR_INVALID_DATA;
  11269. }
  11270. }
  11271. std::string e;
  11272. int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table,
  11273. memory, size, &e);
  11274. if (ret != TINYEXR_SUCCESS) {
  11275. if (!e.empty()) {
  11276. tinyexr::SetErrorMessage(e, err);
  11277. }
  11278. return ret;
  11279. }
  11280. }
  11281. return TINYEXR_SUCCESS;
  11282. }
  11283. int LoadEXRMultipartImageFromFile(EXRImage *exr_images,
  11284. const EXRHeader **exr_headers,
  11285. unsigned int num_parts, const char *filename,
  11286. const char **err) {
  11287. if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
  11288. tinyexr::SetErrorMessage(
  11289. "Invalid argument for LoadEXRMultipartImageFromFile", err);
  11290. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11291. }
  11292. #ifdef _WIN32
  11293. FILE *fp = NULL;
  11294. fopen_s(&fp, filename, "rb");
  11295. #else
  11296. FILE *fp = fopen(filename, "rb");
  11297. #endif
  11298. if (!fp) {
  11299. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11300. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11301. }
  11302. size_t filesize;
  11303. // Compute size
  11304. fseek(fp, 0, SEEK_END);
  11305. filesize = static_cast<size_t>(ftell(fp));
  11306. fseek(fp, 0, SEEK_SET);
  11307. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11308. {
  11309. size_t ret;
  11310. ret = fread(&buf[0], 1, filesize, fp);
  11311. assert(ret == filesize);
  11312. fclose(fp);
  11313. (void)ret;
  11314. }
  11315. return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
  11316. &buf.at(0), filesize, err);
  11317. }
  11318. int SaveEXR(const float *data, int width, int height, int components,
  11319. const int save_as_fp16, const char *outfilename, const char **err) {
  11320. if ((components == 1) || components == 3 || components == 4) {
  11321. // OK
  11322. } else {
  11323. std::stringstream ss;
  11324. ss << "Unsupported component value : " << components << std::endl;
  11325. tinyexr::SetErrorMessage(ss.str(), err);
  11326. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11327. }
  11328. EXRHeader header;
  11329. InitEXRHeader(&header);
  11330. if ((width < 16) && (height < 16)) {
  11331. // No compression for small image.
  11332. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;
  11333. } else {
  11334. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  11335. }
  11336. EXRImage image;
  11337. InitEXRImage(&image);
  11338. image.num_channels = components;
  11339. std::vector<float> images[4];
  11340. if (components == 1) {
  11341. images[0].resize(static_cast<size_t>(width * height));
  11342. memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
  11343. } else {
  11344. images[0].resize(static_cast<size_t>(width * height));
  11345. images[1].resize(static_cast<size_t>(width * height));
  11346. images[2].resize(static_cast<size_t>(width * height));
  11347. images[3].resize(static_cast<size_t>(width * height));
  11348. // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
  11349. for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
  11350. images[0][i] = data[static_cast<size_t>(components) * i + 0];
  11351. images[1][i] = data[static_cast<size_t>(components) * i + 1];
  11352. images[2][i] = data[static_cast<size_t>(components) * i + 2];
  11353. if (components == 4) {
  11354. images[3][i] = data[static_cast<size_t>(components) * i + 3];
  11355. }
  11356. }
  11357. }
  11358. float *image_ptr[4] = {0, 0, 0, 0};
  11359. if (components == 4) {
  11360. image_ptr[0] = &(images[3].at(0)); // A
  11361. image_ptr[1] = &(images[2].at(0)); // B
  11362. image_ptr[2] = &(images[1].at(0)); // G
  11363. image_ptr[3] = &(images[0].at(0)); // R
  11364. } else if (components == 3) {
  11365. image_ptr[0] = &(images[2].at(0)); // B
  11366. image_ptr[1] = &(images[1].at(0)); // G
  11367. image_ptr[2] = &(images[0].at(0)); // R
  11368. } else if (components == 1) {
  11369. image_ptr[0] = &(images[0].at(0)); // A
  11370. }
  11371. image.images = reinterpret_cast<unsigned char **>(image_ptr);
  11372. image.width = width;
  11373. image.height = height;
  11374. header.num_channels = components;
  11375. header.channels = static_cast<EXRChannelInfo *>(malloc(
  11376. sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
  11377. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  11378. if (components == 4) {
  11379. #ifdef _MSC_VER
  11380. strncpy_s(header.channels[0].name, "A", 255);
  11381. strncpy_s(header.channels[1].name, "B", 255);
  11382. strncpy_s(header.channels[2].name, "G", 255);
  11383. strncpy_s(header.channels[3].name, "R", 255);
  11384. #else
  11385. strncpy(header.channels[0].name, "A", 255);
  11386. strncpy(header.channels[1].name, "B", 255);
  11387. strncpy(header.channels[2].name, "G", 255);
  11388. strncpy(header.channels[3].name, "R", 255);
  11389. #endif
  11390. header.channels[0].name[strlen("A")] = '\0';
  11391. header.channels[1].name[strlen("B")] = '\0';
  11392. header.channels[2].name[strlen("G")] = '\0';
  11393. header.channels[3].name[strlen("R")] = '\0';
  11394. } else if (components == 3) {
  11395. #ifdef _MSC_VER
  11396. strncpy_s(header.channels[0].name, "B", 255);
  11397. strncpy_s(header.channels[1].name, "G", 255);
  11398. strncpy_s(header.channels[2].name, "R", 255);
  11399. #else
  11400. strncpy(header.channels[0].name, "B", 255);
  11401. strncpy(header.channels[1].name, "G", 255);
  11402. strncpy(header.channels[2].name, "R", 255);
  11403. #endif
  11404. header.channels[0].name[strlen("B")] = '\0';
  11405. header.channels[1].name[strlen("G")] = '\0';
  11406. header.channels[2].name[strlen("R")] = '\0';
  11407. } else {
  11408. #ifdef _MSC_VER
  11409. strncpy_s(header.channels[0].name, "A", 255);
  11410. #else
  11411. strncpy(header.channels[0].name, "A", 255);
  11412. #endif
  11413. header.channels[0].name[strlen("A")] = '\0';
  11414. }
  11415. header.pixel_types = static_cast<int *>(
  11416. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11417. header.requested_pixel_types = static_cast<int *>(
  11418. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11419. for (int i = 0; i < header.num_channels; i++) {
  11420. header.pixel_types[i] =
  11421. TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
  11422. if (save_as_fp16 > 0) {
  11423. header.requested_pixel_types[i] =
  11424. TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
  11425. } else {
  11426. header.requested_pixel_types[i] =
  11427. TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
  11428. // no precision reduction)
  11429. }
  11430. }
  11431. int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
  11432. if (ret != TINYEXR_SUCCESS) {
  11433. return ret;
  11434. }
  11435. free(header.channels);
  11436. free(header.pixel_types);
  11437. free(header.requested_pixel_types);
  11438. return ret;
  11439. }
  11440. #ifdef __clang__
  11441. // zero-as-null-ppinter-constant
  11442. #pragma clang diagnostic pop
  11443. #endif
  11444. #endif // TINYEXR_IMPLEMENTATION_DEIFNED
  11445. #endif // TINYEXR_IMPLEMENTATION