tinyexr.h 462 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327
  1. /*
  2. Copyright (c) 2014 - 2019, 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 (-6)
  102. #define TINYEXR_ERROR_CANT_OPEN_FILE (-7)
  103. #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8)
  104. #define TINYEXR_ERROR_INVALID_HEADER (-9)
  105. #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10)
  106. #define TINYEXR_ERROR_CANT_WRITE_FILE (-11)
  107. #define TINYEXR_ERROR_SERIALZATION_FAILED (-12)
  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
  234. // others
  235. extern int IsEXR(const char *filename);
  236. // @deprecated { to be removed. }
  237. // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
  238. // components must be 1(Grayscale), 3(RGB) or 4(RGBA).
  239. // Input image format is: `float x width x height`, or `float x RGB(A) x width x
  240. // hight`
  241. // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
  242. // value.
  243. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
  244. // Use ZIP compression by default.
  245. // Returns negative value and may set error string in `err` when there's an
  246. // error
  247. extern int SaveEXR(const float *data, const int width, const int height,
  248. const int components, const int save_as_fp16,
  249. const char *filename, const char **err);
  250. // Initialize EXRHeader struct
  251. extern void InitEXRHeader(EXRHeader *exr_header);
  252. // Initialize EXRImage struct
  253. extern void InitEXRImage(EXRImage *exr_image);
  254. // Free's internal data of EXRHeader struct
  255. extern int FreeEXRHeader(EXRHeader *exr_header);
  256. // Free's internal data of EXRImage struct
  257. extern int FreeEXRImage(EXRImage *exr_image);
  258. // Free's error message
  259. extern void FreeEXRErrorMessage(const char *msg);
  260. // Parse EXR version header of a file.
  261. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);
  262. // Parse EXR version header from memory-mapped EXR data.
  263. extern int ParseEXRVersionFromMemory(EXRVersion *version,
  264. const unsigned char *memory, size_t size);
  265. // Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
  266. // When there was an error message, Application must free `err` with
  267. // FreeEXRErrorMessage()
  268. extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,
  269. const char *filename, const char **err);
  270. // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
  271. // When there was an error message, Application must free `err` with
  272. // FreeEXRErrorMessage()
  273. extern int ParseEXRHeaderFromMemory(EXRHeader *header,
  274. const EXRVersion *version,
  275. const unsigned char *memory, size_t size,
  276. const char **err);
  277. // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
  278. // array.
  279. // When there was an error message, Application must free `err` with
  280. // FreeEXRErrorMessage()
  281. extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,
  282. int *num_headers,
  283. const EXRVersion *version,
  284. const char *filename,
  285. const char **err);
  286. // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
  287. // array
  288. // When there was an error message, Application must free `err` with
  289. // FreeEXRErrorMessage()
  290. extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,
  291. int *num_headers,
  292. const EXRVersion *version,
  293. const unsigned char *memory,
  294. size_t size, const char **err);
  295. // Loads single-part OpenEXR image from a file.
  296. // Application must setup `ParseEXRHeaderFromFile` before calling this function.
  297. // Application can free EXRImage using `FreeEXRImage`
  298. // Returns negative value and may set error string in `err` when there's an
  299. // error
  300. // When there was an error message, Application must free `err` with
  301. // FreeEXRErrorMessage()
  302. extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,
  303. const char *filename, const char **err);
  304. // Loads single-part OpenEXR image from a memory.
  305. // Application must setup `EXRHeader` with
  306. // `ParseEXRHeaderFromMemory` before calling this function.
  307. // Application can free EXRImage using `FreeEXRImage`
  308. // Returns negative value and may set error string in `err` when there's an
  309. // error
  310. // When there was an error message, Application must free `err` with
  311. // FreeEXRErrorMessage()
  312. extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,
  313. const unsigned char *memory,
  314. const size_t size, const char **err);
  315. // Loads multi-part OpenEXR image from a file.
  316. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
  317. // function.
  318. // Application can free EXRImage using `FreeEXRImage`
  319. // Returns negative value and may set error string in `err` when there's an
  320. // error
  321. // When there was an error message, Application must free `err` with
  322. // FreeEXRErrorMessage()
  323. extern int LoadEXRMultipartImageFromFile(EXRImage *images,
  324. const EXRHeader **headers,
  325. unsigned int num_parts,
  326. const char *filename,
  327. const char **err);
  328. // Loads multi-part OpenEXR image from a memory.
  329. // Application must setup `EXRHeader*` array with
  330. // `ParseEXRMultipartHeaderFromMemory` before calling this function.
  331. // Application can free EXRImage using `FreeEXRImage`
  332. // Returns negative value and may set error string in `err` when there's an
  333. // error
  334. // When there was an error message, Application must free `err` with
  335. // FreeEXRErrorMessage()
  336. extern int LoadEXRMultipartImageFromMemory(EXRImage *images,
  337. const EXRHeader **headers,
  338. unsigned int num_parts,
  339. const unsigned char *memory,
  340. const size_t size, const char **err);
  341. // Saves multi-channel, single-frame OpenEXR image to a file.
  342. // Returns negative value and may set error string in `err` when there's an
  343. // error
  344. // When there was an error message, Application must free `err` with
  345. // FreeEXRErrorMessage()
  346. extern int SaveEXRImageToFile(const EXRImage *image,
  347. const EXRHeader *exr_header, const char *filename,
  348. const char **err);
  349. // Saves multi-channel, single-frame OpenEXR image to a memory.
  350. // Image is compressed using EXRImage.compression value.
  351. // Return the number of bytes if success.
  352. // Return zero and will set error string in `err` when there's an
  353. // error.
  354. // When there was an error message, Application must free `err` with
  355. // FreeEXRErrorMessage()
  356. extern size_t SaveEXRImageToMemory(const EXRImage *image,
  357. const EXRHeader *exr_header,
  358. unsigned char **memory, const char **err);
  359. // Loads single-frame OpenEXR deep image.
  360. // Application must free memory of variables in DeepImage(image, offset_table)
  361. // Returns negative value and may set error string in `err` when there's an
  362. // error
  363. // When there was an error message, Application must free `err` with
  364. // FreeEXRErrorMessage()
  365. extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
  366. const char **err);
  367. // NOT YET IMPLEMENTED:
  368. // Saves single-frame OpenEXR deep image.
  369. // Returns negative value and may set error string in `err` when there's an
  370. // error
  371. // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
  372. // const char **err);
  373. // NOT YET IMPLEMENTED:
  374. // Loads multi-part OpenEXR deep image.
  375. // Application must free memory of variables in DeepImage(image, offset_table)
  376. // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
  377. // char *filename,
  378. // const char **err);
  379. // For emscripten.
  380. // Loads single-frame OpenEXR image from memory. Assume EXR image contains
  381. // RGB(A) channels.
  382. // Returns negative value and may set error string in `err` when there's an
  383. // error
  384. // When there was an error message, Application must free `err` with
  385. // FreeEXRErrorMessage()
  386. extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  387. const unsigned char *memory, size_t size,
  388. const char **err);
  389. #ifdef __cplusplus
  390. }
  391. #endif
  392. #endif // TINYEXR_H_
  393. #ifdef TINYEXR_IMPLEMENTATION
  394. #ifndef TINYEXR_IMPLEMENTATION_DEIFNED
  395. #define TINYEXR_IMPLEMENTATION_DEIFNED
  396. #include <algorithm>
  397. #include <cassert>
  398. #include <cstdio>
  399. #include <cstdlib>
  400. #include <cstring>
  401. #include <sstream>
  402. //#include <iostream> // debug
  403. #include <limits>
  404. #include <string>
  405. #include <vector>
  406. #if __cplusplus > 199711L
  407. // C++11
  408. #include <cstdint>
  409. #endif // __cplusplus > 199711L
  410. #ifdef _OPENMP
  411. #include <omp.h>
  412. #endif
  413. #if TINYEXR_USE_MINIZ
  414. #else
  415. // Issue #46. Please include your own zlib-compatible API header before
  416. // including `tinyexr.h`
  417. //#include "zlib.h"
  418. #endif
  419. #if TINYEXR_USE_ZFP
  420. #include "zfp.h"
  421. #endif
  422. namespace tinyexr {
  423. #if __cplusplus > 199711L
  424. // C++11
  425. typedef uint64_t tinyexr_uint64;
  426. typedef int64_t tinyexr_int64;
  427. #else
  428. // Although `long long` is not a standard type pre C++11, assume it is defined
  429. // as a compiler's extension.
  430. #ifdef __clang__
  431. #pragma clang diagnostic push
  432. #pragma clang diagnostic ignored "-Wc++11-long-long"
  433. #endif
  434. typedef unsigned long long tinyexr_uint64;
  435. typedef long long tinyexr_int64;
  436. #ifdef __clang__
  437. #pragma clang diagnostic pop
  438. #endif
  439. #endif
  440. #if TINYEXR_USE_MINIZ
  441. namespace miniz {
  442. #ifdef __clang__
  443. #pragma clang diagnostic push
  444. #pragma clang diagnostic ignored "-Wc++11-long-long"
  445. #pragma clang diagnostic ignored "-Wold-style-cast"
  446. #pragma clang diagnostic ignored "-Wpadded"
  447. #pragma clang diagnostic ignored "-Wsign-conversion"
  448. #pragma clang diagnostic ignored "-Wc++11-extensions"
  449. #pragma clang diagnostic ignored "-Wconversion"
  450. #pragma clang diagnostic ignored "-Wunused-function"
  451. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  452. #pragma clang diagnostic ignored "-Wundef"
  453. #if __has_warning("-Wcomma")
  454. #pragma clang diagnostic ignored "-Wcomma"
  455. #endif
  456. #if __has_warning("-Wmacro-redefined")
  457. #pragma clang diagnostic ignored "-Wmacro-redefined"
  458. #endif
  459. #if __has_warning("-Wcast-qual")
  460. #pragma clang diagnostic ignored "-Wcast-qual"
  461. #endif
  462. #if __has_warning("-Wzero-as-null-pointer-constant")
  463. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  464. #endif
  465. #if __has_warning("-Wtautological-constant-compare")
  466. #pragma clang diagnostic ignored "-Wtautological-constant-compare"
  467. #endif
  468. #if __has_warning("-Wextra-semi-stmt")
  469. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  470. #endif
  471. #endif
  472. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
  473. reading/writing/appending, PNG writing
  474. See "unlicense" statement at the end of this file.
  475. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
  476. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
  477. http://www.ietf.org/rfc/rfc1951.txt
  478. Most API's defined in miniz.c are optional. For example, to disable the
  479. archive related functions just define
  480. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
  481. (see the list below for more macros).
  482. * Change History
  483. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
  484. release with Zip64 support (almost there!):
  485. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
  486. (thanks kahmyong.moon@hp.com) which could cause locate files to not find
  487. files. This bug
  488. would only have occured in earlier versions if you explicitly used this
  489. flag, OR if you used mz_zip_extract_archive_file_to_heap() or
  490. mz_zip_add_mem_to_archive_file_in_place()
  491. (which used this flag). If you can't switch to v1.15 but want to fix
  492. this bug, just remove the uses of this flag from both helper funcs (and of
  493. course don't use the flag).
  494. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
  495. pUser_read_buf is not NULL and compressed size is > uncompressed size
  496. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
  497. compressed data from directory entries, to account for weird zipfiles which
  498. contain zero-size compressed data on dir entries.
  499. Hopefully this fix won't cause any issues on weird zip archives,
  500. because it assumes the low 16-bits of zip external attributes are DOS
  501. attributes (which I believe they always are in practice).
  502. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
  503. internal attributes, just the filename and external attributes
  504. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  505. - Added cmake support for Linux builds which builds all the examples,
  506. tested with clang v3.3 and gcc v4.6.
  507. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  508. - Merged MZ_FORCEINLINE fix from hdeanclark
  509. - Fix <time.h> include before config #ifdef, thanks emil.brink
  510. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
  511. (super useful for OpenGL apps), and explicit control over the compression
  512. level (so you can
  513. set it to 1 for real-time compression).
  514. - Merged in some compiler fixes from paulharris's github repro.
  515. - Retested this build under Windows (VS 2010, including static analysis),
  516. tcc 0.9.26, gcc v4.6 and clang v3.3.
  517. - Added example6.c, which dumps an image of the mandelbrot set to a PNG
  518. file.
  519. - Modified example2 to help test the
  520. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  521. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
  522. possible src file fclose() leak if alignment bytes+local header file write
  523. faiiled
  524. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
  525. Was pushing the wrong central dir header offset, appears harmless in this
  526. release, but it became a problem in the zip64 branch
  527. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
  528. #include <time.h> (thanks fermtect).
  529. 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
  530. mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  531. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
  532. re-ran a randomized regression test on ~500k files.
  533. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  534. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
  535. (static analysis) option and fixed all warnings (except for the silly
  536. "Use of the comma-operator in a tested expression.." analysis warning,
  537. which I purposely use to work around a MSVC compiler warning).
  538. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
  539. tested Linux executables. The codeblocks workspace is compatible with
  540. Linux+Win32/x64.
  541. - Added miniz_tester solution/project, which is a useful little app
  542. derived from LZHAM's tester app that I use as part of the regression test.
  543. - Ran miniz.c and tinfl.c through another series of regression testing on
  544. ~500,000 files and archives.
  545. - Modified example5.c so it purposely disables a bunch of high-level
  546. functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
  547. MINIZ_NO_STDIO bug report.)
  548. - Fix ftell() usage in examples so they exit with an error on files which
  549. are too large (a limitation of the examples, not miniz itself).
  550. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
  551. minor level_and_flags issues in the archive API's.
  552. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
  553. Dawson <bruced@valvesoftware.com> for the feedback/bug report.
  554. 5/28/11 v1.11 - Added statement from unlicense.org
  555. 5/27/11 v1.10 - Substantial compressor optimizations:
  556. - Level 1 is now ~4x faster than before. The L1 compressor's throughput
  557. now varies between 70-110MB/sec. on a
  558. - Core i7 (actual throughput varies depending on the type of data, and x64
  559. vs. x86).
  560. - Improved baseline L2-L9 compression perf. Also, greatly improved
  561. compression perf. issues on some file types.
  562. - Refactored the compression code for better readability and
  563. maintainability.
  564. - Added level 10 compression level (L10 has slightly better ratio than
  565. level 9, but could have a potentially large
  566. drop in throughput on some files).
  567. 5/15/11 v1.09 - Initial stable release.
  568. * Low-level Deflate/Inflate implementation notes:
  569. Compression: Use the "tdefl" API's. The compressor supports raw, static,
  570. and dynamic blocks, lazy or
  571. greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
  572. It performs and compresses
  573. approximately as well as zlib.
  574. Decompression: Use the "tinfl" API's. The entire decompressor is
  575. implemented as a single function
  576. coroutine: see tinfl_decompress(). It supports decompression into a 32KB
  577. (or larger power of 2) wrapping buffer, or into a memory
  578. block large enough to hold the entire file.
  579. The low-level tdefl/tinfl API's do not make any use of dynamic memory
  580. allocation.
  581. * zlib-style API notes:
  582. miniz.c implements a fairly large subset of zlib. There's enough
  583. functionality present for it to be a drop-in
  584. zlib replacement in many apps:
  585. The z_stream struct, optional memory allocation callbacks
  586. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  587. inflateInit/inflateInit2/inflate/inflateEnd
  588. compress, compress2, compressBound, uncompress
  589. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
  590. routines.
  591. Supports raw deflate streams or standard zlib streams with adler-32
  592. checking.
  593. Limitations:
  594. The callback API's are not implemented yet. No support for gzip headers or
  595. zlib static dictionaries.
  596. I've tried to closely emulate zlib's various flavors of stream flushing
  597. and return status codes, but
  598. there are no guarantees that miniz.c pulls this off perfectly.
  599. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
  600. originally written by
  601. Alex Evans. Supports 1-4 bytes/pixel images.
  602. * ZIP archive API notes:
  603. The ZIP archive API's where designed with simplicity and efficiency in
  604. mind, with just enough abstraction to
  605. get the job done with minimal fuss. There are simple API's to retrieve file
  606. information, read files from
  607. existing archives, create new archives, append new files to existing
  608. archives, or clone archive data from
  609. one archive to another. It supports archives located in memory or the heap,
  610. on disk (using stdio.h),
  611. or you can specify custom file read/write callbacks.
  612. - Archive reading: Just call this function to read a single file from a
  613. disk archive:
  614. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
  615. char *pArchive_name,
  616. size_t *pSize, mz_uint zip_flags);
  617. For more complex cases, use the "mz_zip_reader" functions. Upon opening an
  618. archive, the entire central
  619. directory is located and read as-is into memory, and subsequent file access
  620. only occurs when reading individual files.
  621. - Archives file scanning: The simple way is to use this function to scan a
  622. loaded archive for a specific file:
  623. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  624. const char *pComment, mz_uint flags);
  625. The locate operation can optionally check file comments too, which (as one
  626. example) can be used to identify
  627. multiple versions of the same file in an archive. This function uses a
  628. simple linear search through the central
  629. directory, so it's not very fast.
  630. Alternately, you can iterate through all the files in an archive (using
  631. mz_zip_reader_get_num_files()) and
  632. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  633. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
  634. immediately writes compressed file data
  635. to disk and builds an exact image of the central directory in memory. The
  636. central directory image is written
  637. all at once at the end of the archive file when the archive is finalized.
  638. The archive writer can optionally align each file's local header and file
  639. data to any power of 2 alignment,
  640. which can be useful when the archive will be read from optical media. Also,
  641. the writer supports placing
  642. arbitrary data blobs at the very beginning of ZIP archives. Archives
  643. written using either feature are still
  644. readable by any ZIP tool.
  645. - Archive appending: The simple way to add a single file to an archive is
  646. to call this function:
  647. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
  648. const char *pArchive_name,
  649. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
  650. comment_size, mz_uint level_and_flags);
  651. The archive will be created if it doesn't already exist, otherwise it'll be
  652. appended to.
  653. Note the appending is done in-place and is not an atomic operation, so if
  654. something goes wrong
  655. during the operation it's possible the archive could be left without a
  656. central directory (although the local
  657. file headers and file data will be fine, so the archive will be
  658. recoverable).
  659. For more complex archive modification scenarios:
  660. 1. The safest way is to use a mz_zip_reader to read the existing archive,
  661. cloning only those bits you want to
  662. preserve into a new archive using using the
  663. mz_zip_writer_add_from_zip_reader() function (which compiles the
  664. compressed file data as-is). When you're done, delete the old archive and
  665. rename the newly written archive, and
  666. you're done. This is safe but requires a bunch of temporary disk space or
  667. heap memory.
  668. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
  669. mz_zip_writer_init_from_reader(),
  670. append new files as needed, then finalize the archive which will write an
  671. updated central directory to the
  672. original archive. (This is basically what
  673. mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  674. possibility that the archive's central directory could be lost with this
  675. method if anything goes wrong, though.
  676. - ZIP archive support limitations:
  677. No zip64 or spanning support. Extraction functions can only handle
  678. unencrypted, stored or deflated files.
  679. Requires streams capable of seeking.
  680. * This is a header file library, like stb_image.c. To get only a header file,
  681. either cut and paste the
  682. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
  683. include miniz.c from it.
  684. * Important: For best perf. be sure to customize the below macros for your
  685. target platform:
  686. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  687. #define MINIZ_LITTLE_ENDIAN 1
  688. #define MINIZ_HAS_64BIT_REGISTERS 1
  689. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
  690. including miniz.c to ensure miniz
  691. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
  692. able to process large files
  693. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  694. */
  695. #ifndef MINIZ_HEADER_INCLUDED
  696. #define MINIZ_HEADER_INCLUDED
  697. //#include <stdlib.h>
  698. // Defines to completely disable specific portions of miniz.c:
  699. // If all macros here are defined the only functionality remaining will be
  700. // CRC-32, adler-32, tinfl, and tdefl.
  701. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
  702. // stdio for file I/O.
  703. //#define MINIZ_NO_STDIO
  704. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
  705. // to get the current time, or
  706. // get/set file times, and the C run-time funcs that get/set times won't be
  707. // called.
  708. // The current downside is the times written to your archives will be from 1979.
  709. #define MINIZ_NO_TIME
  710. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  711. #define MINIZ_NO_ARCHIVE_APIS
  712. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
  713. // API's.
  714. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  715. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
  716. // API's.
  717. //#define MINIZ_NO_ZLIB_APIS
  718. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
  719. // conflicts against stock zlib.
  720. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  721. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  722. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
  723. // user alloc/free/realloc
  724. // callbacks to the zlib and archive API's, and a few stand-alone helper API's
  725. // which don't provide custom user
  726. // functions (such as tdefl_compress_mem_to_heap() and
  727. // tinfl_decompress_mem_to_heap()) won't work.
  728. //#define MINIZ_NO_MALLOC
  729. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  730. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
  731. // on Linux
  732. #define MINIZ_NO_TIME
  733. #endif
  734. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  735. //#include <time.h>
  736. #endif
  737. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
  738. defined(__i386) || defined(__i486__) || defined(__i486) || \
  739. defined(i386) || defined(__ia64__) || defined(__x86_64__)
  740. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  741. #define MINIZ_X86_OR_X64_CPU 1
  742. #endif
  743. #if defined(__sparcv9)
  744. // Big endian
  745. #else
  746. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  747. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  748. #define MINIZ_LITTLE_ENDIAN 1
  749. #endif
  750. #endif
  751. #if MINIZ_X86_OR_X64_CPU
  752. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
  753. // integer loads and stores from unaligned addresses.
  754. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  755. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
  756. 0 // disable to suppress compiler warnings
  757. #endif
  758. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
  759. defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
  760. defined(__x86_64__)
  761. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
  762. // reasonably fast (and don't involve compiler generated calls to helper
  763. // functions).
  764. #define MINIZ_HAS_64BIT_REGISTERS 1
  765. #endif
  766. #ifdef __cplusplus
  767. extern "C" {
  768. #endif
  769. // ------------------- zlib-style API Definitions.
  770. // For more compatibility with zlib, miniz.c uses unsigned long for some
  771. // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  772. typedef unsigned long mz_ulong;
  773. // mz_free() internally uses the MZ_FREE() macro (which by default calls free()
  774. // unless you've modified the MZ_MALLOC macro) to release a block allocated from
  775. // the heap.
  776. void mz_free(void *p);
  777. #define MZ_ADLER32_INIT (1)
  778. // mz_adler32() returns the initial adler-32 value to use when called with
  779. // ptr==NULL.
  780. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  781. #define MZ_CRC32_INIT (0)
  782. // mz_crc32() returns the initial CRC-32 value to use when called with
  783. // ptr==NULL.
  784. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  785. // Compression strategies.
  786. enum {
  787. MZ_DEFAULT_STRATEGY = 0,
  788. MZ_FILTERED = 1,
  789. MZ_HUFFMAN_ONLY = 2,
  790. MZ_RLE = 3,
  791. MZ_FIXED = 4
  792. };
  793. // Method
  794. #define MZ_DEFLATED 8
  795. #ifndef MINIZ_NO_ZLIB_APIS
  796. // Heap allocation callbacks.
  797. // Note that mz_alloc_func parameter types purpsosely differ from zlib's:
  798. // items/size is size_t, not unsigned long.
  799. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  800. typedef void (*mz_free_func)(void *opaque, void *address);
  801. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
  802. size_t size);
  803. #define MZ_VERSION "9.1.15"
  804. #define MZ_VERNUM 0x91F0
  805. #define MZ_VER_MAJOR 9
  806. #define MZ_VER_MINOR 1
  807. #define MZ_VER_REVISION 15
  808. #define MZ_VER_SUBREVISION 0
  809. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
  810. // other values are for advanced use (refer to the zlib docs).
  811. enum {
  812. MZ_NO_FLUSH = 0,
  813. MZ_PARTIAL_FLUSH = 1,
  814. MZ_SYNC_FLUSH = 2,
  815. MZ_FULL_FLUSH = 3,
  816. MZ_FINISH = 4,
  817. MZ_BLOCK = 5
  818. };
  819. // Return status codes. MZ_PARAM_ERROR is non-standard.
  820. enum {
  821. MZ_OK = 0,
  822. MZ_STREAM_END = 1,
  823. MZ_NEED_DICT = 2,
  824. MZ_ERRNO = -1,
  825. MZ_STREAM_ERROR = -2,
  826. MZ_DATA_ERROR = -3,
  827. MZ_MEM_ERROR = -4,
  828. MZ_BUF_ERROR = -5,
  829. MZ_VERSION_ERROR = -6,
  830. MZ_PARAM_ERROR = -10000
  831. };
  832. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best
  833. // possible compression (not zlib compatible, and may be very slow),
  834. // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  835. enum {
  836. MZ_NO_COMPRESSION = 0,
  837. MZ_BEST_SPEED = 1,
  838. MZ_BEST_COMPRESSION = 9,
  839. MZ_UBER_COMPRESSION = 10,
  840. MZ_DEFAULT_LEVEL = 6,
  841. MZ_DEFAULT_COMPRESSION = -1
  842. };
  843. // Window bits
  844. #define MZ_DEFAULT_WINDOW_BITS 15
  845. struct mz_internal_state;
  846. // Compression/decompression stream struct.
  847. typedef struct mz_stream_s {
  848. const unsigned char *next_in; // pointer to next byte to read
  849. unsigned int avail_in; // number of bytes available at next_in
  850. mz_ulong total_in; // total number of bytes consumed so far
  851. unsigned char *next_out; // pointer to next byte to write
  852. unsigned int avail_out; // number of bytes that can be written to next_out
  853. mz_ulong total_out; // total number of bytes produced so far
  854. char *msg; // error msg (unused)
  855. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  856. mz_alloc_func
  857. zalloc; // optional heap allocation function (defaults to malloc)
  858. mz_free_func zfree; // optional heap free function (defaults to free)
  859. void *opaque; // heap alloc function user pointer
  860. int data_type; // data_type (unused)
  861. mz_ulong adler; // adler32 of the source or uncompressed data
  862. mz_ulong reserved; // not used
  863. } mz_stream;
  864. typedef mz_stream *mz_streamp;
  865. // Returns the version string of miniz.c.
  866. const char *mz_version(void);
  867. // mz_deflateInit() initializes a compressor with default options:
  868. // Parameters:
  869. // pStream must point to an initialized mz_stream struct.
  870. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  871. // level 1 enables a specially optimized compression function that's been
  872. // optimized purely for performance, not ratio.
  873. // (This special func. is currently only enabled when
  874. // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  875. // Return values:
  876. // MZ_OK on success.
  877. // MZ_STREAM_ERROR if the stream is bogus.
  878. // MZ_PARAM_ERROR if the input parameters are bogus.
  879. // MZ_MEM_ERROR on out of memory.
  880. int mz_deflateInit(mz_streamp pStream, int level);
  881. // mz_deflateInit2() is like mz_deflate(), except with more control:
  882. // Additional parameters:
  883. // method must be MZ_DEFLATED
  884. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
  885. // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
  886. // header or footer)
  887. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  888. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  889. int mem_level, int strategy);
  890. // Quickly resets a compressor without having to reallocate anything. Same as
  891. // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  892. int mz_deflateReset(mz_streamp pStream);
  893. // mz_deflate() compresses the input to output, consuming as much of the input
  894. // and producing as much output as possible.
  895. // Parameters:
  896. // pStream is the stream to read from and write to. You must initialize/update
  897. // the next_in, avail_in, next_out, and avail_out members.
  898. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
  899. // MZ_FINISH.
  900. // Return values:
  901. // MZ_OK on success (when flushing, or if more input is needed but not
  902. // available, and/or there's more output to be written but the output buffer
  903. // is full).
  904. // MZ_STREAM_END if all input has been consumed and all output bytes have been
  905. // written. Don't call mz_deflate() on the stream anymore.
  906. // MZ_STREAM_ERROR if the stream is bogus.
  907. // MZ_PARAM_ERROR if one of the parameters is invalid.
  908. // MZ_BUF_ERROR if no forward progress is possible because the input and/or
  909. // output buffers are empty. (Fill up the input buffer or free up some output
  910. // space and try again.)
  911. int mz_deflate(mz_streamp pStream, int flush);
  912. // mz_deflateEnd() deinitializes a compressor:
  913. // Return values:
  914. // MZ_OK on success.
  915. // MZ_STREAM_ERROR if the stream is bogus.
  916. int mz_deflateEnd(mz_streamp pStream);
  917. // mz_deflateBound() returns a (very) conservative upper bound on the amount of
  918. // data that could be generated by deflate(), assuming flush is set to only
  919. // MZ_NO_FLUSH or MZ_FINISH.
  920. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  921. // Single-call compression functions mz_compress() and mz_compress2():
  922. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on
  923. // failure.
  924. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  925. const unsigned char *pSource, mz_ulong source_len);
  926. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  927. const unsigned char *pSource, mz_ulong source_len, int level);
  928. // mz_compressBound() returns a (very) conservative upper bound on the amount of
  929. // data that could be generated by calling mz_compress().
  930. mz_ulong mz_compressBound(mz_ulong source_len);
  931. // Initializes a decompressor.
  932. int mz_inflateInit(mz_streamp pStream);
  933. // mz_inflateInit2() is like mz_inflateInit() with an additional option that
  934. // controls the window size and whether or not the stream has been wrapped with
  935. // a zlib header/footer:
  936. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
  937. // -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  938. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  939. // Decompresses the input stream to the output, consuming only as much of the
  940. // input as needed, and writing as much to the output as possible.
  941. // Parameters:
  942. // pStream is the stream to read from and write to. You must initialize/update
  943. // the next_in, avail_in, next_out, and avail_out members.
  944. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  945. // On the first call, if flush is MZ_FINISH it's assumed the input and output
  946. // buffers are both sized large enough to decompress the entire stream in a
  947. // single call (this is slightly faster).
  948. // MZ_FINISH implies that there are no more source bytes available beside
  949. // what's already in the input buffer, and that the output buffer is large
  950. // enough to hold the rest of the decompressed data.
  951. // Return values:
  952. // MZ_OK on success. Either more input is needed but not available, and/or
  953. // there's more output to be written but the output buffer is full.
  954. // MZ_STREAM_END if all needed input has been consumed and all output bytes
  955. // have been written. For zlib streams, the adler-32 of the decompressed data
  956. // has also been verified.
  957. // MZ_STREAM_ERROR if the stream is bogus.
  958. // MZ_DATA_ERROR if the deflate stream is invalid.
  959. // MZ_PARAM_ERROR if one of the parameters is invalid.
  960. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is
  961. // empty but the inflater needs more input to continue, or if the output
  962. // buffer is not large enough. Call mz_inflate() again
  963. // with more input data, or with more room in the output buffer (except when
  964. // using single call decompression, described above).
  965. int mz_inflate(mz_streamp pStream, int flush);
  966. // Deinitializes a decompressor.
  967. int mz_inflateEnd(mz_streamp pStream);
  968. // Single-call decompression.
  969. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on
  970. // failure.
  971. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  972. const unsigned char *pSource, mz_ulong source_len);
  973. // Returns a string description of the specified error code, or NULL if the
  974. // error code is invalid.
  975. const char *mz_error(int err);
  976. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
  977. // as a drop-in replacement for the subset of zlib that miniz.c supports.
  978. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
  979. // use zlib in the same project.
  980. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  981. typedef unsigned char Byte;
  982. typedef unsigned int uInt;
  983. typedef mz_ulong uLong;
  984. typedef Byte Bytef;
  985. typedef uInt uIntf;
  986. typedef char charf;
  987. typedef int intf;
  988. typedef void *voidpf;
  989. typedef uLong uLongf;
  990. typedef void *voidp;
  991. typedef void *const voidpc;
  992. #define Z_NULL 0
  993. #define Z_NO_FLUSH MZ_NO_FLUSH
  994. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  995. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  996. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  997. #define Z_FINISH MZ_FINISH
  998. #define Z_BLOCK MZ_BLOCK
  999. #define Z_OK MZ_OK
  1000. #define Z_STREAM_END MZ_STREAM_END
  1001. #define Z_NEED_DICT MZ_NEED_DICT
  1002. #define Z_ERRNO MZ_ERRNO
  1003. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  1004. #define Z_DATA_ERROR MZ_DATA_ERROR
  1005. #define Z_MEM_ERROR MZ_MEM_ERROR
  1006. #define Z_BUF_ERROR MZ_BUF_ERROR
  1007. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  1008. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  1009. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  1010. #define Z_BEST_SPEED MZ_BEST_SPEED
  1011. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  1012. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  1013. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  1014. #define Z_FILTERED MZ_FILTERED
  1015. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  1016. #define Z_RLE MZ_RLE
  1017. #define Z_FIXED MZ_FIXED
  1018. #define Z_DEFLATED MZ_DEFLATED
  1019. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  1020. #define alloc_func mz_alloc_func
  1021. #define free_func mz_free_func
  1022. #define internal_state mz_internal_state
  1023. #define z_stream mz_stream
  1024. #define deflateInit mz_deflateInit
  1025. #define deflateInit2 mz_deflateInit2
  1026. #define deflateReset mz_deflateReset
  1027. #define deflate mz_deflate
  1028. #define deflateEnd mz_deflateEnd
  1029. #define deflateBound mz_deflateBound
  1030. #define compress mz_compress
  1031. #define compress2 mz_compress2
  1032. #define compressBound mz_compressBound
  1033. #define inflateInit mz_inflateInit
  1034. #define inflateInit2 mz_inflateInit2
  1035. #define inflate mz_inflate
  1036. #define inflateEnd mz_inflateEnd
  1037. #define uncompress mz_uncompress
  1038. #define crc32 mz_crc32
  1039. #define adler32 mz_adler32
  1040. #define MAX_WBITS 15
  1041. #define MAX_MEM_LEVEL 9
  1042. #define zError mz_error
  1043. #define ZLIB_VERSION MZ_VERSION
  1044. #define ZLIB_VERNUM MZ_VERNUM
  1045. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  1046. #define ZLIB_VER_MINOR MZ_VER_MINOR
  1047. #define ZLIB_VER_REVISION MZ_VER_REVISION
  1048. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  1049. #define zlibVersion mz_version
  1050. #define zlib_version mz_version()
  1051. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  1052. #endif // MINIZ_NO_ZLIB_APIS
  1053. // ------------------- Types and macros
  1054. typedef unsigned char mz_uint8;
  1055. typedef signed short mz_int16;
  1056. typedef unsigned short mz_uint16;
  1057. typedef unsigned int mz_uint32;
  1058. typedef unsigned int mz_uint;
  1059. typedef long long mz_int64;
  1060. typedef unsigned long long mz_uint64;
  1061. typedef int mz_bool;
  1062. #define MZ_FALSE (0)
  1063. #define MZ_TRUE (1)
  1064. // An attempt to work around MSVC's spammy "warning C4127: conditional
  1065. // expression is constant" message.
  1066. #ifdef _MSC_VER
  1067. #define MZ_MACRO_END while (0, 0)
  1068. #else
  1069. #define MZ_MACRO_END while (0)
  1070. #endif
  1071. // ------------------- ZIP archive reading/writing
  1072. #ifndef MINIZ_NO_ARCHIVE_APIS
  1073. enum {
  1074. MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
  1075. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  1076. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  1077. };
  1078. typedef struct {
  1079. mz_uint32 m_file_index;
  1080. mz_uint32 m_central_dir_ofs;
  1081. mz_uint16 m_version_made_by;
  1082. mz_uint16 m_version_needed;
  1083. mz_uint16 m_bit_flag;
  1084. mz_uint16 m_method;
  1085. #ifndef MINIZ_NO_TIME
  1086. time_t m_time;
  1087. #endif
  1088. mz_uint32 m_crc32;
  1089. mz_uint64 m_comp_size;
  1090. mz_uint64 m_uncomp_size;
  1091. mz_uint16 m_internal_attr;
  1092. mz_uint32 m_external_attr;
  1093. mz_uint64 m_local_header_ofs;
  1094. mz_uint32 m_comment_size;
  1095. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  1096. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  1097. } mz_zip_archive_file_stat;
  1098. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
  1099. void *pBuf, size_t n);
  1100. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
  1101. const void *pBuf, size_t n);
  1102. struct mz_zip_internal_state_tag;
  1103. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  1104. typedef enum {
  1105. MZ_ZIP_MODE_INVALID = 0,
  1106. MZ_ZIP_MODE_READING = 1,
  1107. MZ_ZIP_MODE_WRITING = 2,
  1108. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  1109. } mz_zip_mode;
  1110. typedef struct mz_zip_archive_tag {
  1111. mz_uint64 m_archive_size;
  1112. mz_uint64 m_central_directory_file_ofs;
  1113. mz_uint m_total_files;
  1114. mz_zip_mode m_zip_mode;
  1115. mz_uint m_file_offset_alignment;
  1116. mz_alloc_func m_pAlloc;
  1117. mz_free_func m_pFree;
  1118. mz_realloc_func m_pRealloc;
  1119. void *m_pAlloc_opaque;
  1120. mz_file_read_func m_pRead;
  1121. mz_file_write_func m_pWrite;
  1122. void *m_pIO_opaque;
  1123. mz_zip_internal_state *m_pState;
  1124. } mz_zip_archive;
  1125. typedef enum {
  1126. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  1127. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  1128. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  1129. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  1130. } mz_zip_flags;
  1131. // ZIP archive reading
  1132. // Inits a ZIP archive reader.
  1133. // These functions read and validate the archive's central directory.
  1134. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  1135. mz_uint32 flags);
  1136. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  1137. size_t size, mz_uint32 flags);
  1138. #ifndef MINIZ_NO_STDIO
  1139. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  1140. mz_uint32 flags);
  1141. #endif
  1142. // Returns the total number of files in the archive.
  1143. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  1144. // Returns detailed information about an archive file entry.
  1145. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  1146. mz_zip_archive_file_stat *pStat);
  1147. // Determines if an archive file entry is a directory entry.
  1148. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  1149. mz_uint file_index);
  1150. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  1151. mz_uint file_index);
  1152. // Retrieves the filename of an archive file entry.
  1153. // Returns the number of bytes written to pFilename, or if filename_buf_size is
  1154. // 0 this function returns the number of bytes needed to fully store the
  1155. // filename.
  1156. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  1157. char *pFilename, mz_uint filename_buf_size);
  1158. // Attempts to locates a file in the archive's central directory.
  1159. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  1160. // Returns -1 if the file cannot be found.
  1161. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  1162. const char *pComment, mz_uint flags);
  1163. // Extracts a archive file to a memory buffer using no memory allocation.
  1164. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  1165. mz_uint file_index, void *pBuf,
  1166. size_t buf_size, mz_uint flags,
  1167. void *pUser_read_buf,
  1168. size_t user_read_buf_size);
  1169. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  1170. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  1171. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  1172. // Extracts a archive file to a memory buffer.
  1173. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  1174. void *pBuf, size_t buf_size,
  1175. mz_uint flags);
  1176. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  1177. const char *pFilename, void *pBuf,
  1178. size_t buf_size, mz_uint flags);
  1179. // Extracts a archive file to a dynamically allocated heap buffer.
  1180. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  1181. size_t *pSize, mz_uint flags);
  1182. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  1183. const char *pFilename, size_t *pSize,
  1184. mz_uint flags);
  1185. // Extracts a archive file using a callback function to output the file's data.
  1186. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  1187. mz_uint file_index,
  1188. mz_file_write_func pCallback,
  1189. void *pOpaque, mz_uint flags);
  1190. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  1191. const char *pFilename,
  1192. mz_file_write_func pCallback,
  1193. void *pOpaque, mz_uint flags);
  1194. #ifndef MINIZ_NO_STDIO
  1195. // Extracts a archive file to a disk file and sets its last accessed and
  1196. // modified times.
  1197. // This function only extracts files, not archive directory records.
  1198. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  1199. const char *pDst_filename, mz_uint flags);
  1200. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  1201. const char *pArchive_filename,
  1202. const char *pDst_filename,
  1203. mz_uint flags);
  1204. #endif
  1205. // Ends archive reading, freeing all allocations, and closing the input archive
  1206. // file if mz_zip_reader_init_file() was used.
  1207. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  1208. // ZIP archive writing
  1209. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1210. // Inits a ZIP archive writer.
  1211. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  1212. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  1213. size_t size_to_reserve_at_beginning,
  1214. size_t initial_allocation_size);
  1215. #ifndef MINIZ_NO_STDIO
  1216. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  1217. mz_uint64 size_to_reserve_at_beginning);
  1218. #endif
  1219. // Converts a ZIP archive reader object into a writer object, to allow efficient
  1220. // in-place file appends to occur on an existing archive.
  1221. // For archives opened using mz_zip_reader_init_file, pFilename must be the
  1222. // archive's filename so it can be reopened for writing. If the file can't be
  1223. // reopened, mz_zip_reader_end() will be called.
  1224. // For archives opened using mz_zip_reader_init_mem, the memory block must be
  1225. // growable using the realloc callback (which defaults to realloc unless you've
  1226. // overridden it).
  1227. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
  1228. // user provided m_pWrite function cannot be NULL.
  1229. // Note: In-place archive modification is not recommended unless you know what
  1230. // you're doing, because if execution stops or something goes wrong before
  1231. // the archive is finalized the file's central directory will be hosed.
  1232. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  1233. const char *pFilename);
  1234. // Adds the contents of a memory buffer to an archive. These functions record
  1235. // the current local time into the archive.
  1236. // To add a directory entry, call this method with an archive name ending in a
  1237. // forwardslash with empty buffer.
  1238. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1239. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1240. // just set to MZ_DEFAULT_COMPRESSION.
  1241. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  1242. const void *pBuf, size_t buf_size,
  1243. mz_uint level_and_flags);
  1244. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  1245. const char *pArchive_name, const void *pBuf,
  1246. size_t buf_size, const void *pComment,
  1247. mz_uint16 comment_size,
  1248. mz_uint level_and_flags, mz_uint64 uncomp_size,
  1249. mz_uint32 uncomp_crc32);
  1250. #ifndef MINIZ_NO_STDIO
  1251. // Adds the contents of a disk file to an archive. This function also records
  1252. // the disk file's modified time into the archive.
  1253. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1254. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1255. // just set to MZ_DEFAULT_COMPRESSION.
  1256. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  1257. const char *pSrc_filename, const void *pComment,
  1258. mz_uint16 comment_size, mz_uint level_and_flags);
  1259. #endif
  1260. // Adds a file to an archive by fully cloning the data from another archive.
  1261. // This function fully clones the source file's compressed data (no
  1262. // recompression), along with its full filename, extra data, and comment fields.
  1263. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  1264. mz_zip_archive *pSource_zip,
  1265. mz_uint file_index);
  1266. // Finalizes the archive by writing the central directory records followed by
  1267. // the end of central directory record.
  1268. // After an archive is finalized, the only valid call on the mz_zip_archive
  1269. // struct is mz_zip_writer_end().
  1270. // An archive must be manually finalized by calling this function for it to be
  1271. // valid.
  1272. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  1273. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  1274. size_t *pSize);
  1275. // Ends archive writing, freeing all allocations, and closing the output file if
  1276. // mz_zip_writer_init_file() was used.
  1277. // Note for the archive to be valid, it must have been finalized before ending.
  1278. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  1279. // Misc. high-level helper functions:
  1280. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
  1281. // appends a memory blob to a ZIP archive.
  1282. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
  1283. // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
  1284. // just set to MZ_DEFAULT_COMPRESSION.
  1285. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  1286. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  1287. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  1288. mz_uint level_and_flags);
  1289. // Reads a single file from an archive into a heap block.
  1290. // Returns NULL on failure.
  1291. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  1292. const char *pArchive_name,
  1293. size_t *pSize, mz_uint zip_flags);
  1294. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  1295. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  1296. // ------------------- Low-level Decompression API Definitions
  1297. // Decompression flags used by tinfl_decompress().
  1298. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
  1299. // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
  1300. // input is a raw deflate stream.
  1301. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
  1302. // beyond the end of the supplied input buffer. If clear, the input buffer
  1303. // contains all remaining input.
  1304. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
  1305. // enough to hold the entire decompressed stream. If clear, the output buffer is
  1306. // at least the size of the dictionary (typically 32KB).
  1307. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
  1308. // decompressed bytes.
  1309. enum {
  1310. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  1311. TINFL_FLAG_HAS_MORE_INPUT = 2,
  1312. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  1313. TINFL_FLAG_COMPUTE_ADLER32 = 8
  1314. };
  1315. // High level decompression functions:
  1316. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
  1317. // allocated via malloc().
  1318. // On entry:
  1319. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
  1320. // to decompress.
  1321. // On return:
  1322. // Function returns a pointer to the decompressed data, or NULL on failure.
  1323. // *pOut_len will be set to the decompressed data's size, which could be larger
  1324. // than src_buf_len on uncompressible data.
  1325. // The caller must call mz_free() on the returned block when it's no longer
  1326. // needed.
  1327. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1328. size_t *pOut_len, int flags);
  1329. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
  1330. // in memory.
  1331. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
  1332. // written on success.
  1333. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  1334. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1335. const void *pSrc_buf, size_t src_buf_len,
  1336. int flags);
  1337. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an
  1338. // internal 32KB buffer, and a user provided callback function will be called to
  1339. // flush the buffer.
  1340. // Returns 1 on success or 0 on failure.
  1341. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
  1342. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  1343. tinfl_put_buf_func_ptr pPut_buf_func,
  1344. void *pPut_buf_user, int flags);
  1345. struct tinfl_decompressor_tag;
  1346. typedef struct tinfl_decompressor_tag tinfl_decompressor;
  1347. // Max size of LZ dictionary.
  1348. #define TINFL_LZ_DICT_SIZE 32768
  1349. // Return status.
  1350. typedef enum {
  1351. TINFL_STATUS_BAD_PARAM = -3,
  1352. TINFL_STATUS_ADLER32_MISMATCH = -2,
  1353. TINFL_STATUS_FAILED = -1,
  1354. TINFL_STATUS_DONE = 0,
  1355. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  1356. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  1357. } tinfl_status;
  1358. // Initializes the decompressor to its initial state.
  1359. #define tinfl_init(r) \
  1360. do { \
  1361. (r)->m_state = 0; \
  1362. } \
  1363. MZ_MACRO_END
  1364. #define tinfl_get_adler32(r) (r)->m_check_adler32
  1365. // Main low-level decompressor coroutine function. This is the only function
  1366. // actually needed for decompression. All the other functions are just
  1367. // high-level helpers for improved usability.
  1368. // This is a universal API, i.e. it can be used as a building block to build any
  1369. // desired higher level decompression API. In the limit case, it can be called
  1370. // once per every byte input or output.
  1371. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  1372. const mz_uint8 *pIn_buf_next,
  1373. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  1374. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  1375. const mz_uint32 decomp_flags);
  1376. // Internal/private bits follow.
  1377. enum {
  1378. TINFL_MAX_HUFF_TABLES = 3,
  1379. TINFL_MAX_HUFF_SYMBOLS_0 = 288,
  1380. TINFL_MAX_HUFF_SYMBOLS_1 = 32,
  1381. TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  1382. TINFL_FAST_LOOKUP_BITS = 10,
  1383. TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  1384. };
  1385. typedef struct {
  1386. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  1387. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
  1388. m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  1389. } tinfl_huff_table;
  1390. #if MINIZ_HAS_64BIT_REGISTERS
  1391. #define TINFL_USE_64BIT_BITBUF 1
  1392. #endif
  1393. #if TINFL_USE_64BIT_BITBUF
  1394. typedef mz_uint64 tinfl_bit_buf_t;
  1395. #define TINFL_BITBUF_SIZE (64)
  1396. #else
  1397. typedef mz_uint32 tinfl_bit_buf_t;
  1398. #define TINFL_BITBUF_SIZE (32)
  1399. #endif
  1400. struct tinfl_decompressor_tag {
  1401. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
  1402. m_check_adler32, m_dist, m_counter, m_num_extra,
  1403. m_table_sizes[TINFL_MAX_HUFF_TABLES];
  1404. tinfl_bit_buf_t m_bit_buf;
  1405. size_t m_dist_from_out_buf_start;
  1406. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  1407. mz_uint8 m_raw_header[4],
  1408. m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  1409. };
  1410. // ------------------- Low-level Compression API Definitions
  1411. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
  1412. // slower, and raw/dynamic blocks will be output more frequently).
  1413. #define TDEFL_LESS_MEMORY 0
  1414. // tdefl_init() compression flags logically OR'd together (low 12 bits contain
  1415. // the max. number of probes per dictionary search):
  1416. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
  1417. // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
  1418. // compression), 4095=Huffman+LZ (slowest/best compression).
  1419. enum {
  1420. TDEFL_HUFFMAN_ONLY = 0,
  1421. TDEFL_DEFAULT_MAX_PROBES = 128,
  1422. TDEFL_MAX_PROBES_MASK = 0xFFF
  1423. };
  1424. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
  1425. // the deflate data, and the Adler-32 of the source data at the end. Otherwise,
  1426. // you'll get raw deflate data.
  1427. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
  1428. // when not writing zlib headers).
  1429. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
  1430. // efficient lazy parsing.
  1431. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
  1432. // initialization time to the minimum, but the output may vary from run to run
  1433. // given the same input (depending on the contents of memory).
  1434. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  1435. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  1436. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  1437. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  1438. // The low 12 bits are reserved to control the max # of hash probes per
  1439. // dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  1440. enum {
  1441. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  1442. TDEFL_COMPUTE_ADLER32 = 0x02000,
  1443. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  1444. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  1445. TDEFL_RLE_MATCHES = 0x10000,
  1446. TDEFL_FILTER_MATCHES = 0x20000,
  1447. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  1448. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  1449. };
  1450. // High level compression functions:
  1451. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
  1452. // allocated via malloc().
  1453. // On entry:
  1454. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  1455. // flags: The max match finder probes (default is 128) logically OR'd against
  1456. // the above flags. Higher probes are slower but improve compression.
  1457. // On return:
  1458. // Function returns a pointer to the compressed data, or NULL on failure.
  1459. // *pOut_len will be set to the compressed data's size, which could be larger
  1460. // than src_buf_len on uncompressible data.
  1461. // The caller must free() the returned block when it's no longer needed.
  1462. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  1463. size_t *pOut_len, int flags);
  1464. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in
  1465. // memory.
  1466. // Returns 0 on failure.
  1467. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  1468. const void *pSrc_buf, size_t src_buf_len,
  1469. int flags);
  1470. // Compresses an image to a compressed PNG file in memory.
  1471. // On entry:
  1472. // pImage, w, h, and num_chans describe the image to compress. num_chans may be
  1473. // 1, 2, 3, or 4.
  1474. // The image pitch in bytes per scanline will be w*num_chans. The leftmost
  1475. // pixel on the top scanline is stored first in memory.
  1476. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
  1477. // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  1478. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL
  1479. // apps).
  1480. // On return:
  1481. // Function returns a pointer to the compressed data, or NULL on failure.
  1482. // *pLen_out will be set to the size of the PNG image file.
  1483. // The caller must mz_free() the returned heap block (which will typically be
  1484. // larger than *pLen_out) when it's no longer needed.
  1485. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  1486. int h, int num_chans,
  1487. size_t *pLen_out,
  1488. mz_uint level, mz_bool flip);
  1489. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  1490. int num_chans, size_t *pLen_out);
  1491. // Output stream interface. The compressor uses this interface to write
  1492. // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  1493. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
  1494. void *pUser);
  1495. // tdefl_compress_mem_to_output() compresses a block to an output stream. The
  1496. // above helpers use this function internally.
  1497. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  1498. tdefl_put_buf_func_ptr pPut_buf_func,
  1499. void *pPut_buf_user, int flags);
  1500. enum {
  1501. TDEFL_MAX_HUFF_TABLES = 3,
  1502. TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
  1503. TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
  1504. TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
  1505. TDEFL_LZ_DICT_SIZE = 32768,
  1506. TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
  1507. TDEFL_MIN_MATCH_LEN = 3,
  1508. TDEFL_MAX_MATCH_LEN = 258
  1509. };
  1510. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
  1511. // output block (using static/fixed Huffman codes).
  1512. #if TDEFL_LESS_MEMORY
  1513. enum {
  1514. TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
  1515. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1516. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1517. TDEFL_LZ_HASH_BITS = 12,
  1518. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1519. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1520. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1521. };
  1522. #else
  1523. enum {
  1524. TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
  1525. TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
  1526. TDEFL_MAX_HUFF_SYMBOLS = 288,
  1527. TDEFL_LZ_HASH_BITS = 15,
  1528. TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
  1529. TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
  1530. TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
  1531. };
  1532. #endif
  1533. // The low-level tdefl functions below may be used directly if the above helper
  1534. // functions aren't flexible enough. The low-level functions don't make any heap
  1535. // allocations, unlike the above helper functions.
  1536. typedef enum {
  1537. TDEFL_STATUS_BAD_PARAM = -2,
  1538. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  1539. TDEFL_STATUS_OKAY = 0,
  1540. TDEFL_STATUS_DONE = 1
  1541. } tdefl_status;
  1542. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  1543. typedef enum {
  1544. TDEFL_NO_FLUSH = 0,
  1545. TDEFL_SYNC_FLUSH = 2,
  1546. TDEFL_FULL_FLUSH = 3,
  1547. TDEFL_FINISH = 4
  1548. } tdefl_flush;
  1549. // tdefl's compression state structure.
  1550. typedef struct {
  1551. tdefl_put_buf_func_ptr m_pPut_buf_func;
  1552. void *m_pPut_buf_user;
  1553. mz_uint m_flags, m_max_probes[2];
  1554. int m_greedy_parsing;
  1555. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  1556. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  1557. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
  1558. m_bit_buffer;
  1559. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
  1560. m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
  1561. m_wants_to_finish;
  1562. tdefl_status m_prev_return_status;
  1563. const void *m_pIn_buf;
  1564. void *m_pOut_buf;
  1565. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  1566. tdefl_flush m_flush;
  1567. const mz_uint8 *m_pSrc;
  1568. size_t m_src_buf_left, m_out_buf_ofs;
  1569. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  1570. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1571. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1572. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  1573. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  1574. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  1575. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  1576. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  1577. } tdefl_compressor;
  1578. // Initializes the compressor.
  1579. // There is no corresponding deinit() function because the tdefl API's do not
  1580. // dynamically allocate memory.
  1581. // pBut_buf_func: If NULL, output data will be supplied to the specified
  1582. // callback. In this case, the user should call the tdefl_compress_buffer() API
  1583. // for compression.
  1584. // If pBut_buf_func is NULL the user should always call the tdefl_compress()
  1585. // API.
  1586. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
  1587. // etc.)
  1588. tdefl_status tdefl_init(tdefl_compressor *d,
  1589. tdefl_put_buf_func_ptr pPut_buf_func,
  1590. void *pPut_buf_user, int flags);
  1591. // Compresses a block of data, consuming as much of the specified input buffer
  1592. // as possible, and writing as much compressed data to the specified output
  1593. // buffer as possible.
  1594. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  1595. size_t *pIn_buf_size, void *pOut_buf,
  1596. size_t *pOut_buf_size, tdefl_flush flush);
  1597. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
  1598. // non-NULL tdefl_put_buf_func_ptr.
  1599. // tdefl_compress_buffer() always consumes the entire input buffer.
  1600. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  1601. size_t in_buf_size, tdefl_flush flush);
  1602. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  1603. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  1604. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
  1605. // defined, because it uses some of its macros.
  1606. #ifndef MINIZ_NO_ZLIB_APIS
  1607. // Create tdefl_compress() flags given zlib-style compression parameters.
  1608. // level may range from [0,10] (where 10 is absolute max compression, but may be
  1609. // much slower on some files)
  1610. // window_bits may be -15 (raw deflate) or 15 (zlib)
  1611. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
  1612. // MZ_RLE, or MZ_FIXED
  1613. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  1614. int strategy);
  1615. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  1616. #ifdef __cplusplus
  1617. }
  1618. #endif
  1619. #endif // MINIZ_HEADER_INCLUDED
  1620. // ------------------- End of Header: Implementation follows. (If you only want
  1621. // the header, define MINIZ_HEADER_FILE_ONLY.)
  1622. #ifndef MINIZ_HEADER_FILE_ONLY
  1623. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
  1624. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
  1625. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
  1626. //#include <assert.h>
  1627. //#include <string.h>
  1628. #define MZ_ASSERT(x) assert(x)
  1629. #ifdef MINIZ_NO_MALLOC
  1630. #define MZ_MALLOC(x) NULL
  1631. #define MZ_FREE(x) (void)x, ((void)0)
  1632. #define MZ_REALLOC(p, x) NULL
  1633. #else
  1634. #define MZ_MALLOC(x) malloc(x)
  1635. #define MZ_FREE(x) free(x)
  1636. #define MZ_REALLOC(p, x) realloc(p, x)
  1637. #endif
  1638. #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
  1639. #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
  1640. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  1641. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1642. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  1643. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  1644. #else
  1645. #define MZ_READ_LE16(p) \
  1646. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1647. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  1648. #define MZ_READ_LE32(p) \
  1649. ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
  1650. ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
  1651. ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
  1652. ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  1653. #endif
  1654. #ifdef _MSC_VER
  1655. #define MZ_FORCEINLINE __forceinline
  1656. #elif defined(__GNUC__)
  1657. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  1658. #else
  1659. #define MZ_FORCEINLINE inline
  1660. #endif
  1661. #ifdef __cplusplus
  1662. extern "C" {
  1663. #endif
  1664. // ------------------- zlib-style API's
  1665. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
  1666. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
  1667. size_t block_len = buf_len % 5552;
  1668. if (!ptr) return MZ_ADLER32_INIT;
  1669. while (buf_len) {
  1670. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  1671. s1 += ptr[0], s2 += s1;
  1672. s1 += ptr[1], s2 += s1;
  1673. s1 += ptr[2], s2 += s1;
  1674. s1 += ptr[3], s2 += s1;
  1675. s1 += ptr[4], s2 += s1;
  1676. s1 += ptr[5], s2 += s1;
  1677. s1 += ptr[6], s2 += s1;
  1678. s1 += ptr[7], s2 += s1;
  1679. }
  1680. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1681. s1 %= 65521U, s2 %= 65521U;
  1682. buf_len -= block_len;
  1683. block_len = 5552;
  1684. }
  1685. return (s2 << 16) + s1;
  1686. }
  1687. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
  1688. // implementation that balances processor cache usage against speed":
  1689. // http://www.geocities.com/malbrain/
  1690. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
  1691. static const mz_uint32 s_crc32[16] = {
  1692. 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
  1693. 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
  1694. 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
  1695. mz_uint32 crcu32 = (mz_uint32)crc;
  1696. if (!ptr) return MZ_CRC32_INIT;
  1697. crcu32 = ~crcu32;
  1698. while (buf_len--) {
  1699. mz_uint8 b = *ptr++;
  1700. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
  1701. crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
  1702. }
  1703. return ~crcu32;
  1704. }
  1705. void mz_free(void *p) { MZ_FREE(p); }
  1706. #ifndef MINIZ_NO_ZLIB_APIS
  1707. static void *def_alloc_func(void *opaque, size_t items, size_t size) {
  1708. (void)opaque, (void)items, (void)size;
  1709. return MZ_MALLOC(items * size);
  1710. }
  1711. static void def_free_func(void *opaque, void *address) {
  1712. (void)opaque, (void)address;
  1713. MZ_FREE(address);
  1714. }
  1715. // static void *def_realloc_func(void *opaque, void *address, size_t items,
  1716. // size_t size) {
  1717. // (void)opaque, (void)address, (void)items, (void)size;
  1718. // return MZ_REALLOC(address, items * size);
  1719. //}
  1720. const char *mz_version(void) { return MZ_VERSION; }
  1721. int mz_deflateInit(mz_streamp pStream, int level) {
  1722. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
  1723. MZ_DEFAULT_STRATEGY);
  1724. }
  1725. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
  1726. int mem_level, int strategy) {
  1727. tdefl_compressor *pComp;
  1728. mz_uint comp_flags =
  1729. TDEFL_COMPUTE_ADLER32 |
  1730. tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  1731. if (!pStream) return MZ_STREAM_ERROR;
  1732. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
  1733. ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1734. (-window_bits != MZ_DEFAULT_WINDOW_BITS)))
  1735. return MZ_PARAM_ERROR;
  1736. pStream->data_type = 0;
  1737. pStream->adler = MZ_ADLER32_INIT;
  1738. pStream->msg = NULL;
  1739. pStream->reserved = 0;
  1740. pStream->total_in = 0;
  1741. pStream->total_out = 0;
  1742. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1743. if (!pStream->zfree) pStream->zfree = def_free_func;
  1744. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
  1745. sizeof(tdefl_compressor));
  1746. if (!pComp) return MZ_MEM_ERROR;
  1747. pStream->state = (struct mz_internal_state *)pComp;
  1748. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
  1749. mz_deflateEnd(pStream);
  1750. return MZ_PARAM_ERROR;
  1751. }
  1752. return MZ_OK;
  1753. }
  1754. int mz_deflateReset(mz_streamp pStream) {
  1755. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
  1756. (!pStream->zfree))
  1757. return MZ_STREAM_ERROR;
  1758. pStream->total_in = pStream->total_out = 0;
  1759. tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
  1760. ((tdefl_compressor *)pStream->state)->m_flags);
  1761. return MZ_OK;
  1762. }
  1763. int mz_deflate(mz_streamp pStream, int flush) {
  1764. size_t in_bytes, out_bytes;
  1765. mz_ulong orig_total_in, orig_total_out;
  1766. int mz_status = MZ_OK;
  1767. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
  1768. (!pStream->next_out))
  1769. return MZ_STREAM_ERROR;
  1770. if (!pStream->avail_out) return MZ_BUF_ERROR;
  1771. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1772. if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
  1773. TDEFL_STATUS_DONE)
  1774. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  1775. orig_total_in = pStream->total_in;
  1776. orig_total_out = pStream->total_out;
  1777. for (;;) {
  1778. tdefl_status defl_status;
  1779. in_bytes = pStream->avail_in;
  1780. out_bytes = pStream->avail_out;
  1781. defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
  1782. pStream->next_in, &in_bytes, pStream->next_out,
  1783. &out_bytes, (tdefl_flush)flush);
  1784. pStream->next_in += (mz_uint)in_bytes;
  1785. pStream->avail_in -= (mz_uint)in_bytes;
  1786. pStream->total_in += (mz_uint)in_bytes;
  1787. pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
  1788. pStream->next_out += (mz_uint)out_bytes;
  1789. pStream->avail_out -= (mz_uint)out_bytes;
  1790. pStream->total_out += (mz_uint)out_bytes;
  1791. if (defl_status < 0) {
  1792. mz_status = MZ_STREAM_ERROR;
  1793. break;
  1794. } else if (defl_status == TDEFL_STATUS_DONE) {
  1795. mz_status = MZ_STREAM_END;
  1796. break;
  1797. } else if (!pStream->avail_out)
  1798. break;
  1799. else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
  1800. if ((flush) || (pStream->total_in != orig_total_in) ||
  1801. (pStream->total_out != orig_total_out))
  1802. break;
  1803. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  1804. }
  1805. }
  1806. return mz_status;
  1807. }
  1808. int mz_deflateEnd(mz_streamp pStream) {
  1809. if (!pStream) return MZ_STREAM_ERROR;
  1810. if (pStream->state) {
  1811. pStream->zfree(pStream->opaque, pStream->state);
  1812. pStream->state = NULL;
  1813. }
  1814. return MZ_OK;
  1815. }
  1816. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
  1817. (void)pStream;
  1818. // This is really over conservative. (And lame, but it's actually pretty
  1819. // tricky to compute a true upper bound given the way tdefl's blocking works.)
  1820. return MZ_MAX(128 + (source_len * 110) / 100,
  1821. 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  1822. }
  1823. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
  1824. const unsigned char *pSource, mz_ulong source_len, int level) {
  1825. int status;
  1826. mz_stream stream;
  1827. memset(&stream, 0, sizeof(stream));
  1828. // In case mz_ulong is 64-bits (argh I hate longs).
  1829. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1830. stream.next_in = pSource;
  1831. stream.avail_in = (mz_uint32)source_len;
  1832. stream.next_out = pDest;
  1833. stream.avail_out = (mz_uint32)*pDest_len;
  1834. status = mz_deflateInit(&stream, level);
  1835. if (status != MZ_OK) return status;
  1836. status = mz_deflate(&stream, MZ_FINISH);
  1837. if (status != MZ_STREAM_END) {
  1838. mz_deflateEnd(&stream);
  1839. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1840. }
  1841. *pDest_len = stream.total_out;
  1842. return mz_deflateEnd(&stream);
  1843. }
  1844. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
  1845. const unsigned char *pSource, mz_ulong source_len) {
  1846. return mz_compress2(pDest, pDest_len, pSource, source_len,
  1847. MZ_DEFAULT_COMPRESSION);
  1848. }
  1849. mz_ulong mz_compressBound(mz_ulong source_len) {
  1850. return mz_deflateBound(NULL, source_len);
  1851. }
  1852. typedef struct {
  1853. tinfl_decompressor m_decomp;
  1854. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
  1855. int m_window_bits;
  1856. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1857. tinfl_status m_last_status;
  1858. } inflate_state;
  1859. int mz_inflateInit2(mz_streamp pStream, int window_bits) {
  1860. inflate_state *pDecomp;
  1861. if (!pStream) return MZ_STREAM_ERROR;
  1862. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
  1863. (-window_bits != MZ_DEFAULT_WINDOW_BITS))
  1864. return MZ_PARAM_ERROR;
  1865. pStream->data_type = 0;
  1866. pStream->adler = 0;
  1867. pStream->msg = NULL;
  1868. pStream->total_in = 0;
  1869. pStream->total_out = 0;
  1870. pStream->reserved = 0;
  1871. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1872. if (!pStream->zfree) pStream->zfree = def_free_func;
  1873. pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
  1874. sizeof(inflate_state));
  1875. if (!pDecomp) return MZ_MEM_ERROR;
  1876. pStream->state = (struct mz_internal_state *)pDecomp;
  1877. tinfl_init(&pDecomp->m_decomp);
  1878. pDecomp->m_dict_ofs = 0;
  1879. pDecomp->m_dict_avail = 0;
  1880. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1881. pDecomp->m_first_call = 1;
  1882. pDecomp->m_has_flushed = 0;
  1883. pDecomp->m_window_bits = window_bits;
  1884. return MZ_OK;
  1885. }
  1886. int mz_inflateInit(mz_streamp pStream) {
  1887. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1888. }
  1889. int mz_inflate(mz_streamp pStream, int flush) {
  1890. inflate_state *pState;
  1891. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1892. size_t in_bytes, out_bytes, orig_avail_in;
  1893. tinfl_status status;
  1894. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  1895. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1896. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
  1897. return MZ_STREAM_ERROR;
  1898. pState = (inflate_state *)pStream->state;
  1899. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1900. orig_avail_in = pStream->avail_in;
  1901. first_call = pState->m_first_call;
  1902. pState->m_first_call = 0;
  1903. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1904. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1905. pState->m_has_flushed |= (flush == MZ_FINISH);
  1906. if ((flush == MZ_FINISH) && (first_call)) {
  1907. // MZ_FINISH on the first call implies that the input and output buffers are
  1908. // large enough to hold the entire compressed/decompressed file.
  1909. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1910. in_bytes = pStream->avail_in;
  1911. out_bytes = pStream->avail_out;
  1912. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
  1913. pStream->next_out, pStream->next_out, &out_bytes,
  1914. decomp_flags);
  1915. pState->m_last_status = status;
  1916. pStream->next_in += (mz_uint)in_bytes;
  1917. pStream->avail_in -= (mz_uint)in_bytes;
  1918. pStream->total_in += (mz_uint)in_bytes;
  1919. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1920. pStream->next_out += (mz_uint)out_bytes;
  1921. pStream->avail_out -= (mz_uint)out_bytes;
  1922. pStream->total_out += (mz_uint)out_bytes;
  1923. if (status < 0)
  1924. return MZ_DATA_ERROR;
  1925. else if (status != TINFL_STATUS_DONE) {
  1926. pState->m_last_status = TINFL_STATUS_FAILED;
  1927. return MZ_BUF_ERROR;
  1928. }
  1929. return MZ_STREAM_END;
  1930. }
  1931. // flush != MZ_FINISH then we must assume there's more input.
  1932. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1933. if (pState->m_dict_avail) {
  1934. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1935. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1936. pStream->next_out += n;
  1937. pStream->avail_out -= n;
  1938. pStream->total_out += n;
  1939. pState->m_dict_avail -= n;
  1940. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1941. return ((pState->m_last_status == TINFL_STATUS_DONE) &&
  1942. (!pState->m_dict_avail))
  1943. ? MZ_STREAM_END
  1944. : MZ_OK;
  1945. }
  1946. for (;;) {
  1947. in_bytes = pStream->avail_in;
  1948. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1949. status = tinfl_decompress(
  1950. &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
  1951. pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1952. pState->m_last_status = status;
  1953. pStream->next_in += (mz_uint)in_bytes;
  1954. pStream->avail_in -= (mz_uint)in_bytes;
  1955. pStream->total_in += (mz_uint)in_bytes;
  1956. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1957. pState->m_dict_avail = (mz_uint)out_bytes;
  1958. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1959. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1960. pStream->next_out += n;
  1961. pStream->avail_out -= n;
  1962. pStream->total_out += n;
  1963. pState->m_dict_avail -= n;
  1964. pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1965. if (status < 0)
  1966. return MZ_DATA_ERROR; // Stream is corrupted (there could be some
  1967. // uncompressed data left in the output dictionary -
  1968. // oh well).
  1969. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1970. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
  1971. // without supplying more input or by setting flush
  1972. // to MZ_FINISH.
  1973. else if (flush == MZ_FINISH) {
  1974. // The output buffer MUST be large to hold the remaining uncompressed data
  1975. // when flush==MZ_FINISH.
  1976. if (status == TINFL_STATUS_DONE)
  1977. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1978. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
  1979. // at least 1 more byte on the way. If there's no more room left in the
  1980. // output buffer then something is wrong.
  1981. else if (!pStream->avail_out)
  1982. return MZ_BUF_ERROR;
  1983. } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
  1984. (!pStream->avail_out) || (pState->m_dict_avail))
  1985. break;
  1986. }
  1987. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
  1988. ? MZ_STREAM_END
  1989. : MZ_OK;
  1990. }
  1991. int mz_inflateEnd(mz_streamp pStream) {
  1992. if (!pStream) return MZ_STREAM_ERROR;
  1993. if (pStream->state) {
  1994. pStream->zfree(pStream->opaque, pStream->state);
  1995. pStream->state = NULL;
  1996. }
  1997. return MZ_OK;
  1998. }
  1999. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
  2000. const unsigned char *pSource, mz_ulong source_len) {
  2001. mz_stream stream;
  2002. int status;
  2003. memset(&stream, 0, sizeof(stream));
  2004. // In case mz_ulong is 64-bits (argh I hate longs).
  2005. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  2006. stream.next_in = pSource;
  2007. stream.avail_in = (mz_uint32)source_len;
  2008. stream.next_out = pDest;
  2009. stream.avail_out = (mz_uint32)*pDest_len;
  2010. status = mz_inflateInit(&stream);
  2011. if (status != MZ_OK) return status;
  2012. status = mz_inflate(&stream, MZ_FINISH);
  2013. if (status != MZ_STREAM_END) {
  2014. mz_inflateEnd(&stream);
  2015. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
  2016. : status;
  2017. }
  2018. *pDest_len = stream.total_out;
  2019. return mz_inflateEnd(&stream);
  2020. }
  2021. const char *mz_error(int err) {
  2022. static struct {
  2023. int m_err;
  2024. const char *m_pDesc;
  2025. } s_error_descs[] = {{MZ_OK, ""},
  2026. {MZ_STREAM_END, "stream end"},
  2027. {MZ_NEED_DICT, "need dictionary"},
  2028. {MZ_ERRNO, "file error"},
  2029. {MZ_STREAM_ERROR, "stream error"},
  2030. {MZ_DATA_ERROR, "data error"},
  2031. {MZ_MEM_ERROR, "out of memory"},
  2032. {MZ_BUF_ERROR, "buf error"},
  2033. {MZ_VERSION_ERROR, "version error"},
  2034. {MZ_PARAM_ERROR, "parameter error"}};
  2035. mz_uint i;
  2036. for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
  2037. if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  2038. return NULL;
  2039. }
  2040. #endif // MINIZ_NO_ZLIB_APIS
  2041. // ------------------- Low-level Decompression (completely independent from all
  2042. // compression API's)
  2043. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  2044. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  2045. #define TINFL_CR_BEGIN \
  2046. switch (r->m_state) { \
  2047. case 0:
  2048. #define TINFL_CR_RETURN(state_index, result) \
  2049. do { \
  2050. status = result; \
  2051. r->m_state = state_index; \
  2052. goto common_exit; \
  2053. case state_index:; \
  2054. } \
  2055. MZ_MACRO_END
  2056. #define TINFL_CR_RETURN_FOREVER(state_index, result) \
  2057. do { \
  2058. for (;;) { \
  2059. TINFL_CR_RETURN(state_index, result); \
  2060. } \
  2061. } \
  2062. MZ_MACRO_END
  2063. #define TINFL_CR_FINISH }
  2064. // TODO: If the caller has indicated that there's no more input, and we attempt
  2065. // to read beyond the input buf, then something is wrong with the input because
  2066. // the inflator never
  2067. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
  2068. // the stream with 0's in this scenario.
  2069. #define TINFL_GET_BYTE(state_index, c) \
  2070. do { \
  2071. if (pIn_buf_cur >= pIn_buf_end) { \
  2072. for (;;) { \
  2073. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  2074. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  2075. if (pIn_buf_cur < pIn_buf_end) { \
  2076. c = *pIn_buf_cur++; \
  2077. break; \
  2078. } \
  2079. } else { \
  2080. c = 0; \
  2081. break; \
  2082. } \
  2083. } \
  2084. } else \
  2085. c = *pIn_buf_cur++; \
  2086. } \
  2087. MZ_MACRO_END
  2088. #define TINFL_NEED_BITS(state_index, n) \
  2089. do { \
  2090. mz_uint c; \
  2091. TINFL_GET_BYTE(state_index, c); \
  2092. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2093. num_bits += 8; \
  2094. } while (num_bits < (mz_uint)(n))
  2095. #define TINFL_SKIP_BITS(state_index, n) \
  2096. do { \
  2097. if (num_bits < (mz_uint)(n)) { \
  2098. TINFL_NEED_BITS(state_index, n); \
  2099. } \
  2100. bit_buf >>= (n); \
  2101. num_bits -= (n); \
  2102. } \
  2103. MZ_MACRO_END
  2104. #define TINFL_GET_BITS(state_index, b, n) \
  2105. do { \
  2106. if (num_bits < (mz_uint)(n)) { \
  2107. TINFL_NEED_BITS(state_index, n); \
  2108. } \
  2109. b = bit_buf & ((1 << (n)) - 1); \
  2110. bit_buf >>= (n); \
  2111. num_bits -= (n); \
  2112. } \
  2113. MZ_MACRO_END
  2114. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
  2115. // remaining in the input buffer falls below 2.
  2116. // It reads just enough bytes from the input stream that are needed to decode
  2117. // the next Huffman code (and absolutely no more). It works by trying to fully
  2118. // decode a
  2119. // Huffman code by using whatever bits are currently present in the bit buffer.
  2120. // If this fails, it reads another byte, and tries again until it succeeds or
  2121. // until the
  2122. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  2123. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  2124. do { \
  2125. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  2126. if (temp >= 0) { \
  2127. code_len = temp >> 9; \
  2128. if ((code_len) && (num_bits >= code_len)) break; \
  2129. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  2130. code_len = TINFL_FAST_LOOKUP_BITS; \
  2131. do { \
  2132. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2133. } while ((temp < 0) && (num_bits >= (code_len + 1))); \
  2134. if (temp >= 0) break; \
  2135. } \
  2136. TINFL_GET_BYTE(state_index, c); \
  2137. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  2138. num_bits += 8; \
  2139. } while (num_bits < 15);
  2140. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
  2141. // than you would initially expect because the zlib API expects the decompressor
  2142. // to never read
  2143. // beyond the final byte of the deflate stream. (In other words, when this macro
  2144. // wants to read another byte from the input, it REALLY needs another byte in
  2145. // order to fully
  2146. // decode the next Huffman code.) Handling this properly is particularly
  2147. // important on raw deflate (non-zlib) streams, which aren't followed by a byte
  2148. // aligned adler-32.
  2149. // The slow path is only executed at the very end of the input buffer.
  2150. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
  2151. do { \
  2152. int temp; \
  2153. mz_uint code_len, c; \
  2154. if (num_bits < 15) { \
  2155. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  2156. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  2157. } else { \
  2158. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
  2159. (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
  2160. pIn_buf_cur += 2; \
  2161. num_bits += 16; \
  2162. } \
  2163. } \
  2164. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
  2165. 0) \
  2166. code_len = temp >> 9, temp &= 511; \
  2167. else { \
  2168. code_len = TINFL_FAST_LOOKUP_BITS; \
  2169. do { \
  2170. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  2171. } while (temp < 0); \
  2172. } \
  2173. sym = temp; \
  2174. bit_buf >>= code_len; \
  2175. num_bits -= code_len; \
  2176. } \
  2177. MZ_MACRO_END
  2178. tinfl_status tinfl_decompress(tinfl_decompressor *r,
  2179. const mz_uint8 *pIn_buf_next,
  2180. size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
  2181. mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
  2182. const mz_uint32 decomp_flags) {
  2183. static const int s_length_base[31] = {
  2184. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  2185. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  2186. static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
  2187. 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
  2188. 4, 4, 5, 5, 5, 5, 0, 0, 0};
  2189. static const int s_dist_base[32] = {
  2190. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
  2191. 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
  2192. 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
  2193. static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  2194. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  2195. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
  2196. static const mz_uint8 s_length_dezigzag[19] = {
  2197. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2198. static const int s_min_table_sizes[3] = {257, 1, 4};
  2199. tinfl_status status = TINFL_STATUS_FAILED;
  2200. mz_uint32 num_bits, dist, counter, num_extra;
  2201. tinfl_bit_buf_t bit_buf;
  2202. const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end =
  2203. pIn_buf_next + *pIn_buf_size;
  2204. mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end =
  2205. pOut_buf_next + *pOut_buf_size;
  2206. size_t out_buf_size_mask =
  2207. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
  2208. ? (size_t)-1
  2209. : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
  2210. dist_from_out_buf_start;
  2211. // Ensure the output buffer's size is a power of 2, unless the output buffer
  2212. // is large enough to hold the entire output file (in which case it doesn't
  2213. // matter).
  2214. if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
  2215. (pOut_buf_next < pOut_buf_start)) {
  2216. *pIn_buf_size = *pOut_buf_size = 0;
  2217. return TINFL_STATUS_BAD_PARAM;
  2218. }
  2219. num_bits = r->m_num_bits;
  2220. bit_buf = r->m_bit_buf;
  2221. dist = r->m_dist;
  2222. counter = r->m_counter;
  2223. num_extra = r->m_num_extra;
  2224. dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  2225. TINFL_CR_BEGIN
  2226. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
  2227. r->m_z_adler32 = r->m_check_adler32 = 1;
  2228. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2229. TINFL_GET_BYTE(1, r->m_zhdr0);
  2230. TINFL_GET_BYTE(2, r->m_zhdr1);
  2231. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
  2232. (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  2233. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  2234. counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
  2235. ((out_buf_size_mask + 1) <
  2236. (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4)))));
  2237. if (counter) {
  2238. TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
  2239. }
  2240. }
  2241. do {
  2242. TINFL_GET_BITS(3, r->m_final, 3);
  2243. r->m_type = r->m_final >> 1;
  2244. if (r->m_type == 0) {
  2245. TINFL_SKIP_BITS(5, num_bits & 7);
  2246. for (counter = 0; counter < 4; ++counter) {
  2247. if (num_bits)
  2248. TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
  2249. else
  2250. TINFL_GET_BYTE(7, r->m_raw_header[counter]);
  2251. }
  2252. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
  2253. (mz_uint)(0xFFFF ^
  2254. (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
  2255. TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
  2256. }
  2257. while ((counter) && (num_bits)) {
  2258. TINFL_GET_BITS(51, dist, 8);
  2259. while (pOut_buf_cur >= pOut_buf_end) {
  2260. TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
  2261. }
  2262. *pOut_buf_cur++ = (mz_uint8)dist;
  2263. counter--;
  2264. }
  2265. while (counter) {
  2266. size_t n;
  2267. while (pOut_buf_cur >= pOut_buf_end) {
  2268. TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
  2269. }
  2270. while (pIn_buf_cur >= pIn_buf_end) {
  2271. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
  2272. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  2273. } else {
  2274. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  2275. }
  2276. }
  2277. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
  2278. (size_t)(pIn_buf_end - pIn_buf_cur)),
  2279. counter);
  2280. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
  2281. pIn_buf_cur += n;
  2282. pOut_buf_cur += n;
  2283. counter -= (mz_uint)n;
  2284. }
  2285. } else if (r->m_type == 3) {
  2286. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  2287. } else {
  2288. if (r->m_type == 1) {
  2289. mz_uint8 *p = r->m_tables[0].m_code_size;
  2290. mz_uint i;
  2291. r->m_table_sizes[0] = 288;
  2292. r->m_table_sizes[1] = 32;
  2293. TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  2294. for (i = 0; i <= 143; ++i) *p++ = 8;
  2295. for (; i <= 255; ++i) *p++ = 9;
  2296. for (; i <= 279; ++i) *p++ = 7;
  2297. for (; i <= 287; ++i) *p++ = 8;
  2298. } else {
  2299. for (counter = 0; counter < 3; counter++) {
  2300. TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
  2301. r->m_table_sizes[counter] += s_min_table_sizes[counter];
  2302. }
  2303. MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
  2304. for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
  2305. mz_uint s;
  2306. TINFL_GET_BITS(14, s, 3);
  2307. r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
  2308. }
  2309. r->m_table_sizes[2] = 19;
  2310. }
  2311. for (; (int)r->m_type >= 0; r->m_type--) {
  2312. int tree_next, tree_cur;
  2313. tinfl_huff_table *pTable;
  2314. mz_uint i, j, used_syms, total, sym_index, next_code[17],
  2315. total_syms[16];
  2316. pTable = &r->m_tables[r->m_type];
  2317. MZ_CLEAR_OBJ(total_syms);
  2318. MZ_CLEAR_OBJ(pTable->m_look_up);
  2319. MZ_CLEAR_OBJ(pTable->m_tree);
  2320. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
  2321. total_syms[pTable->m_code_size[i]]++;
  2322. used_syms = 0, total = 0;
  2323. next_code[0] = next_code[1] = 0;
  2324. for (i = 1; i <= 15; ++i) {
  2325. used_syms += total_syms[i];
  2326. next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
  2327. }
  2328. if ((65536 != total) && (used_syms > 1)) {
  2329. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  2330. }
  2331. for (tree_next = -1, sym_index = 0;
  2332. sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
  2333. mz_uint rev_code = 0, l, cur_code,
  2334. code_size = pTable->m_code_size[sym_index];
  2335. if (!code_size) continue;
  2336. cur_code = next_code[code_size]++;
  2337. for (l = code_size; l > 0; l--, cur_code >>= 1)
  2338. rev_code = (rev_code << 1) | (cur_code & 1);
  2339. if (code_size <= TINFL_FAST_LOOKUP_BITS) {
  2340. mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
  2341. while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
  2342. pTable->m_look_up[rev_code] = k;
  2343. rev_code += (1 << code_size);
  2344. }
  2345. continue;
  2346. }
  2347. if (0 ==
  2348. (tree_cur = pTable->m_look_up[rev_code &
  2349. (TINFL_FAST_LOOKUP_SIZE - 1)])) {
  2350. pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
  2351. (mz_int16)tree_next;
  2352. tree_cur = tree_next;
  2353. tree_next -= 2;
  2354. }
  2355. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  2356. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
  2357. tree_cur -= ((rev_code >>= 1) & 1);
  2358. if (!pTable->m_tree[-tree_cur - 1]) {
  2359. pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
  2360. tree_cur = tree_next;
  2361. tree_next -= 2;
  2362. } else
  2363. tree_cur = pTable->m_tree[-tree_cur - 1];
  2364. }
  2365. tree_cur -= ((rev_code >>= 1) & 1);
  2366. pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  2367. }
  2368. if (r->m_type == 2) {
  2369. for (counter = 0;
  2370. counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
  2371. mz_uint s;
  2372. TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
  2373. if (dist < 16) {
  2374. r->m_len_codes[counter++] = (mz_uint8)dist;
  2375. continue;
  2376. }
  2377. if ((dist == 16) && (!counter)) {
  2378. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  2379. }
  2380. num_extra = "\02\03\07"[dist - 16];
  2381. TINFL_GET_BITS(18, s, num_extra);
  2382. s += "\03\03\013"[dist - 16];
  2383. TINFL_MEMSET(r->m_len_codes + counter,
  2384. (dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
  2385. counter += s;
  2386. }
  2387. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
  2388. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  2389. }
  2390. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
  2391. r->m_table_sizes[0]);
  2392. TINFL_MEMCPY(r->m_tables[1].m_code_size,
  2393. r->m_len_codes + r->m_table_sizes[0],
  2394. r->m_table_sizes[1]);
  2395. }
  2396. }
  2397. for (;;) {
  2398. mz_uint8 *pSrc;
  2399. for (;;) {
  2400. if (((pIn_buf_end - pIn_buf_cur) < 4) ||
  2401. ((pOut_buf_end - pOut_buf_cur) < 2)) {
  2402. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  2403. if (counter >= 256) break;
  2404. while (pOut_buf_cur >= pOut_buf_end) {
  2405. TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
  2406. }
  2407. *pOut_buf_cur++ = (mz_uint8)counter;
  2408. } else {
  2409. int sym2;
  2410. mz_uint code_len;
  2411. #if TINFL_USE_64BIT_BITBUF
  2412. if (num_bits < 30) {
  2413. bit_buf |=
  2414. (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
  2415. pIn_buf_cur += 4;
  2416. num_bits += 32;
  2417. }
  2418. #else
  2419. if (num_bits < 15) {
  2420. bit_buf |=
  2421. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2422. pIn_buf_cur += 2;
  2423. num_bits += 16;
  2424. }
  2425. #endif
  2426. if ((sym2 =
  2427. r->m_tables[0]
  2428. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2429. 0)
  2430. code_len = sym2 >> 9;
  2431. else {
  2432. code_len = TINFL_FAST_LOOKUP_BITS;
  2433. do {
  2434. sym2 = r->m_tables[0]
  2435. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2436. } while (sym2 < 0);
  2437. }
  2438. counter = sym2;
  2439. bit_buf >>= code_len;
  2440. num_bits -= code_len;
  2441. if (counter & 256) break;
  2442. #if !TINFL_USE_64BIT_BITBUF
  2443. if (num_bits < 15) {
  2444. bit_buf |=
  2445. (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
  2446. pIn_buf_cur += 2;
  2447. num_bits += 16;
  2448. }
  2449. #endif
  2450. if ((sym2 =
  2451. r->m_tables[0]
  2452. .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
  2453. 0)
  2454. code_len = sym2 >> 9;
  2455. else {
  2456. code_len = TINFL_FAST_LOOKUP_BITS;
  2457. do {
  2458. sym2 = r->m_tables[0]
  2459. .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
  2460. } while (sym2 < 0);
  2461. }
  2462. bit_buf >>= code_len;
  2463. num_bits -= code_len;
  2464. pOut_buf_cur[0] = (mz_uint8)counter;
  2465. if (sym2 & 256) {
  2466. pOut_buf_cur++;
  2467. counter = sym2;
  2468. break;
  2469. }
  2470. pOut_buf_cur[1] = (mz_uint8)sym2;
  2471. pOut_buf_cur += 2;
  2472. }
  2473. }
  2474. if ((counter &= 511) == 256) break;
  2475. num_extra = s_length_extra[counter - 257];
  2476. counter = s_length_base[counter - 257];
  2477. if (num_extra) {
  2478. mz_uint extra_bits;
  2479. TINFL_GET_BITS(25, extra_bits, num_extra);
  2480. counter += extra_bits;
  2481. }
  2482. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  2483. num_extra = s_dist_extra[dist];
  2484. dist = s_dist_base[dist];
  2485. if (num_extra) {
  2486. mz_uint extra_bits;
  2487. TINFL_GET_BITS(27, extra_bits, num_extra);
  2488. dist += extra_bits;
  2489. }
  2490. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  2491. if ((dist > dist_from_out_buf_start) &&
  2492. (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
  2493. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  2494. }
  2495. pSrc = pOut_buf_start +
  2496. ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  2497. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
  2498. while (counter--) {
  2499. while (pOut_buf_cur >= pOut_buf_end) {
  2500. TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
  2501. }
  2502. *pOut_buf_cur++ =
  2503. pOut_buf_start[(dist_from_out_buf_start++ - dist) &
  2504. out_buf_size_mask];
  2505. }
  2506. continue;
  2507. }
  2508. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2509. else if ((counter >= 9) && (counter <= dist)) {
  2510. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  2511. do {
  2512. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  2513. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  2514. pOut_buf_cur += 8;
  2515. } while ((pSrc += 8) < pSrc_end);
  2516. if ((counter &= 7) < 3) {
  2517. if (counter) {
  2518. pOut_buf_cur[0] = pSrc[0];
  2519. if (counter > 1) pOut_buf_cur[1] = pSrc[1];
  2520. pOut_buf_cur += counter;
  2521. }
  2522. continue;
  2523. }
  2524. }
  2525. #endif
  2526. do {
  2527. pOut_buf_cur[0] = pSrc[0];
  2528. pOut_buf_cur[1] = pSrc[1];
  2529. pOut_buf_cur[2] = pSrc[2];
  2530. pOut_buf_cur += 3;
  2531. pSrc += 3;
  2532. } while ((int)(counter -= 3) > 2);
  2533. if ((int)counter > 0) {
  2534. pOut_buf_cur[0] = pSrc[0];
  2535. if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1];
  2536. pOut_buf_cur += counter;
  2537. }
  2538. }
  2539. }
  2540. } while (!(r->m_final & 1));
  2541. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
  2542. TINFL_SKIP_BITS(32, num_bits & 7);
  2543. for (counter = 0; counter < 4; ++counter) {
  2544. mz_uint s;
  2545. if (num_bits)
  2546. TINFL_GET_BITS(41, s, 8);
  2547. else
  2548. TINFL_GET_BYTE(42, s);
  2549. r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
  2550. }
  2551. }
  2552. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  2553. TINFL_CR_FINISH
  2554. common_exit:
  2555. r->m_num_bits = num_bits;
  2556. r->m_bit_buf = bit_buf;
  2557. r->m_dist = dist;
  2558. r->m_counter = counter;
  2559. r->m_num_extra = num_extra;
  2560. r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  2561. *pIn_buf_size = pIn_buf_cur - pIn_buf_next;
  2562. *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  2563. if ((decomp_flags &
  2564. (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
  2565. (status >= 0)) {
  2566. const mz_uint8 *ptr = pOut_buf_next;
  2567. size_t buf_len = *pOut_buf_size;
  2568. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
  2569. s2 = r->m_check_adler32 >> 16;
  2570. size_t block_len = buf_len % 5552;
  2571. while (buf_len) {
  2572. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  2573. s1 += ptr[0], s2 += s1;
  2574. s1 += ptr[1], s2 += s1;
  2575. s1 += ptr[2], s2 += s1;
  2576. s1 += ptr[3], s2 += s1;
  2577. s1 += ptr[4], s2 += s1;
  2578. s1 += ptr[5], s2 += s1;
  2579. s1 += ptr[6], s2 += s1;
  2580. s1 += ptr[7], s2 += s1;
  2581. }
  2582. for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  2583. s1 %= 65521U, s2 %= 65521U;
  2584. buf_len -= block_len;
  2585. block_len = 5552;
  2586. }
  2587. r->m_check_adler32 = (s2 << 16) + s1;
  2588. if ((status == TINFL_STATUS_DONE) &&
  2589. (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
  2590. (r->m_check_adler32 != r->m_z_adler32))
  2591. status = TINFL_STATUS_ADLER32_MISMATCH;
  2592. }
  2593. return status;
  2594. }
  2595. // Higher level helper functions.
  2596. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  2597. size_t *pOut_len, int flags) {
  2598. tinfl_decompressor decomp;
  2599. void *pBuf = NULL, *pNew_buf;
  2600. size_t src_buf_ofs = 0, out_buf_capacity = 0;
  2601. *pOut_len = 0;
  2602. tinfl_init(&decomp);
  2603. for (;;) {
  2604. size_t src_buf_size = src_buf_len - src_buf_ofs,
  2605. dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  2606. tinfl_status status = tinfl_decompress(
  2607. &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
  2608. (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
  2609. &dst_buf_size,
  2610. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2611. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2612. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
  2613. MZ_FREE(pBuf);
  2614. *pOut_len = 0;
  2615. return NULL;
  2616. }
  2617. src_buf_ofs += src_buf_size;
  2618. *pOut_len += dst_buf_size;
  2619. if (status == TINFL_STATUS_DONE) break;
  2620. new_out_buf_capacity = out_buf_capacity * 2;
  2621. if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  2622. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  2623. if (!pNew_buf) {
  2624. MZ_FREE(pBuf);
  2625. *pOut_len = 0;
  2626. return NULL;
  2627. }
  2628. pBuf = pNew_buf;
  2629. out_buf_capacity = new_out_buf_capacity;
  2630. }
  2631. return pBuf;
  2632. }
  2633. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  2634. const void *pSrc_buf, size_t src_buf_len,
  2635. int flags) {
  2636. tinfl_decompressor decomp;
  2637. tinfl_status status;
  2638. tinfl_init(&decomp);
  2639. status =
  2640. tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
  2641. (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
  2642. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
  2643. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  2644. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
  2645. : out_buf_len;
  2646. }
  2647. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
  2648. tinfl_put_buf_func_ptr pPut_buf_func,
  2649. void *pPut_buf_user, int flags) {
  2650. int result = 0;
  2651. tinfl_decompressor decomp;
  2652. mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
  2653. size_t in_buf_ofs = 0, dict_ofs = 0;
  2654. if (!pDict) return TINFL_STATUS_FAILED;
  2655. tinfl_init(&decomp);
  2656. for (;;) {
  2657. size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
  2658. dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  2659. tinfl_status status =
  2660. tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
  2661. &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  2662. (flags & ~(TINFL_FLAG_HAS_MORE_INPUT |
  2663. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  2664. in_buf_ofs += in_buf_size;
  2665. if ((dst_buf_size) &&
  2666. (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  2667. break;
  2668. if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
  2669. result = (status == TINFL_STATUS_DONE);
  2670. break;
  2671. }
  2672. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  2673. }
  2674. MZ_FREE(pDict);
  2675. *pIn_buf_size = in_buf_ofs;
  2676. return result;
  2677. }
  2678. // ------------------- Low-level Compression (independent from all decompression
  2679. // API's)
  2680. // Purposely making these tables static for faster init and thread safety.
  2681. static const mz_uint16 s_tdefl_len_sym[256] = {
  2682. 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
  2683. 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
  2684. 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
  2685. 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
  2686. 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
  2687. 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
  2688. 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
  2689. 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
  2690. 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
  2691. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
  2692. 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
  2693. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
  2694. 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
  2695. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  2696. 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
  2697. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2698. 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
  2699. 285};
  2700. static const mz_uint8 s_tdefl_len_extra[256] = {
  2701. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
  2702. 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  2703. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  2704. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2705. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  2706. 4, 4, 4, 4, 4, 4, 4, 4, 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, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2708. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2709. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2710. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  2711. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
  2712. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  2713. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  2714. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
  2715. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  2716. 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2717. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2718. 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2719. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
  2720. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2721. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2722. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  2723. 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2724. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2725. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  2726. 15, 15, 15, 15, 15, 15, 15, 15, 15, 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, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2730. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2731. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2732. 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
  2733. 16, 16, 16, 16, 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, 17,
  2736. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2737. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2738. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
  2739. 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
  2740. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  2741. 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,
  2742. 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,
  2743. 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,
  2744. 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,
  2745. 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,
  2746. 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,
  2747. 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,
  2748. 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,
  2749. 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,
  2750. 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,
  2751. 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,
  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, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  2758. 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,
  2759. 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,
  2760. 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,
  2761. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
  2762. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  2763. 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
  2764. 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
  2765. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  2766. 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2767. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  2768. 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  2769. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
  2770. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  2771. 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
  2772. 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
  2773. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  2774. 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2775. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2776. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  2777. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
  2778. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
  2779. // values.
  2780. typedef struct {
  2781. mz_uint16 m_key, m_sym_index;
  2782. } tdefl_sym_freq;
  2783. static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
  2784. tdefl_sym_freq *pSyms0,
  2785. tdefl_sym_freq *pSyms1) {
  2786. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  2787. tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  2788. MZ_CLEAR_OBJ(hist);
  2789. for (i = 0; i < num_syms; i++) {
  2790. mz_uint freq = pSyms0[i].m_key;
  2791. hist[freq & 0xFF]++;
  2792. hist[256 + ((freq >> 8) & 0xFF)]++;
  2793. }
  2794. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  2795. total_passes--;
  2796. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
  2797. const mz_uint32 *pHist = &hist[pass << 8];
  2798. mz_uint offsets[256], cur_ofs = 0;
  2799. for (i = 0; i < 256; i++) {
  2800. offsets[i] = cur_ofs;
  2801. cur_ofs += pHist[i];
  2802. }
  2803. for (i = 0; i < num_syms; i++)
  2804. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
  2805. pCur_syms[i];
  2806. {
  2807. tdefl_sym_freq *t = pCur_syms;
  2808. pCur_syms = pNew_syms;
  2809. pNew_syms = t;
  2810. }
  2811. }
  2812. return pCur_syms;
  2813. }
  2814. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
  2815. // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
  2816. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
  2817. int root, leaf, next, avbl, used, dpth;
  2818. if (n == 0)
  2819. return;
  2820. else if (n == 1) {
  2821. A[0].m_key = 1;
  2822. return;
  2823. }
  2824. A[0].m_key += A[1].m_key;
  2825. root = 0;
  2826. leaf = 2;
  2827. for (next = 1; next < n - 1; next++) {
  2828. if (leaf >= n || A[root].m_key < A[leaf].m_key) {
  2829. A[next].m_key = A[root].m_key;
  2830. A[root++].m_key = (mz_uint16)next;
  2831. } else
  2832. A[next].m_key = A[leaf++].m_key;
  2833. if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
  2834. A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
  2835. A[root++].m_key = (mz_uint16)next;
  2836. } else
  2837. A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  2838. }
  2839. A[n - 2].m_key = 0;
  2840. for (next = n - 3; next >= 0; next--)
  2841. A[next].m_key = A[A[next].m_key].m_key + 1;
  2842. avbl = 1;
  2843. used = dpth = 0;
  2844. root = n - 2;
  2845. next = n - 1;
  2846. while (avbl > 0) {
  2847. while (root >= 0 && (int)A[root].m_key == dpth) {
  2848. used++;
  2849. root--;
  2850. }
  2851. while (avbl > used) {
  2852. A[next--].m_key = (mz_uint16)(dpth);
  2853. avbl--;
  2854. }
  2855. avbl = 2 * used;
  2856. dpth++;
  2857. used = 0;
  2858. }
  2859. }
  2860. // Limits canonical Huffman code table's max code size.
  2861. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  2862. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
  2863. int code_list_len,
  2864. int max_code_size) {
  2865. int i;
  2866. mz_uint32 total = 0;
  2867. if (code_list_len <= 1) return;
  2868. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
  2869. pNum_codes[max_code_size] += pNum_codes[i];
  2870. for (i = max_code_size; i > 0; i--)
  2871. total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  2872. while (total != (1UL << max_code_size)) {
  2873. pNum_codes[max_code_size]--;
  2874. for (i = max_code_size - 1; i > 0; i--)
  2875. if (pNum_codes[i]) {
  2876. pNum_codes[i]--;
  2877. pNum_codes[i + 1] += 2;
  2878. break;
  2879. }
  2880. total--;
  2881. }
  2882. }
  2883. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
  2884. int table_len, int code_size_limit,
  2885. int static_table) {
  2886. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
  2887. mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
  2888. MZ_CLEAR_OBJ(num_codes);
  2889. if (static_table) {
  2890. for (i = 0; i < table_len; i++)
  2891. num_codes[d->m_huff_code_sizes[table_num][i]]++;
  2892. } else {
  2893. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
  2894. *pSyms;
  2895. int num_used_syms = 0;
  2896. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  2897. for (i = 0; i < table_len; i++)
  2898. if (pSym_count[i]) {
  2899. syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
  2900. syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
  2901. }
  2902. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
  2903. tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  2904. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  2905. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
  2906. code_size_limit);
  2907. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
  2908. MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  2909. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  2910. for (l = num_codes[i]; l > 0; l--)
  2911. d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  2912. }
  2913. next_code[1] = 0;
  2914. for (j = 0, i = 2; i <= code_size_limit; i++)
  2915. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  2916. for (i = 0; i < table_len; i++) {
  2917. mz_uint rev_code = 0, code, code_size;
  2918. if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  2919. code = next_code[code_size]++;
  2920. for (l = code_size; l > 0; l--, code >>= 1)
  2921. rev_code = (rev_code << 1) | (code & 1);
  2922. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  2923. }
  2924. }
  2925. #define TDEFL_PUT_BITS(b, l) \
  2926. do { \
  2927. mz_uint bits = b; \
  2928. mz_uint len = l; \
  2929. MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  2930. d->m_bit_buffer |= (bits << d->m_bits_in); \
  2931. d->m_bits_in += len; \
  2932. while (d->m_bits_in >= 8) { \
  2933. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  2934. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  2935. d->m_bit_buffer >>= 8; \
  2936. d->m_bits_in -= 8; \
  2937. } \
  2938. } \
  2939. MZ_MACRO_END
  2940. #define TDEFL_RLE_PREV_CODE_SIZE() \
  2941. { \
  2942. if (rle_repeat_count) { \
  2943. if (rle_repeat_count < 3) { \
  2944. d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
  2945. d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  2946. while (rle_repeat_count--) \
  2947. packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  2948. } else { \
  2949. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
  2950. packed_code_sizes[num_packed_code_sizes++] = 16; \
  2951. packed_code_sizes[num_packed_code_sizes++] = \
  2952. (mz_uint8)(rle_repeat_count - 3); \
  2953. } \
  2954. rle_repeat_count = 0; \
  2955. } \
  2956. }
  2957. #define TDEFL_RLE_ZERO_CODE_SIZE() \
  2958. { \
  2959. if (rle_z_count) { \
  2960. if (rle_z_count < 3) { \
  2961. d->m_huff_count[2][0] = \
  2962. (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
  2963. while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  2964. } else if (rle_z_count <= 10) { \
  2965. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
  2966. packed_code_sizes[num_packed_code_sizes++] = 17; \
  2967. packed_code_sizes[num_packed_code_sizes++] = \
  2968. (mz_uint8)(rle_z_count - 3); \
  2969. } else { \
  2970. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
  2971. packed_code_sizes[num_packed_code_sizes++] = 18; \
  2972. packed_code_sizes[num_packed_code_sizes++] = \
  2973. (mz_uint8)(rle_z_count - 11); \
  2974. } \
  2975. rle_z_count = 0; \
  2976. } \
  2977. }
  2978. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
  2979. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  2980. static void tdefl_start_dynamic_block(tdefl_compressor *d) {
  2981. int num_lit_codes, num_dist_codes, num_bit_lengths;
  2982. mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
  2983. rle_repeat_count, packed_code_sizes_index;
  2984. mz_uint8
  2985. code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2986. packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
  2987. prev_code_size = 0xFF;
  2988. d->m_huff_count[0][256] = 1;
  2989. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  2990. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  2991. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
  2992. if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  2993. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
  2994. if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  2995. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  2996. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
  2997. num_dist_codes);
  2998. total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
  2999. num_packed_code_sizes = 0;
  3000. rle_z_count = 0;
  3001. rle_repeat_count = 0;
  3002. memset(&d->m_huff_count[2][0], 0,
  3003. sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  3004. for (i = 0; i < total_code_sizes_to_pack; i++) {
  3005. mz_uint8 code_size = code_sizes_to_pack[i];
  3006. if (!code_size) {
  3007. TDEFL_RLE_PREV_CODE_SIZE();
  3008. if (++rle_z_count == 138) {
  3009. TDEFL_RLE_ZERO_CODE_SIZE();
  3010. }
  3011. } else {
  3012. TDEFL_RLE_ZERO_CODE_SIZE();
  3013. if (code_size != prev_code_size) {
  3014. TDEFL_RLE_PREV_CODE_SIZE();
  3015. d->m_huff_count[2][code_size] =
  3016. (mz_uint16)(d->m_huff_count[2][code_size] + 1);
  3017. packed_code_sizes[num_packed_code_sizes++] = code_size;
  3018. } else if (++rle_repeat_count == 6) {
  3019. TDEFL_RLE_PREV_CODE_SIZE();
  3020. }
  3021. }
  3022. prev_code_size = code_size;
  3023. }
  3024. if (rle_repeat_count) {
  3025. TDEFL_RLE_PREV_CODE_SIZE();
  3026. } else {
  3027. TDEFL_RLE_ZERO_CODE_SIZE();
  3028. }
  3029. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  3030. TDEFL_PUT_BITS(2, 2);
  3031. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  3032. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  3033. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
  3034. if (d->m_huff_code_sizes
  3035. [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
  3036. break;
  3037. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
  3038. TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  3039. for (i = 0; (int)i < num_bit_lengths; i++)
  3040. TDEFL_PUT_BITS(
  3041. d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  3042. for (packed_code_sizes_index = 0;
  3043. packed_code_sizes_index < num_packed_code_sizes;) {
  3044. mz_uint code = packed_code_sizes[packed_code_sizes_index++];
  3045. MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  3046. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  3047. if (code >= 16)
  3048. TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
  3049. "\02\03\07"[code - 16]);
  3050. }
  3051. }
  3052. static void tdefl_start_static_block(tdefl_compressor *d) {
  3053. mz_uint i;
  3054. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  3055. for (i = 0; i <= 143; ++i) *p++ = 8;
  3056. for (; i <= 255; ++i) *p++ = 9;
  3057. for (; i <= 279; ++i) *p++ = 7;
  3058. for (; i <= 287; ++i) *p++ = 8;
  3059. memset(d->m_huff_code_sizes[1], 5, 32);
  3060. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  3061. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  3062. TDEFL_PUT_BITS(1, 2);
  3063. }
  3064. static const mz_uint mz_bitmasks[17] = {
  3065. 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  3066. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
  3067. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
  3068. MINIZ_HAS_64BIT_REGISTERS
  3069. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3070. mz_uint flags;
  3071. mz_uint8 *pLZ_codes;
  3072. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  3073. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  3074. mz_uint64 bit_buffer = d->m_bit_buffer;
  3075. mz_uint bits_in = d->m_bits_in;
  3076. #define TDEFL_PUT_BITS_FAST(b, l) \
  3077. { \
  3078. bit_buffer |= (((mz_uint64)(b)) << bits_in); \
  3079. bits_in += (l); \
  3080. }
  3081. flags = 1;
  3082. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
  3083. flags >>= 1) {
  3084. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3085. if (flags & 1) {
  3086. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  3087. mz_uint match_len = pLZ_codes[0],
  3088. match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
  3089. pLZ_codes += 3;
  3090. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3091. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3092. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3093. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3094. s_tdefl_len_extra[match_len]);
  3095. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  3096. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3097. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  3098. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  3099. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  3100. sym = (match_dist < 512) ? s0 : s1;
  3101. num_extra_bits = (match_dist < 512) ? n0 : n1;
  3102. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3103. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
  3104. d->m_huff_code_sizes[1][sym]);
  3105. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
  3106. num_extra_bits);
  3107. } else {
  3108. mz_uint 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. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
  3119. flags >>= 1;
  3120. lit = *pLZ_codes++;
  3121. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3122. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
  3123. d->m_huff_code_sizes[0][lit]);
  3124. }
  3125. }
  3126. }
  3127. if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE;
  3128. *(mz_uint64 *)pOutput_buf = bit_buffer;
  3129. pOutput_buf += (bits_in >> 3);
  3130. bit_buffer >>= (bits_in & ~7);
  3131. bits_in &= 7;
  3132. }
  3133. #undef TDEFL_PUT_BITS_FAST
  3134. d->m_pOutput_buf = pOutput_buf;
  3135. d->m_bits_in = 0;
  3136. d->m_bit_buffer = 0;
  3137. while (bits_in) {
  3138. mz_uint32 n = MZ_MIN(bits_in, 16);
  3139. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  3140. bit_buffer >>= n;
  3141. bits_in -= n;
  3142. }
  3143. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3144. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3145. }
  3146. #else
  3147. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
  3148. mz_uint flags;
  3149. mz_uint8 *pLZ_codes;
  3150. flags = 1;
  3151. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
  3152. flags >>= 1) {
  3153. if (flags == 1) flags = *pLZ_codes++ | 0x100;
  3154. if (flags & 1) {
  3155. mz_uint sym, num_extra_bits;
  3156. mz_uint match_len = pLZ_codes[0],
  3157. match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
  3158. pLZ_codes += 3;
  3159. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3160. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
  3161. d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  3162. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
  3163. s_tdefl_len_extra[match_len]);
  3164. if (match_dist < 512) {
  3165. sym = s_tdefl_small_dist_sym[match_dist];
  3166. num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  3167. } else {
  3168. sym = s_tdefl_large_dist_sym[match_dist >> 8];
  3169. num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  3170. }
  3171. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  3172. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  3173. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  3174. } else {
  3175. mz_uint lit = *pLZ_codes++;
  3176. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  3177. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  3178. }
  3179. }
  3180. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  3181. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  3182. }
  3183. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
  3184. // MINIZ_HAS_64BIT_REGISTERS
  3185. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
  3186. if (static_block)
  3187. tdefl_start_static_block(d);
  3188. else
  3189. tdefl_start_dynamic_block(d);
  3190. return tdefl_compress_lz_codes(d);
  3191. }
  3192. static int tdefl_flush_block(tdefl_compressor *d, int flush) {
  3193. mz_uint saved_bit_buf, saved_bits_in;
  3194. mz_uint8 *pSaved_output_buf;
  3195. mz_bool comp_block_succeeded = MZ_FALSE;
  3196. int n, use_raw_block =
  3197. ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
  3198. (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  3199. mz_uint8 *pOutput_buf_start =
  3200. ((d->m_pPut_buf_func == NULL) &&
  3201. ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
  3202. ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
  3203. : d->m_output_buf;
  3204. d->m_pOutput_buf = pOutput_buf_start;
  3205. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  3206. MZ_ASSERT(!d->m_output_flush_remaining);
  3207. d->m_output_flush_ofs = 0;
  3208. d->m_output_flush_remaining = 0;
  3209. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  3210. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  3211. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
  3212. TDEFL_PUT_BITS(0x78, 8);
  3213. TDEFL_PUT_BITS(0x01, 8);
  3214. }
  3215. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  3216. pSaved_output_buf = d->m_pOutput_buf;
  3217. saved_bit_buf = d->m_bit_buffer;
  3218. saved_bits_in = d->m_bits_in;
  3219. if (!use_raw_block)
  3220. comp_block_succeeded =
  3221. tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
  3222. (d->m_total_lz_bytes < 48));
  3223. // If the block gets expanded, forget the current contents of the output
  3224. // buffer and send a raw block instead.
  3225. if (((use_raw_block) ||
  3226. ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
  3227. d->m_total_lz_bytes))) &&
  3228. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
  3229. mz_uint i;
  3230. d->m_pOutput_buf = pSaved_output_buf;
  3231. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3232. TDEFL_PUT_BITS(0, 2);
  3233. if (d->m_bits_in) {
  3234. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3235. }
  3236. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
  3237. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  3238. }
  3239. for (i = 0; i < d->m_total_lz_bytes; ++i) {
  3240. TDEFL_PUT_BITS(
  3241. d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
  3242. 8);
  3243. }
  3244. }
  3245. // Check for the extremely unlikely (if not impossible) case of the compressed
  3246. // block not fitting into the output buffer when using dynamic codes.
  3247. else if (!comp_block_succeeded) {
  3248. d->m_pOutput_buf = pSaved_output_buf;
  3249. d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  3250. tdefl_compress_block(d, MZ_TRUE);
  3251. }
  3252. if (flush) {
  3253. if (flush == TDEFL_FINISH) {
  3254. if (d->m_bits_in) {
  3255. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3256. }
  3257. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
  3258. mz_uint i, a = d->m_adler32;
  3259. for (i = 0; i < 4; i++) {
  3260. TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
  3261. a <<= 8;
  3262. }
  3263. }
  3264. } else {
  3265. mz_uint i, z = 0;
  3266. TDEFL_PUT_BITS(0, 3);
  3267. if (d->m_bits_in) {
  3268. TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
  3269. }
  3270. for (i = 2; i; --i, z ^= 0xFFFF) {
  3271. TDEFL_PUT_BITS(z & 0xFFFF, 16);
  3272. }
  3273. }
  3274. }
  3275. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  3276. memset(&d->m_huff_count[0][0], 0,
  3277. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3278. memset(&d->m_huff_count[1][0], 0,
  3279. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3280. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3281. d->m_pLZ_flags = d->m_lz_code_buf;
  3282. d->m_num_flags_left = 8;
  3283. d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
  3284. d->m_total_lz_bytes = 0;
  3285. d->m_block_index++;
  3286. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
  3287. if (d->m_pPut_buf_func) {
  3288. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3289. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  3290. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  3291. } else if (pOutput_buf_start == d->m_output_buf) {
  3292. int bytes_to_copy = (int)MZ_MIN(
  3293. (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  3294. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
  3295. bytes_to_copy);
  3296. d->m_out_buf_ofs += bytes_to_copy;
  3297. if ((n -= bytes_to_copy) != 0) {
  3298. d->m_output_flush_ofs = bytes_to_copy;
  3299. d->m_output_flush_remaining = n;
  3300. }
  3301. } else {
  3302. d->m_out_buf_ofs += n;
  3303. }
  3304. }
  3305. return d->m_output_flush_remaining;
  3306. }
  3307. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3308. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
  3309. static MZ_FORCEINLINE void tdefl_find_match(
  3310. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3311. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3312. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3313. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3314. probe_len;
  3315. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3316. const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
  3317. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
  3318. s01 = TDEFL_READ_UNALIGNED_WORD(s);
  3319. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3320. if (max_match_len <= match_len) return;
  3321. for (;;) {
  3322. for (;;) {
  3323. if (--num_probes_left == 0) return;
  3324. #define TDEFL_PROBE \
  3325. next_probe_pos = d->m_next[probe_pos]; \
  3326. if ((!next_probe_pos) || \
  3327. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3328. return; \
  3329. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3330. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
  3331. break;
  3332. TDEFL_PROBE;
  3333. TDEFL_PROBE;
  3334. TDEFL_PROBE;
  3335. }
  3336. if (!dist) break;
  3337. q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3338. if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue;
  3339. p = s;
  3340. probe_len = 32;
  3341. do {
  3342. } while (
  3343. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3344. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3345. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3346. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3347. (--probe_len > 0));
  3348. if (!probe_len) {
  3349. *pMatch_dist = dist;
  3350. *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
  3351. break;
  3352. } else if ((probe_len = ((mz_uint)(p - s) * 2) +
  3353. (mz_uint)(*(const mz_uint8 *)p ==
  3354. *(const mz_uint8 *)q)) > match_len) {
  3355. *pMatch_dist = dist;
  3356. if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
  3357. max_match_len)
  3358. break;
  3359. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  3360. }
  3361. }
  3362. }
  3363. #else
  3364. static MZ_FORCEINLINE void tdefl_find_match(
  3365. tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
  3366. mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
  3367. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
  3368. match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
  3369. probe_len;
  3370. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  3371. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  3372. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  3373. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
  3374. if (max_match_len <= match_len) return;
  3375. for (;;) {
  3376. for (;;) {
  3377. if (--num_probes_left == 0) return;
  3378. #define TDEFL_PROBE \
  3379. next_probe_pos = d->m_next[probe_pos]; \
  3380. if ((!next_probe_pos) || \
  3381. ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
  3382. return; \
  3383. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  3384. if ((d->m_dict[probe_pos + match_len] == c0) && \
  3385. (d->m_dict[probe_pos + match_len - 1] == c1)) \
  3386. break;
  3387. TDEFL_PROBE;
  3388. TDEFL_PROBE;
  3389. TDEFL_PROBE;
  3390. }
  3391. if (!dist) break;
  3392. p = s;
  3393. q = d->m_dict + probe_pos;
  3394. for (probe_len = 0; probe_len < max_match_len; probe_len++)
  3395. if (*p++ != *q++) break;
  3396. if (probe_len > match_len) {
  3397. *pMatch_dist = dist;
  3398. if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  3399. c0 = d->m_dict[pos + match_len];
  3400. c1 = d->m_dict[pos + match_len - 1];
  3401. }
  3402. }
  3403. }
  3404. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  3405. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3406. static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
  3407. // Faster, minimally featured LZRW1-style match+parse loop with better
  3408. // register utilization. Intended for applications where raw throughput is
  3409. // valued more highly than ratio.
  3410. mz_uint lookahead_pos = d->m_lookahead_pos,
  3411. lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
  3412. total_lz_bytes = d->m_total_lz_bytes,
  3413. num_flags_left = d->m_num_flags_left;
  3414. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  3415. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3416. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
  3417. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  3418. mz_uint dst_pos =
  3419. (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  3420. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3421. d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  3422. d->m_src_buf_left -= num_bytes_to_process;
  3423. lookahead_size += num_bytes_to_process;
  3424. while (num_bytes_to_process) {
  3425. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  3426. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  3427. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3428. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
  3429. MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  3430. d->m_pSrc += n;
  3431. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  3432. num_bytes_to_process -= n;
  3433. }
  3434. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  3435. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
  3436. break;
  3437. while (lookahead_size >= 4) {
  3438. mz_uint cur_match_dist, cur_match_len = 1;
  3439. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  3440. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  3441. mz_uint hash =
  3442. (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
  3443. TDEFL_LEVEL1_HASH_SIZE_MASK;
  3444. mz_uint probe_pos = d->m_hash[hash];
  3445. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  3446. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
  3447. dict_size) &&
  3448. ((*(const mz_uint32 *)(d->m_dict +
  3449. (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
  3450. 0xFFFFFF) == first_trigram)) {
  3451. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  3452. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  3453. mz_uint32 probe_len = 32;
  3454. do {
  3455. } while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
  3456. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3457. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3458. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3459. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3460. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3461. (TDEFL_READ_UNALIGNED_WORD(++p) ==
  3462. TDEFL_READ_UNALIGNED_WORD(++q)) &&
  3463. (--probe_len > 0));
  3464. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
  3465. (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  3466. if (!probe_len)
  3467. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  3468. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
  3469. ((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3470. (cur_match_dist >= 8U * 1024U))) {
  3471. cur_match_len = 1;
  3472. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3473. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3474. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3475. } else {
  3476. mz_uint32 s0, s1;
  3477. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  3478. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
  3479. (cur_match_dist >= 1) &&
  3480. (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  3481. cur_match_dist--;
  3482. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  3483. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  3484. pLZ_code_buf += 3;
  3485. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  3486. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  3487. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  3488. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  3489. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
  3490. TDEFL_MIN_MATCH_LEN]]++;
  3491. }
  3492. } else {
  3493. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  3494. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3495. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  3496. }
  3497. if (--num_flags_left == 0) {
  3498. num_flags_left = 8;
  3499. pLZ_flags = pLZ_code_buf++;
  3500. }
  3501. total_lz_bytes += cur_match_len;
  3502. lookahead_pos += cur_match_len;
  3503. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  3504. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  3505. MZ_ASSERT(lookahead_size >= cur_match_len);
  3506. lookahead_size -= cur_match_len;
  3507. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3508. int n;
  3509. d->m_lookahead_pos = lookahead_pos;
  3510. d->m_lookahead_size = lookahead_size;
  3511. d->m_dict_size = dict_size;
  3512. d->m_total_lz_bytes = total_lz_bytes;
  3513. d->m_pLZ_code_buf = pLZ_code_buf;
  3514. d->m_pLZ_flags = pLZ_flags;
  3515. d->m_num_flags_left = num_flags_left;
  3516. if ((n = tdefl_flush_block(d, 0)) != 0)
  3517. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3518. total_lz_bytes = d->m_total_lz_bytes;
  3519. pLZ_code_buf = d->m_pLZ_code_buf;
  3520. pLZ_flags = d->m_pLZ_flags;
  3521. num_flags_left = d->m_num_flags_left;
  3522. }
  3523. }
  3524. while (lookahead_size) {
  3525. mz_uint8 lit = d->m_dict[cur_pos];
  3526. total_lz_bytes++;
  3527. *pLZ_code_buf++ = lit;
  3528. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  3529. if (--num_flags_left == 0) {
  3530. num_flags_left = 8;
  3531. pLZ_flags = pLZ_code_buf++;
  3532. }
  3533. d->m_huff_count[0][lit]++;
  3534. lookahead_pos++;
  3535. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  3536. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3537. lookahead_size--;
  3538. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
  3539. int n;
  3540. d->m_lookahead_pos = lookahead_pos;
  3541. d->m_lookahead_size = lookahead_size;
  3542. d->m_dict_size = dict_size;
  3543. d->m_total_lz_bytes = total_lz_bytes;
  3544. d->m_pLZ_code_buf = pLZ_code_buf;
  3545. d->m_pLZ_flags = pLZ_flags;
  3546. d->m_num_flags_left = num_flags_left;
  3547. if ((n = tdefl_flush_block(d, 0)) != 0)
  3548. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3549. total_lz_bytes = d->m_total_lz_bytes;
  3550. pLZ_code_buf = d->m_pLZ_code_buf;
  3551. pLZ_flags = d->m_pLZ_flags;
  3552. num_flags_left = d->m_num_flags_left;
  3553. }
  3554. }
  3555. }
  3556. d->m_lookahead_pos = lookahead_pos;
  3557. d->m_lookahead_size = lookahead_size;
  3558. d->m_dict_size = dict_size;
  3559. d->m_total_lz_bytes = total_lz_bytes;
  3560. d->m_pLZ_code_buf = pLZ_code_buf;
  3561. d->m_pLZ_flags = pLZ_flags;
  3562. d->m_num_flags_left = num_flags_left;
  3563. return MZ_TRUE;
  3564. }
  3565. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3566. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
  3567. mz_uint8 lit) {
  3568. d->m_total_lz_bytes++;
  3569. *d->m_pLZ_code_buf++ = lit;
  3570. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
  3571. if (--d->m_num_flags_left == 0) {
  3572. d->m_num_flags_left = 8;
  3573. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3574. }
  3575. d->m_huff_count[0][lit]++;
  3576. }
  3577. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d,
  3578. mz_uint match_len,
  3579. mz_uint match_dist) {
  3580. mz_uint32 s0, s1;
  3581. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
  3582. (match_dist <= TDEFL_LZ_DICT_SIZE));
  3583. d->m_total_lz_bytes += match_len;
  3584. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  3585. match_dist -= 1;
  3586. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  3587. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
  3588. d->m_pLZ_code_buf += 3;
  3589. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
  3590. if (--d->m_num_flags_left == 0) {
  3591. d->m_num_flags_left = 8;
  3592. d->m_pLZ_flags = d->m_pLZ_code_buf++;
  3593. }
  3594. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  3595. s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  3596. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  3597. if (match_len >= TDEFL_MIN_MATCH_LEN)
  3598. d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  3599. }
  3600. static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
  3601. const mz_uint8 *pSrc = d->m_pSrc;
  3602. size_t src_buf_left = d->m_src_buf_left;
  3603. tdefl_flush flush = d->m_flush;
  3604. while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
  3605. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  3606. // Update dictionary and hash chains. Keeps the lookahead size equal to
  3607. // TDEFL_MAX_MATCH_LEN.
  3608. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
  3609. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3610. TDEFL_LZ_DICT_SIZE_MASK,
  3611. ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  3612. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3613. << TDEFL_LZ_HASH_SHIFT) ^
  3614. d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3615. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
  3616. src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  3617. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  3618. src_buf_left -= num_bytes_to_process;
  3619. d->m_lookahead_size += num_bytes_to_process;
  3620. while (pSrc != pSrc_end) {
  3621. mz_uint8 c = *pSrc++;
  3622. d->m_dict[dst_pos] = c;
  3623. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3624. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3625. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  3626. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3627. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3628. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  3629. ins_pos++;
  3630. }
  3631. } else {
  3632. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
  3633. mz_uint8 c = *pSrc++;
  3634. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
  3635. TDEFL_LZ_DICT_SIZE_MASK;
  3636. src_buf_left--;
  3637. d->m_dict[dst_pos] = c;
  3638. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  3639. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  3640. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
  3641. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  3642. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
  3643. << (TDEFL_LZ_HASH_SHIFT * 2)) ^
  3644. (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
  3645. << TDEFL_LZ_HASH_SHIFT) ^
  3646. c) &
  3647. (TDEFL_LZ_HASH_SIZE - 1);
  3648. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
  3649. d->m_hash[hash] = (mz_uint16)(ins_pos);
  3650. }
  3651. }
  3652. }
  3653. d->m_dict_size =
  3654. MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  3655. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break;
  3656. // Simple lazy/greedy parsing state machine.
  3657. len_to_move = 1;
  3658. cur_match_dist = 0;
  3659. cur_match_len =
  3660. d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
  3661. cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  3662. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
  3663. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
  3664. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  3665. cur_match_len = 0;
  3666. while (cur_match_len < d->m_lookahead_size) {
  3667. if (d->m_dict[cur_pos + cur_match_len] != c) break;
  3668. cur_match_len++;
  3669. }
  3670. if (cur_match_len < TDEFL_MIN_MATCH_LEN)
  3671. cur_match_len = 0;
  3672. else
  3673. cur_match_dist = 1;
  3674. }
  3675. } else {
  3676. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
  3677. d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  3678. }
  3679. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
  3680. (cur_match_dist >= 8U * 1024U)) ||
  3681. (cur_pos == cur_match_dist) ||
  3682. ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
  3683. cur_match_dist = cur_match_len = 0;
  3684. }
  3685. if (d->m_saved_match_len) {
  3686. if (cur_match_len > d->m_saved_match_len) {
  3687. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  3688. if (cur_match_len >= 128) {
  3689. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3690. d->m_saved_match_len = 0;
  3691. len_to_move = cur_match_len;
  3692. } else {
  3693. d->m_saved_lit = d->m_dict[cur_pos];
  3694. d->m_saved_match_dist = cur_match_dist;
  3695. d->m_saved_match_len = cur_match_len;
  3696. }
  3697. } else {
  3698. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  3699. len_to_move = d->m_saved_match_len - 1;
  3700. d->m_saved_match_len = 0;
  3701. }
  3702. } else if (!cur_match_dist)
  3703. tdefl_record_literal(d,
  3704. d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  3705. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
  3706. (cur_match_len >= 128)) {
  3707. tdefl_record_match(d, cur_match_len, cur_match_dist);
  3708. len_to_move = cur_match_len;
  3709. } else {
  3710. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
  3711. d->m_saved_match_dist = cur_match_dist;
  3712. d->m_saved_match_len = cur_match_len;
  3713. }
  3714. // Move the lookahead forward by len_to_move bytes.
  3715. d->m_lookahead_pos += len_to_move;
  3716. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  3717. d->m_lookahead_size -= len_to_move;
  3718. d->m_dict_size =
  3719. MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
  3720. // Check if it's time to flush the current LZ codes to the internal output
  3721. // buffer.
  3722. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  3723. ((d->m_total_lz_bytes > 31 * 1024) &&
  3724. (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
  3725. d->m_total_lz_bytes) ||
  3726. (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
  3727. int n;
  3728. d->m_pSrc = pSrc;
  3729. d->m_src_buf_left = src_buf_left;
  3730. if ((n = tdefl_flush_block(d, 0)) != 0)
  3731. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  3732. }
  3733. }
  3734. d->m_pSrc = pSrc;
  3735. d->m_src_buf_left = src_buf_left;
  3736. return MZ_TRUE;
  3737. }
  3738. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
  3739. if (d->m_pIn_buf_size) {
  3740. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  3741. }
  3742. if (d->m_pOut_buf_size) {
  3743. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
  3744. d->m_output_flush_remaining);
  3745. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
  3746. d->m_output_buf + d->m_output_flush_ofs, n);
  3747. d->m_output_flush_ofs += (mz_uint)n;
  3748. d->m_output_flush_remaining -= (mz_uint)n;
  3749. d->m_out_buf_ofs += n;
  3750. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  3751. }
  3752. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
  3753. : TDEFL_STATUS_OKAY;
  3754. }
  3755. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
  3756. size_t *pIn_buf_size, void *pOut_buf,
  3757. size_t *pOut_buf_size, tdefl_flush flush) {
  3758. if (!d) {
  3759. if (pIn_buf_size) *pIn_buf_size = 0;
  3760. if (pOut_buf_size) *pOut_buf_size = 0;
  3761. return TDEFL_STATUS_BAD_PARAM;
  3762. }
  3763. d->m_pIn_buf = pIn_buf;
  3764. d->m_pIn_buf_size = pIn_buf_size;
  3765. d->m_pOut_buf = pOut_buf;
  3766. d->m_pOut_buf_size = pOut_buf_size;
  3767. d->m_pSrc = (const mz_uint8 *)(pIn_buf);
  3768. d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  3769. d->m_out_buf_ofs = 0;
  3770. d->m_flush = flush;
  3771. if (((d->m_pPut_buf_func != NULL) ==
  3772. ((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
  3773. (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  3774. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
  3775. (pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
  3776. (pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
  3777. if (pIn_buf_size) *pIn_buf_size = 0;
  3778. if (pOut_buf_size) *pOut_buf_size = 0;
  3779. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  3780. }
  3781. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  3782. if ((d->m_output_flush_remaining) || (d->m_finished))
  3783. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3784. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3785. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  3786. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  3787. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
  3788. TDEFL_RLE_MATCHES)) == 0)) {
  3789. if (!tdefl_compress_fast(d)) return d->m_prev_return_status;
  3790. } else
  3791. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  3792. {
  3793. if (!tdefl_compress_normal(d)) return d->m_prev_return_status;
  3794. }
  3795. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
  3796. (pIn_buf))
  3797. d->m_adler32 =
  3798. (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
  3799. d->m_pSrc - (const mz_uint8 *)pIn_buf);
  3800. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
  3801. (!d->m_output_flush_remaining)) {
  3802. if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status;
  3803. d->m_finished = (flush == TDEFL_FINISH);
  3804. if (flush == TDEFL_FULL_FLUSH) {
  3805. MZ_CLEAR_OBJ(d->m_hash);
  3806. MZ_CLEAR_OBJ(d->m_next);
  3807. d->m_dict_size = 0;
  3808. }
  3809. }
  3810. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  3811. }
  3812. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
  3813. size_t in_buf_size, tdefl_flush flush) {
  3814. MZ_ASSERT(d->m_pPut_buf_func);
  3815. return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  3816. }
  3817. tdefl_status tdefl_init(tdefl_compressor *d,
  3818. tdefl_put_buf_func_ptr pPut_buf_func,
  3819. void *pPut_buf_user, int flags) {
  3820. d->m_pPut_buf_func = pPut_buf_func;
  3821. d->m_pPut_buf_user = pPut_buf_user;
  3822. d->m_flags = (mz_uint)(flags);
  3823. d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
  3824. d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  3825. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  3826. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  3827. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
  3828. d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  3829. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
  3830. d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  3831. d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
  3832. d->m_pLZ_flags = d->m_lz_code_buf;
  3833. d->m_num_flags_left = 8;
  3834. d->m_pOutput_buf = d->m_output_buf;
  3835. d->m_pOutput_buf_end = d->m_output_buf;
  3836. d->m_prev_return_status = TDEFL_STATUS_OKAY;
  3837. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
  3838. d->m_adler32 = 1;
  3839. d->m_pIn_buf = NULL;
  3840. d->m_pOut_buf = NULL;
  3841. d->m_pIn_buf_size = NULL;
  3842. d->m_pOut_buf_size = NULL;
  3843. d->m_flush = TDEFL_NO_FLUSH;
  3844. d->m_pSrc = NULL;
  3845. d->m_src_buf_left = 0;
  3846. d->m_out_buf_ofs = 0;
  3847. memset(&d->m_huff_count[0][0], 0,
  3848. sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  3849. memset(&d->m_huff_count[1][0], 0,
  3850. sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  3851. return TDEFL_STATUS_OKAY;
  3852. }
  3853. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
  3854. return d->m_prev_return_status;
  3855. }
  3856. mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
  3857. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
  3858. tdefl_put_buf_func_ptr pPut_buf_func,
  3859. void *pPut_buf_user, int flags) {
  3860. tdefl_compressor *pComp;
  3861. mz_bool succeeded;
  3862. if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  3863. pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3864. if (!pComp) return MZ_FALSE;
  3865. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
  3866. TDEFL_STATUS_OKAY);
  3867. succeeded =
  3868. succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
  3869. TDEFL_STATUS_DONE);
  3870. MZ_FREE(pComp);
  3871. return succeeded;
  3872. }
  3873. typedef struct {
  3874. size_t m_size, m_capacity;
  3875. mz_uint8 *m_pBuf;
  3876. mz_bool m_expandable;
  3877. } tdefl_output_buffer;
  3878. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
  3879. void *pUser) {
  3880. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  3881. size_t new_size = p->m_size + len;
  3882. if (new_size > p->m_capacity) {
  3883. size_t new_capacity = p->m_capacity;
  3884. mz_uint8 *pNew_buf;
  3885. if (!p->m_expandable) return MZ_FALSE;
  3886. do {
  3887. new_capacity = MZ_MAX(128U, new_capacity << 1U);
  3888. } while (new_size > new_capacity);
  3889. pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
  3890. if (!pNew_buf) return MZ_FALSE;
  3891. p->m_pBuf = pNew_buf;
  3892. p->m_capacity = new_capacity;
  3893. }
  3894. memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
  3895. p->m_size = new_size;
  3896. return MZ_TRUE;
  3897. }
  3898. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
  3899. size_t *pOut_len, int flags) {
  3900. tdefl_output_buffer out_buf;
  3901. MZ_CLEAR_OBJ(out_buf);
  3902. if (!pOut_len)
  3903. return MZ_FALSE;
  3904. else
  3905. *pOut_len = 0;
  3906. out_buf.m_expandable = MZ_TRUE;
  3907. if (!tdefl_compress_mem_to_output(
  3908. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3909. return NULL;
  3910. *pOut_len = out_buf.m_size;
  3911. return out_buf.m_pBuf;
  3912. }
  3913. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
  3914. const void *pSrc_buf, size_t src_buf_len,
  3915. int flags) {
  3916. tdefl_output_buffer out_buf;
  3917. MZ_CLEAR_OBJ(out_buf);
  3918. if (!pOut_buf) return 0;
  3919. out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
  3920. out_buf.m_capacity = out_buf_len;
  3921. if (!tdefl_compress_mem_to_output(
  3922. pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
  3923. return 0;
  3924. return out_buf.m_size;
  3925. }
  3926. #ifndef MINIZ_NO_ZLIB_APIS
  3927. static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
  3928. 128, 256, 512, 768, 1500};
  3929. // level may actually range from [0,10] (10 is a "hidden" max level, where we
  3930. // want a bit more compression and it's fine if throughput to fall off a cliff
  3931. // on some files).
  3932. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
  3933. int strategy) {
  3934. mz_uint comp_flags =
  3935. s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
  3936. ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  3937. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  3938. if (!level)
  3939. comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  3940. else if (strategy == MZ_FILTERED)
  3941. comp_flags |= TDEFL_FILTER_MATCHES;
  3942. else if (strategy == MZ_HUFFMAN_ONLY)
  3943. comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  3944. else if (strategy == MZ_FIXED)
  3945. comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  3946. else if (strategy == MZ_RLE)
  3947. comp_flags |= TDEFL_RLE_MATCHES;
  3948. return comp_flags;
  3949. }
  3950. #endif // MINIZ_NO_ZLIB_APIS
  3951. #ifdef _MSC_VER
  3952. #pragma warning(push)
  3953. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  3954. // aggregate initializer (also supported by GNU
  3955. // C and C99, so no big deal)
  3956. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  3957. // 'int', possible loss of data
  3958. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  3959. // 'int', possible loss of data
  3960. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  3961. // deprecated. Instead, use the ISO C and C++
  3962. // conformant name: _strdup.
  3963. #endif
  3964. // Simple PNG writer function by Alex Evans, 2011. Released into the public
  3965. // domain: https://gist.github.com/908299, more context at
  3966. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  3967. // This is actually a modification of Alex's original code so PNG files
  3968. // generated by this function pass pngcheck.
  3969. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
  3970. int h, int num_chans,
  3971. size_t *pLen_out,
  3972. mz_uint level, mz_bool flip) {
  3973. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
  3974. // defined.
  3975. static const mz_uint s_tdefl_png_num_probes[11] = {
  3976. 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
  3977. tdefl_compressor *pComp =
  3978. (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
  3979. tdefl_output_buffer out_buf;
  3980. int i, bpl = w * num_chans, y, z;
  3981. mz_uint32 c;
  3982. *pLen_out = 0;
  3983. if (!pComp) return NULL;
  3984. MZ_CLEAR_OBJ(out_buf);
  3985. out_buf.m_expandable = MZ_TRUE;
  3986. out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
  3987. if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
  3988. MZ_FREE(pComp);
  3989. return NULL;
  3990. }
  3991. // write dummy header
  3992. for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  3993. // compress image data
  3994. tdefl_init(
  3995. pComp, tdefl_output_buffer_putter, &out_buf,
  3996. s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  3997. for (y = 0; y < h; ++y) {
  3998. tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
  3999. tdefl_compress_buffer(pComp,
  4000. (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
  4001. bpl, TDEFL_NO_FLUSH);
  4002. }
  4003. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
  4004. TDEFL_STATUS_DONE) {
  4005. MZ_FREE(pComp);
  4006. MZ_FREE(out_buf.m_pBuf);
  4007. return NULL;
  4008. }
  4009. // write real header
  4010. *pLen_out = out_buf.m_size - 41;
  4011. {
  4012. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  4013. mz_uint8 pnghdr[41] = {0x89,
  4014. 0x50,
  4015. 0x4e,
  4016. 0x47,
  4017. 0x0d,
  4018. 0x0a,
  4019. 0x1a,
  4020. 0x0a,
  4021. 0x00,
  4022. 0x00,
  4023. 0x00,
  4024. 0x0d,
  4025. 0x49,
  4026. 0x48,
  4027. 0x44,
  4028. 0x52,
  4029. 0,
  4030. 0,
  4031. (mz_uint8)(w >> 8),
  4032. (mz_uint8)w,
  4033. 0,
  4034. 0,
  4035. (mz_uint8)(h >> 8),
  4036. (mz_uint8)h,
  4037. 8,
  4038. chans[num_chans],
  4039. 0,
  4040. 0,
  4041. 0,
  4042. 0,
  4043. 0,
  4044. 0,
  4045. 0,
  4046. (mz_uint8)(*pLen_out >> 24),
  4047. (mz_uint8)(*pLen_out >> 16),
  4048. (mz_uint8)(*pLen_out >> 8),
  4049. (mz_uint8)*pLen_out,
  4050. 0x49,
  4051. 0x44,
  4052. 0x41,
  4053. 0x54};
  4054. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
  4055. for (i = 0; i < 4; ++i, c <<= 8)
  4056. ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
  4057. memcpy(out_buf.m_pBuf, pnghdr, 41);
  4058. }
  4059. // write footer (IDAT CRC-32, followed by IEND chunk)
  4060. if (!tdefl_output_buffer_putter(
  4061. "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
  4062. *pLen_out = 0;
  4063. MZ_FREE(pComp);
  4064. MZ_FREE(out_buf.m_pBuf);
  4065. return NULL;
  4066. }
  4067. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
  4068. *pLen_out + 4);
  4069. for (i = 0; i < 4; ++i, c <<= 8)
  4070. (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
  4071. // compute final size of file, grab compressed data buffer and return
  4072. *pLen_out += 57;
  4073. MZ_FREE(pComp);
  4074. return out_buf.m_pBuf;
  4075. }
  4076. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
  4077. int num_chans, size_t *pLen_out) {
  4078. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
  4079. // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
  4080. // where #defined out)
  4081. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
  4082. pLen_out, 6, MZ_FALSE);
  4083. }
  4084. // ------------------- .ZIP archive reading
  4085. #ifndef MINIZ_NO_ARCHIVE_APIS
  4086. #error "No arvhive APIs"
  4087. #ifdef MINIZ_NO_STDIO
  4088. #define MZ_FILE void *
  4089. #else
  4090. #include <stdio.h>
  4091. #include <sys/stat.h>
  4092. #if defined(_MSC_VER) || defined(__MINGW64__)
  4093. static FILE *mz_fopen(const char *pFilename, const char *pMode) {
  4094. FILE *pFile = NULL;
  4095. fopen_s(&pFile, pFilename, pMode);
  4096. return pFile;
  4097. }
  4098. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
  4099. FILE *pFile = NULL;
  4100. if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL;
  4101. return pFile;
  4102. }
  4103. #ifndef MINIZ_NO_TIME
  4104. #include <sys/utime.h>
  4105. #endif
  4106. #define MZ_FILE FILE
  4107. #define MZ_FOPEN mz_fopen
  4108. #define MZ_FCLOSE fclose
  4109. #define MZ_FREAD fread
  4110. #define MZ_FWRITE fwrite
  4111. #define MZ_FTELL64 _ftelli64
  4112. #define MZ_FSEEK64 _fseeki64
  4113. #define MZ_FILE_STAT_STRUCT _stat
  4114. #define MZ_FILE_STAT _stat
  4115. #define MZ_FFLUSH fflush
  4116. #define MZ_FREOPEN mz_freopen
  4117. #define MZ_DELETE_FILE remove
  4118. #elif defined(__MINGW32__)
  4119. #ifndef MINIZ_NO_TIME
  4120. #include <sys/utime.h>
  4121. #endif
  4122. #define MZ_FILE FILE
  4123. #define MZ_FOPEN(f, m) fopen(f, m)
  4124. #define MZ_FCLOSE fclose
  4125. #define MZ_FREAD fread
  4126. #define MZ_FWRITE fwrite
  4127. #define MZ_FTELL64 ftello64
  4128. #define MZ_FSEEK64 fseeko64
  4129. #define MZ_FILE_STAT_STRUCT _stat
  4130. #define MZ_FILE_STAT _stat
  4131. #define MZ_FFLUSH fflush
  4132. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4133. #define MZ_DELETE_FILE remove
  4134. #elif defined(__TINYC__)
  4135. #ifndef MINIZ_NO_TIME
  4136. #include <sys/utime.h>
  4137. #endif
  4138. #define MZ_FILE FILE
  4139. #define MZ_FOPEN(f, m) fopen(f, m)
  4140. #define MZ_FCLOSE fclose
  4141. #define MZ_FREAD fread
  4142. #define MZ_FWRITE fwrite
  4143. #define MZ_FTELL64 ftell
  4144. #define MZ_FSEEK64 fseek
  4145. #define MZ_FILE_STAT_STRUCT stat
  4146. #define MZ_FILE_STAT stat
  4147. #define MZ_FFLUSH fflush
  4148. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4149. #define MZ_DELETE_FILE remove
  4150. #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
  4151. #ifndef MINIZ_NO_TIME
  4152. #include <utime.h>
  4153. #endif
  4154. #define MZ_FILE FILE
  4155. #define MZ_FOPEN(f, m) fopen64(f, m)
  4156. #define MZ_FCLOSE fclose
  4157. #define MZ_FREAD fread
  4158. #define MZ_FWRITE fwrite
  4159. #define MZ_FTELL64 ftello64
  4160. #define MZ_FSEEK64 fseeko64
  4161. #define MZ_FILE_STAT_STRUCT stat64
  4162. #define MZ_FILE_STAT stat64
  4163. #define MZ_FFLUSH fflush
  4164. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  4165. #define MZ_DELETE_FILE remove
  4166. #else
  4167. #ifndef MINIZ_NO_TIME
  4168. #include <utime.h>
  4169. #endif
  4170. #define MZ_FILE FILE
  4171. #define MZ_FOPEN(f, m) fopen(f, m)
  4172. #define MZ_FCLOSE fclose
  4173. #define MZ_FREAD fread
  4174. #define MZ_FWRITE fwrite
  4175. #define MZ_FTELL64 ftello
  4176. #define MZ_FSEEK64 fseeko
  4177. #define MZ_FILE_STAT_STRUCT stat
  4178. #define MZ_FILE_STAT stat
  4179. #define MZ_FFLUSH fflush
  4180. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  4181. #define MZ_DELETE_FILE remove
  4182. #endif // #ifdef _MSC_VER
  4183. #endif // #ifdef MINIZ_NO_STDIO
  4184. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  4185. // Various ZIP archive enums. To completely avoid cross platform compiler
  4186. // alignment and platform endian issues, miniz.c doesn't use structs for any of
  4187. // this stuff.
  4188. enum {
  4189. // ZIP archive identifiers and record sizes
  4190. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
  4191. MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
  4192. MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  4193. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
  4194. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
  4195. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  4196. // Central directory header record offsets
  4197. MZ_ZIP_CDH_SIG_OFS = 0,
  4198. MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
  4199. MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
  4200. MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  4201. MZ_ZIP_CDH_METHOD_OFS = 10,
  4202. MZ_ZIP_CDH_FILE_TIME_OFS = 12,
  4203. MZ_ZIP_CDH_FILE_DATE_OFS = 14,
  4204. MZ_ZIP_CDH_CRC32_OFS = 16,
  4205. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
  4206. MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
  4207. MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
  4208. MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  4209. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
  4210. MZ_ZIP_CDH_DISK_START_OFS = 34,
  4211. MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
  4212. MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
  4213. MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  4214. // Local directory header offsets
  4215. MZ_ZIP_LDH_SIG_OFS = 0,
  4216. MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
  4217. MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
  4218. MZ_ZIP_LDH_METHOD_OFS = 8,
  4219. MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  4220. MZ_ZIP_LDH_FILE_DATE_OFS = 12,
  4221. MZ_ZIP_LDH_CRC32_OFS = 14,
  4222. MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
  4223. MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  4224. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
  4225. MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  4226. // End of central directory offsets
  4227. MZ_ZIP_ECDH_SIG_OFS = 0,
  4228. MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
  4229. MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
  4230. MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  4231. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
  4232. MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
  4233. MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
  4234. MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  4235. };
  4236. typedef struct {
  4237. void *m_p;
  4238. size_t m_size, m_capacity;
  4239. mz_uint m_element_size;
  4240. } mz_zip_array;
  4241. struct mz_zip_internal_state_tag {
  4242. mz_zip_array m_central_dir;
  4243. mz_zip_array m_central_dir_offsets;
  4244. mz_zip_array m_sorted_central_dir_offsets;
  4245. MZ_FILE *m_pFile;
  4246. void *m_pMem;
  4247. size_t m_mem_size;
  4248. size_t m_mem_capacity;
  4249. };
  4250. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
  4251. (array_ptr)->m_element_size = element_size
  4252. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
  4253. ((element_type *)((array_ptr)->m_p))[index]
  4254. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
  4255. mz_zip_array *pArray) {
  4256. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  4257. memset(pArray, 0, sizeof(mz_zip_array));
  4258. }
  4259. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
  4260. mz_zip_array *pArray,
  4261. size_t min_new_capacity,
  4262. mz_uint growing) {
  4263. void *pNew_p;
  4264. size_t new_capacity = min_new_capacity;
  4265. MZ_ASSERT(pArray->m_element_size);
  4266. if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  4267. if (growing) {
  4268. new_capacity = MZ_MAX(1, pArray->m_capacity);
  4269. while (new_capacity < min_new_capacity) new_capacity *= 2;
  4270. }
  4271. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
  4272. pArray->m_element_size, new_capacity)))
  4273. return MZ_FALSE;
  4274. pArray->m_p = pNew_p;
  4275. pArray->m_capacity = new_capacity;
  4276. return MZ_TRUE;
  4277. }
  4278. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip,
  4279. mz_zip_array *pArray,
  4280. size_t new_capacity,
  4281. mz_uint growing) {
  4282. if (new_capacity > pArray->m_capacity) {
  4283. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
  4284. return MZ_FALSE;
  4285. }
  4286. return MZ_TRUE;
  4287. }
  4288. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip,
  4289. mz_zip_array *pArray,
  4290. size_t new_size,
  4291. mz_uint growing) {
  4292. if (new_size > pArray->m_capacity) {
  4293. if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
  4294. return MZ_FALSE;
  4295. }
  4296. pArray->m_size = new_size;
  4297. return MZ_TRUE;
  4298. }
  4299. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip,
  4300. mz_zip_array *pArray,
  4301. size_t n) {
  4302. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  4303. }
  4304. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip,
  4305. mz_zip_array *pArray,
  4306. const void *pElements,
  4307. size_t n) {
  4308. size_t orig_size = pArray->m_size;
  4309. if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
  4310. return MZ_FALSE;
  4311. memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
  4312. pElements, n * pArray->m_element_size);
  4313. return MZ_TRUE;
  4314. }
  4315. #ifndef MINIZ_NO_TIME
  4316. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
  4317. struct tm tm;
  4318. memset(&tm, 0, sizeof(tm));
  4319. tm.tm_isdst = -1;
  4320. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
  4321. tm.tm_mon = ((dos_date >> 5) & 15) - 1;
  4322. tm.tm_mday = dos_date & 31;
  4323. tm.tm_hour = (dos_time >> 11) & 31;
  4324. tm.tm_min = (dos_time >> 5) & 63;
  4325. tm.tm_sec = (dos_time << 1) & 62;
  4326. return mktime(&tm);
  4327. }
  4328. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
  4329. mz_uint16 *pDOS_date) {
  4330. #ifdef _MSC_VER
  4331. struct tm tm_struct;
  4332. struct tm *tm = &tm_struct;
  4333. errno_t err = localtime_s(tm, &time);
  4334. if (err) {
  4335. *pDOS_date = 0;
  4336. *pDOS_time = 0;
  4337. return;
  4338. }
  4339. #else
  4340. struct tm *tm = localtime(&time);
  4341. #endif
  4342. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
  4343. ((tm->tm_sec) >> 1));
  4344. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
  4345. ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  4346. }
  4347. #endif
  4348. #ifndef MINIZ_NO_STDIO
  4349. static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
  4350. mz_uint16 *pDOS_time,
  4351. mz_uint16 *pDOS_date) {
  4352. #ifdef MINIZ_NO_TIME
  4353. (void)pFilename;
  4354. *pDOS_date = *pDOS_time = 0;
  4355. #else
  4356. struct MZ_FILE_STAT_STRUCT file_stat;
  4357. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
  4358. // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  4359. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE;
  4360. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  4361. #endif // #ifdef MINIZ_NO_TIME
  4362. return MZ_TRUE;
  4363. }
  4364. #ifndef MINIZ_NO_TIME
  4365. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
  4366. time_t modified_time) {
  4367. struct utimbuf t;
  4368. t.actime = access_time;
  4369. t.modtime = modified_time;
  4370. return !utime(pFilename, &t);
  4371. }
  4372. #endif // #ifndef MINIZ_NO_TIME
  4373. #endif // #ifndef MINIZ_NO_STDIO
  4374. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
  4375. mz_uint32 flags) {
  4376. (void)flags;
  4377. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  4378. return MZ_FALSE;
  4379. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  4380. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  4381. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  4382. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  4383. pZip->m_archive_size = 0;
  4384. pZip->m_central_directory_file_ofs = 0;
  4385. pZip->m_total_files = 0;
  4386. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  4387. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  4388. return MZ_FALSE;
  4389. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  4390. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  4391. sizeof(mz_uint8));
  4392. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  4393. sizeof(mz_uint32));
  4394. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  4395. sizeof(mz_uint32));
  4396. return MZ_TRUE;
  4397. }
  4398. static MZ_FORCEINLINE mz_bool
  4399. mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
  4400. const mz_zip_array *pCentral_dir_offsets,
  4401. mz_uint l_index, mz_uint r_index) {
  4402. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4403. pCentral_dir_array, mz_uint8,
  4404. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4405. l_index)),
  4406. *pE;
  4407. const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(
  4408. pCentral_dir_array, mz_uint8,
  4409. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  4410. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
  4411. r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4412. mz_uint8 l = 0, r = 0;
  4413. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4414. pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4415. pE = pL + MZ_MIN(l_len, r_len);
  4416. while (pL < pE) {
  4417. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4418. pL++;
  4419. pR++;
  4420. }
  4421. return (pL == pE) ? (l_len < r_len) : (l < r);
  4422. }
  4423. #define MZ_SWAP_UINT32(a, b) \
  4424. do { \
  4425. mz_uint32 t = a; \
  4426. a = b; \
  4427. b = t; \
  4428. } \
  4429. MZ_MACRO_END
  4430. // Heap sort of lowercased filenames, used to help accelerate plain central
  4431. // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
  4432. // but it could allocate memory.)
  4433. static void mz_zip_reader_sort_central_dir_offsets_by_filename(
  4434. mz_zip_archive *pZip) {
  4435. mz_zip_internal_state *pState = pZip->m_pState;
  4436. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4437. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4438. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4439. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4440. const int size = pZip->m_total_files;
  4441. int start = (size - 2) >> 1, end;
  4442. while (start >= 0) {
  4443. int child, root = start;
  4444. for (;;) {
  4445. if ((child = (root << 1) + 1) >= size) break;
  4446. child +=
  4447. (((child + 1) < size) &&
  4448. (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4449. pIndices[child], pIndices[child + 1])));
  4450. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4451. pIndices[root], pIndices[child]))
  4452. break;
  4453. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4454. root = child;
  4455. }
  4456. start--;
  4457. }
  4458. end = size - 1;
  4459. while (end > 0) {
  4460. int child, root = 0;
  4461. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  4462. for (;;) {
  4463. if ((child = (root << 1) + 1) >= end) break;
  4464. child +=
  4465. (((child + 1) < end) &&
  4466. mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4467. pIndices[child], pIndices[child + 1]));
  4468. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
  4469. pIndices[root], pIndices[child]))
  4470. break;
  4471. MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
  4472. root = child;
  4473. }
  4474. end--;
  4475. }
  4476. }
  4477. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
  4478. mz_uint32 flags) {
  4479. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  4480. mz_uint64 cdir_ofs;
  4481. mz_int64 cur_file_ofs;
  4482. const mz_uint8 *p;
  4483. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
  4484. mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  4485. mz_bool sort_central_dir =
  4486. ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  4487. // Basic sanity checks - reject files which are too small, and check the first
  4488. // 4 bytes of the file to make sure a local header is there.
  4489. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4490. return MZ_FALSE;
  4491. // Find the end of central directory record by scanning the file from the end
  4492. // towards the beginning.
  4493. cur_file_ofs =
  4494. MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  4495. for (;;) {
  4496. int i,
  4497. n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  4498. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  4499. return MZ_FALSE;
  4500. for (i = n - 4; i >= 0; --i)
  4501. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break;
  4502. if (i >= 0) {
  4503. cur_file_ofs += i;
  4504. break;
  4505. }
  4506. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
  4507. (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  4508. return MZ_FALSE;
  4509. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  4510. }
  4511. // Read and verify the end of central directory record.
  4512. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4513. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
  4514. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  4515. return MZ_FALSE;
  4516. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
  4517. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  4518. ((pZip->m_total_files =
  4519. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
  4520. MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  4521. return MZ_FALSE;
  4522. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  4523. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  4524. if (((num_this_disk | cdir_disk_index) != 0) &&
  4525. ((num_this_disk != 1) || (cdir_disk_index != 1)))
  4526. return MZ_FALSE;
  4527. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
  4528. pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  4529. return MZ_FALSE;
  4530. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  4531. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE;
  4532. pZip->m_central_directory_file_ofs = cdir_ofs;
  4533. if (pZip->m_total_files) {
  4534. mz_uint i, n;
  4535. // Read the entire central directory into a heap block, and allocate another
  4536. // heap block to hold the unsorted central dir file record offsets, and
  4537. // another to hold the sorted indices.
  4538. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
  4539. MZ_FALSE)) ||
  4540. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
  4541. pZip->m_total_files, MZ_FALSE)))
  4542. return MZ_FALSE;
  4543. if (sort_central_dir) {
  4544. if (!mz_zip_array_resize(pZip,
  4545. &pZip->m_pState->m_sorted_central_dir_offsets,
  4546. pZip->m_total_files, MZ_FALSE))
  4547. return MZ_FALSE;
  4548. }
  4549. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
  4550. pZip->m_pState->m_central_dir.m_p,
  4551. cdir_size) != cdir_size)
  4552. return MZ_FALSE;
  4553. // Now create an index into the central directory file records, do some
  4554. // basic sanity checking on each record, and check for zip64 entries (which
  4555. // are not yet supported).
  4556. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  4557. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
  4558. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  4559. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
  4560. (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  4561. return MZ_FALSE;
  4562. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4563. i) =
  4564. (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  4565. if (sort_central_dir)
  4566. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
  4567. mz_uint32, i) = i;
  4568. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4569. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4570. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
  4571. (decomp_size != comp_size)) ||
  4572. (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
  4573. (comp_size == 0xFFFFFFFF))
  4574. return MZ_FALSE;
  4575. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  4576. if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE;
  4577. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
  4578. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  4579. return MZ_FALSE;
  4580. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4581. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4582. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  4583. MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
  4584. n)
  4585. return MZ_FALSE;
  4586. n -= total_header_size;
  4587. p += total_header_size;
  4588. }
  4589. }
  4590. if (sort_central_dir)
  4591. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  4592. return MZ_TRUE;
  4593. }
  4594. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
  4595. mz_uint32 flags) {
  4596. if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE;
  4597. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4598. pZip->m_archive_size = size;
  4599. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4600. mz_zip_reader_end(pZip);
  4601. return MZ_FALSE;
  4602. }
  4603. return MZ_TRUE;
  4604. }
  4605. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
  4606. void *pBuf, size_t n) {
  4607. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4608. size_t s = (file_ofs >= pZip->m_archive_size)
  4609. ? 0
  4610. : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  4611. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  4612. return s;
  4613. }
  4614. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
  4615. size_t size, mz_uint32 flags) {
  4616. if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
  4617. pZip->m_archive_size = size;
  4618. pZip->m_pRead = mz_zip_mem_read_func;
  4619. pZip->m_pIO_opaque = pZip;
  4620. #ifdef __cplusplus
  4621. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  4622. #else
  4623. pZip->m_pState->m_pMem = (void *)pMem;
  4624. #endif
  4625. pZip->m_pState->m_mem_size = size;
  4626. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4627. mz_zip_reader_end(pZip);
  4628. return MZ_FALSE;
  4629. }
  4630. return MZ_TRUE;
  4631. }
  4632. #ifndef MINIZ_NO_STDIO
  4633. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
  4634. void *pBuf, size_t n) {
  4635. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  4636. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  4637. if (((mz_int64)file_ofs < 0) ||
  4638. (((cur_ofs != (mz_int64)file_ofs)) &&
  4639. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  4640. return 0;
  4641. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  4642. }
  4643. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
  4644. mz_uint32 flags) {
  4645. mz_uint64 file_size;
  4646. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  4647. if (!pFile) return MZ_FALSE;
  4648. if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
  4649. MZ_FCLOSE(pFile);
  4650. return MZ_FALSE;
  4651. }
  4652. file_size = MZ_FTELL64(pFile);
  4653. if (!mz_zip_reader_init_internal(pZip, flags)) {
  4654. MZ_FCLOSE(pFile);
  4655. return MZ_FALSE;
  4656. }
  4657. pZip->m_pRead = mz_zip_file_read_func;
  4658. pZip->m_pIO_opaque = pZip;
  4659. pZip->m_pState->m_pFile = pFile;
  4660. pZip->m_archive_size = file_size;
  4661. if (!mz_zip_reader_read_central_dir(pZip, flags)) {
  4662. mz_zip_reader_end(pZip);
  4663. return MZ_FALSE;
  4664. }
  4665. return MZ_TRUE;
  4666. }
  4667. #endif // #ifndef MINIZ_NO_STDIO
  4668. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
  4669. return pZip ? pZip->m_total_files : 0;
  4670. }
  4671. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(
  4672. mz_zip_archive *pZip, mz_uint file_index) {
  4673. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
  4674. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4675. return NULL;
  4676. return &MZ_ZIP_ARRAY_ELEMENT(
  4677. &pZip->m_pState->m_central_dir, mz_uint8,
  4678. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4679. file_index));
  4680. }
  4681. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
  4682. mz_uint file_index) {
  4683. mz_uint m_bit_flag;
  4684. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4685. if (!p) return MZ_FALSE;
  4686. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4687. return (m_bit_flag & 1);
  4688. }
  4689. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
  4690. mz_uint file_index) {
  4691. mz_uint filename_len, external_attr;
  4692. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4693. if (!p) return MZ_FALSE;
  4694. // First see if the filename ends with a '/' character.
  4695. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4696. if (filename_len) {
  4697. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  4698. return MZ_TRUE;
  4699. }
  4700. // Bugfix: This code was also checking if the internal attribute was non-zero,
  4701. // which wasn't correct.
  4702. // Most/all zip writers (hopefully) set DOS file/directory attributes in the
  4703. // low 16-bits, so check for the DOS directory flag and ignore the source OS
  4704. // ID in the created by field.
  4705. // FIXME: Remove this check? Is it necessary - we already check the filename.
  4706. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4707. if ((external_attr & 0x10) != 0) return MZ_TRUE;
  4708. return MZ_FALSE;
  4709. }
  4710. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
  4711. mz_zip_archive_file_stat *pStat) {
  4712. mz_uint n;
  4713. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4714. if ((!p) || (!pStat)) return MZ_FALSE;
  4715. // Unpack the central directory record.
  4716. pStat->m_file_index = file_index;
  4717. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
  4718. &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  4719. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  4720. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  4721. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  4722. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  4723. #ifndef MINIZ_NO_TIME
  4724. pStat->m_time =
  4725. mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
  4726. MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  4727. #endif
  4728. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  4729. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4730. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  4731. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  4732. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  4733. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4734. // Copy as much of the filename and comment as possible.
  4735. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4736. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  4737. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4738. pStat->m_filename[n] = '\0';
  4739. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4740. n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  4741. pStat->m_comment_size = n;
  4742. memcpy(pStat->m_comment,
  4743. p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  4744. MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  4745. MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4746. n);
  4747. pStat->m_comment[n] = '\0';
  4748. return MZ_TRUE;
  4749. }
  4750. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
  4751. char *pFilename, mz_uint filename_buf_size) {
  4752. mz_uint n;
  4753. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  4754. if (!p) {
  4755. if (filename_buf_size) pFilename[0] = '\0';
  4756. return 0;
  4757. }
  4758. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4759. if (filename_buf_size) {
  4760. n = MZ_MIN(n, filename_buf_size - 1);
  4761. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  4762. pFilename[n] = '\0';
  4763. }
  4764. return n + 1;
  4765. }
  4766. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA,
  4767. const char *pB,
  4768. mz_uint len,
  4769. mz_uint flags) {
  4770. mz_uint i;
  4771. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len);
  4772. for (i = 0; i < len; ++i)
  4773. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE;
  4774. return MZ_TRUE;
  4775. }
  4776. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(
  4777. const mz_zip_array *pCentral_dir_array,
  4778. const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR,
  4779. mz_uint r_len) {
  4780. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
  4781. pCentral_dir_array, mz_uint8,
  4782. MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
  4783. l_index)),
  4784. *pE;
  4785. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4786. mz_uint8 l = 0, r = 0;
  4787. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4788. pE = pL + MZ_MIN(l_len, r_len);
  4789. while (pL < pE) {
  4790. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
  4791. pL++;
  4792. pR++;
  4793. }
  4794. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  4795. }
  4796. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
  4797. const char *pFilename) {
  4798. mz_zip_internal_state *pState = pZip->m_pState;
  4799. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  4800. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  4801. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
  4802. &pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  4803. const int size = pZip->m_total_files;
  4804. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  4805. int l = 0, h = size - 1;
  4806. while (l <= h) {
  4807. int m = (l + h) >> 1, file_index = pIndices[m],
  4808. comp =
  4809. mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
  4810. file_index, pFilename, filename_len);
  4811. if (!comp)
  4812. return file_index;
  4813. else if (comp < 0)
  4814. l = m + 1;
  4815. else
  4816. h = m - 1;
  4817. }
  4818. return -1;
  4819. }
  4820. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
  4821. const char *pComment, mz_uint flags) {
  4822. mz_uint file_index;
  4823. size_t name_len, comment_len;
  4824. if ((!pZip) || (!pZip->m_pState) || (!pName) ||
  4825. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  4826. return -1;
  4827. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
  4828. (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  4829. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  4830. name_len = strlen(pName);
  4831. if (name_len > 0xFFFF) return -1;
  4832. comment_len = pComment ? strlen(pComment) : 0;
  4833. if (comment_len > 0xFFFF) return -1;
  4834. for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
  4835. const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(
  4836. &pZip->m_pState->m_central_dir, mz_uint8,
  4837. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
  4838. file_index));
  4839. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  4840. const char *pFilename =
  4841. (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  4842. if (filename_len < name_len) continue;
  4843. if (comment_len) {
  4844. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
  4845. file_comment_len =
  4846. MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4847. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  4848. if ((file_comment_len != comment_len) ||
  4849. (!mz_zip_reader_string_equal(pComment, pFile_comment,
  4850. file_comment_len, flags)))
  4851. continue;
  4852. }
  4853. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
  4854. int ofs = filename_len - 1;
  4855. do {
  4856. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
  4857. (pFilename[ofs] == ':'))
  4858. break;
  4859. } while (--ofs >= 0);
  4860. ofs++;
  4861. pFilename += ofs;
  4862. filename_len -= ofs;
  4863. }
  4864. if ((filename_len == name_len) &&
  4865. (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  4866. return file_index;
  4867. }
  4868. return -1;
  4869. }
  4870. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
  4871. mz_uint file_index, void *pBuf,
  4872. size_t buf_size, mz_uint flags,
  4873. void *pUser_read_buf,
  4874. size_t user_read_buf_size) {
  4875. int status = TINFL_STATUS_DONE;
  4876. mz_uint64 needed_size, cur_file_ofs, comp_remaining,
  4877. out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  4878. mz_zip_archive_file_stat file_stat;
  4879. void *pRead_buf;
  4880. mz_uint32
  4881. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  4882. sizeof(mz_uint32)];
  4883. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4884. tinfl_decompressor inflator;
  4885. if ((buf_size) && (!pBuf)) return MZ_FALSE;
  4886. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  4887. // Empty file, or a directory (but not always a directory - I've seen odd zips
  4888. // with directories that have compressed data which inflates to 0 bytes)
  4889. if (!file_stat.m_comp_size) return MZ_TRUE;
  4890. // Entry is a subdirectory (I've seen old zips with dir entries which have
  4891. // compressed deflate data which inflates to 0 bytes, but these entries claim
  4892. // to uncompress to 512 bytes in the headers).
  4893. // I'm torn how to handle this case - should it fail instead?
  4894. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  4895. // Encryption and patch files are not supported.
  4896. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  4897. // This function only supports stored and deflate.
  4898. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  4899. (file_stat.m_method != MZ_DEFLATED))
  4900. return MZ_FALSE;
  4901. // Ensure supplied output buffer is large enough.
  4902. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
  4903. : file_stat.m_uncomp_size;
  4904. if (buf_size < needed_size) return MZ_FALSE;
  4905. // Read and parse the local directory entry.
  4906. cur_file_ofs = file_stat.m_local_header_ofs;
  4907. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  4908. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  4909. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4910. return MZ_FALSE;
  4911. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4912. return MZ_FALSE;
  4913. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  4914. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  4915. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4916. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  4917. return MZ_FALSE;
  4918. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  4919. // The file is stored or the caller has requested the compressed data.
  4920. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
  4921. (size_t)needed_size) != needed_size)
  4922. return MZ_FALSE;
  4923. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
  4924. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4925. (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  4926. }
  4927. // Decompress the file either directly from memory or from a file input
  4928. // buffer.
  4929. tinfl_init(&inflator);
  4930. if (pZip->m_pState->m_pMem) {
  4931. // Read directly from the archive in memory.
  4932. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  4933. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  4934. comp_remaining = 0;
  4935. } else if (pUser_read_buf) {
  4936. // Use a user provided read buffer.
  4937. if (!user_read_buf_size) return MZ_FALSE;
  4938. pRead_buf = (mz_uint8 *)pUser_read_buf;
  4939. read_buf_size = user_read_buf_size;
  4940. read_buf_avail = 0;
  4941. comp_remaining = file_stat.m_comp_size;
  4942. } else {
  4943. // Temporarily allocate a read buffer.
  4944. read_buf_size =
  4945. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  4946. #ifdef _MSC_VER
  4947. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  4948. (read_buf_size > 0x7FFFFFFF))
  4949. #else
  4950. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  4951. #endif
  4952. return MZ_FALSE;
  4953. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  4954. (size_t)read_buf_size)))
  4955. return MZ_FALSE;
  4956. read_buf_avail = 0;
  4957. comp_remaining = file_stat.m_comp_size;
  4958. }
  4959. do {
  4960. size_t in_buf_size,
  4961. out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  4962. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  4963. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  4964. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  4965. (size_t)read_buf_avail) != read_buf_avail) {
  4966. status = TINFL_STATUS_FAILED;
  4967. break;
  4968. }
  4969. cur_file_ofs += read_buf_avail;
  4970. comp_remaining -= read_buf_avail;
  4971. read_buf_ofs = 0;
  4972. }
  4973. in_buf_size = (size_t)read_buf_avail;
  4974. status = tinfl_decompress(
  4975. &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  4976. (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
  4977. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
  4978. (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  4979. read_buf_avail -= in_buf_size;
  4980. read_buf_ofs += in_buf_size;
  4981. out_buf_ofs += out_buf_size;
  4982. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  4983. if (status == TINFL_STATUS_DONE) {
  4984. // Make sure the entire file was decompressed, and check its CRC.
  4985. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  4986. (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
  4987. (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  4988. status = TINFL_STATUS_FAILED;
  4989. }
  4990. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  4991. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4992. return status == TINFL_STATUS_DONE;
  4993. }
  4994. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
  4995. mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
  4996. mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
  4997. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  4998. if (file_index < 0) return MZ_FALSE;
  4999. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  5000. flags, pUser_read_buf,
  5001. user_read_buf_size);
  5002. }
  5003. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
  5004. void *pBuf, size_t buf_size,
  5005. mz_uint flags) {
  5006. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
  5007. flags, NULL, 0);
  5008. }
  5009. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
  5010. const char *pFilename, void *pBuf,
  5011. size_t buf_size, mz_uint flags) {
  5012. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
  5013. buf_size, flags, NULL, 0);
  5014. }
  5015. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
  5016. size_t *pSize, mz_uint flags) {
  5017. mz_uint64 comp_size, uncomp_size, alloc_size;
  5018. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  5019. void *pBuf;
  5020. if (pSize) *pSize = 0;
  5021. if (!p) return NULL;
  5022. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5023. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  5024. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  5025. #ifdef _MSC_VER
  5026. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5027. #else
  5028. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  5029. #endif
  5030. return NULL;
  5031. if (NULL ==
  5032. (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  5033. return NULL;
  5034. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
  5035. flags)) {
  5036. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5037. return NULL;
  5038. }
  5039. if (pSize) *pSize = (size_t)alloc_size;
  5040. return pBuf;
  5041. }
  5042. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
  5043. const char *pFilename, size_t *pSize,
  5044. mz_uint flags) {
  5045. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5046. if (file_index < 0) {
  5047. if (pSize) *pSize = 0;
  5048. return MZ_FALSE;
  5049. }
  5050. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  5051. }
  5052. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
  5053. mz_uint file_index,
  5054. mz_file_write_func pCallback,
  5055. void *pOpaque, mz_uint flags) {
  5056. int status = TINFL_STATUS_DONE;
  5057. mz_uint file_crc32 = MZ_CRC32_INIT;
  5058. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
  5059. out_buf_ofs = 0, cur_file_ofs;
  5060. mz_zip_archive_file_stat file_stat;
  5061. void *pRead_buf = NULL;
  5062. void *pWrite_buf = NULL;
  5063. mz_uint32
  5064. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5065. sizeof(mz_uint32)];
  5066. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5067. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5068. // Empty file, or a directory (but not always a directory - I've seen odd zips
  5069. // with directories that have compressed data which inflates to 0 bytes)
  5070. if (!file_stat.m_comp_size) return MZ_TRUE;
  5071. // Entry is a subdirectory (I've seen old zips with dir entries which have
  5072. // compressed deflate data which inflates to 0 bytes, but these entries claim
  5073. // to uncompress to 512 bytes in the headers).
  5074. // I'm torn how to handle this case - should it fail instead?
  5075. if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
  5076. // Encryption and patch files are not supported.
  5077. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
  5078. // This function only supports stored and deflate.
  5079. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
  5080. (file_stat.m_method != MZ_DEFLATED))
  5081. return MZ_FALSE;
  5082. // Read and parse the local directory entry.
  5083. cur_file_ofs = file_stat.m_local_header_ofs;
  5084. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
  5085. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5086. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5087. return MZ_FALSE;
  5088. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5089. return MZ_FALSE;
  5090. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
  5091. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5092. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5093. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  5094. return MZ_FALSE;
  5095. // Decompress the file either directly from memory or from a file input
  5096. // buffer.
  5097. if (pZip->m_pState->m_pMem) {
  5098. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  5099. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  5100. comp_remaining = 0;
  5101. } else {
  5102. read_buf_size =
  5103. MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5104. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5105. (size_t)read_buf_size)))
  5106. return MZ_FALSE;
  5107. read_buf_avail = 0;
  5108. comp_remaining = file_stat.m_comp_size;
  5109. }
  5110. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
  5111. // The file is stored or the caller has requested the compressed data.
  5112. if (pZip->m_pState->m_pMem) {
  5113. #ifdef _MSC_VER
  5114. if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
  5115. (file_stat.m_comp_size > 0xFFFFFFFF))
  5116. #else
  5117. if (((sizeof(size_t) == sizeof(mz_uint32))) &&
  5118. (file_stat.m_comp_size > 0xFFFFFFFF))
  5119. #endif
  5120. return MZ_FALSE;
  5121. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5122. (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  5123. status = TINFL_STATUS_FAILED;
  5124. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5125. file_crc32 =
  5126. (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
  5127. (size_t)file_stat.m_comp_size);
  5128. cur_file_ofs += file_stat.m_comp_size;
  5129. out_buf_ofs += file_stat.m_comp_size;
  5130. comp_remaining = 0;
  5131. } else {
  5132. while (comp_remaining) {
  5133. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5134. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5135. (size_t)read_buf_avail) != read_buf_avail) {
  5136. status = TINFL_STATUS_FAILED;
  5137. break;
  5138. }
  5139. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  5140. file_crc32 = (mz_uint32)mz_crc32(
  5141. file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  5142. if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
  5143. (size_t)read_buf_avail) != read_buf_avail) {
  5144. status = TINFL_STATUS_FAILED;
  5145. break;
  5146. }
  5147. cur_file_ofs += read_buf_avail;
  5148. out_buf_ofs += read_buf_avail;
  5149. comp_remaining -= read_buf_avail;
  5150. }
  5151. }
  5152. } else {
  5153. tinfl_decompressor inflator;
  5154. tinfl_init(&inflator);
  5155. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
  5156. TINFL_LZ_DICT_SIZE)))
  5157. status = TINFL_STATUS_FAILED;
  5158. else {
  5159. do {
  5160. mz_uint8 *pWrite_buf_cur =
  5161. (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5162. size_t in_buf_size,
  5163. out_buf_size =
  5164. TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  5165. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
  5166. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  5167. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
  5168. (size_t)read_buf_avail) != read_buf_avail) {
  5169. status = TINFL_STATUS_FAILED;
  5170. break;
  5171. }
  5172. cur_file_ofs += read_buf_avail;
  5173. comp_remaining -= read_buf_avail;
  5174. read_buf_ofs = 0;
  5175. }
  5176. in_buf_size = (size_t)read_buf_avail;
  5177. status = tinfl_decompress(
  5178. &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
  5179. (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
  5180. comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  5181. read_buf_avail -= in_buf_size;
  5182. read_buf_ofs += in_buf_size;
  5183. if (out_buf_size) {
  5184. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
  5185. out_buf_size) {
  5186. status = TINFL_STATUS_FAILED;
  5187. break;
  5188. }
  5189. file_crc32 =
  5190. (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  5191. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
  5192. status = TINFL_STATUS_FAILED;
  5193. break;
  5194. }
  5195. }
  5196. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
  5197. (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  5198. }
  5199. }
  5200. if ((status == TINFL_STATUS_DONE) &&
  5201. (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
  5202. // Make sure the entire file was decompressed, and check its CRC.
  5203. if ((out_buf_ofs != file_stat.m_uncomp_size) ||
  5204. (file_crc32 != file_stat.m_crc32))
  5205. status = TINFL_STATUS_FAILED;
  5206. }
  5207. if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5208. if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  5209. return status == TINFL_STATUS_DONE;
  5210. }
  5211. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
  5212. const char *pFilename,
  5213. mz_file_write_func pCallback,
  5214. void *pOpaque, mz_uint flags) {
  5215. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  5216. if (file_index < 0) return MZ_FALSE;
  5217. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
  5218. flags);
  5219. }
  5220. #ifndef MINIZ_NO_STDIO
  5221. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
  5222. const void *pBuf, size_t n) {
  5223. (void)ofs;
  5224. return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
  5225. }
  5226. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
  5227. const char *pDst_filename,
  5228. mz_uint flags) {
  5229. mz_bool status;
  5230. mz_zip_archive_file_stat file_stat;
  5231. MZ_FILE *pFile;
  5232. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
  5233. pFile = MZ_FOPEN(pDst_filename, "wb");
  5234. if (!pFile) return MZ_FALSE;
  5235. status = mz_zip_reader_extract_to_callback(
  5236. pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  5237. if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE;
  5238. #ifndef MINIZ_NO_TIME
  5239. if (status)
  5240. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  5241. #endif
  5242. return status;
  5243. }
  5244. #endif // #ifndef MINIZ_NO_STDIO
  5245. mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
  5246. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  5247. (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5248. return MZ_FALSE;
  5249. if (pZip->m_pState) {
  5250. mz_zip_internal_state *pState = pZip->m_pState;
  5251. pZip->m_pState = NULL;
  5252. mz_zip_array_clear(pZip, &pState->m_central_dir);
  5253. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  5254. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  5255. #ifndef MINIZ_NO_STDIO
  5256. if (pState->m_pFile) {
  5257. MZ_FCLOSE(pState->m_pFile);
  5258. pState->m_pFile = NULL;
  5259. }
  5260. #endif // #ifndef MINIZ_NO_STDIO
  5261. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  5262. }
  5263. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  5264. return MZ_TRUE;
  5265. }
  5266. #ifndef MINIZ_NO_STDIO
  5267. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
  5268. const char *pArchive_filename,
  5269. const char *pDst_filename,
  5270. mz_uint flags) {
  5271. int file_index =
  5272. mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  5273. if (file_index < 0) return MZ_FALSE;
  5274. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  5275. }
  5276. #endif
  5277. // ------------------- .ZIP archive writing
  5278. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  5279. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
  5280. p[0] = (mz_uint8)v;
  5281. p[1] = (mz_uint8)(v >> 8);
  5282. }
  5283. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
  5284. p[0] = (mz_uint8)v;
  5285. p[1] = (mz_uint8)(v >> 8);
  5286. p[2] = (mz_uint8)(v >> 16);
  5287. p[3] = (mz_uint8)(v >> 24);
  5288. }
  5289. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  5290. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  5291. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
  5292. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
  5293. (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  5294. return MZ_FALSE;
  5295. if (pZip->m_file_offset_alignment) {
  5296. // Ensure user specified file offset alignment is a power of 2.
  5297. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  5298. return MZ_FALSE;
  5299. }
  5300. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  5301. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  5302. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  5303. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5304. pZip->m_archive_size = existing_size;
  5305. pZip->m_central_directory_file_ofs = 0;
  5306. pZip->m_total_files = 0;
  5307. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
  5308. pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  5309. return MZ_FALSE;
  5310. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  5311. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
  5312. sizeof(mz_uint8));
  5313. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
  5314. sizeof(mz_uint32));
  5315. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
  5316. sizeof(mz_uint32));
  5317. return MZ_TRUE;
  5318. }
  5319. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
  5320. const void *pBuf, size_t n) {
  5321. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5322. mz_zip_internal_state *pState = pZip->m_pState;
  5323. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  5324. #ifdef _MSC_VER
  5325. if ((!n) ||
  5326. ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5327. #else
  5328. if ((!n) ||
  5329. ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  5330. #endif
  5331. return 0;
  5332. if (new_size > pState->m_mem_capacity) {
  5333. void *pNew_block;
  5334. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
  5335. while (new_capacity < new_size) new_capacity *= 2;
  5336. if (NULL == (pNew_block = pZip->m_pRealloc(
  5337. pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  5338. return 0;
  5339. pState->m_pMem = pNew_block;
  5340. pState->m_mem_capacity = new_capacity;
  5341. }
  5342. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  5343. pState->m_mem_size = (size_t)new_size;
  5344. return n;
  5345. }
  5346. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
  5347. size_t size_to_reserve_at_beginning,
  5348. size_t initial_allocation_size) {
  5349. pZip->m_pWrite = mz_zip_heap_write_func;
  5350. pZip->m_pIO_opaque = pZip;
  5351. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5352. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
  5353. size_to_reserve_at_beginning))) {
  5354. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
  5355. pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
  5356. mz_zip_writer_end(pZip);
  5357. return MZ_FALSE;
  5358. }
  5359. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  5360. }
  5361. return MZ_TRUE;
  5362. }
  5363. #ifndef MINIZ_NO_STDIO
  5364. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
  5365. const void *pBuf, size_t n) {
  5366. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  5367. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  5368. if (((mz_int64)file_ofs < 0) ||
  5369. (((cur_ofs != (mz_int64)file_ofs)) &&
  5370. (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  5371. return 0;
  5372. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  5373. }
  5374. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
  5375. mz_uint64 size_to_reserve_at_beginning) {
  5376. MZ_FILE *pFile;
  5377. pZip->m_pWrite = mz_zip_file_write_func;
  5378. pZip->m_pIO_opaque = pZip;
  5379. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
  5380. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
  5381. mz_zip_writer_end(pZip);
  5382. return MZ_FALSE;
  5383. }
  5384. pZip->m_pState->m_pFile = pFile;
  5385. if (size_to_reserve_at_beginning) {
  5386. mz_uint64 cur_ofs = 0;
  5387. char buf[4096];
  5388. MZ_CLEAR_OBJ(buf);
  5389. do {
  5390. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  5391. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
  5392. mz_zip_writer_end(pZip);
  5393. return MZ_FALSE;
  5394. }
  5395. cur_ofs += n;
  5396. size_to_reserve_at_beginning -= n;
  5397. } while (size_to_reserve_at_beginning);
  5398. }
  5399. return MZ_TRUE;
  5400. }
  5401. #endif // #ifndef MINIZ_NO_STDIO
  5402. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
  5403. const char *pFilename) {
  5404. mz_zip_internal_state *pState;
  5405. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  5406. return MZ_FALSE;
  5407. // No sense in trying to write to an archive that's already at the support max
  5408. // size
  5409. if ((pZip->m_total_files == 0xFFFF) ||
  5410. ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5411. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  5412. return MZ_FALSE;
  5413. pState = pZip->m_pState;
  5414. if (pState->m_pFile) {
  5415. #ifdef MINIZ_NO_STDIO
  5416. pFilename;
  5417. return MZ_FALSE;
  5418. #else
  5419. // Archive is being read from stdio - try to reopen as writable.
  5420. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5421. if (!pFilename) return MZ_FALSE;
  5422. pZip->m_pWrite = mz_zip_file_write_func;
  5423. if (NULL ==
  5424. (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
  5425. // The mz_zip_archive is now in a bogus state because pState->m_pFile is
  5426. // NULL, so just close it.
  5427. mz_zip_reader_end(pZip);
  5428. return MZ_FALSE;
  5429. }
  5430. #endif // #ifdef MINIZ_NO_STDIO
  5431. } else if (pState->m_pMem) {
  5432. // Archive lives in a memory block. Assume it's from the heap that we can
  5433. // resize using the realloc callback.
  5434. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
  5435. pState->m_mem_capacity = pState->m_mem_size;
  5436. pZip->m_pWrite = mz_zip_heap_write_func;
  5437. }
  5438. // Archive is being read via a user provided read function - make sure the
  5439. // user has specified a write function too.
  5440. else if (!pZip->m_pWrite)
  5441. return MZ_FALSE;
  5442. // Start writing new files at the archive's current central directory
  5443. // location.
  5444. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  5445. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  5446. pZip->m_central_directory_file_ofs = 0;
  5447. return MZ_TRUE;
  5448. }
  5449. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
  5450. const void *pBuf, size_t buf_size,
  5451. mz_uint level_and_flags) {
  5452. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
  5453. level_and_flags, 0, 0);
  5454. }
  5455. typedef struct {
  5456. mz_zip_archive *m_pZip;
  5457. mz_uint64 m_cur_archive_file_ofs;
  5458. mz_uint64 m_comp_size;
  5459. } mz_zip_writer_add_state;
  5460. static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
  5461. void *pUser) {
  5462. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  5463. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
  5464. pState->m_cur_archive_file_ofs, pBuf,
  5465. len) != len)
  5466. return MZ_FALSE;
  5467. pState->m_cur_archive_file_ofs += len;
  5468. pState->m_comp_size += len;
  5469. return MZ_TRUE;
  5470. }
  5471. static mz_bool mz_zip_writer_create_local_dir_header(
  5472. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5473. mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5474. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5475. mz_uint16 dos_time, mz_uint16 dos_date) {
  5476. (void)pZip;
  5477. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  5478. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  5479. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5480. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  5481. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  5482. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  5483. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  5484. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  5485. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  5486. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5487. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  5488. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  5489. return MZ_TRUE;
  5490. }
  5491. static mz_bool mz_zip_writer_create_central_dir_header(
  5492. mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
  5493. mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
  5494. mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
  5495. mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
  5496. mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
  5497. (void)pZip;
  5498. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5499. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  5500. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  5501. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  5502. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  5503. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  5504. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  5505. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  5506. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  5507. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  5508. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  5509. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  5510. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  5511. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  5512. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  5513. return MZ_TRUE;
  5514. }
  5515. static mz_bool mz_zip_writer_add_to_central_dir(
  5516. mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
  5517. const void *pExtra, mz_uint16 extra_size, const void *pComment,
  5518. mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
  5519. mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
  5520. mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
  5521. mz_uint32 ext_attributes) {
  5522. mz_zip_internal_state *pState = pZip->m_pState;
  5523. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  5524. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  5525. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5526. // No zip64 support yet
  5527. if ((local_header_ofs > 0xFFFFFFFF) ||
  5528. (((mz_uint64)pState->m_central_dir.m_size +
  5529. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
  5530. comment_size) > 0xFFFFFFFF))
  5531. return MZ_FALSE;
  5532. if (!mz_zip_writer_create_central_dir_header(
  5533. pZip, central_dir_header, filename_size, extra_size, comment_size,
  5534. uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
  5535. dos_date, local_header_ofs, ext_attributes))
  5536. return MZ_FALSE;
  5537. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
  5538. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  5539. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
  5540. filename_size)) ||
  5541. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
  5542. extra_size)) ||
  5543. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
  5544. comment_size)) ||
  5545. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
  5546. &central_dir_ofs, 1))) {
  5547. // Try to push the central directory array back into its original state.
  5548. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  5549. MZ_FALSE);
  5550. return MZ_FALSE;
  5551. }
  5552. return MZ_TRUE;
  5553. }
  5554. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
  5555. // Basic ZIP archive filename validity checks: Valid filenames cannot start
  5556. // with a forward slash, cannot contain a drive letter, and cannot use
  5557. // DOS-style backward slashes.
  5558. if (*pArchive_name == '/') return MZ_FALSE;
  5559. while (*pArchive_name) {
  5560. if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE;
  5561. pArchive_name++;
  5562. }
  5563. return MZ_TRUE;
  5564. }
  5565. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(
  5566. mz_zip_archive *pZip) {
  5567. mz_uint32 n;
  5568. if (!pZip->m_file_offset_alignment) return 0;
  5569. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  5570. return (pZip->m_file_offset_alignment - n) &
  5571. (pZip->m_file_offset_alignment - 1);
  5572. }
  5573. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
  5574. mz_uint64 cur_file_ofs, mz_uint32 n) {
  5575. char buf[4096];
  5576. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  5577. while (n) {
  5578. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  5579. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  5580. return MZ_FALSE;
  5581. cur_file_ofs += s;
  5582. n -= s;
  5583. }
  5584. return MZ_TRUE;
  5585. }
  5586. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
  5587. const char *pArchive_name, const void *pBuf,
  5588. size_t buf_size, const void *pComment,
  5589. mz_uint16 comment_size,
  5590. mz_uint level_and_flags, mz_uint64 uncomp_size,
  5591. mz_uint32 uncomp_crc32) {
  5592. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  5593. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  5594. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5595. cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  5596. size_t archive_name_size;
  5597. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5598. tdefl_compressor *pComp = NULL;
  5599. mz_bool store_data_uncompressed;
  5600. mz_zip_internal_state *pState;
  5601. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5602. level = level_and_flags & 0xF;
  5603. store_data_uncompressed =
  5604. ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  5605. if ((!pZip) || (!pZip->m_pState) ||
  5606. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
  5607. (!pArchive_name) || ((comment_size) && (!pComment)) ||
  5608. (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  5609. return MZ_FALSE;
  5610. pState = pZip->m_pState;
  5611. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  5612. return MZ_FALSE;
  5613. // No zip64 support yet
  5614. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE;
  5615. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5616. #ifndef MINIZ_NO_TIME
  5617. {
  5618. time_t cur_time;
  5619. time(&cur_time);
  5620. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  5621. }
  5622. #endif // #ifndef MINIZ_NO_TIME
  5623. archive_name_size = strlen(pArchive_name);
  5624. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5625. num_alignment_padding_bytes =
  5626. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5627. // no zip64 support yet
  5628. if ((pZip->m_total_files == 0xFFFF) ||
  5629. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5630. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5631. comment_size + archive_name_size) > 0xFFFFFFFF))
  5632. return MZ_FALSE;
  5633. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
  5634. // Set DOS Subdirectory attribute bit.
  5635. ext_attributes |= 0x10;
  5636. // Subdirectories cannot contain data.
  5637. if ((buf_size) || (uncomp_size)) return MZ_FALSE;
  5638. }
  5639. // Try to do any allocations before writing to the archive, so if an
  5640. // allocation fails the file remains unmodified. (A good idea if we're doing
  5641. // an in-place modification.)
  5642. if ((!mz_zip_array_ensure_room(
  5643. pZip, &pState->m_central_dir,
  5644. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) ||
  5645. (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  5646. return MZ_FALSE;
  5647. if ((!store_data_uncompressed) && (buf_size)) {
  5648. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5649. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  5650. return MZ_FALSE;
  5651. }
  5652. if (!mz_zip_writer_write_zeros(
  5653. pZip, cur_archive_file_ofs,
  5654. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5655. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5656. return MZ_FALSE;
  5657. }
  5658. local_dir_header_ofs += num_alignment_padding_bytes;
  5659. if (pZip->m_file_offset_alignment) {
  5660. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5661. 0);
  5662. }
  5663. cur_archive_file_ofs +=
  5664. num_alignment_padding_bytes + sizeof(local_dir_header);
  5665. MZ_CLEAR_OBJ(local_dir_header);
  5666. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5667. archive_name_size) != archive_name_size) {
  5668. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5669. return MZ_FALSE;
  5670. }
  5671. cur_archive_file_ofs += archive_name_size;
  5672. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
  5673. uncomp_crc32 =
  5674. (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
  5675. uncomp_size = buf_size;
  5676. if (uncomp_size <= 3) {
  5677. level = 0;
  5678. store_data_uncompressed = MZ_TRUE;
  5679. }
  5680. }
  5681. if (store_data_uncompressed) {
  5682. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
  5683. buf_size) != buf_size) {
  5684. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5685. return MZ_FALSE;
  5686. }
  5687. cur_archive_file_ofs += buf_size;
  5688. comp_size = buf_size;
  5689. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED;
  5690. } else if (buf_size) {
  5691. mz_zip_writer_add_state state;
  5692. state.m_pZip = pZip;
  5693. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5694. state.m_comp_size = 0;
  5695. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5696. tdefl_create_comp_flags_from_zip_params(
  5697. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5698. TDEFL_STATUS_OKAY) ||
  5699. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
  5700. TDEFL_STATUS_DONE)) {
  5701. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5702. return MZ_FALSE;
  5703. }
  5704. comp_size = state.m_comp_size;
  5705. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5706. method = MZ_DEFLATED;
  5707. }
  5708. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5709. pComp = NULL;
  5710. // no zip64 support yet
  5711. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5712. return MZ_FALSE;
  5713. if (!mz_zip_writer_create_local_dir_header(
  5714. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5715. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5716. return MZ_FALSE;
  5717. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5718. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5719. return MZ_FALSE;
  5720. if (!mz_zip_writer_add_to_central_dir(
  5721. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5722. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5723. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5724. return MZ_FALSE;
  5725. pZip->m_total_files++;
  5726. pZip->m_archive_size = cur_archive_file_ofs;
  5727. return MZ_TRUE;
  5728. }
  5729. #ifndef MINIZ_NO_STDIO
  5730. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
  5731. const char *pSrc_filename, const void *pComment,
  5732. mz_uint16 comment_size,
  5733. mz_uint level_and_flags) {
  5734. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  5735. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  5736. mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
  5737. cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
  5738. comp_size = 0;
  5739. size_t archive_name_size;
  5740. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  5741. MZ_FILE *pSrc_file = NULL;
  5742. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  5743. level = level_and_flags & 0xF;
  5744. if ((!pZip) || (!pZip->m_pState) ||
  5745. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
  5746. ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  5747. return MZ_FALSE;
  5748. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE;
  5749. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  5750. archive_name_size = strlen(pArchive_name);
  5751. if (archive_name_size > 0xFFFF) return MZ_FALSE;
  5752. num_alignment_padding_bytes =
  5753. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5754. // no zip64 support yet
  5755. if ((pZip->m_total_files == 0xFFFF) ||
  5756. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5757. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
  5758. comment_size + archive_name_size) > 0xFFFFFFFF))
  5759. return MZ_FALSE;
  5760. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  5761. return MZ_FALSE;
  5762. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  5763. if (!pSrc_file) return MZ_FALSE;
  5764. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  5765. uncomp_size = MZ_FTELL64(pSrc_file);
  5766. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  5767. if (uncomp_size > 0xFFFFFFFF) {
  5768. // No zip64 support yet
  5769. MZ_FCLOSE(pSrc_file);
  5770. return MZ_FALSE;
  5771. }
  5772. if (uncomp_size <= 3) level = 0;
  5773. if (!mz_zip_writer_write_zeros(
  5774. pZip, cur_archive_file_ofs,
  5775. num_alignment_padding_bytes + sizeof(local_dir_header))) {
  5776. MZ_FCLOSE(pSrc_file);
  5777. return MZ_FALSE;
  5778. }
  5779. local_dir_header_ofs += num_alignment_padding_bytes;
  5780. if (pZip->m_file_offset_alignment) {
  5781. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5782. 0);
  5783. }
  5784. cur_archive_file_ofs +=
  5785. num_alignment_padding_bytes + sizeof(local_dir_header);
  5786. MZ_CLEAR_OBJ(local_dir_header);
  5787. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
  5788. archive_name_size) != archive_name_size) {
  5789. MZ_FCLOSE(pSrc_file);
  5790. return MZ_FALSE;
  5791. }
  5792. cur_archive_file_ofs += archive_name_size;
  5793. if (uncomp_size) {
  5794. mz_uint64 uncomp_remaining = uncomp_size;
  5795. void *pRead_buf =
  5796. pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  5797. if (!pRead_buf) {
  5798. MZ_FCLOSE(pSrc_file);
  5799. return MZ_FALSE;
  5800. }
  5801. if (!level) {
  5802. while (uncomp_remaining) {
  5803. mz_uint n =
  5804. (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  5805. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
  5806. (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
  5807. n) != n)) {
  5808. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5809. MZ_FCLOSE(pSrc_file);
  5810. return MZ_FALSE;
  5811. }
  5812. uncomp_crc32 =
  5813. (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  5814. uncomp_remaining -= n;
  5815. cur_archive_file_ofs += n;
  5816. }
  5817. comp_size = uncomp_size;
  5818. } else {
  5819. mz_bool result = MZ_FALSE;
  5820. mz_zip_writer_add_state state;
  5821. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
  5822. pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  5823. if (!pComp) {
  5824. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5825. MZ_FCLOSE(pSrc_file);
  5826. return MZ_FALSE;
  5827. }
  5828. state.m_pZip = pZip;
  5829. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  5830. state.m_comp_size = 0;
  5831. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
  5832. tdefl_create_comp_flags_from_zip_params(
  5833. level, -15, MZ_DEFAULT_STRATEGY)) !=
  5834. TDEFL_STATUS_OKAY) {
  5835. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5836. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5837. MZ_FCLOSE(pSrc_file);
  5838. return MZ_FALSE;
  5839. }
  5840. for (;;) {
  5841. size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining,
  5842. (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
  5843. tdefl_status status;
  5844. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  5845. break;
  5846. uncomp_crc32 = (mz_uint32)mz_crc32(
  5847. uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  5848. uncomp_remaining -= in_buf_size;
  5849. status = tdefl_compress_buffer(
  5850. pComp, pRead_buf, in_buf_size,
  5851. uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  5852. if (status == TDEFL_STATUS_DONE) {
  5853. result = MZ_TRUE;
  5854. break;
  5855. } else if (status != TDEFL_STATUS_OKAY)
  5856. break;
  5857. }
  5858. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  5859. if (!result) {
  5860. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5861. MZ_FCLOSE(pSrc_file);
  5862. return MZ_FALSE;
  5863. }
  5864. comp_size = state.m_comp_size;
  5865. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  5866. method = MZ_DEFLATED;
  5867. }
  5868. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  5869. }
  5870. MZ_FCLOSE(pSrc_file);
  5871. pSrc_file = NULL;
  5872. // no zip64 support yet
  5873. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  5874. return MZ_FALSE;
  5875. if (!mz_zip_writer_create_local_dir_header(
  5876. pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
  5877. comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  5878. return MZ_FALSE;
  5879. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
  5880. sizeof(local_dir_header)) != sizeof(local_dir_header))
  5881. return MZ_FALSE;
  5882. if (!mz_zip_writer_add_to_central_dir(
  5883. pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
  5884. comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
  5885. dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  5886. return MZ_FALSE;
  5887. pZip->m_total_files++;
  5888. pZip->m_archive_size = cur_archive_file_ofs;
  5889. return MZ_TRUE;
  5890. }
  5891. #endif // #ifndef MINIZ_NO_STDIO
  5892. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
  5893. mz_zip_archive *pSource_zip,
  5894. mz_uint file_index) {
  5895. mz_uint n, bit_flags, num_alignment_padding_bytes;
  5896. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  5897. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  5898. mz_uint32
  5899. local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
  5900. sizeof(mz_uint32)];
  5901. mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  5902. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  5903. size_t orig_central_dir_size;
  5904. mz_zip_internal_state *pState;
  5905. void *pBuf;
  5906. const mz_uint8 *pSrc_central_header;
  5907. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  5908. return MZ_FALSE;
  5909. if (NULL ==
  5910. (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  5911. return MZ_FALSE;
  5912. pState = pZip->m_pState;
  5913. num_alignment_padding_bytes =
  5914. mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  5915. // no zip64 support yet
  5916. if ((pZip->m_total_files == 0xFFFF) ||
  5917. ((pZip->m_archive_size + num_alignment_padding_bytes +
  5918. MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
  5919. 0xFFFFFFFF))
  5920. return MZ_FALSE;
  5921. cur_src_file_ofs =
  5922. MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  5923. cur_dst_file_ofs = pZip->m_archive_size;
  5924. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
  5925. pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5926. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5927. return MZ_FALSE;
  5928. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  5929. return MZ_FALSE;
  5930. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5931. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
  5932. num_alignment_padding_bytes))
  5933. return MZ_FALSE;
  5934. cur_dst_file_ofs += num_alignment_padding_bytes;
  5935. local_dir_header_ofs = cur_dst_file_ofs;
  5936. if (pZip->m_file_offset_alignment) {
  5937. MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
  5938. 0);
  5939. }
  5940. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
  5941. MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
  5942. MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  5943. return MZ_FALSE;
  5944. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  5945. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
  5946. MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  5947. comp_bytes_remaining =
  5948. n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  5949. if (NULL == (pBuf = pZip->m_pAlloc(
  5950. pZip->m_pAlloc_opaque, 1,
  5951. (size_t)MZ_MAX(sizeof(mz_uint32) * 4,
  5952. MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
  5953. comp_bytes_remaining)))))
  5954. return MZ_FALSE;
  5955. while (comp_bytes_remaining) {
  5956. n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  5957. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5958. n) != n) {
  5959. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5960. return MZ_FALSE;
  5961. }
  5962. cur_src_file_ofs += n;
  5963. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5964. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5965. return MZ_FALSE;
  5966. }
  5967. cur_dst_file_ofs += n;
  5968. comp_bytes_remaining -= n;
  5969. }
  5970. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  5971. if (bit_flags & 8) {
  5972. // Copy data descriptor
  5973. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
  5974. sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
  5975. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5976. return MZ_FALSE;
  5977. }
  5978. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  5979. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
  5980. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5981. return MZ_FALSE;
  5982. }
  5983. cur_src_file_ofs += n;
  5984. cur_dst_file_ofs += n;
  5985. }
  5986. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  5987. // no zip64 support yet
  5988. if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE;
  5989. orig_central_dir_size = pState->m_central_dir.m_size;
  5990. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  5991. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
  5992. local_dir_header_ofs);
  5993. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
  5994. MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  5995. return MZ_FALSE;
  5996. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
  5997. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
  5998. MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  5999. if (!mz_zip_array_push_back(
  6000. pZip, &pState->m_central_dir,
  6001. pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
  6002. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  6003. MZ_FALSE);
  6004. return MZ_FALSE;
  6005. }
  6006. if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE;
  6007. n = (mz_uint32)orig_central_dir_size;
  6008. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
  6009. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
  6010. MZ_FALSE);
  6011. return MZ_FALSE;
  6012. }
  6013. pZip->m_total_files++;
  6014. pZip->m_archive_size = cur_dst_file_ofs;
  6015. return MZ_TRUE;
  6016. }
  6017. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
  6018. mz_zip_internal_state *pState;
  6019. mz_uint64 central_dir_ofs, central_dir_size;
  6020. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  6021. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  6022. return MZ_FALSE;
  6023. pState = pZip->m_pState;
  6024. // no zip64 support yet
  6025. if ((pZip->m_total_files > 0xFFFF) ||
  6026. ((pZip->m_archive_size + pState->m_central_dir.m_size +
  6027. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  6028. return MZ_FALSE;
  6029. central_dir_ofs = 0;
  6030. central_dir_size = 0;
  6031. if (pZip->m_total_files) {
  6032. // Write central directory
  6033. central_dir_ofs = pZip->m_archive_size;
  6034. central_dir_size = pState->m_central_dir.m_size;
  6035. pZip->m_central_directory_file_ofs = central_dir_ofs;
  6036. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
  6037. pState->m_central_dir.m_p,
  6038. (size_t)central_dir_size) != central_dir_size)
  6039. return MZ_FALSE;
  6040. pZip->m_archive_size += central_dir_size;
  6041. }
  6042. // Write end of central directory record
  6043. MZ_CLEAR_OBJ(hdr);
  6044. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
  6045. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  6046. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
  6047. pZip->m_total_files);
  6048. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  6049. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  6050. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  6051. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
  6052. sizeof(hdr)) != sizeof(hdr))
  6053. return MZ_FALSE;
  6054. #ifndef MINIZ_NO_STDIO
  6055. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE;
  6056. #endif // #ifndef MINIZ_NO_STDIO
  6057. pZip->m_archive_size += sizeof(hdr);
  6058. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  6059. return MZ_TRUE;
  6060. }
  6061. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
  6062. size_t *pSize) {
  6063. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE;
  6064. if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE;
  6065. if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE;
  6066. *pBuf = pZip->m_pState->m_pMem;
  6067. *pSize = pZip->m_pState->m_mem_size;
  6068. pZip->m_pState->m_pMem = NULL;
  6069. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  6070. return MZ_TRUE;
  6071. }
  6072. mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
  6073. mz_zip_internal_state *pState;
  6074. mz_bool status = MZ_TRUE;
  6075. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
  6076. ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
  6077. (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  6078. return MZ_FALSE;
  6079. pState = pZip->m_pState;
  6080. pZip->m_pState = NULL;
  6081. mz_zip_array_clear(pZip, &pState->m_central_dir);
  6082. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  6083. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  6084. #ifndef MINIZ_NO_STDIO
  6085. if (pState->m_pFile) {
  6086. MZ_FCLOSE(pState->m_pFile);
  6087. pState->m_pFile = NULL;
  6088. }
  6089. #endif // #ifndef MINIZ_NO_STDIO
  6090. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
  6091. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  6092. pState->m_pMem = NULL;
  6093. }
  6094. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  6095. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  6096. return status;
  6097. }
  6098. #ifndef MINIZ_NO_STDIO
  6099. mz_bool mz_zip_add_mem_to_archive_file_in_place(
  6100. const char *pZip_filename, const char *pArchive_name, const void *pBuf,
  6101. size_t buf_size, const void *pComment, mz_uint16 comment_size,
  6102. mz_uint level_and_flags) {
  6103. mz_bool status, created_new_archive = MZ_FALSE;
  6104. mz_zip_archive zip_archive;
  6105. struct MZ_FILE_STAT_STRUCT file_stat;
  6106. MZ_CLEAR_OBJ(zip_archive);
  6107. if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
  6108. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
  6109. ((comment_size) && (!pComment)) ||
  6110. ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  6111. return MZ_FALSE;
  6112. if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
  6113. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
  6114. // Create a new archive.
  6115. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  6116. return MZ_FALSE;
  6117. created_new_archive = MZ_TRUE;
  6118. } else {
  6119. // Append to an existing archive.
  6120. if (!mz_zip_reader_init_file(
  6121. &zip_archive, pZip_filename,
  6122. level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6123. return MZ_FALSE;
  6124. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
  6125. mz_zip_reader_end(&zip_archive);
  6126. return MZ_FALSE;
  6127. }
  6128. }
  6129. status =
  6130. mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
  6131. pComment, comment_size, level_and_flags, 0, 0);
  6132. // Always finalize, even if adding failed for some reason, so we have a valid
  6133. // central directory. (This may not always succeed, but we can try.)
  6134. if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE;
  6135. if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE;
  6136. if ((!status) && (created_new_archive)) {
  6137. // It's a new archive and something went wrong, so just delete it.
  6138. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  6139. (void)ignoredStatus;
  6140. }
  6141. return status;
  6142. }
  6143. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
  6144. const char *pArchive_name,
  6145. size_t *pSize, mz_uint flags) {
  6146. int file_index;
  6147. mz_zip_archive zip_archive;
  6148. void *p = NULL;
  6149. if (pSize) *pSize = 0;
  6150. if ((!pZip_filename) || (!pArchive_name)) return NULL;
  6151. MZ_CLEAR_OBJ(zip_archive);
  6152. if (!mz_zip_reader_init_file(
  6153. &zip_archive, pZip_filename,
  6154. flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  6155. return NULL;
  6156. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
  6157. flags)) >= 0)
  6158. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  6159. mz_zip_reader_end(&zip_archive);
  6160. return p;
  6161. }
  6162. #endif // #ifndef MINIZ_NO_STDIO
  6163. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  6164. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  6165. #ifdef __cplusplus
  6166. }
  6167. #endif
  6168. #endif // MINIZ_HEADER_FILE_ONLY
  6169. /*
  6170. This is free and unencumbered software released into the public domain.
  6171. Anyone is free to copy, modify, publish, use, compile, sell, or
  6172. distribute this software, either in source code form or as a compiled
  6173. binary, for any purpose, commercial or non-commercial, and by any
  6174. means.
  6175. In jurisdictions that recognize copyright laws, the author or authors
  6176. of this software dedicate any and all copyright interest in the
  6177. software to the public domain. We make this dedication for the benefit
  6178. of the public at large and to the detriment of our heirs and
  6179. successors. We intend this dedication to be an overt act of
  6180. relinquishment in perpetuity of all present and future rights to this
  6181. software under copyright law.
  6182. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6183. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6184. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  6185. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  6186. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  6187. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  6188. OTHER DEALINGS IN THE SOFTWARE.
  6189. For more information, please refer to <http://unlicense.org/>
  6190. */
  6191. // ---------------------- end of miniz ----------------------------------------
  6192. #ifdef __clang__
  6193. #pragma clang diagnostic pop
  6194. #endif
  6195. #ifdef _MSC_VER
  6196. #pragma warning(pop)
  6197. #endif
  6198. } // namespace miniz
  6199. #else
  6200. // Reuse MINIZ_LITTE_ENDIAN macro
  6201. #if defined(__sparcv9)
  6202. // Big endian
  6203. #else
  6204. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  6205. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  6206. #define MINIZ_LITTLE_ENDIAN 1
  6207. #endif
  6208. #endif
  6209. #endif // TINYEXR_USE_MINIZ
  6210. // static bool IsBigEndian(void) {
  6211. // union {
  6212. // unsigned int i;
  6213. // char c[4];
  6214. // } bint = {0x01020304};
  6215. //
  6216. // return bint.c[0] == 1;
  6217. //}
  6218. static void SetErrorMessage(const std::string &msg, const char **err) {
  6219. if (err) {
  6220. #ifdef _WIN32
  6221. (*err) = _strdup(msg.c_str());
  6222. #else
  6223. (*err) = strdup(msg.c_str());
  6224. #endif
  6225. }
  6226. }
  6227. static const int kEXRVersionSize = 8;
  6228. static void cpy2(unsigned short *dst_val, const unsigned short *src_val) {
  6229. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6230. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6231. dst[0] = src[0];
  6232. dst[1] = src[1];
  6233. }
  6234. static void swap2(unsigned short *val) {
  6235. #ifdef MINIZ_LITTLE_ENDIAN
  6236. (void)val;
  6237. #else
  6238. unsigned short tmp = *val;
  6239. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6240. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6241. dst[0] = src[1];
  6242. dst[1] = src[0];
  6243. #endif
  6244. }
  6245. #ifdef __clang__
  6246. #pragma clang diagnostic push
  6247. #pragma clang diagnostic ignored "-Wunused-function"
  6248. #endif
  6249. #ifdef __GNUC__
  6250. #pragma GCC diagnostic push
  6251. #pragma GCC diagnostic ignored "-Wunused-function"
  6252. #endif
  6253. static void cpy4(int *dst_val, const int *src_val) {
  6254. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6255. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6256. dst[0] = src[0];
  6257. dst[1] = src[1];
  6258. dst[2] = src[2];
  6259. dst[3] = src[3];
  6260. }
  6261. static void cpy4(unsigned int *dst_val, const unsigned int *src_val) {
  6262. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6263. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6264. dst[0] = src[0];
  6265. dst[1] = src[1];
  6266. dst[2] = src[2];
  6267. dst[3] = src[3];
  6268. }
  6269. static void cpy4(float *dst_val, const float *src_val) {
  6270. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6271. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6272. dst[0] = src[0];
  6273. dst[1] = src[1];
  6274. dst[2] = src[2];
  6275. dst[3] = src[3];
  6276. }
  6277. #ifdef __clang__
  6278. #pragma clang diagnostic pop
  6279. #endif
  6280. #ifdef __GNUC__
  6281. #pragma GCC diagnostic pop
  6282. #endif
  6283. static void swap4(unsigned int *val) {
  6284. #ifdef MINIZ_LITTLE_ENDIAN
  6285. (void)val;
  6286. #else
  6287. unsigned int tmp = *val;
  6288. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6289. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6290. dst[0] = src[3];
  6291. dst[1] = src[2];
  6292. dst[2] = src[1];
  6293. dst[3] = src[0];
  6294. #endif
  6295. }
  6296. #if 0
  6297. static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
  6298. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  6299. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  6300. dst[0] = src[0];
  6301. dst[1] = src[1];
  6302. dst[2] = src[2];
  6303. dst[3] = src[3];
  6304. dst[4] = src[4];
  6305. dst[5] = src[5];
  6306. dst[6] = src[6];
  6307. dst[7] = src[7];
  6308. }
  6309. #endif
  6310. static void swap8(tinyexr::tinyexr_uint64 *val) {
  6311. #ifdef MINIZ_LITTLE_ENDIAN
  6312. (void)val;
  6313. #else
  6314. tinyexr::tinyexr_uint64 tmp = (*val);
  6315. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  6316. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  6317. dst[0] = src[7];
  6318. dst[1] = src[6];
  6319. dst[2] = src[5];
  6320. dst[3] = src[4];
  6321. dst[4] = src[3];
  6322. dst[5] = src[2];
  6323. dst[6] = src[1];
  6324. dst[7] = src[0];
  6325. #endif
  6326. }
  6327. // https://gist.github.com/rygorous/2156668
  6328. // Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
  6329. union FP32 {
  6330. unsigned int u;
  6331. float f;
  6332. struct {
  6333. #if MINIZ_LITTLE_ENDIAN
  6334. unsigned int Mantissa : 23;
  6335. unsigned int Exponent : 8;
  6336. unsigned int Sign : 1;
  6337. #else
  6338. unsigned int Sign : 1;
  6339. unsigned int Exponent : 8;
  6340. unsigned int Mantissa : 23;
  6341. #endif
  6342. } s;
  6343. };
  6344. #ifdef __clang__
  6345. #pragma clang diagnostic push
  6346. #pragma clang diagnostic ignored "-Wpadded"
  6347. #endif
  6348. union FP16 {
  6349. unsigned short u;
  6350. struct {
  6351. #if MINIZ_LITTLE_ENDIAN
  6352. unsigned int Mantissa : 10;
  6353. unsigned int Exponent : 5;
  6354. unsigned int Sign : 1;
  6355. #else
  6356. unsigned int Sign : 1;
  6357. unsigned int Exponent : 5;
  6358. unsigned int Mantissa : 10;
  6359. #endif
  6360. } s;
  6361. };
  6362. #ifdef __clang__
  6363. #pragma clang diagnostic pop
  6364. #endif
  6365. static FP32 half_to_float(FP16 h) {
  6366. static const FP32 magic = {113 << 23};
  6367. static const unsigned int shifted_exp = 0x7c00
  6368. << 13; // exponent mask after shift
  6369. FP32 o;
  6370. o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
  6371. unsigned int exp_ = shifted_exp & o.u; // just the exponent
  6372. o.u += (127 - 15) << 23; // exponent adjust
  6373. // handle exponent special cases
  6374. if (exp_ == shifted_exp) // Inf/NaN?
  6375. o.u += (128 - 16) << 23; // extra exp adjust
  6376. else if (exp_ == 0) // Zero/Denormal?
  6377. {
  6378. o.u += 1 << 23; // extra exp adjust
  6379. o.f -= magic.f; // renormalize
  6380. }
  6381. o.u |= (h.u & 0x8000U) << 16U; // sign bit
  6382. return o;
  6383. }
  6384. static FP16 float_to_half_full(FP32 f) {
  6385. FP16 o = {0};
  6386. // Based on ISPC reference code (with minor modifications)
  6387. if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
  6388. o.s.Exponent = 0;
  6389. else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
  6390. {
  6391. o.s.Exponent = 31;
  6392. o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
  6393. } else // Normalized number
  6394. {
  6395. // Exponent unbias the single, then bias the halfp
  6396. int newexp = f.s.Exponent - 127 + 15;
  6397. if (newexp >= 31) // Overflow, return signed infinity
  6398. o.s.Exponent = 31;
  6399. else if (newexp <= 0) // Underflow
  6400. {
  6401. if ((14 - newexp) <= 24) // Mantissa might be non-zero
  6402. {
  6403. unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
  6404. o.s.Mantissa = mant >> (14 - newexp);
  6405. if ((mant >> (13 - newexp)) & 1) // Check for rounding
  6406. o.u++; // Round, might overflow into exp bit, but this is OK
  6407. }
  6408. } else {
  6409. o.s.Exponent = static_cast<unsigned int>(newexp);
  6410. o.s.Mantissa = f.s.Mantissa >> 13;
  6411. if (f.s.Mantissa & 0x1000) // Check for rounding
  6412. o.u++; // Round, might overflow to inf, this is OK
  6413. }
  6414. }
  6415. o.s.Sign = f.s.Sign;
  6416. return o;
  6417. }
  6418. // NOTE: From OpenEXR code
  6419. // #define IMF_INCREASING_Y 0
  6420. // #define IMF_DECREASING_Y 1
  6421. // #define IMF_RAMDOM_Y 2
  6422. //
  6423. // #define IMF_NO_COMPRESSION 0
  6424. // #define IMF_RLE_COMPRESSION 1
  6425. // #define IMF_ZIPS_COMPRESSION 2
  6426. // #define IMF_ZIP_COMPRESSION 3
  6427. // #define IMF_PIZ_COMPRESSION 4
  6428. // #define IMF_PXR24_COMPRESSION 5
  6429. // #define IMF_B44_COMPRESSION 6
  6430. // #define IMF_B44A_COMPRESSION 7
  6431. #ifdef __clang__
  6432. #pragma clang diagnostic push
  6433. #if __has_warning("-Wzero-as-null-pointer-constant")
  6434. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  6435. #endif
  6436. #endif
  6437. static const char *ReadString(std::string *s, const char *ptr, size_t len) {
  6438. // Read untile NULL(\0).
  6439. const char *p = ptr;
  6440. const char *q = ptr;
  6441. while ((size_t(q - ptr) < len) && (*q) != 0) {
  6442. q++;
  6443. }
  6444. if (size_t(q - ptr) >= len) {
  6445. (*s) = std::string();
  6446. return NULL;
  6447. }
  6448. (*s) = std::string(p, q);
  6449. return q + 1; // skip '\0'
  6450. }
  6451. static bool ReadAttribute(std::string *name, std::string *type,
  6452. std::vector<unsigned char> *data, size_t *marker_size,
  6453. const char *marker, size_t size) {
  6454. size_t name_len = strnlen(marker, size);
  6455. if (name_len == size) {
  6456. // String does not have a terminating character.
  6457. return false;
  6458. }
  6459. *name = std::string(marker, name_len);
  6460. marker += name_len + 1;
  6461. size -= name_len + 1;
  6462. size_t type_len = strnlen(marker, size);
  6463. if (type_len == size) {
  6464. return false;
  6465. }
  6466. *type = std::string(marker, type_len);
  6467. marker += type_len + 1;
  6468. size -= type_len + 1;
  6469. if (size < sizeof(uint32_t)) {
  6470. return false;
  6471. }
  6472. uint32_t data_len;
  6473. memcpy(&data_len, marker, sizeof(uint32_t));
  6474. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  6475. if (data_len == 0) {
  6476. if ((*type).compare("string") == 0) {
  6477. // Accept empty string attribute.
  6478. marker += sizeof(uint32_t);
  6479. size -= sizeof(uint32_t);
  6480. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
  6481. data->resize(1);
  6482. (*data)[0] = '\0';
  6483. return true;
  6484. } else {
  6485. return false;
  6486. }
  6487. }
  6488. marker += sizeof(uint32_t);
  6489. size -= sizeof(uint32_t);
  6490. if (size < data_len) {
  6491. return false;
  6492. }
  6493. data->resize(static_cast<size_t>(data_len));
  6494. memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
  6495. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
  6496. return true;
  6497. }
  6498. static void WriteAttributeToMemory(std::vector<unsigned char> *out,
  6499. const char *name, const char *type,
  6500. const unsigned char *data, int len) {
  6501. out->insert(out->end(), name, name + strlen(name) + 1);
  6502. out->insert(out->end(), type, type + strlen(type) + 1);
  6503. int outLen = len;
  6504. tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen));
  6505. out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),
  6506. reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
  6507. out->insert(out->end(), data, data + len);
  6508. }
  6509. typedef struct {
  6510. std::string name; // less than 255 bytes long
  6511. int pixel_type;
  6512. int x_sampling;
  6513. int y_sampling;
  6514. unsigned char p_linear;
  6515. unsigned char pad[3];
  6516. } ChannelInfo;
  6517. typedef struct {
  6518. std::vector<tinyexr::ChannelInfo> channels;
  6519. std::vector<EXRAttribute> attributes;
  6520. int data_window[4];
  6521. int line_order;
  6522. int display_window[4];
  6523. float screen_window_center[2];
  6524. float screen_window_width;
  6525. float pixel_aspect_ratio;
  6526. int chunk_count;
  6527. // Tiled format
  6528. int tile_size_x;
  6529. int tile_size_y;
  6530. int tile_level_mode;
  6531. int tile_rounding_mode;
  6532. unsigned int header_len;
  6533. int compression_type;
  6534. void clear() {
  6535. channels.clear();
  6536. attributes.clear();
  6537. data_window[0] = 0;
  6538. data_window[1] = 0;
  6539. data_window[2] = 0;
  6540. data_window[3] = 0;
  6541. line_order = 0;
  6542. display_window[0] = 0;
  6543. display_window[1] = 0;
  6544. display_window[2] = 0;
  6545. display_window[3] = 0;
  6546. screen_window_center[0] = 0.0f;
  6547. screen_window_center[1] = 0.0f;
  6548. screen_window_width = 0.0f;
  6549. pixel_aspect_ratio = 0.0f;
  6550. chunk_count = 0;
  6551. // Tiled format
  6552. tile_size_x = 0;
  6553. tile_size_y = 0;
  6554. tile_level_mode = 0;
  6555. tile_rounding_mode = 0;
  6556. header_len = 0;
  6557. compression_type = 0;
  6558. }
  6559. } HeaderInfo;
  6560. static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,
  6561. const std::vector<unsigned char> &data) {
  6562. const char *p = reinterpret_cast<const char *>(&data.at(0));
  6563. for (;;) {
  6564. if ((*p) == 0) {
  6565. break;
  6566. }
  6567. ChannelInfo info;
  6568. tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -
  6569. (p - reinterpret_cast<const char *>(data.data()));
  6570. if (data_len < 0) {
  6571. return false;
  6572. }
  6573. p = ReadString(&info.name, p, size_t(data_len));
  6574. if ((p == NULL) && (info.name.empty())) {
  6575. // Buffer overrun. Issue #51.
  6576. return false;
  6577. }
  6578. const unsigned char *data_end =
  6579. reinterpret_cast<const unsigned char *>(p) + 16;
  6580. if (data_end >= (data.data() + data.size())) {
  6581. return false;
  6582. }
  6583. memcpy(&info.pixel_type, p, sizeof(int));
  6584. p += 4;
  6585. info.p_linear = static_cast<unsigned char>(p[0]); // uchar
  6586. p += 1 + 3; // reserved: uchar[3]
  6587. memcpy(&info.x_sampling, p, sizeof(int)); // int
  6588. p += 4;
  6589. memcpy(&info.y_sampling, p, sizeof(int)); // int
  6590. p += 4;
  6591. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type));
  6592. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling));
  6593. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling));
  6594. channels.push_back(info);
  6595. }
  6596. return true;
  6597. }
  6598. static void WriteChannelInfo(std::vector<unsigned char> &data,
  6599. const std::vector<ChannelInfo> &channels) {
  6600. size_t sz = 0;
  6601. // Calculate total size.
  6602. for (size_t c = 0; c < channels.size(); c++) {
  6603. sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
  6604. sz += 16; // 4 * int
  6605. }
  6606. data.resize(sz + 1);
  6607. unsigned char *p = &data.at(0);
  6608. for (size_t c = 0; c < channels.size(); c++) {
  6609. memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
  6610. p += strlen(channels[c].name.c_str());
  6611. (*p) = '\0';
  6612. p++;
  6613. int pixel_type = channels[c].pixel_type;
  6614. int x_sampling = channels[c].x_sampling;
  6615. int y_sampling = channels[c].y_sampling;
  6616. tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type));
  6617. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling));
  6618. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling));
  6619. memcpy(p, &pixel_type, sizeof(int));
  6620. p += sizeof(int);
  6621. (*p) = channels[c].p_linear;
  6622. p += 4;
  6623. memcpy(p, &x_sampling, sizeof(int));
  6624. p += sizeof(int);
  6625. memcpy(p, &y_sampling, sizeof(int));
  6626. p += sizeof(int);
  6627. }
  6628. (*p) = '\0';
  6629. }
  6630. static void CompressZip(unsigned char *dst,
  6631. tinyexr::tinyexr_uint64 &compressedSize,
  6632. const unsigned char *src, unsigned long src_size) {
  6633. std::vector<unsigned char> tmpBuf(src_size);
  6634. //
  6635. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6636. // ImfZipCompressor.cpp
  6637. //
  6638. //
  6639. // Reorder the pixel data.
  6640. //
  6641. const char *srcPtr = reinterpret_cast<const char *>(src);
  6642. {
  6643. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6644. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6645. const char *stop = srcPtr + src_size;
  6646. for (;;) {
  6647. if (srcPtr < stop)
  6648. *(t1++) = *(srcPtr++);
  6649. else
  6650. break;
  6651. if (srcPtr < stop)
  6652. *(t2++) = *(srcPtr++);
  6653. else
  6654. break;
  6655. }
  6656. }
  6657. //
  6658. // Predictor.
  6659. //
  6660. {
  6661. unsigned char *t = &tmpBuf.at(0) + 1;
  6662. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6663. int p = t[-1];
  6664. while (t < stop) {
  6665. int d = int(t[0]) - p + (128 + 256);
  6666. p = t[0];
  6667. t[0] = static_cast<unsigned char>(d);
  6668. ++t;
  6669. }
  6670. }
  6671. #if TINYEXR_USE_MINIZ
  6672. //
  6673. // Compress the data using miniz
  6674. //
  6675. miniz::mz_ulong outSize = miniz::mz_compressBound(src_size);
  6676. int ret = miniz::mz_compress(
  6677. dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),
  6678. src_size);
  6679. assert(ret == miniz::MZ_OK);
  6680. (void)ret;
  6681. compressedSize = outSize;
  6682. #else
  6683. uLong outSize = compressBound(static_cast<uLong>(src_size));
  6684. int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),
  6685. src_size);
  6686. assert(ret == Z_OK);
  6687. compressedSize = outSize;
  6688. #endif
  6689. // Use uncompressed data when compressed data is larger than uncompressed.
  6690. // (Issue 40)
  6691. if (compressedSize >= src_size) {
  6692. compressedSize = src_size;
  6693. memcpy(dst, src, src_size);
  6694. }
  6695. }
  6696. static bool DecompressZip(unsigned char *dst,
  6697. unsigned long *uncompressed_size /* inout */,
  6698. const unsigned char *src, unsigned long src_size) {
  6699. if ((*uncompressed_size) == src_size) {
  6700. // Data is not compressed(Issue 40).
  6701. memcpy(dst, src, src_size);
  6702. return true;
  6703. }
  6704. std::vector<unsigned char> tmpBuf(*uncompressed_size);
  6705. #if TINYEXR_USE_MINIZ
  6706. int ret =
  6707. miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6708. if (miniz::MZ_OK != ret) {
  6709. return false;
  6710. }
  6711. #else
  6712. int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  6713. if (Z_OK != ret) {
  6714. return false;
  6715. }
  6716. #endif
  6717. //
  6718. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6719. // ImfZipCompressor.cpp
  6720. //
  6721. // Predictor.
  6722. {
  6723. unsigned char *t = &tmpBuf.at(0) + 1;
  6724. unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);
  6725. while (t < stop) {
  6726. int d = int(t[-1]) + int(t[0]) - 128;
  6727. t[0] = static_cast<unsigned char>(d);
  6728. ++t;
  6729. }
  6730. }
  6731. // Reorder the pixel data.
  6732. {
  6733. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6734. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6735. (*uncompressed_size + 1) / 2;
  6736. char *s = reinterpret_cast<char *>(dst);
  6737. char *stop = s + (*uncompressed_size);
  6738. for (;;) {
  6739. if (s < stop)
  6740. *(s++) = *(t1++);
  6741. else
  6742. break;
  6743. if (s < stop)
  6744. *(s++) = *(t2++);
  6745. else
  6746. break;
  6747. }
  6748. }
  6749. return true;
  6750. }
  6751. // RLE code from OpenEXR --------------------------------------
  6752. #ifdef __clang__
  6753. #pragma clang diagnostic push
  6754. #pragma clang diagnostic ignored "-Wsign-conversion"
  6755. #if __has_warning("-Wextra-semi-stmt")
  6756. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  6757. #endif
  6758. #endif
  6759. #ifdef _MSC_VER
  6760. #pragma warning(push)
  6761. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  6762. // aggregate initializer (also supported by GNU
  6763. // C and C99, so no big deal)
  6764. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  6765. // 'int', possible loss of data
  6766. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  6767. // 'int', possible loss of data
  6768. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  6769. // deprecated. Instead, use the ISO C and C++
  6770. // conformant name: _strdup.
  6771. #endif
  6772. const int MIN_RUN_LENGTH = 3;
  6773. const int MAX_RUN_LENGTH = 127;
  6774. //
  6775. // Compress an array of bytes, using run-length encoding,
  6776. // and return the length of the compressed data.
  6777. //
  6778. static int rleCompress(int inLength, const char in[], signed char out[]) {
  6779. const char *inEnd = in + inLength;
  6780. const char *runStart = in;
  6781. const char *runEnd = in + 1;
  6782. signed char *outWrite = out;
  6783. while (runStart < inEnd) {
  6784. while (runEnd < inEnd && *runStart == *runEnd &&
  6785. runEnd - runStart - 1 < MAX_RUN_LENGTH) {
  6786. ++runEnd;
  6787. }
  6788. if (runEnd - runStart >= MIN_RUN_LENGTH) {
  6789. //
  6790. // Compressable run
  6791. //
  6792. *outWrite++ = static_cast<char>(runEnd - runStart) - 1;
  6793. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart));
  6794. runStart = runEnd;
  6795. } else {
  6796. //
  6797. // Uncompressable run
  6798. //
  6799. while (runEnd < inEnd &&
  6800. ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||
  6801. (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&
  6802. runEnd - runStart < MAX_RUN_LENGTH) {
  6803. ++runEnd;
  6804. }
  6805. *outWrite++ = static_cast<char>(runStart - runEnd);
  6806. while (runStart < runEnd) {
  6807. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));
  6808. }
  6809. }
  6810. ++runEnd;
  6811. }
  6812. return static_cast<int>(outWrite - out);
  6813. }
  6814. //
  6815. // Uncompress an array of bytes compressed with rleCompress().
  6816. // Returns the length of the oncompressed data, or 0 if the
  6817. // length of the uncompressed data would be more than maxLength.
  6818. //
  6819. static int rleUncompress(int inLength, int maxLength, const signed char in[],
  6820. char out[]) {
  6821. char *outStart = out;
  6822. while (inLength > 0) {
  6823. if (*in < 0) {
  6824. int count = -(static_cast<int>(*in++));
  6825. inLength -= count + 1;
  6826. // Fixes #116: Add bounds check to in buffer.
  6827. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0;
  6828. memcpy(out, in, count);
  6829. out += count;
  6830. in += count;
  6831. } else {
  6832. int count = *in++;
  6833. inLength -= 2;
  6834. if (0 > (maxLength -= count + 1)) return 0;
  6835. memset(out, *reinterpret_cast<const char *>(in), count + 1);
  6836. out += count + 1;
  6837. in++;
  6838. }
  6839. }
  6840. return static_cast<int>(out - outStart);
  6841. }
  6842. #ifdef __clang__
  6843. #pragma clang diagnostic pop
  6844. #endif
  6845. // End of RLE code from OpenEXR -----------------------------------
  6846. static void CompressRle(unsigned char *dst,
  6847. tinyexr::tinyexr_uint64 &compressedSize,
  6848. const unsigned char *src, unsigned long src_size) {
  6849. std::vector<unsigned char> tmpBuf(src_size);
  6850. //
  6851. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6852. // ImfRleCompressor.cpp
  6853. //
  6854. //
  6855. // Reorder the pixel data.
  6856. //
  6857. const char *srcPtr = reinterpret_cast<const char *>(src);
  6858. {
  6859. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  6860. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  6861. const char *stop = srcPtr + src_size;
  6862. for (;;) {
  6863. if (srcPtr < stop)
  6864. *(t1++) = *(srcPtr++);
  6865. else
  6866. break;
  6867. if (srcPtr < stop)
  6868. *(t2++) = *(srcPtr++);
  6869. else
  6870. break;
  6871. }
  6872. }
  6873. //
  6874. // Predictor.
  6875. //
  6876. {
  6877. unsigned char *t = &tmpBuf.at(0) + 1;
  6878. unsigned char *stop = &tmpBuf.at(0) + src_size;
  6879. int p = t[-1];
  6880. while (t < stop) {
  6881. int d = int(t[0]) - p + (128 + 256);
  6882. p = t[0];
  6883. t[0] = static_cast<unsigned char>(d);
  6884. ++t;
  6885. }
  6886. }
  6887. // outSize will be (srcSiz * 3) / 2 at max.
  6888. int outSize = rleCompress(static_cast<int>(src_size),
  6889. reinterpret_cast<const char *>(&tmpBuf.at(0)),
  6890. reinterpret_cast<signed char *>(dst));
  6891. assert(outSize > 0);
  6892. compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
  6893. // Use uncompressed data when compressed data is larger than uncompressed.
  6894. // (Issue 40)
  6895. if (compressedSize >= src_size) {
  6896. compressedSize = src_size;
  6897. memcpy(dst, src, src_size);
  6898. }
  6899. }
  6900. static bool DecompressRle(unsigned char *dst,
  6901. const unsigned long uncompressed_size,
  6902. const unsigned char *src, unsigned long src_size) {
  6903. if (uncompressed_size == src_size) {
  6904. // Data is not compressed(Issue 40).
  6905. memcpy(dst, src, src_size);
  6906. return true;
  6907. }
  6908. // Workaround for issue #112.
  6909. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.
  6910. if (src_size <= 2) {
  6911. return false;
  6912. }
  6913. std::vector<unsigned char> tmpBuf(uncompressed_size);
  6914. int ret = rleUncompress(static_cast<int>(src_size),
  6915. static_cast<int>(uncompressed_size),
  6916. reinterpret_cast<const signed char *>(src),
  6917. reinterpret_cast<char *>(&tmpBuf.at(0)));
  6918. if (ret != static_cast<int>(uncompressed_size)) {
  6919. return false;
  6920. }
  6921. //
  6922. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  6923. // ImfRleCompressor.cpp
  6924. //
  6925. // Predictor.
  6926. {
  6927. unsigned char *t = &tmpBuf.at(0) + 1;
  6928. unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;
  6929. while (t < stop) {
  6930. int d = int(t[-1]) + int(t[0]) - 128;
  6931. t[0] = static_cast<unsigned char>(d);
  6932. ++t;
  6933. }
  6934. }
  6935. // Reorder the pixel data.
  6936. {
  6937. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  6938. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  6939. (uncompressed_size + 1) / 2;
  6940. char *s = reinterpret_cast<char *>(dst);
  6941. char *stop = s + uncompressed_size;
  6942. for (;;) {
  6943. if (s < stop)
  6944. *(s++) = *(t1++);
  6945. else
  6946. break;
  6947. if (s < stop)
  6948. *(s++) = *(t2++);
  6949. else
  6950. break;
  6951. }
  6952. }
  6953. return true;
  6954. }
  6955. #if TINYEXR_USE_PIZ
  6956. #ifdef __clang__
  6957. #pragma clang diagnostic push
  6958. #pragma clang diagnostic ignored "-Wc++11-long-long"
  6959. #pragma clang diagnostic ignored "-Wold-style-cast"
  6960. #pragma clang diagnostic ignored "-Wpadded"
  6961. #pragma clang diagnostic ignored "-Wsign-conversion"
  6962. #pragma clang diagnostic ignored "-Wc++11-extensions"
  6963. #pragma clang diagnostic ignored "-Wconversion"
  6964. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  6965. #if __has_warning("-Wcast-qual")
  6966. #pragma clang diagnostic ignored "-Wcast-qual"
  6967. #endif
  6968. #if __has_warning("-Wextra-semi-stmt")
  6969. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  6970. #endif
  6971. #endif
  6972. //
  6973. // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
  6974. //
  6975. // -----------------------------------------------------------------
  6976. // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
  6977. // Digital Ltd. LLC)
  6978. // (3 clause BSD license)
  6979. //
  6980. struct PIZChannelData {
  6981. unsigned short *start;
  6982. unsigned short *end;
  6983. int nx;
  6984. int ny;
  6985. int ys;
  6986. int size;
  6987. };
  6988. //-----------------------------------------------------------------------------
  6989. //
  6990. // 16-bit Haar Wavelet encoding and decoding
  6991. //
  6992. // The source code in this file is derived from the encoding
  6993. // and decoding routines written by Christian Rouet for his
  6994. // PIZ image file format.
  6995. //
  6996. //-----------------------------------------------------------------------------
  6997. //
  6998. // Wavelet basis functions without modulo arithmetic; they produce
  6999. // the best compression ratios when the wavelet-transformed data are
  7000. // Huffman-encoded, but the wavelet transform works only for 14-bit
  7001. // data (untransformed data values must be less than (1 << 14)).
  7002. //
  7003. inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
  7004. unsigned short &h) {
  7005. short as = static_cast<short>(a);
  7006. short bs = static_cast<short>(b);
  7007. short ms = (as + bs) >> 1;
  7008. short ds = as - bs;
  7009. l = static_cast<unsigned short>(ms);
  7010. h = static_cast<unsigned short>(ds);
  7011. }
  7012. inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
  7013. unsigned short &b) {
  7014. short ls = static_cast<short>(l);
  7015. short hs = static_cast<short>(h);
  7016. int hi = hs;
  7017. int ai = ls + (hi & 1) + (hi >> 1);
  7018. short as = static_cast<short>(ai);
  7019. short bs = static_cast<short>(ai - hi);
  7020. a = static_cast<unsigned short>(as);
  7021. b = static_cast<unsigned short>(bs);
  7022. }
  7023. //
  7024. // Wavelet basis functions with modulo arithmetic; they work with full
  7025. // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
  7026. // compress the data quite as well.
  7027. //
  7028. const int NBITS = 16;
  7029. const int A_OFFSET = 1 << (NBITS - 1);
  7030. const int M_OFFSET = 1 << (NBITS - 1);
  7031. const int MOD_MASK = (1 << NBITS) - 1;
  7032. inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
  7033. unsigned short &h) {
  7034. int ao = (a + A_OFFSET) & MOD_MASK;
  7035. int m = ((ao + b) >> 1);
  7036. int d = ao - b;
  7037. if (d < 0) m = (m + M_OFFSET) & MOD_MASK;
  7038. d &= MOD_MASK;
  7039. l = static_cast<unsigned short>(m);
  7040. h = static_cast<unsigned short>(d);
  7041. }
  7042. inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
  7043. unsigned short &b) {
  7044. int m = l;
  7045. int d = h;
  7046. int bb = (m - (d >> 1)) & MOD_MASK;
  7047. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  7048. b = static_cast<unsigned short>(bb);
  7049. a = static_cast<unsigned short>(aa);
  7050. }
  7051. //
  7052. // 2D Wavelet encoding:
  7053. //
  7054. static void wav2Encode(
  7055. unsigned short *in, // io: values are transformed in place
  7056. int nx, // i : x size
  7057. int ox, // i : x offset
  7058. int ny, // i : y size
  7059. int oy, // i : y offset
  7060. unsigned short mx) // i : maximum in[x][y] value
  7061. {
  7062. bool w14 = (mx < (1 << 14));
  7063. int n = (nx > ny) ? ny : nx;
  7064. int p = 1; // == 1 << level
  7065. int p2 = 2; // == 1 << (level+1)
  7066. //
  7067. // Hierachical loop on smaller dimension n
  7068. //
  7069. while (p2 <= n) {
  7070. unsigned short *py = in;
  7071. unsigned short *ey = in + oy * (ny - p2);
  7072. int oy1 = oy * p;
  7073. int oy2 = oy * p2;
  7074. int ox1 = ox * p;
  7075. int ox2 = ox * p2;
  7076. unsigned short i00, i01, i10, i11;
  7077. //
  7078. // Y loop
  7079. //
  7080. for (; py <= ey; py += oy2) {
  7081. unsigned short *px = py;
  7082. unsigned short *ex = py + ox * (nx - p2);
  7083. //
  7084. // X loop
  7085. //
  7086. for (; px <= ex; px += ox2) {
  7087. unsigned short *p01 = px + ox1;
  7088. unsigned short *p10 = px + oy1;
  7089. unsigned short *p11 = p10 + ox1;
  7090. //
  7091. // 2D wavelet encoding
  7092. //
  7093. if (w14) {
  7094. wenc14(*px, *p01, i00, i01);
  7095. wenc14(*p10, *p11, i10, i11);
  7096. wenc14(i00, i10, *px, *p10);
  7097. wenc14(i01, i11, *p01, *p11);
  7098. } else {
  7099. wenc16(*px, *p01, i00, i01);
  7100. wenc16(*p10, *p11, i10, i11);
  7101. wenc16(i00, i10, *px, *p10);
  7102. wenc16(i01, i11, *p01, *p11);
  7103. }
  7104. }
  7105. //
  7106. // Encode (1D) odd column (still in Y loop)
  7107. //
  7108. if (nx & p) {
  7109. unsigned short *p10 = px + oy1;
  7110. if (w14)
  7111. wenc14(*px, *p10, i00, *p10);
  7112. else
  7113. wenc16(*px, *p10, i00, *p10);
  7114. *px = i00;
  7115. }
  7116. }
  7117. //
  7118. // Encode (1D) odd line (must loop in X)
  7119. //
  7120. if (ny & p) {
  7121. unsigned short *px = py;
  7122. unsigned short *ex = py + ox * (nx - p2);
  7123. for (; px <= ex; px += ox2) {
  7124. unsigned short *p01 = px + ox1;
  7125. if (w14)
  7126. wenc14(*px, *p01, i00, *p01);
  7127. else
  7128. wenc16(*px, *p01, i00, *p01);
  7129. *px = i00;
  7130. }
  7131. }
  7132. //
  7133. // Next level
  7134. //
  7135. p = p2;
  7136. p2 <<= 1;
  7137. }
  7138. }
  7139. //
  7140. // 2D Wavelet decoding:
  7141. //
  7142. static void wav2Decode(
  7143. unsigned short *in, // io: values are transformed in place
  7144. int nx, // i : x size
  7145. int ox, // i : x offset
  7146. int ny, // i : y size
  7147. int oy, // i : y offset
  7148. unsigned short mx) // i : maximum in[x][y] value
  7149. {
  7150. bool w14 = (mx < (1 << 14));
  7151. int n = (nx > ny) ? ny : nx;
  7152. int p = 1;
  7153. int p2;
  7154. //
  7155. // Search max level
  7156. //
  7157. while (p <= n) p <<= 1;
  7158. p >>= 1;
  7159. p2 = p;
  7160. p >>= 1;
  7161. //
  7162. // Hierarchical loop on smaller dimension n
  7163. //
  7164. while (p >= 1) {
  7165. unsigned short *py = in;
  7166. unsigned short *ey = in + oy * (ny - p2);
  7167. int oy1 = oy * p;
  7168. int oy2 = oy * p2;
  7169. int ox1 = ox * p;
  7170. int ox2 = ox * p2;
  7171. unsigned short i00, i01, i10, i11;
  7172. //
  7173. // Y loop
  7174. //
  7175. for (; py <= ey; py += oy2) {
  7176. unsigned short *px = py;
  7177. unsigned short *ex = py + ox * (nx - p2);
  7178. //
  7179. // X loop
  7180. //
  7181. for (; px <= ex; px += ox2) {
  7182. unsigned short *p01 = px + ox1;
  7183. unsigned short *p10 = px + oy1;
  7184. unsigned short *p11 = p10 + ox1;
  7185. //
  7186. // 2D wavelet decoding
  7187. //
  7188. if (w14) {
  7189. wdec14(*px, *p10, i00, i10);
  7190. wdec14(*p01, *p11, i01, i11);
  7191. wdec14(i00, i01, *px, *p01);
  7192. wdec14(i10, i11, *p10, *p11);
  7193. } else {
  7194. wdec16(*px, *p10, i00, i10);
  7195. wdec16(*p01, *p11, i01, i11);
  7196. wdec16(i00, i01, *px, *p01);
  7197. wdec16(i10, i11, *p10, *p11);
  7198. }
  7199. }
  7200. //
  7201. // Decode (1D) odd column (still in Y loop)
  7202. //
  7203. if (nx & p) {
  7204. unsigned short *p10 = px + oy1;
  7205. if (w14)
  7206. wdec14(*px, *p10, i00, *p10);
  7207. else
  7208. wdec16(*px, *p10, i00, *p10);
  7209. *px = i00;
  7210. }
  7211. }
  7212. //
  7213. // Decode (1D) odd line (must loop in X)
  7214. //
  7215. if (ny & p) {
  7216. unsigned short *px = py;
  7217. unsigned short *ex = py + ox * (nx - p2);
  7218. for (; px <= ex; px += ox2) {
  7219. unsigned short *p01 = px + ox1;
  7220. if (w14)
  7221. wdec14(*px, *p01, i00, *p01);
  7222. else
  7223. wdec16(*px, *p01, i00, *p01);
  7224. *px = i00;
  7225. }
  7226. }
  7227. //
  7228. // Next level
  7229. //
  7230. p2 = p;
  7231. p >>= 1;
  7232. }
  7233. }
  7234. //-----------------------------------------------------------------------------
  7235. //
  7236. // 16-bit Huffman compression and decompression.
  7237. //
  7238. // The source code in this file is derived from the 8-bit
  7239. // Huffman compression and decompression routines written
  7240. // by Christian Rouet for his PIZ image file format.
  7241. //
  7242. //-----------------------------------------------------------------------------
  7243. // Adds some modification for tinyexr.
  7244. const int HUF_ENCBITS = 16; // literal (value) bit length
  7245. const int HUF_DECBITS = 14; // decoding bit size (>= 8)
  7246. const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
  7247. const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  7248. const int HUF_DECMASK = HUF_DECSIZE - 1;
  7249. struct HufDec { // short code long code
  7250. //-------------------------------
  7251. int len : 8; // code length 0
  7252. int lit : 24; // lit p size
  7253. int *p; // 0 lits
  7254. };
  7255. inline long long hufLength(long long code) { return code & 63; }
  7256. inline long long hufCode(long long code) { return code >> 6; }
  7257. inline void outputBits(int nBits, long long bits, long long &c, int &lc,
  7258. char *&out) {
  7259. c <<= nBits;
  7260. lc += nBits;
  7261. c |= bits;
  7262. while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));
  7263. }
  7264. inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
  7265. while (lc < nBits) {
  7266. c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));
  7267. lc += 8;
  7268. }
  7269. lc -= nBits;
  7270. return (c >> lc) & ((1 << nBits) - 1);
  7271. }
  7272. //
  7273. // ENCODING TABLE BUILDING & (UN)PACKING
  7274. //
  7275. //
  7276. // Build a "canonical" Huffman code table:
  7277. // - for each (uncompressed) symbol, hcode contains the length
  7278. // of the corresponding code (in the compressed data)
  7279. // - canonical codes are computed and stored in hcode
  7280. // - the rules for constructing canonical codes are as follows:
  7281. // * shorter codes (if filled with zeroes to the right)
  7282. // have a numerically higher value than longer codes
  7283. // * for codes with the same length, numerical values
  7284. // increase with numerical symbol values
  7285. // - because the canonical code table can be constructed from
  7286. // symbol lengths alone, the code table can be transmitted
  7287. // without sending the actual code values
  7288. // - see http://www.compressconsult.com/huffman/
  7289. //
  7290. static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
  7291. long long n[59];
  7292. //
  7293. // For each i from 0 through 58, count the
  7294. // number of different codes of length i, and
  7295. // store the count in n[i].
  7296. //
  7297. for (int i = 0; i <= 58; ++i) n[i] = 0;
  7298. for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;
  7299. //
  7300. // For each i from 58 through 1, compute the
  7301. // numerically lowest code with length i, and
  7302. // store that code in n[i].
  7303. //
  7304. long long c = 0;
  7305. for (int i = 58; i > 0; --i) {
  7306. long long nc = ((c + n[i]) >> 1);
  7307. n[i] = c;
  7308. c = nc;
  7309. }
  7310. //
  7311. // hcode[i] contains the length, l, of the
  7312. // code for symbol i. Assign the next available
  7313. // code of length l to the symbol and store both
  7314. // l and the code in hcode[i].
  7315. //
  7316. for (int i = 0; i < HUF_ENCSIZE; ++i) {
  7317. int l = static_cast<int>(hcode[i]);
  7318. if (l > 0) hcode[i] = l | (n[l]++ << 6);
  7319. }
  7320. }
  7321. //
  7322. // Compute Huffman codes (based on frq input) and store them in frq:
  7323. // - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
  7324. // - max code length is 58 bits;
  7325. // - codes outside the range [im-iM] have a null length (unused values);
  7326. // - original frequencies are destroyed;
  7327. // - encoding tables are used by hufEncode() and hufBuildDecTable();
  7328. //
  7329. struct FHeapCompare {
  7330. bool operator()(long long *a, long long *b) { return *a > *b; }
  7331. };
  7332. static void hufBuildEncTable(
  7333. long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
  7334. int *im, // o: min frq index
  7335. int *iM) // o: max frq index
  7336. {
  7337. //
  7338. // This function assumes that when it is called, array frq
  7339. // indicates the frequency of all possible symbols in the data
  7340. // that are to be Huffman-encoded. (frq[i] contains the number
  7341. // of occurrences of symbol i in the data.)
  7342. //
  7343. // The loop below does three things:
  7344. //
  7345. // 1) Finds the minimum and maximum indices that point
  7346. // to non-zero entries in frq:
  7347. //
  7348. // frq[im] != 0, and frq[i] == 0 for all i < im
  7349. // frq[iM] != 0, and frq[i] == 0 for all i > iM
  7350. //
  7351. // 2) Fills array fHeap with pointers to all non-zero
  7352. // entries in frq.
  7353. //
  7354. // 3) Initializes array hlink such that hlink[i] == i
  7355. // for all array entries.
  7356. //
  7357. std::vector<int> hlink(HUF_ENCSIZE);
  7358. std::vector<long long *> fHeap(HUF_ENCSIZE);
  7359. *im = 0;
  7360. while (!frq[*im]) (*im)++;
  7361. int nf = 0;
  7362. for (int i = *im; i < HUF_ENCSIZE; i++) {
  7363. hlink[i] = i;
  7364. if (frq[i]) {
  7365. fHeap[nf] = &frq[i];
  7366. nf++;
  7367. *iM = i;
  7368. }
  7369. }
  7370. //
  7371. // Add a pseudo-symbol, with a frequency count of 1, to frq;
  7372. // adjust the fHeap and hlink array accordingly. Function
  7373. // hufEncode() uses the pseudo-symbol for run-length encoding.
  7374. //
  7375. (*iM)++;
  7376. frq[*iM] = 1;
  7377. fHeap[nf] = &frq[*iM];
  7378. nf++;
  7379. //
  7380. // Build an array, scode, such that scode[i] contains the number
  7381. // of bits assigned to symbol i. Conceptually this is done by
  7382. // constructing a tree whose leaves are the symbols with non-zero
  7383. // frequency:
  7384. //
  7385. // Make a heap that contains all symbols with a non-zero frequency,
  7386. // with the least frequent symbol on top.
  7387. //
  7388. // Repeat until only one symbol is left on the heap:
  7389. //
  7390. // Take the two least frequent symbols off the top of the heap.
  7391. // Create a new node that has first two nodes as children, and
  7392. // whose frequency is the sum of the frequencies of the first
  7393. // two nodes. Put the new node back into the heap.
  7394. //
  7395. // The last node left on the heap is the root of the tree. For each
  7396. // leaf node, the distance between the root and the leaf is the length
  7397. // of the code for the corresponding symbol.
  7398. //
  7399. // The loop below doesn't actually build the tree; instead we compute
  7400. // the distances of the leaves from the root on the fly. When a new
  7401. // node is added to the heap, then that node's descendants are linked
  7402. // into a single linear list that starts at the new node, and the code
  7403. // lengths of the descendants (that is, their distance from the root
  7404. // of the tree) are incremented by one.
  7405. //
  7406. std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7407. std::vector<long long> scode(HUF_ENCSIZE);
  7408. memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
  7409. while (nf > 1) {
  7410. //
  7411. // Find the indices, mm and m, of the two smallest non-zero frq
  7412. // values in fHeap, add the smallest frq to the second-smallest
  7413. // frq, and remove the smallest frq value from fHeap.
  7414. //
  7415. int mm = fHeap[0] - frq;
  7416. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7417. --nf;
  7418. int m = fHeap[0] - frq;
  7419. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7420. frq[m] += frq[mm];
  7421. std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  7422. //
  7423. // The entries in scode are linked into lists with the
  7424. // entries in hlink serving as "next" pointers and with
  7425. // the end of a list marked by hlink[j] == j.
  7426. //
  7427. // Traverse the lists that start at scode[m] and scode[mm].
  7428. // For each element visited, increment the length of the
  7429. // corresponding code by one bit. (If we visit scode[j]
  7430. // during the traversal, then the code for symbol j becomes
  7431. // one bit longer.)
  7432. //
  7433. // Merge the lists that start at scode[m] and scode[mm]
  7434. // into a single list that starts at scode[m].
  7435. //
  7436. //
  7437. // Add a bit to all codes in the first list.
  7438. //
  7439. for (int j = m;; j = hlink[j]) {
  7440. scode[j]++;
  7441. assert(scode[j] <= 58);
  7442. if (hlink[j] == j) {
  7443. //
  7444. // Merge the two lists.
  7445. //
  7446. hlink[j] = mm;
  7447. break;
  7448. }
  7449. }
  7450. //
  7451. // Add a bit to all codes in the second list
  7452. //
  7453. for (int j = mm;; j = hlink[j]) {
  7454. scode[j]++;
  7455. assert(scode[j] <= 58);
  7456. if (hlink[j] == j) break;
  7457. }
  7458. }
  7459. //
  7460. // Build a canonical Huffman code table, replacing the code
  7461. // lengths in scode with (code, code length) pairs. Copy the
  7462. // code table from scode into frq.
  7463. //
  7464. hufCanonicalCodeTable(scode.data());
  7465. memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
  7466. }
  7467. //
  7468. // Pack an encoding table:
  7469. // - only code lengths, not actual codes, are stored
  7470. // - runs of zeroes are compressed as follows:
  7471. //
  7472. // unpacked packed
  7473. // --------------------------------
  7474. // 1 zero 0 (6 bits)
  7475. // 2 zeroes 59
  7476. // 3 zeroes 60
  7477. // 4 zeroes 61
  7478. // 5 zeroes 62
  7479. // n zeroes (6 or more) 63 n-6 (6 + 8 bits)
  7480. //
  7481. const int SHORT_ZEROCODE_RUN = 59;
  7482. const int LONG_ZEROCODE_RUN = 63;
  7483. const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  7484. const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
  7485. static void hufPackEncTable(
  7486. const long long *hcode, // i : encoding table [HUF_ENCSIZE]
  7487. int im, // i : min hcode index
  7488. int iM, // i : max hcode index
  7489. char **pcode) // o: ptr to packed table (updated)
  7490. {
  7491. char *p = *pcode;
  7492. long long c = 0;
  7493. int lc = 0;
  7494. for (; im <= iM; im++) {
  7495. int l = hufLength(hcode[im]);
  7496. if (l == 0) {
  7497. int zerun = 1;
  7498. while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
  7499. if (hufLength(hcode[im + 1]) > 0) break;
  7500. im++;
  7501. zerun++;
  7502. }
  7503. if (zerun >= 2) {
  7504. if (zerun >= SHORTEST_LONG_RUN) {
  7505. outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
  7506. outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
  7507. } else {
  7508. outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
  7509. }
  7510. continue;
  7511. }
  7512. }
  7513. outputBits(6, l, c, lc, p);
  7514. }
  7515. if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));
  7516. *pcode = p;
  7517. }
  7518. //
  7519. // Unpack an encoding table packed by hufPackEncTable():
  7520. //
  7521. static bool hufUnpackEncTable(
  7522. const char **pcode, // io: ptr to packed table (updated)
  7523. int ni, // i : input size (in bytes)
  7524. int im, // i : min hcode index
  7525. int iM, // i : max hcode index
  7526. long long *hcode) // o: encoding table [HUF_ENCSIZE]
  7527. {
  7528. memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
  7529. const char *p = *pcode;
  7530. long long c = 0;
  7531. int lc = 0;
  7532. for (; im <= iM; im++) {
  7533. if (p - *pcode >= ni) {
  7534. return false;
  7535. }
  7536. long long l = hcode[im] = getBits(6, c, lc, p); // code length
  7537. if (l == (long long)LONG_ZEROCODE_RUN) {
  7538. if (p - *pcode > ni) {
  7539. return false;
  7540. }
  7541. int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
  7542. if (im + zerun > iM + 1) {
  7543. return false;
  7544. }
  7545. while (zerun--) hcode[im++] = 0;
  7546. im--;
  7547. } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
  7548. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  7549. if (im + zerun > iM + 1) {
  7550. return false;
  7551. }
  7552. while (zerun--) hcode[im++] = 0;
  7553. im--;
  7554. }
  7555. }
  7556. *pcode = const_cast<char *>(p);
  7557. hufCanonicalCodeTable(hcode);
  7558. return true;
  7559. }
  7560. //
  7561. // DECODING TABLE BUILDING
  7562. //
  7563. //
  7564. // Clear a newly allocated decoding table so that it contains only zeroes.
  7565. //
  7566. static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
  7567. // decoding table [HUF_DECSIZE]
  7568. {
  7569. for (int i = 0; i < HUF_DECSIZE; i++) {
  7570. hdecod[i].len = 0;
  7571. hdecod[i].lit = 0;
  7572. hdecod[i].p = NULL;
  7573. }
  7574. // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
  7575. }
  7576. //
  7577. // Build a decoding hash table based on the encoding table hcode:
  7578. // - short codes (<= HUF_DECBITS) are resolved with a single table access;
  7579. // - long code entry allocations are not optimized, because long codes are
  7580. // unfrequent;
  7581. // - decoding tables are used by hufDecode();
  7582. //
  7583. static bool hufBuildDecTable(const long long *hcode, // i : encoding table
  7584. int im, // i : min index in hcode
  7585. int iM, // i : max index in hcode
  7586. HufDec *hdecod) // o: (allocated by caller)
  7587. // decoding table [HUF_DECSIZE]
  7588. {
  7589. //
  7590. // Init hashtable & loop on all codes.
  7591. // Assumes that hufClearDecTable(hdecod) has already been called.
  7592. //
  7593. for (; im <= iM; im++) {
  7594. long long c = hufCode(hcode[im]);
  7595. int l = hufLength(hcode[im]);
  7596. if (c >> l) {
  7597. //
  7598. // Error: c is supposed to be an l-bit code,
  7599. // but c contains a value that is greater
  7600. // than the largest l-bit number.
  7601. //
  7602. // invalidTableEntry();
  7603. return false;
  7604. }
  7605. if (l > HUF_DECBITS) {
  7606. //
  7607. // Long code: add a secondary entry
  7608. //
  7609. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  7610. if (pl->len) {
  7611. //
  7612. // Error: a short code has already
  7613. // been stored in table entry *pl.
  7614. //
  7615. // invalidTableEntry();
  7616. return false;
  7617. }
  7618. pl->lit++;
  7619. if (pl->p) {
  7620. int *p = pl->p;
  7621. pl->p = new int[pl->lit];
  7622. for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i];
  7623. delete[] p;
  7624. } else {
  7625. pl->p = new int[1];
  7626. }
  7627. pl->p[pl->lit - 1] = im;
  7628. } else if (l) {
  7629. //
  7630. // Short code: init all primary entries
  7631. //
  7632. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  7633. for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
  7634. if (pl->len || pl->p) {
  7635. //
  7636. // Error: a short code or a long code has
  7637. // already been stored in table entry *pl.
  7638. //
  7639. // invalidTableEntry();
  7640. return false;
  7641. }
  7642. pl->len = l;
  7643. pl->lit = im;
  7644. }
  7645. }
  7646. }
  7647. return true;
  7648. }
  7649. //
  7650. // Free the long code entries of a decoding table built by hufBuildDecTable()
  7651. //
  7652. static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
  7653. {
  7654. for (int i = 0; i < HUF_DECSIZE; i++) {
  7655. if (hdecod[i].p) {
  7656. delete[] hdecod[i].p;
  7657. hdecod[i].p = 0;
  7658. }
  7659. }
  7660. }
  7661. //
  7662. // ENCODING
  7663. //
  7664. inline void outputCode(long long code, long long &c, int &lc, char *&out) {
  7665. outputBits(hufLength(code), hufCode(code), c, lc, out);
  7666. }
  7667. inline void sendCode(long long sCode, int runCount, long long runCode,
  7668. long long &c, int &lc, char *&out) {
  7669. //
  7670. // Output a run of runCount instances of the symbol sCount.
  7671. // Output the symbols explicitly, or if that is shorter, output
  7672. // the sCode symbol once followed by a runCode symbol and runCount
  7673. // expressed as an 8-bit number.
  7674. //
  7675. if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
  7676. outputCode(sCode, c, lc, out);
  7677. outputCode(runCode, c, lc, out);
  7678. outputBits(8, runCount, c, lc, out);
  7679. } else {
  7680. while (runCount-- >= 0) outputCode(sCode, c, lc, out);
  7681. }
  7682. }
  7683. //
  7684. // Encode (compress) ni values based on the Huffman encoding table hcode:
  7685. //
  7686. static int hufEncode // return: output size (in bits)
  7687. (const long long *hcode, // i : encoding table
  7688. const unsigned short *in, // i : uncompressed input buffer
  7689. const int ni, // i : input buffer size (in bytes)
  7690. int rlc, // i : rl code
  7691. char *out) // o: compressed output buffer
  7692. {
  7693. char *outStart = out;
  7694. long long c = 0; // bits not yet written to out
  7695. int lc = 0; // number of valid bits in c (LSB)
  7696. int s = in[0];
  7697. int cs = 0;
  7698. //
  7699. // Loop on input values
  7700. //
  7701. for (int i = 1; i < ni; i++) {
  7702. //
  7703. // Count same values or send code
  7704. //
  7705. if (s == in[i] && cs < 255) {
  7706. cs++;
  7707. } else {
  7708. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7709. cs = 0;
  7710. }
  7711. s = in[i];
  7712. }
  7713. //
  7714. // Send remaining code
  7715. //
  7716. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  7717. if (lc) *out = (c << (8 - lc)) & 0xff;
  7718. return (out - outStart) * 8 + lc;
  7719. }
  7720. //
  7721. // DECODING
  7722. //
  7723. //
  7724. // In order to force the compiler to inline them,
  7725. // getChar() and getCode() are implemented as macros
  7726. // instead of "inline" functions.
  7727. //
  7728. #define getChar(c, lc, in) \
  7729. { \
  7730. c = (c << 8) | *(unsigned char *)(in++); \
  7731. lc += 8; \
  7732. }
  7733. #if 0
  7734. #define getCode(po, rlc, c, lc, in, out, ob, oe) \
  7735. { \
  7736. if (po == rlc) { \
  7737. if (lc < 8) getChar(c, lc, in); \
  7738. \
  7739. lc -= 8; \
  7740. \
  7741. unsigned char cs = (c >> lc); \
  7742. \
  7743. if (out + cs > oe) return false; \
  7744. \
  7745. /* TinyEXR issue 78 */ \
  7746. unsigned short s = out[-1]; \
  7747. \
  7748. while (cs-- > 0) *out++ = s; \
  7749. } else if (out < oe) { \
  7750. *out++ = po; \
  7751. } else { \
  7752. return false; \
  7753. } \
  7754. }
  7755. #else
  7756. static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,
  7757. const char *in_end, unsigned short *&out,
  7758. const unsigned short *ob, const unsigned short *oe) {
  7759. (void)ob;
  7760. if (po == rlc) {
  7761. if (lc < 8) {
  7762. /* TinyEXR issue 78 */
  7763. if ((in + 1) >= in_end) {
  7764. return false;
  7765. }
  7766. getChar(c, lc, in);
  7767. }
  7768. lc -= 8;
  7769. unsigned char cs = (c >> lc);
  7770. if (out + cs > oe) return false;
  7771. // Bounds check for safety
  7772. // Issue 100.
  7773. if ((out - 1) < ob) return false;
  7774. unsigned short s = out[-1];
  7775. while (cs-- > 0) *out++ = s;
  7776. } else if (out < oe) {
  7777. *out++ = po;
  7778. } else {
  7779. return false;
  7780. }
  7781. return true;
  7782. }
  7783. #endif
  7784. //
  7785. // Decode (uncompress) ni bits based on encoding & decoding tables:
  7786. //
  7787. static bool hufDecode(const long long *hcode, // i : encoding table
  7788. const HufDec *hdecod, // i : decoding table
  7789. const char *in, // i : compressed input buffer
  7790. int ni, // i : input size (in bits)
  7791. int rlc, // i : run-length code
  7792. int no, // i : expected output size (in bytes)
  7793. unsigned short *out) // o: uncompressed output buffer
  7794. {
  7795. long long c = 0;
  7796. int lc = 0;
  7797. unsigned short *outb = out; // begin
  7798. unsigned short *oe = out + no; // end
  7799. const char *ie = in + (ni + 7) / 8; // input byte size
  7800. //
  7801. // Loop on input bytes
  7802. //
  7803. while (in < ie) {
  7804. getChar(c, lc, in);
  7805. //
  7806. // Access decoding table
  7807. //
  7808. while (lc >= HUF_DECBITS) {
  7809. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  7810. if (pl.len) {
  7811. //
  7812. // Get short code
  7813. //
  7814. lc -= pl.len;
  7815. // std::cout << "lit = " << pl.lit << std::endl;
  7816. // std::cout << "rlc = " << rlc << std::endl;
  7817. // std::cout << "c = " << c << std::endl;
  7818. // std::cout << "lc = " << lc << std::endl;
  7819. // std::cout << "in = " << in << std::endl;
  7820. // std::cout << "out = " << out << std::endl;
  7821. // std::cout << "oe = " << oe << std::endl;
  7822. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7823. return false;
  7824. }
  7825. } else {
  7826. if (!pl.p) {
  7827. return false;
  7828. }
  7829. // invalidCode(); // wrong code
  7830. //
  7831. // Search long code
  7832. //
  7833. int j;
  7834. for (j = 0; j < pl.lit; j++) {
  7835. int l = hufLength(hcode[pl.p[j]]);
  7836. while (lc < l && in < ie) // get more bits
  7837. getChar(c, lc, in);
  7838. if (lc >= l) {
  7839. if (hufCode(hcode[pl.p[j]]) ==
  7840. ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
  7841. //
  7842. // Found : get long code
  7843. //
  7844. lc -= l;
  7845. if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
  7846. return false;
  7847. }
  7848. break;
  7849. }
  7850. }
  7851. }
  7852. if (j == pl.lit) {
  7853. return false;
  7854. // invalidCode(); // Not found
  7855. }
  7856. }
  7857. }
  7858. }
  7859. //
  7860. // Get remaining (short) codes
  7861. //
  7862. int i = (8 - ni) & 7;
  7863. c >>= i;
  7864. lc -= i;
  7865. while (lc > 0) {
  7866. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  7867. if (pl.len) {
  7868. lc -= pl.len;
  7869. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  7870. return false;
  7871. }
  7872. } else {
  7873. return false;
  7874. // invalidCode(); // wrong (long) code
  7875. }
  7876. }
  7877. if (out - outb != no) {
  7878. return false;
  7879. }
  7880. // notEnoughData ();
  7881. return true;
  7882. }
  7883. static void countFrequencies(std::vector<long long> &freq,
  7884. const unsigned short data[/*n*/], int n) {
  7885. for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;
  7886. for (int i = 0; i < n; ++i) ++freq[data[i]];
  7887. }
  7888. static void writeUInt(char buf[4], unsigned int i) {
  7889. unsigned char *b = (unsigned char *)buf;
  7890. b[0] = i;
  7891. b[1] = i >> 8;
  7892. b[2] = i >> 16;
  7893. b[3] = i >> 24;
  7894. }
  7895. static unsigned int readUInt(const char buf[4]) {
  7896. const unsigned char *b = (const unsigned char *)buf;
  7897. return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
  7898. ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
  7899. }
  7900. //
  7901. // EXTERNAL INTERFACE
  7902. //
  7903. static int hufCompress(const unsigned short raw[], int nRaw,
  7904. char compressed[]) {
  7905. if (nRaw == 0) return 0;
  7906. std::vector<long long> freq(HUF_ENCSIZE);
  7907. countFrequencies(freq, raw, nRaw);
  7908. int im = 0;
  7909. int iM = 0;
  7910. hufBuildEncTable(freq.data(), &im, &iM);
  7911. char *tableStart = compressed + 20;
  7912. char *tableEnd = tableStart;
  7913. hufPackEncTable(freq.data(), im, iM, &tableEnd);
  7914. int tableLength = tableEnd - tableStart;
  7915. char *dataStart = tableEnd;
  7916. int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
  7917. int data_length = (nBits + 7) / 8;
  7918. writeUInt(compressed, im);
  7919. writeUInt(compressed + 4, iM);
  7920. writeUInt(compressed + 8, tableLength);
  7921. writeUInt(compressed + 12, nBits);
  7922. writeUInt(compressed + 16, 0); // room for future extensions
  7923. return dataStart + data_length - compressed;
  7924. }
  7925. static bool hufUncompress(const char compressed[], int nCompressed,
  7926. std::vector<unsigned short> *raw) {
  7927. if (nCompressed == 0) {
  7928. if (raw->size() != 0) return false;
  7929. return false;
  7930. }
  7931. int im = readUInt(compressed);
  7932. int iM = readUInt(compressed + 4);
  7933. // int tableLength = readUInt (compressed + 8);
  7934. int nBits = readUInt(compressed + 12);
  7935. if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;
  7936. const char *ptr = compressed + 20;
  7937. //
  7938. // Fast decoder needs at least 2x64-bits of compressed data, and
  7939. // needs to be run-able on this platform. Otherwise, fall back
  7940. // to the original decoder
  7941. //
  7942. // if (FastHufDecoder::enabled() && nBits > 128)
  7943. //{
  7944. // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
  7945. // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
  7946. //}
  7947. // else
  7948. {
  7949. std::vector<long long> freq(HUF_ENCSIZE);
  7950. std::vector<HufDec> hdec(HUF_DECSIZE);
  7951. hufClearDecTable(&hdec.at(0));
  7952. hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
  7953. &freq.at(0));
  7954. {
  7955. if (nBits > 8 * (nCompressed - (ptr - compressed))) {
  7956. return false;
  7957. }
  7958. hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
  7959. hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
  7960. raw->data());
  7961. }
  7962. // catch (...)
  7963. //{
  7964. // hufFreeDecTable (hdec);
  7965. // throw;
  7966. //}
  7967. hufFreeDecTable(&hdec.at(0));
  7968. }
  7969. return true;
  7970. }
  7971. //
  7972. // Functions to compress the range of values in the pixel data
  7973. //
  7974. const int USHORT_RANGE = (1 << 16);
  7975. const int BITMAP_SIZE = (USHORT_RANGE >> 3);
  7976. static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
  7977. unsigned char bitmap[BITMAP_SIZE],
  7978. unsigned short &minNonZero,
  7979. unsigned short &maxNonZero) {
  7980. for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;
  7981. for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
  7982. bitmap[0] &= ~1; // zero is not explicitly stored in
  7983. // the bitmap; we assume that the
  7984. // data always contain zeroes
  7985. minNonZero = BITMAP_SIZE - 1;
  7986. maxNonZero = 0;
  7987. for (int i = 0; i < BITMAP_SIZE; ++i) {
  7988. if (bitmap[i]) {
  7989. if (minNonZero > i) minNonZero = i;
  7990. if (maxNonZero < i) maxNonZero = i;
  7991. }
  7992. }
  7993. }
  7994. static unsigned short forwardLutFromBitmap(
  7995. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  7996. int k = 0;
  7997. for (int i = 0; i < USHORT_RANGE; ++i) {
  7998. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  7999. lut[i] = k++;
  8000. else
  8001. lut[i] = 0;
  8002. }
  8003. return k - 1; // maximum value stored in lut[],
  8004. } // i.e. number of ones in bitmap minus 1
  8005. static unsigned short reverseLutFromBitmap(
  8006. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  8007. int k = 0;
  8008. for (int i = 0; i < USHORT_RANGE; ++i) {
  8009. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;
  8010. }
  8011. int n = k - 1;
  8012. while (k < USHORT_RANGE) lut[k++] = 0;
  8013. return n; // maximum k where lut[k] is non-zero,
  8014. } // i.e. number of ones in bitmap minus 1
  8015. static void applyLut(const unsigned short lut[USHORT_RANGE],
  8016. unsigned short data[/*nData*/], int nData) {
  8017. for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];
  8018. }
  8019. #ifdef __clang__
  8020. #pragma clang diagnostic pop
  8021. #endif // __clang__
  8022. #ifdef _MSC_VER
  8023. #pragma warning(pop)
  8024. #endif
  8025. static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,
  8026. const unsigned char *inPtr, size_t inSize,
  8027. const std::vector<ChannelInfo> &channelInfo,
  8028. int data_width, int num_lines) {
  8029. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  8030. unsigned short minNonZero;
  8031. unsigned short maxNonZero;
  8032. #if !MINIZ_LITTLE_ENDIAN
  8033. // @todo { PIZ compression on BigEndian architecture. }
  8034. assert(0);
  8035. return false;
  8036. #endif
  8037. // Assume `inSize` is multiple of 2 or 4.
  8038. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
  8039. std::vector<PIZChannelData> channelData(channelInfo.size());
  8040. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8041. for (size_t c = 0; c < channelData.size(); c++) {
  8042. PIZChannelData &cd = channelData[c];
  8043. cd.start = tmpBufferEnd;
  8044. cd.end = cd.start;
  8045. cd.nx = data_width;
  8046. cd.ny = num_lines;
  8047. // cd.ys = c.channel().ySampling;
  8048. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8049. if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8050. pixelSize = sizeof(short);
  8051. }
  8052. cd.size = static_cast<int>(pixelSize / sizeof(short));
  8053. tmpBufferEnd += cd.nx * cd.ny * cd.size;
  8054. }
  8055. const unsigned char *ptr = inPtr;
  8056. for (int y = 0; y < num_lines; ++y) {
  8057. for (size_t i = 0; i < channelData.size(); ++i) {
  8058. PIZChannelData &cd = channelData[i];
  8059. // if (modp (y, cd.ys) != 0)
  8060. // continue;
  8061. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8062. memcpy(cd.end, ptr, n * sizeof(unsigned short));
  8063. ptr += n * sizeof(unsigned short);
  8064. cd.end += n;
  8065. }
  8066. }
  8067. bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
  8068. bitmap.data(), minNonZero, maxNonZero);
  8069. std::vector<unsigned short> lut(USHORT_RANGE);
  8070. unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
  8071. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
  8072. //
  8073. // Store range compression info in _outBuffer
  8074. //
  8075. char *buf = reinterpret_cast<char *>(outPtr);
  8076. memcpy(buf, &minNonZero, sizeof(unsigned short));
  8077. buf += sizeof(unsigned short);
  8078. memcpy(buf, &maxNonZero, sizeof(unsigned short));
  8079. buf += sizeof(unsigned short);
  8080. if (minNonZero <= maxNonZero) {
  8081. memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),
  8082. maxNonZero - minNonZero + 1);
  8083. buf += maxNonZero - minNonZero + 1;
  8084. }
  8085. //
  8086. // Apply wavelet encoding
  8087. //
  8088. for (size_t i = 0; i < channelData.size(); ++i) {
  8089. PIZChannelData &cd = channelData[i];
  8090. for (int j = 0; j < cd.size; ++j) {
  8091. wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8092. maxValue);
  8093. }
  8094. }
  8095. //
  8096. // Apply Huffman encoding; append the result to _outBuffer
  8097. //
  8098. // length header(4byte), then huff data. Initialize length header with zero,
  8099. // then later fill it by `length`.
  8100. char *lengthPtr = buf;
  8101. int zero = 0;
  8102. memcpy(buf, &zero, sizeof(int));
  8103. buf += sizeof(int);
  8104. int length =
  8105. hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
  8106. memcpy(lengthPtr, &length, sizeof(int));
  8107. (*outSize) = static_cast<unsigned int>(
  8108. (reinterpret_cast<unsigned char *>(buf) - outPtr) +
  8109. static_cast<unsigned int>(length));
  8110. // Use uncompressed data when compressed data is larger than uncompressed.
  8111. // (Issue 40)
  8112. if ((*outSize) >= inSize) {
  8113. (*outSize) = static_cast<unsigned int>(inSize);
  8114. memcpy(outPtr, inPtr, inSize);
  8115. }
  8116. return true;
  8117. }
  8118. static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,
  8119. size_t tmpBufSize, size_t inLen, int num_channels,
  8120. const EXRChannelInfo *channels, int data_width,
  8121. int num_lines) {
  8122. if (inLen == tmpBufSize) {
  8123. // Data is not compressed(Issue 40).
  8124. memcpy(outPtr, inPtr, inLen);
  8125. return true;
  8126. }
  8127. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  8128. unsigned short minNonZero;
  8129. unsigned short maxNonZero;
  8130. #if !MINIZ_LITTLE_ENDIAN
  8131. // @todo { PIZ compression on BigEndian architecture. }
  8132. assert(0);
  8133. return false;
  8134. #endif
  8135. memset(bitmap.data(), 0, BITMAP_SIZE);
  8136. const unsigned char *ptr = inPtr;
  8137. // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
  8138. tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));
  8139. // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
  8140. tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));
  8141. ptr += 4;
  8142. if (maxNonZero >= BITMAP_SIZE) {
  8143. return false;
  8144. }
  8145. if (minNonZero <= maxNonZero) {
  8146. memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,
  8147. maxNonZero - minNonZero + 1);
  8148. ptr += maxNonZero - minNonZero + 1;
  8149. }
  8150. std::vector<unsigned short> lut(USHORT_RANGE);
  8151. memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
  8152. unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
  8153. //
  8154. // Huffman decoding
  8155. //
  8156. int length;
  8157. // length = *(reinterpret_cast<const int *>(ptr));
  8158. tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));
  8159. ptr += sizeof(int);
  8160. if (size_t((ptr - inPtr) + length) > inLen) {
  8161. return false;
  8162. }
  8163. std::vector<unsigned short> tmpBuffer(tmpBufSize);
  8164. hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);
  8165. //
  8166. // Wavelet decoding
  8167. //
  8168. std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
  8169. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  8170. for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
  8171. const EXRChannelInfo &chan = channels[i];
  8172. size_t pixelSize = sizeof(int); // UINT and FLOAT
  8173. if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8174. pixelSize = sizeof(short);
  8175. }
  8176. channelData[i].start = tmpBufferEnd;
  8177. channelData[i].end = channelData[i].start;
  8178. channelData[i].nx = data_width;
  8179. channelData[i].ny = num_lines;
  8180. // channelData[i].ys = 1;
  8181. channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
  8182. tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
  8183. }
  8184. for (size_t i = 0; i < channelData.size(); ++i) {
  8185. PIZChannelData &cd = channelData[i];
  8186. for (int j = 0; j < cd.size; ++j) {
  8187. wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  8188. maxValue);
  8189. }
  8190. }
  8191. //
  8192. // Expand the pixel data to their original range
  8193. //
  8194. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize));
  8195. for (int y = 0; y < num_lines; y++) {
  8196. for (size_t i = 0; i < channelData.size(); ++i) {
  8197. PIZChannelData &cd = channelData[i];
  8198. // if (modp (y, cd.ys) != 0)
  8199. // continue;
  8200. size_t n = static_cast<size_t>(cd.nx * cd.size);
  8201. memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
  8202. outPtr += n * sizeof(unsigned short);
  8203. cd.end += n;
  8204. }
  8205. }
  8206. return true;
  8207. }
  8208. #endif // TINYEXR_USE_PIZ
  8209. #if TINYEXR_USE_ZFP
  8210. struct ZFPCompressionParam {
  8211. double rate;
  8212. int precision;
  8213. double tolerance;
  8214. int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
  8215. ZFPCompressionParam() {
  8216. type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;
  8217. rate = 2.0;
  8218. precision = 0;
  8219. tolerance = 0.0f;
  8220. }
  8221. };
  8222. bool FindZFPCompressionParam(ZFPCompressionParam *param,
  8223. const EXRAttribute *attributes,
  8224. int num_attributes) {
  8225. bool foundType = false;
  8226. for (int i = 0; i < num_attributes; i++) {
  8227. if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) &&
  8228. (attributes[i].size == 1)) {
  8229. param->type = static_cast<int>(attributes[i].value[0]);
  8230. foundType = true;
  8231. }
  8232. }
  8233. if (!foundType) {
  8234. return false;
  8235. }
  8236. if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8237. for (int i = 0; i < num_attributes; i++) {
  8238. if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&
  8239. (attributes[i].size == 8)) {
  8240. param->rate = *(reinterpret_cast<double *>(attributes[i].value));
  8241. return true;
  8242. }
  8243. }
  8244. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8245. for (int i = 0; i < num_attributes; i++) {
  8246. if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&
  8247. (attributes[i].size == 4)) {
  8248. param->rate = *(reinterpret_cast<int *>(attributes[i].value));
  8249. return true;
  8250. }
  8251. }
  8252. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8253. for (int i = 0; i < num_attributes; i++) {
  8254. if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&
  8255. (attributes[i].size == 8)) {
  8256. param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));
  8257. return true;
  8258. }
  8259. }
  8260. } else {
  8261. assert(0);
  8262. }
  8263. return false;
  8264. }
  8265. // Assume pixel format is FLOAT for all channels.
  8266. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,
  8267. int num_channels, const unsigned char *src,
  8268. unsigned long src_size,
  8269. const ZFPCompressionParam &param) {
  8270. size_t uncompressed_size = dst_width * dst_num_lines * num_channels;
  8271. if (uncompressed_size == src_size) {
  8272. // Data is not compressed(Issue 40).
  8273. memcpy(dst, src, src_size);
  8274. }
  8275. zfp_stream *zfp = NULL;
  8276. zfp_field *field = NULL;
  8277. assert((dst_width % 4) == 0);
  8278. assert((dst_num_lines % 4) == 0);
  8279. if ((dst_width & 3U) || (dst_num_lines & 3U)) {
  8280. return false;
  8281. }
  8282. field =
  8283. zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),
  8284. zfp_type_float, dst_width, dst_num_lines * num_channels);
  8285. zfp = zfp_stream_open(NULL);
  8286. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8287. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2,
  8288. /* write random access */ 0);
  8289. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8290. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8291. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8292. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8293. } else {
  8294. assert(0);
  8295. }
  8296. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8297. std::vector<unsigned char> buf(buf_size);
  8298. memcpy(&buf.at(0), src, src_size);
  8299. bitstream *stream = stream_open(&buf.at(0), buf_size);
  8300. zfp_stream_set_bit_stream(zfp, stream);
  8301. zfp_stream_rewind(zfp);
  8302. size_t image_size = dst_width * dst_num_lines;
  8303. for (int c = 0; c < num_channels; c++) {
  8304. // decompress 4x4 pixel block.
  8305. for (int y = 0; y < dst_num_lines; y += 4) {
  8306. for (int x = 0; x < dst_width; x += 4) {
  8307. float fblock[16];
  8308. zfp_decode_block_float_2(zfp, fblock);
  8309. for (int j = 0; j < 4; j++) {
  8310. for (int i = 0; i < 4; i++) {
  8311. dst[c * image_size + ((y + j) * dst_width + (x + i))] =
  8312. fblock[j * 4 + i];
  8313. }
  8314. }
  8315. }
  8316. }
  8317. }
  8318. zfp_field_free(field);
  8319. zfp_stream_close(zfp);
  8320. stream_close(stream);
  8321. return true;
  8322. }
  8323. // Assume pixel format is FLOAT for all channels.
  8324. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize,
  8325. const float *inPtr, int width, int num_lines, int num_channels,
  8326. const ZFPCompressionParam &param) {
  8327. zfp_stream *zfp = NULL;
  8328. zfp_field *field = NULL;
  8329. assert((width % 4) == 0);
  8330. assert((num_lines % 4) == 0);
  8331. if ((width & 3U) || (num_lines & 3U)) {
  8332. return false;
  8333. }
  8334. // create input array.
  8335. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),
  8336. zfp_type_float, width, num_lines * num_channels);
  8337. zfp = zfp_stream_open(NULL);
  8338. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  8339. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
  8340. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  8341. zfp_stream_set_precision(zfp, param.precision, zfp_type_float);
  8342. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  8343. zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float);
  8344. } else {
  8345. assert(0);
  8346. }
  8347. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  8348. outBuf->resize(buf_size);
  8349. bitstream *stream = stream_open(&outBuf->at(0), buf_size);
  8350. zfp_stream_set_bit_stream(zfp, stream);
  8351. zfp_field_free(field);
  8352. size_t image_size = width * num_lines;
  8353. for (int c = 0; c < num_channels; c++) {
  8354. // compress 4x4 pixel block.
  8355. for (int y = 0; y < num_lines; y += 4) {
  8356. for (int x = 0; x < width; x += 4) {
  8357. float fblock[16];
  8358. for (int j = 0; j < 4; j++) {
  8359. for (int i = 0; i < 4; i++) {
  8360. fblock[j * 4 + i] =
  8361. inPtr[c * image_size + ((y + j) * width + (x + i))];
  8362. }
  8363. }
  8364. zfp_encode_block_float_2(zfp, fblock);
  8365. }
  8366. }
  8367. }
  8368. zfp_stream_flush(zfp);
  8369. (*outSize) = zfp_stream_compressed_size(zfp);
  8370. zfp_stream_close(zfp);
  8371. return true;
  8372. }
  8373. #endif
  8374. //
  8375. // -----------------------------------------------------------------
  8376. //
  8377. // TODO(syoyo): Refactor function arguments.
  8378. static bool DecodePixelData(/* out */ unsigned char **out_images,
  8379. const int *requested_pixel_types,
  8380. const unsigned char *data_ptr, size_t data_len,
  8381. int compression_type, int line_order, int width,
  8382. int height, int x_stride, int y, int line_no,
  8383. int num_lines, size_t pixel_data_size,
  8384. size_t num_attributes,
  8385. const EXRAttribute *attributes, size_t num_channels,
  8386. const EXRChannelInfo *channels,
  8387. const std::vector<size_t> &channel_offset_list) {
  8388. if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
  8389. #if TINYEXR_USE_PIZ
  8390. if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
  8391. // Invalid input #90
  8392. return false;
  8393. }
  8394. // Allocate original data size.
  8395. std::vector<unsigned char> outBuf(static_cast<size_t>(
  8396. static_cast<size_t>(width * num_lines) * pixel_data_size));
  8397. size_t tmpBufLen = outBuf.size();
  8398. bool ret = tinyexr::DecompressPiz(
  8399. reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,
  8400. data_len, static_cast<int>(num_channels), channels, width, num_lines);
  8401. if (!ret) {
  8402. return false;
  8403. }
  8404. // For PIZ_COMPRESSION:
  8405. // pixel sample data for channel 0 for scanline 0
  8406. // pixel sample data for channel 1 for scanline 0
  8407. // pixel sample data for channel ... for scanline 0
  8408. // pixel sample data for channel n for scanline 0
  8409. // pixel sample data for channel 0 for scanline 1
  8410. // pixel sample data for channel 1 for scanline 1
  8411. // pixel sample data for channel ... for scanline 1
  8412. // pixel sample data for channel n for scanline 1
  8413. // ...
  8414. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8415. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8416. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8417. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8418. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8419. channel_offset_list[c] * static_cast<size_t>(width)));
  8420. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8421. FP16 hf;
  8422. // hf.u = line_ptr[u];
  8423. // use `cpy` to avoid unaligned memory access when compiler's
  8424. // optimization is on.
  8425. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8426. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8427. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8428. unsigned short *image =
  8429. reinterpret_cast<unsigned short **>(out_images)[c];
  8430. if (line_order == 0) {
  8431. image += (static_cast<size_t>(line_no) + v) *
  8432. static_cast<size_t>(x_stride) +
  8433. u;
  8434. } else {
  8435. image += static_cast<size_t>(
  8436. (height - 1 - (line_no + static_cast<int>(v)))) *
  8437. static_cast<size_t>(x_stride) +
  8438. u;
  8439. }
  8440. *image = hf.u;
  8441. } else { // HALF -> FLOAT
  8442. FP32 f32 = half_to_float(hf);
  8443. float *image = reinterpret_cast<float **>(out_images)[c];
  8444. size_t offset = 0;
  8445. if (line_order == 0) {
  8446. offset = (static_cast<size_t>(line_no) + v) *
  8447. static_cast<size_t>(x_stride) +
  8448. u;
  8449. } else {
  8450. offset = static_cast<size_t>(
  8451. (height - 1 - (line_no + static_cast<int>(v)))) *
  8452. static_cast<size_t>(x_stride) +
  8453. u;
  8454. }
  8455. image += offset;
  8456. *image = f32.f;
  8457. }
  8458. }
  8459. }
  8460. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8461. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8462. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8463. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8464. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8465. channel_offset_list[c] * static_cast<size_t>(width)));
  8466. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8467. unsigned int val;
  8468. // val = line_ptr[u];
  8469. tinyexr::cpy4(&val, line_ptr + u);
  8470. tinyexr::swap4(&val);
  8471. unsigned int *image =
  8472. reinterpret_cast<unsigned int **>(out_images)[c];
  8473. if (line_order == 0) {
  8474. image += (static_cast<size_t>(line_no) + v) *
  8475. static_cast<size_t>(x_stride) +
  8476. u;
  8477. } else {
  8478. image += static_cast<size_t>(
  8479. (height - 1 - (line_no + static_cast<int>(v)))) *
  8480. static_cast<size_t>(x_stride) +
  8481. u;
  8482. }
  8483. *image = val;
  8484. }
  8485. }
  8486. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8487. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8488. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8489. const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(
  8490. v * pixel_data_size * static_cast<size_t>(x_stride) +
  8491. channel_offset_list[c] * static_cast<size_t>(x_stride)));
  8492. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8493. float val;
  8494. // val = line_ptr[u];
  8495. tinyexr::cpy4(&val, line_ptr + u);
  8496. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8497. float *image = reinterpret_cast<float **>(out_images)[c];
  8498. if (line_order == 0) {
  8499. image += (static_cast<size_t>(line_no) + v) *
  8500. static_cast<size_t>(x_stride) +
  8501. u;
  8502. } else {
  8503. image += static_cast<size_t>(
  8504. (height - 1 - (line_no + static_cast<int>(v)))) *
  8505. static_cast<size_t>(x_stride) +
  8506. u;
  8507. }
  8508. *image = val;
  8509. }
  8510. }
  8511. } else {
  8512. assert(0);
  8513. }
  8514. }
  8515. #else
  8516. assert(0 && "PIZ is enabled in this build");
  8517. return false;
  8518. #endif
  8519. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||
  8520. compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  8521. // Allocate original data size.
  8522. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8523. static_cast<size_t>(num_lines) *
  8524. pixel_data_size);
  8525. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8526. assert(dstLen > 0);
  8527. if (!tinyexr::DecompressZip(
  8528. reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,
  8529. static_cast<unsigned long>(data_len))) {
  8530. return false;
  8531. }
  8532. // For ZIP_COMPRESSION:
  8533. // pixel sample data for channel 0 for scanline 0
  8534. // pixel sample data for channel 1 for scanline 0
  8535. // pixel sample data for channel ... for scanline 0
  8536. // pixel sample data for channel n for scanline 0
  8537. // pixel sample data for channel 0 for scanline 1
  8538. // pixel sample data for channel 1 for scanline 1
  8539. // pixel sample data for channel ... for scanline 1
  8540. // pixel sample data for channel n for scanline 1
  8541. // ...
  8542. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8543. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8544. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8545. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8546. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8547. static_cast<size_t>(width) +
  8548. channel_offset_list[c] * static_cast<size_t>(width)));
  8549. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8550. tinyexr::FP16 hf;
  8551. // hf.u = line_ptr[u];
  8552. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8553. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8554. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8555. unsigned short *image =
  8556. reinterpret_cast<unsigned short **>(out_images)[c];
  8557. if (line_order == 0) {
  8558. image += (static_cast<size_t>(line_no) + v) *
  8559. static_cast<size_t>(x_stride) +
  8560. u;
  8561. } else {
  8562. image += (static_cast<size_t>(height) - 1U -
  8563. (static_cast<size_t>(line_no) + v)) *
  8564. static_cast<size_t>(x_stride) +
  8565. u;
  8566. }
  8567. *image = hf.u;
  8568. } else { // HALF -> FLOAT
  8569. tinyexr::FP32 f32 = half_to_float(hf);
  8570. float *image = reinterpret_cast<float **>(out_images)[c];
  8571. size_t offset = 0;
  8572. if (line_order == 0) {
  8573. offset = (static_cast<size_t>(line_no) + v) *
  8574. static_cast<size_t>(x_stride) +
  8575. u;
  8576. } else {
  8577. offset = (static_cast<size_t>(height) - 1U -
  8578. (static_cast<size_t>(line_no) + v)) *
  8579. static_cast<size_t>(x_stride) +
  8580. u;
  8581. }
  8582. image += offset;
  8583. *image = f32.f;
  8584. }
  8585. }
  8586. }
  8587. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8588. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8589. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8590. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8591. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8592. channel_offset_list[c] * static_cast<size_t>(width)));
  8593. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8594. unsigned int val;
  8595. // val = line_ptr[u];
  8596. tinyexr::cpy4(&val, line_ptr + u);
  8597. tinyexr::swap4(&val);
  8598. unsigned int *image =
  8599. reinterpret_cast<unsigned int **>(out_images)[c];
  8600. if (line_order == 0) {
  8601. image += (static_cast<size_t>(line_no) + v) *
  8602. static_cast<size_t>(x_stride) +
  8603. u;
  8604. } else {
  8605. image += (static_cast<size_t>(height) - 1U -
  8606. (static_cast<size_t>(line_no) + v)) *
  8607. static_cast<size_t>(x_stride) +
  8608. u;
  8609. }
  8610. *image = val;
  8611. }
  8612. }
  8613. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8614. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8615. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8616. const float *line_ptr = reinterpret_cast<float *>(
  8617. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8618. channel_offset_list[c] * static_cast<size_t>(width)));
  8619. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8620. float val;
  8621. // val = line_ptr[u];
  8622. tinyexr::cpy4(&val, line_ptr + u);
  8623. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8624. float *image = reinterpret_cast<float **>(out_images)[c];
  8625. if (line_order == 0) {
  8626. image += (static_cast<size_t>(line_no) + v) *
  8627. static_cast<size_t>(x_stride) +
  8628. u;
  8629. } else {
  8630. image += (static_cast<size_t>(height) - 1U -
  8631. (static_cast<size_t>(line_no) + v)) *
  8632. static_cast<size_t>(x_stride) +
  8633. u;
  8634. }
  8635. *image = val;
  8636. }
  8637. }
  8638. } else {
  8639. assert(0);
  8640. return false;
  8641. }
  8642. }
  8643. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  8644. // Allocate original data size.
  8645. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8646. static_cast<size_t>(num_lines) *
  8647. pixel_data_size);
  8648. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  8649. if (dstLen == 0) {
  8650. return false;
  8651. }
  8652. if (!tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)),
  8653. dstLen, data_ptr,
  8654. static_cast<unsigned long>(data_len))) {
  8655. return false;
  8656. }
  8657. // For RLE_COMPRESSION:
  8658. // pixel sample data for channel 0 for scanline 0
  8659. // pixel sample data for channel 1 for scanline 0
  8660. // pixel sample data for channel ... for scanline 0
  8661. // pixel sample data for channel n for scanline 0
  8662. // pixel sample data for channel 0 for scanline 1
  8663. // pixel sample data for channel 1 for scanline 1
  8664. // pixel sample data for channel ... for scanline 1
  8665. // pixel sample data for channel n for scanline 1
  8666. // ...
  8667. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8668. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8669. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8670. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  8671. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  8672. static_cast<size_t>(width) +
  8673. channel_offset_list[c] * static_cast<size_t>(width)));
  8674. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8675. tinyexr::FP16 hf;
  8676. // hf.u = line_ptr[u];
  8677. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8678. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8679. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8680. unsigned short *image =
  8681. reinterpret_cast<unsigned short **>(out_images)[c];
  8682. if (line_order == 0) {
  8683. image += (static_cast<size_t>(line_no) + v) *
  8684. static_cast<size_t>(x_stride) +
  8685. u;
  8686. } else {
  8687. image += (static_cast<size_t>(height) - 1U -
  8688. (static_cast<size_t>(line_no) + v)) *
  8689. static_cast<size_t>(x_stride) +
  8690. u;
  8691. }
  8692. *image = hf.u;
  8693. } else { // HALF -> FLOAT
  8694. tinyexr::FP32 f32 = half_to_float(hf);
  8695. float *image = reinterpret_cast<float **>(out_images)[c];
  8696. if (line_order == 0) {
  8697. image += (static_cast<size_t>(line_no) + v) *
  8698. static_cast<size_t>(x_stride) +
  8699. u;
  8700. } else {
  8701. image += (static_cast<size_t>(height) - 1U -
  8702. (static_cast<size_t>(line_no) + v)) *
  8703. static_cast<size_t>(x_stride) +
  8704. u;
  8705. }
  8706. *image = f32.f;
  8707. }
  8708. }
  8709. }
  8710. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8711. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  8712. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8713. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  8714. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8715. channel_offset_list[c] * static_cast<size_t>(width)));
  8716. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8717. unsigned int val;
  8718. // val = line_ptr[u];
  8719. tinyexr::cpy4(&val, line_ptr + u);
  8720. tinyexr::swap4(&val);
  8721. unsigned int *image =
  8722. reinterpret_cast<unsigned int **>(out_images)[c];
  8723. if (line_order == 0) {
  8724. image += (static_cast<size_t>(line_no) + v) *
  8725. static_cast<size_t>(x_stride) +
  8726. u;
  8727. } else {
  8728. image += (static_cast<size_t>(height) - 1U -
  8729. (static_cast<size_t>(line_no) + v)) *
  8730. static_cast<size_t>(x_stride) +
  8731. u;
  8732. }
  8733. *image = val;
  8734. }
  8735. }
  8736. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8737. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8738. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8739. const float *line_ptr = reinterpret_cast<float *>(
  8740. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8741. channel_offset_list[c] * static_cast<size_t>(width)));
  8742. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8743. float val;
  8744. // val = line_ptr[u];
  8745. tinyexr::cpy4(&val, line_ptr + u);
  8746. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8747. float *image = reinterpret_cast<float **>(out_images)[c];
  8748. if (line_order == 0) {
  8749. image += (static_cast<size_t>(line_no) + v) *
  8750. static_cast<size_t>(x_stride) +
  8751. u;
  8752. } else {
  8753. image += (static_cast<size_t>(height) - 1U -
  8754. (static_cast<size_t>(line_no) + v)) *
  8755. static_cast<size_t>(x_stride) +
  8756. u;
  8757. }
  8758. *image = val;
  8759. }
  8760. }
  8761. } else {
  8762. assert(0);
  8763. return false;
  8764. }
  8765. }
  8766. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  8767. #if TINYEXR_USE_ZFP
  8768. tinyexr::ZFPCompressionParam zfp_compression_param;
  8769. if (!FindZFPCompressionParam(&zfp_compression_param, attributes,
  8770. num_attributes)) {
  8771. assert(0);
  8772. return false;
  8773. }
  8774. // Allocate original data size.
  8775. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  8776. static_cast<size_t>(num_lines) *
  8777. pixel_data_size);
  8778. unsigned long dstLen = outBuf.size();
  8779. assert(dstLen > 0);
  8780. tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,
  8781. num_lines, num_channels, data_ptr,
  8782. static_cast<unsigned long>(data_len),
  8783. zfp_compression_param);
  8784. // For ZFP_COMPRESSION:
  8785. // pixel sample data for channel 0 for scanline 0
  8786. // pixel sample data for channel 1 for scanline 0
  8787. // pixel sample data for channel ... for scanline 0
  8788. // pixel sample data for channel n for scanline 0
  8789. // pixel sample data for channel 0 for scanline 1
  8790. // pixel sample data for channel 1 for scanline 1
  8791. // pixel sample data for channel ... for scanline 1
  8792. // pixel sample data for channel n for scanline 1
  8793. // ...
  8794. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8795. assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT);
  8796. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8797. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  8798. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8799. const float *line_ptr = reinterpret_cast<float *>(
  8800. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  8801. channel_offset_list[c] * static_cast<size_t>(width)));
  8802. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  8803. float val;
  8804. tinyexr::cpy4(&val, line_ptr + u);
  8805. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8806. float *image = reinterpret_cast<float **>(out_images)[c];
  8807. if (line_order == 0) {
  8808. image += (static_cast<size_t>(line_no) + v) *
  8809. static_cast<size_t>(x_stride) +
  8810. u;
  8811. } else {
  8812. image += (static_cast<size_t>(height) - 1U -
  8813. (static_cast<size_t>(line_no) + v)) *
  8814. static_cast<size_t>(x_stride) +
  8815. u;
  8816. }
  8817. *image = val;
  8818. }
  8819. }
  8820. } else {
  8821. assert(0);
  8822. return false;
  8823. }
  8824. }
  8825. #else
  8826. (void)attributes;
  8827. (void)num_attributes;
  8828. (void)num_channels;
  8829. assert(0);
  8830. return false;
  8831. #endif
  8832. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  8833. for (size_t c = 0; c < num_channels; c++) {
  8834. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  8835. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8836. const unsigned short *line_ptr =
  8837. reinterpret_cast<const unsigned short *>(
  8838. data_ptr + v * pixel_data_size * size_t(width) +
  8839. channel_offset_list[c] * static_cast<size_t>(width));
  8840. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  8841. unsigned short *outLine =
  8842. reinterpret_cast<unsigned short *>(out_images[c]);
  8843. if (line_order == 0) {
  8844. outLine += (size_t(y) + v) * size_t(x_stride);
  8845. } else {
  8846. outLine +=
  8847. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8848. }
  8849. for (int u = 0; u < width; u++) {
  8850. tinyexr::FP16 hf;
  8851. // hf.u = line_ptr[u];
  8852. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8853. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8854. outLine[u] = hf.u;
  8855. }
  8856. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  8857. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8858. if (line_order == 0) {
  8859. outLine += (size_t(y) + v) * size_t(x_stride);
  8860. } else {
  8861. outLine +=
  8862. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8863. }
  8864. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8865. (data_ptr + data_len)) {
  8866. // Insufficient data size
  8867. return false;
  8868. }
  8869. for (int u = 0; u < width; u++) {
  8870. tinyexr::FP16 hf;
  8871. // address may not be aliged. use byte-wise copy for safety.#76
  8872. // hf.u = line_ptr[u];
  8873. tinyexr::cpy2(&(hf.u), line_ptr + u);
  8874. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  8875. tinyexr::FP32 f32 = half_to_float(hf);
  8876. outLine[u] = f32.f;
  8877. }
  8878. } else {
  8879. assert(0);
  8880. return false;
  8881. }
  8882. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8883. const float *line_ptr = reinterpret_cast<const float *>(
  8884. data_ptr + v * pixel_data_size * size_t(width) +
  8885. channel_offset_list[c] * static_cast<size_t>(width));
  8886. float *outLine = reinterpret_cast<float *>(out_images[c]);
  8887. if (line_order == 0) {
  8888. outLine += (size_t(y) + v) * size_t(x_stride);
  8889. } else {
  8890. outLine +=
  8891. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8892. }
  8893. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  8894. (data_ptr + data_len)) {
  8895. // Insufficient data size
  8896. return false;
  8897. }
  8898. for (int u = 0; u < width; u++) {
  8899. float val;
  8900. tinyexr::cpy4(&val, line_ptr + u);
  8901. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8902. outLine[u] = val;
  8903. }
  8904. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8905. const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(
  8906. data_ptr + v * pixel_data_size * size_t(width) +
  8907. channel_offset_list[c] * static_cast<size_t>(width));
  8908. unsigned int *outLine =
  8909. reinterpret_cast<unsigned int *>(out_images[c]);
  8910. if (line_order == 0) {
  8911. outLine += (size_t(y) + v) * size_t(x_stride);
  8912. } else {
  8913. outLine +=
  8914. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  8915. }
  8916. for (int u = 0; u < width; u++) {
  8917. if (reinterpret_cast<const unsigned char *>(line_ptr + u) >=
  8918. (data_ptr + data_len)) {
  8919. // Corrupsed data?
  8920. return false;
  8921. }
  8922. unsigned int val;
  8923. tinyexr::cpy4(&val, line_ptr + u);
  8924. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  8925. outLine[u] = val;
  8926. }
  8927. }
  8928. }
  8929. }
  8930. }
  8931. return true;
  8932. }
  8933. static void DecodeTiledPixelData(
  8934. unsigned char **out_images, int *width, int *height,
  8935. const int *requested_pixel_types, const unsigned char *data_ptr,
  8936. size_t data_len, int compression_type, int line_order, int data_width,
  8937. int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
  8938. int tile_size_y, size_t pixel_data_size, size_t num_attributes,
  8939. const EXRAttribute *attributes, size_t num_channels,
  8940. const EXRChannelInfo *channels,
  8941. const std::vector<size_t> &channel_offset_list) {
  8942. assert(tile_offset_x * tile_size_x < data_width);
  8943. assert(tile_offset_y * tile_size_y < data_height);
  8944. // Compute actual image size in a tile.
  8945. if ((tile_offset_x + 1) * tile_size_x >= data_width) {
  8946. (*width) = data_width - (tile_offset_x * tile_size_x);
  8947. } else {
  8948. (*width) = tile_size_x;
  8949. }
  8950. if ((tile_offset_y + 1) * tile_size_y >= data_height) {
  8951. (*height) = data_height - (tile_offset_y * tile_size_y);
  8952. } else {
  8953. (*height) = tile_size_y;
  8954. }
  8955. // Image size = tile size.
  8956. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
  8957. compression_type, line_order, (*width), tile_size_y,
  8958. /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
  8959. (*height), pixel_data_size, num_attributes, attributes,
  8960. num_channels, channels, channel_offset_list);
  8961. }
  8962. static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,
  8963. int *pixel_data_size, size_t *channel_offset,
  8964. int num_channels,
  8965. const EXRChannelInfo *channels) {
  8966. channel_offset_list->resize(static_cast<size_t>(num_channels));
  8967. (*pixel_data_size) = 0;
  8968. (*channel_offset) = 0;
  8969. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8970. (*channel_offset_list)[c] = (*channel_offset);
  8971. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8972. (*pixel_data_size) += sizeof(unsigned short);
  8973. (*channel_offset) += sizeof(unsigned short);
  8974. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  8975. (*pixel_data_size) += sizeof(float);
  8976. (*channel_offset) += sizeof(float);
  8977. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  8978. (*pixel_data_size) += sizeof(unsigned int);
  8979. (*channel_offset) += sizeof(unsigned int);
  8980. } else {
  8981. // ???
  8982. return false;
  8983. }
  8984. }
  8985. return true;
  8986. }
  8987. static unsigned char **AllocateImage(int num_channels,
  8988. const EXRChannelInfo *channels,
  8989. const int *requested_pixel_types,
  8990. int data_width, int data_height) {
  8991. unsigned char **images =
  8992. reinterpret_cast<unsigned char **>(static_cast<float **>(
  8993. malloc(sizeof(float *) * static_cast<size_t>(num_channels))));
  8994. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  8995. size_t data_len =
  8996. static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
  8997. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  8998. // pixel_data_size += sizeof(unsigned short);
  8999. // channel_offset += sizeof(unsigned short);
  9000. // Alloc internal image for half type.
  9001. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  9002. images[c] =
  9003. reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(
  9004. malloc(sizeof(unsigned short) * data_len)));
  9005. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  9006. images[c] = reinterpret_cast<unsigned char *>(
  9007. static_cast<float *>(malloc(sizeof(float) * data_len)));
  9008. } else {
  9009. assert(0);
  9010. }
  9011. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  9012. // pixel_data_size += sizeof(float);
  9013. // channel_offset += sizeof(float);
  9014. images[c] = reinterpret_cast<unsigned char *>(
  9015. static_cast<float *>(malloc(sizeof(float) * data_len)));
  9016. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  9017. // pixel_data_size += sizeof(unsigned int);
  9018. // channel_offset += sizeof(unsigned int);
  9019. images[c] = reinterpret_cast<unsigned char *>(
  9020. static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));
  9021. } else {
  9022. assert(0);
  9023. }
  9024. }
  9025. return images;
  9026. }
  9027. static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,
  9028. const EXRVersion *version, std::string *err,
  9029. const unsigned char *buf, size_t size) {
  9030. const char *marker = reinterpret_cast<const char *>(&buf[0]);
  9031. if (empty_header) {
  9032. (*empty_header) = false;
  9033. }
  9034. if (version->multipart) {
  9035. if (size > 0 && marker[0] == '\0') {
  9036. // End of header list.
  9037. if (empty_header) {
  9038. (*empty_header) = true;
  9039. }
  9040. return TINYEXR_SUCCESS;
  9041. }
  9042. }
  9043. // According to the spec, the header of every OpenEXR file must contain at
  9044. // least the following attributes:
  9045. //
  9046. // channels chlist
  9047. // compression compression
  9048. // dataWindow box2i
  9049. // displayWindow box2i
  9050. // lineOrder lineOrder
  9051. // pixelAspectRatio float
  9052. // screenWindowCenter v2f
  9053. // screenWindowWidth float
  9054. bool has_channels = false;
  9055. bool has_compression = false;
  9056. bool has_data_window = false;
  9057. bool has_display_window = false;
  9058. bool has_line_order = false;
  9059. bool has_pixel_aspect_ratio = false;
  9060. bool has_screen_window_center = false;
  9061. bool has_screen_window_width = false;
  9062. info->data_window[0] = 0;
  9063. info->data_window[1] = 0;
  9064. info->data_window[2] = 0;
  9065. info->data_window[3] = 0;
  9066. info->line_order = 0; // @fixme
  9067. info->display_window[0] = 0;
  9068. info->display_window[1] = 0;
  9069. info->display_window[2] = 0;
  9070. info->display_window[3] = 0;
  9071. info->screen_window_center[0] = 0.0f;
  9072. info->screen_window_center[1] = 0.0f;
  9073. info->screen_window_width = -1.0f;
  9074. info->pixel_aspect_ratio = -1.0f;
  9075. info->tile_size_x = -1;
  9076. info->tile_size_y = -1;
  9077. info->tile_level_mode = -1;
  9078. info->tile_rounding_mode = -1;
  9079. info->attributes.clear();
  9080. // Read attributes
  9081. size_t orig_size = size;
  9082. for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
  9083. if (0 == size) {
  9084. if (err) {
  9085. (*err) += "Insufficient data size for attributes.\n";
  9086. }
  9087. return TINYEXR_ERROR_INVALID_DATA;
  9088. } else if (marker[0] == '\0') {
  9089. size--;
  9090. break;
  9091. }
  9092. std::string attr_name;
  9093. std::string attr_type;
  9094. std::vector<unsigned char> data;
  9095. size_t marker_size;
  9096. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  9097. marker, size)) {
  9098. if (err) {
  9099. (*err) += "Failed to read attribute.\n";
  9100. }
  9101. return TINYEXR_ERROR_INVALID_DATA;
  9102. }
  9103. marker += marker_size;
  9104. size -= marker_size;
  9105. if (version->tiled && attr_name.compare("tiles") == 0) {
  9106. unsigned int x_size, y_size;
  9107. unsigned char tile_mode;
  9108. assert(data.size() == 9);
  9109. memcpy(&x_size, &data.at(0), sizeof(int));
  9110. memcpy(&y_size, &data.at(4), sizeof(int));
  9111. tile_mode = data[8];
  9112. tinyexr::swap4(&x_size);
  9113. tinyexr::swap4(&y_size);
  9114. info->tile_size_x = static_cast<int>(x_size);
  9115. info->tile_size_y = static_cast<int>(y_size);
  9116. // mode = levelMode + roundingMode * 16
  9117. info->tile_level_mode = tile_mode & 0x3;
  9118. info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
  9119. } else if (attr_name.compare("compression") == 0) {
  9120. bool ok = false;
  9121. if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
  9122. ok = true;
  9123. }
  9124. if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9125. #if TINYEXR_USE_PIZ
  9126. ok = true;
  9127. #else
  9128. if (err) {
  9129. (*err) = "PIZ compression is not supported.";
  9130. }
  9131. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9132. #endif
  9133. }
  9134. if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9135. #if TINYEXR_USE_ZFP
  9136. ok = true;
  9137. #else
  9138. if (err) {
  9139. (*err) = "ZFP compression is not supported.";
  9140. }
  9141. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9142. #endif
  9143. }
  9144. if (!ok) {
  9145. if (err) {
  9146. (*err) = "Unknown compression type.";
  9147. }
  9148. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  9149. }
  9150. info->compression_type = static_cast<int>(data[0]);
  9151. has_compression = true;
  9152. } else if (attr_name.compare("channels") == 0) {
  9153. // name: zero-terminated string, from 1 to 255 bytes long
  9154. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  9155. // pLinear: unsigned char, possible values are 0 and 1
  9156. // reserved: three chars, should be zero
  9157. // xSampling: int
  9158. // ySampling: int
  9159. if (!ReadChannelInfo(info->channels, data)) {
  9160. if (err) {
  9161. (*err) += "Failed to parse channel info.\n";
  9162. }
  9163. return TINYEXR_ERROR_INVALID_DATA;
  9164. }
  9165. if (info->channels.size() < 1) {
  9166. if (err) {
  9167. (*err) += "# of channels is zero.\n";
  9168. }
  9169. return TINYEXR_ERROR_INVALID_DATA;
  9170. }
  9171. has_channels = true;
  9172. } else if (attr_name.compare("dataWindow") == 0) {
  9173. if (data.size() >= 16) {
  9174. memcpy(&info->data_window[0], &data.at(0), sizeof(int));
  9175. memcpy(&info->data_window[1], &data.at(4), sizeof(int));
  9176. memcpy(&info->data_window[2], &data.at(8), sizeof(int));
  9177. memcpy(&info->data_window[3], &data.at(12), sizeof(int));
  9178. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0]));
  9179. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1]));
  9180. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2]));
  9181. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3]));
  9182. has_data_window = true;
  9183. }
  9184. } else if (attr_name.compare("displayWindow") == 0) {
  9185. if (data.size() >= 16) {
  9186. memcpy(&info->display_window[0], &data.at(0), sizeof(int));
  9187. memcpy(&info->display_window[1], &data.at(4), sizeof(int));
  9188. memcpy(&info->display_window[2], &data.at(8), sizeof(int));
  9189. memcpy(&info->display_window[3], &data.at(12), sizeof(int));
  9190. tinyexr::swap4(
  9191. reinterpret_cast<unsigned int *>(&info->display_window[0]));
  9192. tinyexr::swap4(
  9193. reinterpret_cast<unsigned int *>(&info->display_window[1]));
  9194. tinyexr::swap4(
  9195. reinterpret_cast<unsigned int *>(&info->display_window[2]));
  9196. tinyexr::swap4(
  9197. reinterpret_cast<unsigned int *>(&info->display_window[3]));
  9198. has_display_window = true;
  9199. }
  9200. } else if (attr_name.compare("lineOrder") == 0) {
  9201. if (data.size() >= 1) {
  9202. info->line_order = static_cast<int>(data[0]);
  9203. has_line_order = true;
  9204. }
  9205. } else if (attr_name.compare("pixelAspectRatio") == 0) {
  9206. if (data.size() >= sizeof(float)) {
  9207. memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
  9208. tinyexr::swap4(
  9209. reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio));
  9210. has_pixel_aspect_ratio = true;
  9211. }
  9212. } else if (attr_name.compare("screenWindowCenter") == 0) {
  9213. if (data.size() >= 8) {
  9214. memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
  9215. memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
  9216. tinyexr::swap4(
  9217. reinterpret_cast<unsigned int *>(&info->screen_window_center[0]));
  9218. tinyexr::swap4(
  9219. reinterpret_cast<unsigned int *>(&info->screen_window_center[1]));
  9220. has_screen_window_center = true;
  9221. }
  9222. } else if (attr_name.compare("screenWindowWidth") == 0) {
  9223. if (data.size() >= sizeof(float)) {
  9224. memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
  9225. tinyexr::swap4(
  9226. reinterpret_cast<unsigned int *>(&info->screen_window_width));
  9227. has_screen_window_width = true;
  9228. }
  9229. } else if (attr_name.compare("chunkCount") == 0) {
  9230. if (data.size() >= sizeof(int)) {
  9231. memcpy(&info->chunk_count, &data.at(0), sizeof(int));
  9232. tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count));
  9233. }
  9234. } else {
  9235. // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
  9236. if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9237. EXRAttribute attrib;
  9238. #ifdef _MSC_VER
  9239. strncpy_s(attrib.name, attr_name.c_str(), 255);
  9240. strncpy_s(attrib.type, attr_type.c_str(), 255);
  9241. #else
  9242. strncpy(attrib.name, attr_name.c_str(), 255);
  9243. strncpy(attrib.type, attr_type.c_str(), 255);
  9244. #endif
  9245. attrib.name[255] = '\0';
  9246. attrib.type[255] = '\0';
  9247. attrib.size = static_cast<int>(data.size());
  9248. attrib.value = static_cast<unsigned char *>(malloc(data.size()));
  9249. memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),
  9250. data.size());
  9251. info->attributes.push_back(attrib);
  9252. }
  9253. }
  9254. }
  9255. // Check if required attributes exist
  9256. {
  9257. std::stringstream ss_err;
  9258. if (!has_compression) {
  9259. ss_err << "\"compression\" attribute not found in the header."
  9260. << std::endl;
  9261. }
  9262. if (!has_channels) {
  9263. ss_err << "\"channels\" attribute not found in the header." << std::endl;
  9264. }
  9265. if (!has_line_order) {
  9266. ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
  9267. }
  9268. if (!has_display_window) {
  9269. ss_err << "\"displayWindow\" attribute not found in the header."
  9270. << std::endl;
  9271. }
  9272. if (!has_data_window) {
  9273. ss_err << "\"dataWindow\" attribute not found in the header or invalid."
  9274. << std::endl;
  9275. }
  9276. if (!has_pixel_aspect_ratio) {
  9277. ss_err << "\"pixelAspectRatio\" attribute not found in the header."
  9278. << std::endl;
  9279. }
  9280. if (!has_screen_window_width) {
  9281. ss_err << "\"screenWindowWidth\" attribute not found in the header."
  9282. << std::endl;
  9283. }
  9284. if (!has_screen_window_center) {
  9285. ss_err << "\"screenWindowCenter\" attribute not found in the header."
  9286. << std::endl;
  9287. }
  9288. if (!(ss_err.str().empty())) {
  9289. if (err) {
  9290. (*err) += ss_err.str();
  9291. }
  9292. return TINYEXR_ERROR_INVALID_HEADER;
  9293. }
  9294. }
  9295. info->header_len = static_cast<unsigned int>(orig_size - size);
  9296. return TINYEXR_SUCCESS;
  9297. }
  9298. // C++ HeaderInfo to C EXRHeader conversion.
  9299. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) {
  9300. exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
  9301. exr_header->screen_window_center[0] = info.screen_window_center[0];
  9302. exr_header->screen_window_center[1] = info.screen_window_center[1];
  9303. exr_header->screen_window_width = info.screen_window_width;
  9304. exr_header->chunk_count = info.chunk_count;
  9305. exr_header->display_window[0] = info.display_window[0];
  9306. exr_header->display_window[1] = info.display_window[1];
  9307. exr_header->display_window[2] = info.display_window[2];
  9308. exr_header->display_window[3] = info.display_window[3];
  9309. exr_header->data_window[0] = info.data_window[0];
  9310. exr_header->data_window[1] = info.data_window[1];
  9311. exr_header->data_window[2] = info.data_window[2];
  9312. exr_header->data_window[3] = info.data_window[3];
  9313. exr_header->line_order = info.line_order;
  9314. exr_header->compression_type = info.compression_type;
  9315. exr_header->tile_size_x = info.tile_size_x;
  9316. exr_header->tile_size_y = info.tile_size_y;
  9317. exr_header->tile_level_mode = info.tile_level_mode;
  9318. exr_header->tile_rounding_mode = info.tile_rounding_mode;
  9319. exr_header->num_channels = static_cast<int>(info.channels.size());
  9320. exr_header->channels = static_cast<EXRChannelInfo *>(malloc(
  9321. sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
  9322. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9323. #ifdef _MSC_VER
  9324. strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9325. #else
  9326. strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  9327. #endif
  9328. // manually add '\0' for safety.
  9329. exr_header->channels[c].name[255] = '\0';
  9330. exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
  9331. exr_header->channels[c].p_linear = info.channels[c].p_linear;
  9332. exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
  9333. exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
  9334. }
  9335. exr_header->pixel_types = static_cast<int *>(
  9336. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9337. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9338. exr_header->pixel_types[c] = info.channels[c].pixel_type;
  9339. }
  9340. // Initially fill with values of `pixel_types`
  9341. exr_header->requested_pixel_types = static_cast<int *>(
  9342. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  9343. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  9344. exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
  9345. }
  9346. exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
  9347. if (exr_header->num_custom_attributes > 0) {
  9348. // TODO(syoyo): Report warning when # of attributes exceeds
  9349. // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
  9350. if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  9351. exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;
  9352. }
  9353. exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(
  9354. sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
  9355. for (size_t i = 0; i < info.attributes.size(); i++) {
  9356. memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
  9357. 256);
  9358. memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
  9359. 256);
  9360. exr_header->custom_attributes[i].size = info.attributes[i].size;
  9361. // Just copy poiner
  9362. exr_header->custom_attributes[i].value = info.attributes[i].value;
  9363. }
  9364. } else {
  9365. exr_header->custom_attributes = NULL;
  9366. }
  9367. exr_header->header_len = info.header_len;
  9368. }
  9369. static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
  9370. const std::vector<tinyexr::tinyexr_uint64> &offsets,
  9371. const unsigned char *head, const size_t size,
  9372. std::string *err) {
  9373. int num_channels = exr_header->num_channels;
  9374. int num_scanline_blocks = 1;
  9375. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9376. num_scanline_blocks = 16;
  9377. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9378. num_scanline_blocks = 32;
  9379. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9380. num_scanline_blocks = 16;
  9381. }
  9382. int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;
  9383. int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;
  9384. if ((data_width < 0) || (data_height < 0)) {
  9385. if (err) {
  9386. std::stringstream ss;
  9387. ss << "Invalid data width or data height: " << data_width << ", "
  9388. << data_height << std::endl;
  9389. (*err) += ss.str();
  9390. }
  9391. return TINYEXR_ERROR_INVALID_DATA;
  9392. }
  9393. // Do not allow too large data_width and data_height. header invalid?
  9394. {
  9395. const int threshold = 1024 * 8192; // heuristics
  9396. if ((data_width > threshold) || (data_height > threshold)) {
  9397. if (err) {
  9398. std::stringstream ss;
  9399. ss << "data_with or data_height too large. data_width: " << data_width
  9400. << ", "
  9401. << "data_height = " << data_height << std::endl;
  9402. (*err) += ss.str();
  9403. }
  9404. return TINYEXR_ERROR_INVALID_DATA;
  9405. }
  9406. }
  9407. size_t num_blocks = offsets.size();
  9408. std::vector<size_t> channel_offset_list;
  9409. int pixel_data_size = 0;
  9410. size_t channel_offset = 0;
  9411. if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
  9412. &channel_offset, num_channels,
  9413. exr_header->channels)) {
  9414. if (err) {
  9415. (*err) += "Failed to compute channel layout.\n";
  9416. }
  9417. return TINYEXR_ERROR_INVALID_DATA;
  9418. }
  9419. bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety.
  9420. if (exr_header->tiled) {
  9421. // value check
  9422. if (exr_header->tile_size_x < 0) {
  9423. if (err) {
  9424. std::stringstream ss;
  9425. ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n";
  9426. (*err) += ss.str();
  9427. }
  9428. return TINYEXR_ERROR_INVALID_HEADER;
  9429. }
  9430. if (exr_header->tile_size_y < 0) {
  9431. if (err) {
  9432. std::stringstream ss;
  9433. ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n";
  9434. (*err) += ss.str();
  9435. }
  9436. return TINYEXR_ERROR_INVALID_HEADER;
  9437. }
  9438. size_t num_tiles = offsets.size(); // = # of blocks
  9439. exr_image->tiles = static_cast<EXRTile *>(
  9440. calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles)));
  9441. for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
  9442. // Allocate memory for each tile.
  9443. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
  9444. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9445. exr_header->tile_size_x, exr_header->tile_size_y);
  9446. // 16 byte: tile coordinates
  9447. // 4 byte : data size
  9448. // ~ : data(uncompressed or compressed)
  9449. if (offsets[tile_idx] + sizeof(int) * 5 > size) {
  9450. if (err) {
  9451. (*err) += "Insufficient data size.\n";
  9452. }
  9453. return TINYEXR_ERROR_INVALID_DATA;
  9454. }
  9455. size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));
  9456. const unsigned char *data_ptr =
  9457. reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]);
  9458. int tile_coordinates[4];
  9459. memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
  9460. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0]));
  9461. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1]));
  9462. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2]));
  9463. tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3]));
  9464. // @todo{ LoD }
  9465. if (tile_coordinates[2] != 0) {
  9466. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9467. }
  9468. if (tile_coordinates[3] != 0) {
  9469. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  9470. }
  9471. int data_len;
  9472. memcpy(&data_len, data_ptr + 16,
  9473. sizeof(int)); // 16 = sizeof(tile_coordinates)
  9474. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9475. if (data_len < 4 || size_t(data_len) > data_size) {
  9476. if (err) {
  9477. (*err) += "Insufficient data length.\n";
  9478. }
  9479. return TINYEXR_ERROR_INVALID_DATA;
  9480. }
  9481. // Move to data addr: 20 = 16 + 4;
  9482. data_ptr += 20;
  9483. tinyexr::DecodeTiledPixelData(
  9484. exr_image->tiles[tile_idx].images,
  9485. &(exr_image->tiles[tile_idx].width),
  9486. &(exr_image->tiles[tile_idx].height),
  9487. exr_header->requested_pixel_types, data_ptr,
  9488. static_cast<size_t>(data_len), exr_header->compression_type,
  9489. exr_header->line_order, data_width, data_height, tile_coordinates[0],
  9490. tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,
  9491. static_cast<size_t>(pixel_data_size),
  9492. static_cast<size_t>(exr_header->num_custom_attributes),
  9493. exr_header->custom_attributes,
  9494. static_cast<size_t>(exr_header->num_channels), exr_header->channels,
  9495. channel_offset_list);
  9496. exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
  9497. exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
  9498. exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
  9499. exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
  9500. exr_image->num_tiles = static_cast<int>(num_tiles);
  9501. }
  9502. } else { // scanline format
  9503. // Don't allow too large image(256GB * pixel_data_size or more). Workaround
  9504. // for #104.
  9505. size_t total_data_len =
  9506. size_t(data_width) * size_t(data_height) * size_t(num_channels);
  9507. const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false;
  9508. if ((total_data_len == 0) || total_data_len_overflown ) {
  9509. if (err) {
  9510. std::stringstream ss;
  9511. ss << "Image data size is zero or too large: width = " << data_width
  9512. << ", height = " << data_height << ", channels = " << num_channels
  9513. << std::endl;
  9514. (*err) += ss.str();
  9515. }
  9516. return TINYEXR_ERROR_INVALID_DATA;
  9517. }
  9518. exr_image->images = tinyexr::AllocateImage(
  9519. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  9520. data_width, data_height);
  9521. #ifdef _OPENMP
  9522. #pragma omp parallel for
  9523. #endif
  9524. for (int y = 0; y < static_cast<int>(num_blocks); y++) {
  9525. size_t y_idx = static_cast<size_t>(y);
  9526. if (offsets[y_idx] + sizeof(int) * 2 > size) {
  9527. invalid_data = true;
  9528. } else {
  9529. // 4 byte: scan line
  9530. // 4 byte: data size
  9531. // ~ : pixel data(uncompressed or compressed)
  9532. size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));
  9533. const unsigned char *data_ptr =
  9534. reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);
  9535. int line_no;
  9536. memcpy(&line_no, data_ptr, sizeof(int));
  9537. int data_len;
  9538. memcpy(&data_len, data_ptr + 4, sizeof(int));
  9539. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  9540. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9541. if (size_t(data_len) > data_size) {
  9542. invalid_data = true;
  9543. } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {
  9544. // Too large value. Assume this is invalid
  9545. // 2**20 = 1048576 = heuristic value.
  9546. invalid_data = true;
  9547. } else if (data_len == 0) {
  9548. // TODO(syoyo): May be ok to raise the threshold for example `data_len
  9549. // < 4`
  9550. invalid_data = true;
  9551. } else {
  9552. // line_no may be negative.
  9553. int end_line_no = (std::min)(line_no + num_scanline_blocks,
  9554. (exr_header->data_window[3] + 1));
  9555. int num_lines = end_line_no - line_no;
  9556. if (num_lines <= 0) {
  9557. invalid_data = true;
  9558. } else {
  9559. // Move to data addr: 8 = 4 + 4;
  9560. data_ptr += 8;
  9561. // Adjust line_no with data_window.bmin.y
  9562. // overflow check
  9563. tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]);
  9564. if (lno > std::numeric_limits<int>::max()) {
  9565. line_no = -1; // invalid
  9566. } else if (lno < -std::numeric_limits<int>::max()) {
  9567. line_no = -1; // invalid
  9568. } else {
  9569. line_no -= exr_header->data_window[1];
  9570. }
  9571. if (line_no < 0) {
  9572. invalid_data = true;
  9573. } else {
  9574. if (!tinyexr::DecodePixelData(
  9575. exr_image->images, exr_header->requested_pixel_types,
  9576. data_ptr, static_cast<size_t>(data_len),
  9577. exr_header->compression_type, exr_header->line_order,
  9578. data_width, data_height, data_width, y, line_no,
  9579. num_lines, static_cast<size_t>(pixel_data_size),
  9580. static_cast<size_t>(exr_header->num_custom_attributes),
  9581. exr_header->custom_attributes,
  9582. static_cast<size_t>(exr_header->num_channels),
  9583. exr_header->channels, channel_offset_list)) {
  9584. invalid_data = true;
  9585. }
  9586. }
  9587. }
  9588. }
  9589. }
  9590. } // omp parallel
  9591. }
  9592. if (invalid_data) {
  9593. if (err) {
  9594. std::stringstream ss;
  9595. (*err) += "Invalid data found when decoding pixels.\n";
  9596. }
  9597. return TINYEXR_ERROR_INVALID_DATA;
  9598. }
  9599. // Overwrite `pixel_type` with `requested_pixel_type`.
  9600. {
  9601. for (int c = 0; c < exr_header->num_channels; c++) {
  9602. exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
  9603. }
  9604. }
  9605. {
  9606. exr_image->num_channels = num_channels;
  9607. exr_image->width = data_width;
  9608. exr_image->height = data_height;
  9609. }
  9610. return TINYEXR_SUCCESS;
  9611. }
  9612. static bool ReconstructLineOffsets(
  9613. std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,
  9614. const unsigned char *head, const unsigned char *marker, const size_t size) {
  9615. assert(head < marker);
  9616. assert(offsets->size() == n);
  9617. for (size_t i = 0; i < n; i++) {
  9618. size_t offset = static_cast<size_t>(marker - head);
  9619. // Offset should not exceed whole EXR file/data size.
  9620. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
  9621. return false;
  9622. }
  9623. int y;
  9624. unsigned int data_len;
  9625. memcpy(&y, marker, sizeof(int));
  9626. memcpy(&data_len, marker + 4, sizeof(unsigned int));
  9627. if (data_len >= size) {
  9628. return false;
  9629. }
  9630. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  9631. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  9632. (*offsets)[i] = offset;
  9633. marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
  9634. }
  9635. return true;
  9636. }
  9637. static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,
  9638. const unsigned char *head,
  9639. const unsigned char *marker, const size_t size,
  9640. const char **err) {
  9641. if (exr_image == NULL || exr_header == NULL || head == NULL ||
  9642. marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
  9643. tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
  9644. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9645. }
  9646. int num_scanline_blocks = 1;
  9647. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  9648. num_scanline_blocks = 16;
  9649. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  9650. num_scanline_blocks = 32;
  9651. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  9652. num_scanline_blocks = 16;
  9653. }
  9654. int data_width = exr_header->data_window[2] - exr_header->data_window[0];
  9655. if (data_width >= std::numeric_limits<int>::max()) {
  9656. // Issue 63
  9657. tinyexr::SetErrorMessage("Invalid data width value", err);
  9658. return TINYEXR_ERROR_INVALID_DATA;
  9659. }
  9660. data_width++;
  9661. int data_height = exr_header->data_window[3] - exr_header->data_window[1];
  9662. if (data_height >= std::numeric_limits<int>::max()) {
  9663. tinyexr::SetErrorMessage("Invalid data height value", err);
  9664. return TINYEXR_ERROR_INVALID_DATA;
  9665. }
  9666. data_height++;
  9667. if ((data_width < 0) || (data_height < 0)) {
  9668. tinyexr::SetErrorMessage("data width or data height is negative.", err);
  9669. return TINYEXR_ERROR_INVALID_DATA;
  9670. }
  9671. // Do not allow too large data_width and data_height. header invalid?
  9672. {
  9673. const int threshold = 1024 * 8192; // heuristics
  9674. if (data_width > threshold) {
  9675. tinyexr::SetErrorMessage("data width too large.", err);
  9676. return TINYEXR_ERROR_INVALID_DATA;
  9677. }
  9678. if (data_height > threshold) {
  9679. tinyexr::SetErrorMessage("data height too large.", err);
  9680. return TINYEXR_ERROR_INVALID_DATA;
  9681. }
  9682. }
  9683. // Read offset tables.
  9684. size_t num_blocks = 0;
  9685. if (exr_header->chunk_count > 0) {
  9686. // Use `chunkCount` attribute.
  9687. num_blocks = static_cast<size_t>(exr_header->chunk_count);
  9688. } else if (exr_header->tiled) {
  9689. // @todo { LoD }
  9690. size_t num_x_tiles = static_cast<size_t>(data_width) /
  9691. static_cast<size_t>(exr_header->tile_size_x);
  9692. if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) <
  9693. static_cast<size_t>(data_width)) {
  9694. num_x_tiles++;
  9695. }
  9696. size_t num_y_tiles = static_cast<size_t>(data_height) /
  9697. static_cast<size_t>(exr_header->tile_size_y);
  9698. if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) <
  9699. static_cast<size_t>(data_height)) {
  9700. num_y_tiles++;
  9701. }
  9702. num_blocks = num_x_tiles * num_y_tiles;
  9703. } else {
  9704. num_blocks = static_cast<size_t>(data_height) /
  9705. static_cast<size_t>(num_scanline_blocks);
  9706. if (num_blocks * static_cast<size_t>(num_scanline_blocks) <
  9707. static_cast<size_t>(data_height)) {
  9708. num_blocks++;
  9709. }
  9710. }
  9711. std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks);
  9712. for (size_t y = 0; y < num_blocks; y++) {
  9713. tinyexr::tinyexr_uint64 offset;
  9714. // Issue #81
  9715. if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
  9716. tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
  9717. return TINYEXR_ERROR_INVALID_DATA;
  9718. }
  9719. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  9720. tinyexr::swap8(&offset);
  9721. if (offset >= size) {
  9722. tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
  9723. return TINYEXR_ERROR_INVALID_DATA;
  9724. }
  9725. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  9726. offsets[y] = offset;
  9727. }
  9728. // If line offsets are invalid, we try to reconstruct it.
  9729. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
  9730. for (size_t y = 0; y < num_blocks; y++) {
  9731. if (offsets[y] <= 0) {
  9732. // TODO(syoyo) Report as warning?
  9733. // if (err) {
  9734. // stringstream ss;
  9735. // ss << "Incomplete lineOffsets." << std::endl;
  9736. // (*err) += ss.str();
  9737. //}
  9738. bool ret =
  9739. ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
  9740. if (ret) {
  9741. // OK
  9742. break;
  9743. } else {
  9744. tinyexr::SetErrorMessage(
  9745. "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
  9746. return TINYEXR_ERROR_INVALID_DATA;
  9747. }
  9748. }
  9749. }
  9750. {
  9751. std::string e;
  9752. int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e);
  9753. if (ret != TINYEXR_SUCCESS) {
  9754. if (!e.empty()) {
  9755. tinyexr::SetErrorMessage(e, err);
  9756. }
  9757. // release memory(if exists)
  9758. if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
  9759. for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
  9760. if (exr_image->images[c]) {
  9761. free(exr_image->images[c]);
  9762. exr_image->images[c] = NULL;
  9763. }
  9764. }
  9765. free(exr_image->images);
  9766. exr_image->images = NULL;
  9767. }
  9768. }
  9769. return ret;
  9770. }
  9771. }
  9772. } // namespace tinyexr
  9773. int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
  9774. const char **err) {
  9775. if (out_rgba == NULL) {
  9776. tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
  9777. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9778. }
  9779. EXRVersion exr_version;
  9780. EXRImage exr_image;
  9781. EXRHeader exr_header;
  9782. InitEXRHeader(&exr_header);
  9783. InitEXRImage(&exr_image);
  9784. {
  9785. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  9786. if (ret != TINYEXR_SUCCESS) {
  9787. tinyexr::SetErrorMessage("Invalid EXR header.", err);
  9788. return ret;
  9789. }
  9790. if (exr_version.multipart || exr_version.non_image) {
  9791. tinyexr::SetErrorMessage(
  9792. "Loading multipart or DeepImage is not supported in LoadEXR() API",
  9793. err);
  9794. return TINYEXR_ERROR_INVALID_DATA; // @fixme.
  9795. }
  9796. }
  9797. {
  9798. int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
  9799. if (ret != TINYEXR_SUCCESS) {
  9800. FreeEXRHeader(&exr_header);
  9801. return ret;
  9802. }
  9803. }
  9804. // Read HALF channel as FLOAT.
  9805. for (int i = 0; i < exr_header.num_channels; i++) {
  9806. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  9807. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  9808. }
  9809. }
  9810. {
  9811. int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
  9812. if (ret != TINYEXR_SUCCESS) {
  9813. FreeEXRHeader(&exr_header);
  9814. return ret;
  9815. }
  9816. }
  9817. // RGBA
  9818. int idxR = -1;
  9819. int idxG = -1;
  9820. int idxB = -1;
  9821. int idxA = -1;
  9822. for (int c = 0; c < exr_header.num_channels; c++) {
  9823. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  9824. idxR = c;
  9825. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  9826. idxG = c;
  9827. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  9828. idxB = c;
  9829. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  9830. idxA = c;
  9831. }
  9832. }
  9833. if (exr_header.num_channels == 1) {
  9834. // Grayscale channel only.
  9835. (*out_rgba) = reinterpret_cast<float *>(
  9836. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9837. static_cast<size_t>(exr_image.height)));
  9838. if (exr_header.tiled) {
  9839. for (int it = 0; it < exr_image.num_tiles; it++) {
  9840. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9841. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9842. const int ii =
  9843. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9844. const int jj =
  9845. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9846. const int idx = ii + jj * exr_image.width;
  9847. // out of region check.
  9848. if (ii >= exr_image.width) {
  9849. continue;
  9850. }
  9851. if (jj >= exr_image.height) {
  9852. continue;
  9853. }
  9854. const int srcIdx = i + j * exr_header.tile_size_x;
  9855. unsigned char **src = exr_image.tiles[it].images;
  9856. (*out_rgba)[4 * idx + 0] =
  9857. reinterpret_cast<float **>(src)[0][srcIdx];
  9858. (*out_rgba)[4 * idx + 1] =
  9859. reinterpret_cast<float **>(src)[0][srcIdx];
  9860. (*out_rgba)[4 * idx + 2] =
  9861. reinterpret_cast<float **>(src)[0][srcIdx];
  9862. (*out_rgba)[4 * idx + 3] =
  9863. reinterpret_cast<float **>(src)[0][srcIdx];
  9864. }
  9865. }
  9866. }
  9867. } else {
  9868. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9869. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  9870. (*out_rgba)[4 * i + 0] = val;
  9871. (*out_rgba)[4 * i + 1] = val;
  9872. (*out_rgba)[4 * i + 2] = val;
  9873. (*out_rgba)[4 * i + 3] = val;
  9874. }
  9875. }
  9876. } else {
  9877. // Assume RGB(A)
  9878. if (idxR == -1) {
  9879. tinyexr::SetErrorMessage("R channel not found", err);
  9880. // @todo { free exr_image }
  9881. FreeEXRHeader(&exr_header);
  9882. return TINYEXR_ERROR_INVALID_DATA;
  9883. }
  9884. if (idxG == -1) {
  9885. tinyexr::SetErrorMessage("G channel not found", err);
  9886. // @todo { free exr_image }
  9887. FreeEXRHeader(&exr_header);
  9888. return TINYEXR_ERROR_INVALID_DATA;
  9889. }
  9890. if (idxB == -1) {
  9891. tinyexr::SetErrorMessage("B channel not found", err);
  9892. // @todo { free exr_image }
  9893. FreeEXRHeader(&exr_header);
  9894. return TINYEXR_ERROR_INVALID_DATA;
  9895. }
  9896. (*out_rgba) = reinterpret_cast<float *>(
  9897. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  9898. static_cast<size_t>(exr_image.height)));
  9899. if (exr_header.tiled) {
  9900. for (int it = 0; it < exr_image.num_tiles; it++) {
  9901. for (int j = 0; j < exr_header.tile_size_y; j++) {
  9902. for (int i = 0; i < exr_header.tile_size_x; i++) {
  9903. const int ii =
  9904. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  9905. const int jj =
  9906. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  9907. const int idx = ii + jj * exr_image.width;
  9908. // out of region check.
  9909. if (ii >= exr_image.width) {
  9910. continue;
  9911. }
  9912. if (jj >= exr_image.height) {
  9913. continue;
  9914. }
  9915. const int srcIdx = i + j * exr_header.tile_size_x;
  9916. unsigned char **src = exr_image.tiles[it].images;
  9917. (*out_rgba)[4 * idx + 0] =
  9918. reinterpret_cast<float **>(src)[idxR][srcIdx];
  9919. (*out_rgba)[4 * idx + 1] =
  9920. reinterpret_cast<float **>(src)[idxG][srcIdx];
  9921. (*out_rgba)[4 * idx + 2] =
  9922. reinterpret_cast<float **>(src)[idxB][srcIdx];
  9923. if (idxA != -1) {
  9924. (*out_rgba)[4 * idx + 3] =
  9925. reinterpret_cast<float **>(src)[idxA][srcIdx];
  9926. } else {
  9927. (*out_rgba)[4 * idx + 3] = 1.0;
  9928. }
  9929. }
  9930. }
  9931. }
  9932. } else {
  9933. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  9934. (*out_rgba)[4 * i + 0] =
  9935. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  9936. (*out_rgba)[4 * i + 1] =
  9937. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  9938. (*out_rgba)[4 * i + 2] =
  9939. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  9940. if (idxA != -1) {
  9941. (*out_rgba)[4 * i + 3] =
  9942. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  9943. } else {
  9944. (*out_rgba)[4 * i + 3] = 1.0;
  9945. }
  9946. }
  9947. }
  9948. }
  9949. (*width) = exr_image.width;
  9950. (*height) = exr_image.height;
  9951. FreeEXRHeader(&exr_header);
  9952. FreeEXRImage(&exr_image);
  9953. return TINYEXR_SUCCESS;
  9954. }
  9955. int IsEXR(const char *filename) {
  9956. EXRVersion exr_version;
  9957. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  9958. if (ret != TINYEXR_SUCCESS) {
  9959. return TINYEXR_ERROR_INVALID_HEADER;
  9960. }
  9961. return TINYEXR_SUCCESS;
  9962. }
  9963. int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,
  9964. const unsigned char *memory, size_t size,
  9965. const char **err) {
  9966. if (memory == NULL || exr_header == NULL) {
  9967. tinyexr::SetErrorMessage(
  9968. "Invalid argument. `memory` or `exr_header` argument is null in "
  9969. "ParseEXRHeaderFromMemory()",
  9970. err);
  9971. // Invalid argument
  9972. return TINYEXR_ERROR_INVALID_ARGUMENT;
  9973. }
  9974. if (size < tinyexr::kEXRVersionSize) {
  9975. tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
  9976. return TINYEXR_ERROR_INVALID_DATA;
  9977. }
  9978. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  9979. size_t marker_size = size - tinyexr::kEXRVersionSize;
  9980. tinyexr::HeaderInfo info;
  9981. info.clear();
  9982. std::string err_str;
  9983. int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
  9984. if (ret != TINYEXR_SUCCESS) {
  9985. if (err && !err_str.empty()) {
  9986. tinyexr::SetErrorMessage(err_str, err);
  9987. }
  9988. }
  9989. ConvertHeader(exr_header, info);
  9990. // transfoer `tiled` from version.
  9991. exr_header->tiled = version->tiled;
  9992. return ret;
  9993. }
  9994. int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  9995. const unsigned char *memory, size_t size,
  9996. const char **err) {
  9997. if (out_rgba == NULL || memory == NULL) {
  9998. tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
  9999. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10000. }
  10001. EXRVersion exr_version;
  10002. EXRImage exr_image;
  10003. EXRHeader exr_header;
  10004. InitEXRHeader(&exr_header);
  10005. int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
  10006. if (ret != TINYEXR_SUCCESS) {
  10007. tinyexr::SetErrorMessage("Failed to parse EXR version", err);
  10008. return ret;
  10009. }
  10010. ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
  10011. if (ret != TINYEXR_SUCCESS) {
  10012. return ret;
  10013. }
  10014. // Read HALF channel as FLOAT.
  10015. for (int i = 0; i < exr_header.num_channels; i++) {
  10016. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  10017. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  10018. }
  10019. }
  10020. InitEXRImage(&exr_image);
  10021. ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
  10022. if (ret != TINYEXR_SUCCESS) {
  10023. return ret;
  10024. }
  10025. // RGBA
  10026. int idxR = -1;
  10027. int idxG = -1;
  10028. int idxB = -1;
  10029. int idxA = -1;
  10030. for (int c = 0; c < exr_header.num_channels; c++) {
  10031. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  10032. idxR = c;
  10033. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  10034. idxG = c;
  10035. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  10036. idxB = c;
  10037. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  10038. idxA = c;
  10039. }
  10040. }
  10041. // TODO(syoyo): Refactor removing same code as used in LoadEXR().
  10042. if (exr_header.num_channels == 1) {
  10043. // Grayscale channel only.
  10044. (*out_rgba) = reinterpret_cast<float *>(
  10045. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  10046. static_cast<size_t>(exr_image.height)));
  10047. if (exr_header.tiled) {
  10048. for (int it = 0; it < exr_image.num_tiles; it++) {
  10049. for (int j = 0; j < exr_header.tile_size_y; j++) {
  10050. for (int i = 0; i < exr_header.tile_size_x; i++) {
  10051. const int ii =
  10052. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  10053. const int jj =
  10054. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  10055. const int idx = ii + jj * exr_image.width;
  10056. // out of region check.
  10057. if (ii >= exr_image.width) {
  10058. continue;
  10059. }
  10060. if (jj >= exr_image.height) {
  10061. continue;
  10062. }
  10063. const int srcIdx = i + j * exr_header.tile_size_x;
  10064. unsigned char **src = exr_image.tiles[it].images;
  10065. (*out_rgba)[4 * idx + 0] =
  10066. reinterpret_cast<float **>(src)[0][srcIdx];
  10067. (*out_rgba)[4 * idx + 1] =
  10068. reinterpret_cast<float **>(src)[0][srcIdx];
  10069. (*out_rgba)[4 * idx + 2] =
  10070. reinterpret_cast<float **>(src)[0][srcIdx];
  10071. (*out_rgba)[4 * idx + 3] =
  10072. reinterpret_cast<float **>(src)[0][srcIdx];
  10073. }
  10074. }
  10075. }
  10076. } else {
  10077. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  10078. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  10079. (*out_rgba)[4 * i + 0] = val;
  10080. (*out_rgba)[4 * i + 1] = val;
  10081. (*out_rgba)[4 * i + 2] = val;
  10082. (*out_rgba)[4 * i + 3] = val;
  10083. }
  10084. }
  10085. } else {
  10086. // TODO(syoyo): Support non RGBA image.
  10087. if (idxR == -1) {
  10088. tinyexr::SetErrorMessage("R channel not found", err);
  10089. // @todo { free exr_image }
  10090. return TINYEXR_ERROR_INVALID_DATA;
  10091. }
  10092. if (idxG == -1) {
  10093. tinyexr::SetErrorMessage("G channel not found", err);
  10094. // @todo { free exr_image }
  10095. return TINYEXR_ERROR_INVALID_DATA;
  10096. }
  10097. if (idxB == -1) {
  10098. tinyexr::SetErrorMessage("B channel not found", err);
  10099. // @todo { free exr_image }
  10100. return TINYEXR_ERROR_INVALID_DATA;
  10101. }
  10102. (*out_rgba) = reinterpret_cast<float *>(
  10103. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  10104. static_cast<size_t>(exr_image.height)));
  10105. if (exr_header.tiled) {
  10106. for (int it = 0; it < exr_image.num_tiles; it++) {
  10107. for (int j = 0; j < exr_header.tile_size_y; j++)
  10108. for (int i = 0; i < exr_header.tile_size_x; i++) {
  10109. const int ii =
  10110. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  10111. const int jj =
  10112. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  10113. const int idx = ii + jj * exr_image.width;
  10114. // out of region check.
  10115. if (ii >= exr_image.width) {
  10116. continue;
  10117. }
  10118. if (jj >= exr_image.height) {
  10119. continue;
  10120. }
  10121. const int srcIdx = i + j * exr_header.tile_size_x;
  10122. unsigned char **src = exr_image.tiles[it].images;
  10123. (*out_rgba)[4 * idx + 0] =
  10124. reinterpret_cast<float **>(src)[idxR][srcIdx];
  10125. (*out_rgba)[4 * idx + 1] =
  10126. reinterpret_cast<float **>(src)[idxG][srcIdx];
  10127. (*out_rgba)[4 * idx + 2] =
  10128. reinterpret_cast<float **>(src)[idxB][srcIdx];
  10129. if (idxA != -1) {
  10130. (*out_rgba)[4 * idx + 3] =
  10131. reinterpret_cast<float **>(src)[idxA][srcIdx];
  10132. } else {
  10133. (*out_rgba)[4 * idx + 3] = 1.0;
  10134. }
  10135. }
  10136. }
  10137. } else {
  10138. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  10139. (*out_rgba)[4 * i + 0] =
  10140. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  10141. (*out_rgba)[4 * i + 1] =
  10142. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  10143. (*out_rgba)[4 * i + 2] =
  10144. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  10145. if (idxA != -1) {
  10146. (*out_rgba)[4 * i + 3] =
  10147. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  10148. } else {
  10149. (*out_rgba)[4 * i + 3] = 1.0;
  10150. }
  10151. }
  10152. }
  10153. }
  10154. (*width) = exr_image.width;
  10155. (*height) = exr_image.height;
  10156. FreeEXRHeader(&exr_header);
  10157. FreeEXRImage(&exr_image);
  10158. return TINYEXR_SUCCESS;
  10159. }
  10160. int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,
  10161. const char *filename, const char **err) {
  10162. if (exr_image == NULL) {
  10163. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
  10164. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10165. }
  10166. #ifdef _WIN32
  10167. FILE *fp = NULL;
  10168. fopen_s(&fp, filename, "rb");
  10169. #else
  10170. FILE *fp = fopen(filename, "rb");
  10171. #endif
  10172. if (!fp) {
  10173. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  10174. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10175. }
  10176. size_t filesize;
  10177. // Compute size
  10178. fseek(fp, 0, SEEK_END);
  10179. filesize = static_cast<size_t>(ftell(fp));
  10180. fseek(fp, 0, SEEK_SET);
  10181. if (filesize < 16) {
  10182. tinyexr::SetErrorMessage("File size too short " + std::string(filename),
  10183. err);
  10184. return TINYEXR_ERROR_INVALID_FILE;
  10185. }
  10186. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  10187. {
  10188. size_t ret;
  10189. ret = fread(&buf[0], 1, filesize, fp);
  10190. assert(ret == filesize);
  10191. fclose(fp);
  10192. (void)ret;
  10193. }
  10194. return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize,
  10195. err);
  10196. }
  10197. int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,
  10198. const unsigned char *memory, const size_t size,
  10199. const char **err) {
  10200. if (exr_image == NULL || memory == NULL ||
  10201. (size < tinyexr::kEXRVersionSize)) {
  10202. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
  10203. err);
  10204. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10205. }
  10206. if (exr_header->header_len == 0) {
  10207. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  10208. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10209. }
  10210. const unsigned char *head = memory;
  10211. const unsigned char *marker = reinterpret_cast<const unsigned char *>(
  10212. memory + exr_header->header_len +
  10213. 8); // +8 for magic number + version header.
  10214. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
  10215. err);
  10216. }
  10217. size_t SaveEXRImageToMemory(const EXRImage *exr_image,
  10218. const EXRHeader *exr_header,
  10219. unsigned char **memory_out, const char **err) {
  10220. if (exr_image == NULL || memory_out == NULL ||
  10221. exr_header->compression_type < 0) {
  10222. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err);
  10223. return 0;
  10224. }
  10225. #if !TINYEXR_USE_PIZ
  10226. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10227. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10228. err);
  10229. return 0;
  10230. }
  10231. #endif
  10232. #if !TINYEXR_USE_ZFP
  10233. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10234. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10235. err);
  10236. return 0;
  10237. }
  10238. #endif
  10239. #if TINYEXR_USE_ZFP
  10240. for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) {
  10241. if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) {
  10242. tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
  10243. err);
  10244. return 0;
  10245. }
  10246. }
  10247. #endif
  10248. std::vector<unsigned char> memory;
  10249. // Header
  10250. {
  10251. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10252. memory.insert(memory.end(), header, header + 4);
  10253. }
  10254. // Version, scanline.
  10255. {
  10256. char marker[] = {2, 0, 0, 0};
  10257. /* @todo
  10258. if (exr_header->tiled) {
  10259. marker[1] |= 0x2;
  10260. }
  10261. if (exr_header->long_name) {
  10262. marker[1] |= 0x4;
  10263. }
  10264. if (exr_header->non_image) {
  10265. marker[1] |= 0x8;
  10266. }
  10267. if (exr_header->multipart) {
  10268. marker[1] |= 0x10;
  10269. }
  10270. */
  10271. memory.insert(memory.end(), marker, marker + 4);
  10272. }
  10273. int num_scanlines = 1;
  10274. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10275. num_scanlines = 16;
  10276. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10277. num_scanlines = 32;
  10278. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10279. num_scanlines = 16;
  10280. }
  10281. // Write attributes.
  10282. std::vector<tinyexr::ChannelInfo> channels;
  10283. {
  10284. std::vector<unsigned char> data;
  10285. for (int c = 0; c < exr_header->num_channels; c++) {
  10286. tinyexr::ChannelInfo info;
  10287. info.p_linear = 0;
  10288. info.pixel_type = exr_header->requested_pixel_types[c];
  10289. info.x_sampling = 1;
  10290. info.y_sampling = 1;
  10291. info.name = std::string(exr_header->channels[c].name);
  10292. channels.push_back(info);
  10293. }
  10294. tinyexr::WriteChannelInfo(data, channels);
  10295. tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
  10296. static_cast<int>(data.size()));
  10297. }
  10298. {
  10299. int comp = exr_header->compression_type;
  10300. tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp));
  10301. tinyexr::WriteAttributeToMemory(
  10302. &memory, "compression", "compression",
  10303. reinterpret_cast<const unsigned char *>(&comp), 1);
  10304. }
  10305. {
  10306. int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1};
  10307. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0]));
  10308. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1]));
  10309. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2]));
  10310. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3]));
  10311. tinyexr::WriteAttributeToMemory(
  10312. &memory, "dataWindow", "box2i",
  10313. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10314. tinyexr::WriteAttributeToMemory(
  10315. &memory, "displayWindow", "box2i",
  10316. reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4);
  10317. }
  10318. {
  10319. unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
  10320. tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
  10321. &line_order, 1);
  10322. }
  10323. {
  10324. float aspectRatio = 1.0f;
  10325. tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
  10326. tinyexr::WriteAttributeToMemory(
  10327. &memory, "pixelAspectRatio", "float",
  10328. reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
  10329. }
  10330. {
  10331. float center[2] = {0.0f, 0.0f};
  10332. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0]));
  10333. tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1]));
  10334. tinyexr::WriteAttributeToMemory(
  10335. &memory, "screenWindowCenter", "v2f",
  10336. reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float));
  10337. }
  10338. {
  10339. float w = static_cast<float>(exr_image->width);
  10340. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10341. tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
  10342. reinterpret_cast<const unsigned char *>(&w),
  10343. sizeof(float));
  10344. }
  10345. // Custom attributes
  10346. if (exr_header->num_custom_attributes > 0) {
  10347. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  10348. tinyexr::WriteAttributeToMemory(
  10349. &memory, exr_header->custom_attributes[i].name,
  10350. exr_header->custom_attributes[i].type,
  10351. reinterpret_cast<const unsigned char *>(
  10352. exr_header->custom_attributes[i].value),
  10353. exr_header->custom_attributes[i].size);
  10354. }
  10355. }
  10356. { // end of header
  10357. unsigned char e = 0;
  10358. memory.push_back(e);
  10359. }
  10360. int num_blocks = exr_image->height / num_scanlines;
  10361. if (num_blocks * num_scanlines < exr_image->height) {
  10362. num_blocks++;
  10363. }
  10364. std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks));
  10365. size_t headerSize = memory.size();
  10366. tinyexr::tinyexr_uint64 offset =
  10367. headerSize +
  10368. static_cast<size_t>(num_blocks) *
  10369. sizeof(
  10370. tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable)
  10371. std::vector<std::vector<unsigned char> > data_list(
  10372. static_cast<size_t>(num_blocks));
  10373. std::vector<size_t> channel_offset_list(
  10374. static_cast<size_t>(exr_header->num_channels));
  10375. int pixel_data_size = 0;
  10376. size_t channel_offset = 0;
  10377. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10378. channel_offset_list[c] = channel_offset;
  10379. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10380. pixel_data_size += sizeof(unsigned short);
  10381. channel_offset += sizeof(unsigned short);
  10382. } else if (exr_header->requested_pixel_types[c] ==
  10383. TINYEXR_PIXELTYPE_FLOAT) {
  10384. pixel_data_size += sizeof(float);
  10385. channel_offset += sizeof(float);
  10386. } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10387. pixel_data_size += sizeof(unsigned int);
  10388. channel_offset += sizeof(unsigned int);
  10389. } else {
  10390. assert(0);
  10391. }
  10392. }
  10393. #if TINYEXR_USE_ZFP
  10394. tinyexr::ZFPCompressionParam zfp_compression_param;
  10395. // Use ZFP compression parameter from custom attributes(if such a parameter
  10396. // exists)
  10397. {
  10398. bool ret = tinyexr::FindZFPCompressionParam(
  10399. &zfp_compression_param, exr_header->custom_attributes,
  10400. exr_header->num_custom_attributes);
  10401. if (!ret) {
  10402. // Use predefined compression parameter.
  10403. zfp_compression_param.type = 0;
  10404. zfp_compression_param.rate = 2;
  10405. }
  10406. }
  10407. #endif
  10408. // Use signed int since some OpenMP compiler doesn't allow unsigned type for
  10409. // `parallel for`
  10410. #ifdef _OPENMP
  10411. #pragma omp parallel for
  10412. #endif
  10413. for (int i = 0; i < num_blocks; i++) {
  10414. size_t ii = static_cast<size_t>(i);
  10415. int start_y = num_scanlines * i;
  10416. int endY = (std::min)(num_scanlines * (i + 1), exr_image->height);
  10417. int h = endY - start_y;
  10418. std::vector<unsigned char> buf(
  10419. static_cast<size_t>(exr_image->width * h * pixel_data_size));
  10420. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  10421. if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10422. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10423. for (int y = 0; y < h; y++) {
  10424. // Assume increasing Y
  10425. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10426. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10427. channel_offset_list[c] *
  10428. static_cast<size_t>(exr_image->width)));
  10429. for (int x = 0; x < exr_image->width; x++) {
  10430. tinyexr::FP16 h16;
  10431. h16.u = reinterpret_cast<unsigned short **>(
  10432. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10433. tinyexr::FP32 f32 = half_to_float(h16);
  10434. tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f));
  10435. // line_ptr[x] = f32.f;
  10436. tinyexr::cpy4(line_ptr + x, &(f32.f));
  10437. }
  10438. }
  10439. } else if (exr_header->requested_pixel_types[c] ==
  10440. TINYEXR_PIXELTYPE_HALF) {
  10441. for (int y = 0; y < h; y++) {
  10442. // Assume increasing Y
  10443. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10444. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10445. exr_image->width) +
  10446. channel_offset_list[c] *
  10447. static_cast<size_t>(exr_image->width)));
  10448. for (int x = 0; x < exr_image->width; x++) {
  10449. unsigned short val = reinterpret_cast<unsigned short **>(
  10450. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10451. tinyexr::swap2(&val);
  10452. // line_ptr[x] = val;
  10453. tinyexr::cpy2(line_ptr + x, &val);
  10454. }
  10455. }
  10456. } else {
  10457. assert(0);
  10458. }
  10459. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  10460. if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  10461. for (int y = 0; y < h; y++) {
  10462. // Assume increasing Y
  10463. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  10464. &buf.at(static_cast<size_t>(pixel_data_size * y *
  10465. exr_image->width) +
  10466. channel_offset_list[c] *
  10467. static_cast<size_t>(exr_image->width)));
  10468. for (int x = 0; x < exr_image->width; x++) {
  10469. tinyexr::FP32 f32;
  10470. f32.f = reinterpret_cast<float **>(
  10471. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10472. tinyexr::FP16 h16;
  10473. h16 = float_to_half_full(f32);
  10474. tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));
  10475. // line_ptr[x] = h16.u;
  10476. tinyexr::cpy2(line_ptr + x, &(h16.u));
  10477. }
  10478. }
  10479. } else if (exr_header->requested_pixel_types[c] ==
  10480. TINYEXR_PIXELTYPE_FLOAT) {
  10481. for (int y = 0; y < h; y++) {
  10482. // Assume increasing Y
  10483. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  10484. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10485. channel_offset_list[c] *
  10486. static_cast<size_t>(exr_image->width)));
  10487. for (int x = 0; x < exr_image->width; x++) {
  10488. float val = reinterpret_cast<float **>(
  10489. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10490. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  10491. // line_ptr[x] = val;
  10492. tinyexr::cpy4(line_ptr + x, &val);
  10493. }
  10494. }
  10495. } else {
  10496. assert(0);
  10497. }
  10498. } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
  10499. for (int y = 0; y < h; y++) {
  10500. // Assume increasing Y
  10501. unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(
  10502. static_cast<size_t>(pixel_data_size * y * exr_image->width) +
  10503. channel_offset_list[c] * static_cast<size_t>(exr_image->width)));
  10504. for (int x = 0; x < exr_image->width; x++) {
  10505. unsigned int val = reinterpret_cast<unsigned int **>(
  10506. exr_image->images)[c][(y + start_y) * exr_image->width + x];
  10507. tinyexr::swap4(&val);
  10508. // line_ptr[x] = val;
  10509. tinyexr::cpy4(line_ptr + x, &val);
  10510. }
  10511. }
  10512. }
  10513. }
  10514. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  10515. // 4 byte: scan line
  10516. // 4 byte: data size
  10517. // ~ : pixel data(uncompressed)
  10518. std::vector<unsigned char> header(8);
  10519. unsigned int data_len = static_cast<unsigned int>(buf.size());
  10520. memcpy(&header.at(0), &start_y, sizeof(int));
  10521. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10522. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10523. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10524. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10525. data_list[ii].insert(data_list[ii].end(), buf.begin(),
  10526. buf.begin() + data_len);
  10527. } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10528. (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10529. #if TINYEXR_USE_MINIZ
  10530. std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound(
  10531. static_cast<unsigned long>(buf.size())));
  10532. #else
  10533. std::vector<unsigned char> block(
  10534. compressBound(static_cast<uLong>(buf.size())));
  10535. #endif
  10536. tinyexr::tinyexr_uint64 outSize = block.size();
  10537. tinyexr::CompressZip(&block.at(0), outSize,
  10538. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10539. static_cast<unsigned long>(buf.size()));
  10540. // 4 byte: scan line
  10541. // 4 byte: data size
  10542. // ~ : pixel data(compressed)
  10543. std::vector<unsigned char> header(8);
  10544. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10545. memcpy(&header.at(0), &start_y, sizeof(int));
  10546. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10547. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10548. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10549. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10550. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10551. block.begin() + data_len);
  10552. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  10553. // (buf.size() * 3) / 2 would be enough.
  10554. std::vector<unsigned char> block((buf.size() * 3) / 2);
  10555. tinyexr::tinyexr_uint64 outSize = block.size();
  10556. tinyexr::CompressRle(&block.at(0), outSize,
  10557. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10558. static_cast<unsigned long>(buf.size()));
  10559. // 4 byte: scan line
  10560. // 4 byte: data size
  10561. // ~ : pixel data(compressed)
  10562. std::vector<unsigned char> header(8);
  10563. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  10564. memcpy(&header.at(0), &start_y, sizeof(int));
  10565. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10566. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10567. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10568. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10569. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10570. block.begin() + data_len);
  10571. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10572. #if TINYEXR_USE_PIZ
  10573. unsigned int bufLen =
  10574. 8192 + static_cast<unsigned int>(
  10575. 2 * static_cast<unsigned int>(
  10576. buf.size())); // @fixme { compute good bound. }
  10577. std::vector<unsigned char> block(bufLen);
  10578. unsigned int outSize = static_cast<unsigned int>(block.size());
  10579. CompressPiz(&block.at(0), &outSize,
  10580. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  10581. buf.size(), channels, exr_image->width, h);
  10582. // 4 byte: scan line
  10583. // 4 byte: data size
  10584. // ~ : pixel data(compressed)
  10585. std::vector<unsigned char> header(8);
  10586. unsigned int data_len = outSize;
  10587. memcpy(&header.at(0), &start_y, sizeof(int));
  10588. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10589. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10590. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10591. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10592. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10593. block.begin() + data_len);
  10594. #else
  10595. assert(0);
  10596. #endif
  10597. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10598. #if TINYEXR_USE_ZFP
  10599. std::vector<unsigned char> block;
  10600. unsigned int outSize;
  10601. tinyexr::CompressZfp(
  10602. &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),
  10603. exr_image->width, h, exr_header->num_channels, zfp_compression_param);
  10604. // 4 byte: scan line
  10605. // 4 byte: data size
  10606. // ~ : pixel data(compressed)
  10607. std::vector<unsigned char> header(8);
  10608. unsigned int data_len = outSize;
  10609. memcpy(&header.at(0), &start_y, sizeof(int));
  10610. memcpy(&header.at(4), &data_len, sizeof(unsigned int));
  10611. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
  10612. tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
  10613. data_list[ii].insert(data_list[ii].end(), header.begin(), header.end());
  10614. data_list[ii].insert(data_list[ii].end(), block.begin(),
  10615. block.begin() + data_len);
  10616. #else
  10617. assert(0);
  10618. #endif
  10619. } else {
  10620. assert(0);
  10621. }
  10622. } // omp parallel
  10623. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10624. offsets[i] = offset;
  10625. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));
  10626. offset += data_list[i].size();
  10627. }
  10628. size_t totalSize = static_cast<size_t>(offset);
  10629. {
  10630. memory.insert(
  10631. memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)),
  10632. reinterpret_cast<unsigned char *>(&offsets.at(0)) +
  10633. sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks));
  10634. }
  10635. if (memory.size() == 0) {
  10636. tinyexr::SetErrorMessage("Output memory size is zero", err);
  10637. return 0;
  10638. }
  10639. (*memory_out) = static_cast<unsigned char *>(malloc(totalSize));
  10640. memcpy((*memory_out), &memory.at(0), memory.size());
  10641. unsigned char *memory_ptr = *memory_out + memory.size();
  10642. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  10643. memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size());
  10644. memory_ptr += data_list[i].size();
  10645. }
  10646. return totalSize; // OK
  10647. }
  10648. int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,
  10649. const char *filename, const char **err) {
  10650. if (exr_image == NULL || filename == NULL ||
  10651. exr_header->compression_type < 0) {
  10652. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
  10653. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10654. }
  10655. #if !TINYEXR_USE_PIZ
  10656. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  10657. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  10658. err);
  10659. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10660. }
  10661. #endif
  10662. #if !TINYEXR_USE_ZFP
  10663. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  10664. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  10665. err);
  10666. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  10667. }
  10668. #endif
  10669. #ifdef _WIN32
  10670. FILE *fp = NULL;
  10671. fopen_s(&fp, filename, "wb");
  10672. #else
  10673. FILE *fp = fopen(filename, "wb");
  10674. #endif
  10675. if (!fp) {
  10676. tinyexr::SetErrorMessage("Cannot write a file", err);
  10677. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10678. }
  10679. unsigned char *mem = NULL;
  10680. size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
  10681. if (mem_size == 0) {
  10682. return TINYEXR_ERROR_SERIALZATION_FAILED;
  10683. }
  10684. size_t written_size = 0;
  10685. if ((mem_size > 0) && mem) {
  10686. written_size = fwrite(mem, 1, mem_size, fp);
  10687. }
  10688. free(mem);
  10689. fclose(fp);
  10690. if (written_size != mem_size) {
  10691. tinyexr::SetErrorMessage("Cannot write a file", err);
  10692. return TINYEXR_ERROR_CANT_WRITE_FILE;
  10693. }
  10694. return TINYEXR_SUCCESS;
  10695. }
  10696. int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {
  10697. if (deep_image == NULL) {
  10698. tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
  10699. return TINYEXR_ERROR_INVALID_ARGUMENT;
  10700. }
  10701. #ifdef _MSC_VER
  10702. FILE *fp = NULL;
  10703. errno_t errcode = fopen_s(&fp, filename, "rb");
  10704. if ((0 != errcode) || (!fp)) {
  10705. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10706. err);
  10707. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10708. }
  10709. #else
  10710. FILE *fp = fopen(filename, "rb");
  10711. if (!fp) {
  10712. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  10713. err);
  10714. return TINYEXR_ERROR_CANT_OPEN_FILE;
  10715. }
  10716. #endif
  10717. size_t filesize;
  10718. // Compute size
  10719. fseek(fp, 0, SEEK_END);
  10720. filesize = static_cast<size_t>(ftell(fp));
  10721. fseek(fp, 0, SEEK_SET);
  10722. if (filesize == 0) {
  10723. fclose(fp);
  10724. tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
  10725. err);
  10726. return TINYEXR_ERROR_INVALID_FILE;
  10727. }
  10728. std::vector<char> buf(filesize); // @todo { use mmap }
  10729. {
  10730. size_t ret;
  10731. ret = fread(&buf[0], 1, filesize, fp);
  10732. assert(ret == filesize);
  10733. (void)ret;
  10734. }
  10735. fclose(fp);
  10736. const char *head = &buf[0];
  10737. const char *marker = &buf[0];
  10738. // Header check.
  10739. {
  10740. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  10741. if (memcmp(marker, header, 4) != 0) {
  10742. tinyexr::SetErrorMessage("Invalid magic number", err);
  10743. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  10744. }
  10745. marker += 4;
  10746. }
  10747. // Version, scanline.
  10748. {
  10749. // ver 2.0, scanline, deep bit on(0x800)
  10750. // must be [2, 0, 0, 0]
  10751. if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
  10752. tinyexr::SetErrorMessage("Unsupported version or scanline", err);
  10753. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10754. }
  10755. marker += 4;
  10756. }
  10757. int dx = -1;
  10758. int dy = -1;
  10759. int dw = -1;
  10760. int dh = -1;
  10761. int num_scanline_blocks = 1; // 16 for ZIP compression.
  10762. int compression_type = -1;
  10763. int num_channels = -1;
  10764. std::vector<tinyexr::ChannelInfo> channels;
  10765. // Read attributes
  10766. size_t size = filesize - tinyexr::kEXRVersionSize;
  10767. for (;;) {
  10768. if (0 == size) {
  10769. return TINYEXR_ERROR_INVALID_DATA;
  10770. } else if (marker[0] == '\0') {
  10771. marker++;
  10772. size--;
  10773. break;
  10774. }
  10775. std::string attr_name;
  10776. std::string attr_type;
  10777. std::vector<unsigned char> data;
  10778. size_t marker_size;
  10779. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  10780. marker, size)) {
  10781. std::stringstream ss;
  10782. ss << "Failed to parse attribute\n";
  10783. tinyexr::SetErrorMessage(ss.str(), err);
  10784. return TINYEXR_ERROR_INVALID_DATA;
  10785. }
  10786. marker += marker_size;
  10787. size -= marker_size;
  10788. if (attr_name.compare("compression") == 0) {
  10789. compression_type = data[0];
  10790. if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
  10791. std::stringstream ss;
  10792. ss << "Unsupported compression type : " << compression_type;
  10793. tinyexr::SetErrorMessage(ss.str(), err);
  10794. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10795. }
  10796. if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  10797. num_scanline_blocks = 16;
  10798. }
  10799. } else if (attr_name.compare("channels") == 0) {
  10800. // name: zero-terminated string, from 1 to 255 bytes long
  10801. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  10802. // pLinear: unsigned char, possible values are 0 and 1
  10803. // reserved: three chars, should be zero
  10804. // xSampling: int
  10805. // ySampling: int
  10806. if (!tinyexr::ReadChannelInfo(channels, data)) {
  10807. tinyexr::SetErrorMessage("Failed to parse channel info", err);
  10808. return TINYEXR_ERROR_INVALID_DATA;
  10809. }
  10810. num_channels = static_cast<int>(channels.size());
  10811. if (num_channels < 1) {
  10812. tinyexr::SetErrorMessage("Invalid channels format", err);
  10813. return TINYEXR_ERROR_INVALID_DATA;
  10814. }
  10815. } else if (attr_name.compare("dataWindow") == 0) {
  10816. memcpy(&dx, &data.at(0), sizeof(int));
  10817. memcpy(&dy, &data.at(4), sizeof(int));
  10818. memcpy(&dw, &data.at(8), sizeof(int));
  10819. memcpy(&dh, &data.at(12), sizeof(int));
  10820. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx));
  10821. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy));
  10822. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw));
  10823. tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh));
  10824. } else if (attr_name.compare("displayWindow") == 0) {
  10825. int x;
  10826. int y;
  10827. int w;
  10828. int h;
  10829. memcpy(&x, &data.at(0), sizeof(int));
  10830. memcpy(&y, &data.at(4), sizeof(int));
  10831. memcpy(&w, &data.at(8), sizeof(int));
  10832. memcpy(&h, &data.at(12), sizeof(int));
  10833. tinyexr::swap4(reinterpret_cast<unsigned int *>(&x));
  10834. tinyexr::swap4(reinterpret_cast<unsigned int *>(&y));
  10835. tinyexr::swap4(reinterpret_cast<unsigned int *>(&w));
  10836. tinyexr::swap4(reinterpret_cast<unsigned int *>(&h));
  10837. }
  10838. }
  10839. assert(dx >= 0);
  10840. assert(dy >= 0);
  10841. assert(dw >= 0);
  10842. assert(dh >= 0);
  10843. assert(num_channels >= 1);
  10844. int data_width = dw - dx + 1;
  10845. int data_height = dh - dy + 1;
  10846. std::vector<float> image(
  10847. static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA
  10848. // Read offset tables.
  10849. int num_blocks = data_height / num_scanline_blocks;
  10850. if (num_blocks * num_scanline_blocks < data_height) {
  10851. num_blocks++;
  10852. }
  10853. std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
  10854. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10855. tinyexr::tinyexr_int64 offset;
  10856. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
  10857. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));
  10858. marker += sizeof(tinyexr::tinyexr_int64); // = 8
  10859. offsets[y] = offset;
  10860. }
  10861. #if TINYEXR_USE_PIZ
  10862. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10863. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10864. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10865. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||
  10866. (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
  10867. #else
  10868. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  10869. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  10870. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  10871. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  10872. #endif
  10873. // OK
  10874. } else {
  10875. tinyexr::SetErrorMessage("Unsupported compression format", err);
  10876. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  10877. }
  10878. deep_image->image = static_cast<float ***>(
  10879. malloc(sizeof(float **) * static_cast<size_t>(num_channels)));
  10880. for (int c = 0; c < num_channels; c++) {
  10881. deep_image->image[c] = static_cast<float **>(
  10882. malloc(sizeof(float *) * static_cast<size_t>(data_height)));
  10883. for (int y = 0; y < data_height; y++) {
  10884. }
  10885. }
  10886. deep_image->offset_table = static_cast<int **>(
  10887. malloc(sizeof(int *) * static_cast<size_t>(data_height)));
  10888. for (int y = 0; y < data_height; y++) {
  10889. deep_image->offset_table[y] = static_cast<int *>(
  10890. malloc(sizeof(int) * static_cast<size_t>(data_width)));
  10891. }
  10892. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  10893. const unsigned char *data_ptr =
  10894. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  10895. // int: y coordinate
  10896. // int64: packed size of pixel offset table
  10897. // int64: packed size of sample data
  10898. // int64: unpacked size of sample data
  10899. // compressed pixel offset table
  10900. // compressed sample data
  10901. int line_no;
  10902. tinyexr::tinyexr_int64 packedOffsetTableSize;
  10903. tinyexr::tinyexr_int64 packedSampleDataSize;
  10904. tinyexr::tinyexr_int64 unpackedSampleDataSize;
  10905. memcpy(&line_no, data_ptr, sizeof(int));
  10906. memcpy(&packedOffsetTableSize, data_ptr + 4,
  10907. sizeof(tinyexr::tinyexr_int64));
  10908. memcpy(&packedSampleDataSize, data_ptr + 12,
  10909. sizeof(tinyexr::tinyexr_int64));
  10910. memcpy(&unpackedSampleDataSize, data_ptr + 20,
  10911. sizeof(tinyexr::tinyexr_int64));
  10912. tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no));
  10913. tinyexr::swap8(
  10914. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));
  10915. tinyexr::swap8(
  10916. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));
  10917. tinyexr::swap8(
  10918. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));
  10919. std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
  10920. // decode pixel offset table.
  10921. {
  10922. unsigned long dstLen =
  10923. static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
  10924. if (!tinyexr::DecompressZip(
  10925. reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  10926. &dstLen, data_ptr + 28,
  10927. static_cast<unsigned long>(packedOffsetTableSize))) {
  10928. return false;
  10929. }
  10930. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  10931. for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
  10932. deep_image->offset_table[y][i] = pixelOffsetTable[i];
  10933. }
  10934. }
  10935. std::vector<unsigned char> sample_data(
  10936. static_cast<size_t>(unpackedSampleDataSize));
  10937. // decode sample data.
  10938. {
  10939. unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
  10940. if (dstLen) {
  10941. if (!tinyexr::DecompressZip(
  10942. reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,
  10943. data_ptr + 28 + packedOffsetTableSize,
  10944. static_cast<unsigned long>(packedSampleDataSize))) {
  10945. return false;
  10946. }
  10947. assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize));
  10948. }
  10949. }
  10950. // decode sample
  10951. int sampleSize = -1;
  10952. std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
  10953. {
  10954. int channel_offset = 0;
  10955. for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
  10956. channel_offset_list[i] = channel_offset;
  10957. if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
  10958. channel_offset += 4;
  10959. } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
  10960. channel_offset += 2;
  10961. } else if (channels[i].pixel_type ==
  10962. TINYEXR_PIXELTYPE_FLOAT) { // float
  10963. channel_offset += 4;
  10964. } else {
  10965. assert(0);
  10966. }
  10967. }
  10968. sampleSize = channel_offset;
  10969. }
  10970. assert(sampleSize >= 2);
  10971. assert(static_cast<size_t>(
  10972. pixelOffsetTable[static_cast<size_t>(data_width - 1)] *
  10973. sampleSize) == sample_data.size());
  10974. int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
  10975. //
  10976. // Alloc memory
  10977. //
  10978. //
  10979. // pixel data is stored as image[channels][pixel_samples]
  10980. //
  10981. {
  10982. tinyexr::tinyexr_uint64 data_offset = 0;
  10983. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  10984. deep_image->image[c][y] = static_cast<float *>(
  10985. malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
  10986. if (channels[c].pixel_type == 0) { // UINT
  10987. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10988. unsigned int ui;
  10989. unsigned int *src_ptr = reinterpret_cast<unsigned int *>(
  10990. &sample_data.at(size_t(data_offset) + x * sizeof(int)));
  10991. tinyexr::cpy4(&ui, src_ptr);
  10992. deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
  10993. }
  10994. data_offset +=
  10995. sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
  10996. } else if (channels[c].pixel_type == 1) { // half
  10997. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  10998. tinyexr::FP16 f16;
  10999. const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(
  11000. &sample_data.at(size_t(data_offset) + x * sizeof(short)));
  11001. tinyexr::cpy2(&(f16.u), src_ptr);
  11002. tinyexr::FP32 f32 = half_to_float(f16);
  11003. deep_image->image[c][y][x] = f32.f;
  11004. }
  11005. data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
  11006. } else { // float
  11007. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  11008. float f;
  11009. const float *src_ptr = reinterpret_cast<float *>(
  11010. &sample_data.at(size_t(data_offset) + x * sizeof(float)));
  11011. tinyexr::cpy4(&f, src_ptr);
  11012. deep_image->image[c][y][x] = f;
  11013. }
  11014. data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
  11015. }
  11016. }
  11017. }
  11018. } // y
  11019. deep_image->width = data_width;
  11020. deep_image->height = data_height;
  11021. deep_image->channel_names = static_cast<const char **>(
  11022. malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));
  11023. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  11024. #ifdef _WIN32
  11025. deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
  11026. #else
  11027. deep_image->channel_names[c] = strdup(channels[c].name.c_str());
  11028. #endif
  11029. }
  11030. deep_image->num_channels = num_channels;
  11031. return TINYEXR_SUCCESS;
  11032. }
  11033. void InitEXRImage(EXRImage *exr_image) {
  11034. if (exr_image == NULL) {
  11035. return;
  11036. }
  11037. exr_image->width = 0;
  11038. exr_image->height = 0;
  11039. exr_image->num_channels = 0;
  11040. exr_image->images = NULL;
  11041. exr_image->tiles = NULL;
  11042. exr_image->num_tiles = 0;
  11043. }
  11044. void FreeEXRErrorMessage(const char *msg) {
  11045. if (msg) {
  11046. free(reinterpret_cast<void *>(const_cast<char *>(msg)));
  11047. }
  11048. return;
  11049. }
  11050. void InitEXRHeader(EXRHeader *exr_header) {
  11051. if (exr_header == NULL) {
  11052. return;
  11053. }
  11054. memset(exr_header, 0, sizeof(EXRHeader));
  11055. }
  11056. int FreeEXRHeader(EXRHeader *exr_header) {
  11057. if (exr_header == NULL) {
  11058. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11059. }
  11060. if (exr_header->channels) {
  11061. free(exr_header->channels);
  11062. }
  11063. if (exr_header->pixel_types) {
  11064. free(exr_header->pixel_types);
  11065. }
  11066. if (exr_header->requested_pixel_types) {
  11067. free(exr_header->requested_pixel_types);
  11068. }
  11069. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  11070. if (exr_header->custom_attributes[i].value) {
  11071. free(exr_header->custom_attributes[i].value);
  11072. }
  11073. }
  11074. if (exr_header->custom_attributes) {
  11075. free(exr_header->custom_attributes);
  11076. }
  11077. return TINYEXR_SUCCESS;
  11078. }
  11079. int FreeEXRImage(EXRImage *exr_image) {
  11080. if (exr_image == NULL) {
  11081. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11082. }
  11083. for (int i = 0; i < exr_image->num_channels; i++) {
  11084. if (exr_image->images && exr_image->images[i]) {
  11085. free(exr_image->images[i]);
  11086. }
  11087. }
  11088. if (exr_image->images) {
  11089. free(exr_image->images);
  11090. }
  11091. if (exr_image->tiles) {
  11092. for (int tid = 0; tid < exr_image->num_tiles; tid++) {
  11093. for (int i = 0; i < exr_image->num_channels; i++) {
  11094. if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
  11095. free(exr_image->tiles[tid].images[i]);
  11096. }
  11097. }
  11098. if (exr_image->tiles[tid].images) {
  11099. free(exr_image->tiles[tid].images);
  11100. }
  11101. }
  11102. free(exr_image->tiles);
  11103. }
  11104. return TINYEXR_SUCCESS;
  11105. }
  11106. int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,
  11107. const char *filename, const char **err) {
  11108. if (exr_header == NULL || exr_version == NULL || filename == NULL) {
  11109. tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
  11110. err);
  11111. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11112. }
  11113. #ifdef _WIN32
  11114. FILE *fp = NULL;
  11115. fopen_s(&fp, filename, "rb");
  11116. #else
  11117. FILE *fp = fopen(filename, "rb");
  11118. #endif
  11119. if (!fp) {
  11120. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11121. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11122. }
  11123. size_t filesize;
  11124. // Compute size
  11125. fseek(fp, 0, SEEK_END);
  11126. filesize = static_cast<size_t>(ftell(fp));
  11127. fseek(fp, 0, SEEK_SET);
  11128. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11129. {
  11130. size_t ret;
  11131. ret = fread(&buf[0], 1, filesize, fp);
  11132. assert(ret == filesize);
  11133. fclose(fp);
  11134. if (ret != filesize) {
  11135. tinyexr::SetErrorMessage("fread() error on " + std::string(filename),
  11136. err);
  11137. return TINYEXR_ERROR_INVALID_FILE;
  11138. }
  11139. }
  11140. return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize,
  11141. err);
  11142. }
  11143. int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,
  11144. int *num_headers,
  11145. const EXRVersion *exr_version,
  11146. const unsigned char *memory, size_t size,
  11147. const char **err) {
  11148. if (memory == NULL || exr_headers == NULL || num_headers == NULL ||
  11149. exr_version == NULL) {
  11150. // Invalid argument
  11151. tinyexr::SetErrorMessage(
  11152. "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
  11153. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11154. }
  11155. if (size < tinyexr::kEXRVersionSize) {
  11156. tinyexr::SetErrorMessage("Data size too short", err);
  11157. return TINYEXR_ERROR_INVALID_DATA;
  11158. }
  11159. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  11160. size_t marker_size = size - tinyexr::kEXRVersionSize;
  11161. std::vector<tinyexr::HeaderInfo> infos;
  11162. for (;;) {
  11163. tinyexr::HeaderInfo info;
  11164. info.clear();
  11165. std::string err_str;
  11166. bool empty_header = false;
  11167. int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
  11168. marker, marker_size);
  11169. if (ret != TINYEXR_SUCCESS) {
  11170. tinyexr::SetErrorMessage(err_str, err);
  11171. return ret;
  11172. }
  11173. if (empty_header) {
  11174. marker += 1; // skip '\0'
  11175. break;
  11176. }
  11177. // `chunkCount` must exist in the header.
  11178. if (info.chunk_count == 0) {
  11179. tinyexr::SetErrorMessage(
  11180. "`chunkCount' attribute is not found in the header.", err);
  11181. return TINYEXR_ERROR_INVALID_DATA;
  11182. }
  11183. infos.push_back(info);
  11184. // move to next header.
  11185. marker += info.header_len;
  11186. size -= info.header_len;
  11187. }
  11188. // allocate memory for EXRHeader and create array of EXRHeader pointers.
  11189. (*exr_headers) =
  11190. static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));
  11191. for (size_t i = 0; i < infos.size(); i++) {
  11192. EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));
  11193. ConvertHeader(exr_header, infos[i]);
  11194. // transfoer `tiled` from version.
  11195. exr_header->tiled = exr_version->tiled;
  11196. (*exr_headers)[i] = exr_header;
  11197. }
  11198. (*num_headers) = static_cast<int>(infos.size());
  11199. return TINYEXR_SUCCESS;
  11200. }
  11201. int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,
  11202. const EXRVersion *exr_version,
  11203. const char *filename, const char **err) {
  11204. if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||
  11205. filename == NULL) {
  11206. tinyexr::SetErrorMessage(
  11207. "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
  11208. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11209. }
  11210. #ifdef _WIN32
  11211. FILE *fp = NULL;
  11212. fopen_s(&fp, filename, "rb");
  11213. #else
  11214. FILE *fp = fopen(filename, "rb");
  11215. #endif
  11216. if (!fp) {
  11217. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11218. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11219. }
  11220. size_t filesize;
  11221. // Compute size
  11222. fseek(fp, 0, SEEK_END);
  11223. filesize = static_cast<size_t>(ftell(fp));
  11224. fseek(fp, 0, SEEK_SET);
  11225. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11226. {
  11227. size_t ret;
  11228. ret = fread(&buf[0], 1, filesize, fp);
  11229. assert(ret == filesize);
  11230. fclose(fp);
  11231. if (ret != filesize) {
  11232. tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err);
  11233. return TINYEXR_ERROR_INVALID_FILE;
  11234. }
  11235. }
  11236. return ParseEXRMultipartHeaderFromMemory(
  11237. exr_headers, num_headers, exr_version, &buf.at(0), filesize, err);
  11238. }
  11239. int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,
  11240. size_t size) {
  11241. if (version == NULL || memory == NULL) {
  11242. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11243. }
  11244. if (size < tinyexr::kEXRVersionSize) {
  11245. return TINYEXR_ERROR_INVALID_DATA;
  11246. }
  11247. const unsigned char *marker = memory;
  11248. // Header check.
  11249. {
  11250. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  11251. if (memcmp(marker, header, 4) != 0) {
  11252. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  11253. }
  11254. marker += 4;
  11255. }
  11256. version->tiled = false;
  11257. version->long_name = false;
  11258. version->non_image = false;
  11259. version->multipart = false;
  11260. // Parse version header.
  11261. {
  11262. // must be 2
  11263. if (marker[0] != 2) {
  11264. return TINYEXR_ERROR_INVALID_EXR_VERSION;
  11265. }
  11266. if (version == NULL) {
  11267. return TINYEXR_SUCCESS; // May OK
  11268. }
  11269. version->version = 2;
  11270. if (marker[1] & 0x2) { // 9th bit
  11271. version->tiled = true;
  11272. }
  11273. if (marker[1] & 0x4) { // 10th bit
  11274. version->long_name = true;
  11275. }
  11276. if (marker[1] & 0x8) { // 11th bit
  11277. version->non_image = true; // (deep image)
  11278. }
  11279. if (marker[1] & 0x10) { // 12th bit
  11280. version->multipart = true;
  11281. }
  11282. }
  11283. return TINYEXR_SUCCESS;
  11284. }
  11285. int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {
  11286. if (filename == NULL) {
  11287. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11288. }
  11289. #ifdef _WIN32
  11290. FILE *fp = NULL;
  11291. fopen_s(&fp, filename, "rb");
  11292. #else
  11293. FILE *fp = fopen(filename, "rb");
  11294. #endif
  11295. if (!fp) {
  11296. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11297. }
  11298. size_t file_size;
  11299. // Compute size
  11300. fseek(fp, 0, SEEK_END);
  11301. file_size = static_cast<size_t>(ftell(fp));
  11302. fseek(fp, 0, SEEK_SET);
  11303. if (file_size < tinyexr::kEXRVersionSize) {
  11304. return TINYEXR_ERROR_INVALID_FILE;
  11305. }
  11306. unsigned char buf[tinyexr::kEXRVersionSize];
  11307. size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
  11308. fclose(fp);
  11309. if (ret != tinyexr::kEXRVersionSize) {
  11310. return TINYEXR_ERROR_INVALID_FILE;
  11311. }
  11312. return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
  11313. }
  11314. int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,
  11315. const EXRHeader **exr_headers,
  11316. unsigned int num_parts,
  11317. const unsigned char *memory,
  11318. const size_t size, const char **err) {
  11319. if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
  11320. memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
  11321. tinyexr::SetErrorMessage(
  11322. "Invalid argument for LoadEXRMultipartImageFromMemory()", err);
  11323. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11324. }
  11325. // compute total header size.
  11326. size_t total_header_size = 0;
  11327. for (unsigned int i = 0; i < num_parts; i++) {
  11328. if (exr_headers[i]->header_len == 0) {
  11329. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  11330. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11331. }
  11332. total_header_size += exr_headers[i]->header_len;
  11333. }
  11334. const char *marker = reinterpret_cast<const char *>(
  11335. memory + total_header_size + 4 +
  11336. 4); // +8 for magic number and version header.
  11337. marker += 1; // Skip empty header.
  11338. // NOTE 1:
  11339. // In multipart image, There is 'part number' before chunk data.
  11340. // 4 byte : part number
  11341. // 4+ : chunk
  11342. //
  11343. // NOTE 2:
  11344. // EXR spec says 'part number' is 'unsigned long' but actually this is
  11345. // 'unsigned int(4 bytes)' in OpenEXR implementation...
  11346. // http://www.openexr.com/openexrfilelayout.pdf
  11347. // Load chunk offset table.
  11348. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list;
  11349. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11350. std::vector<tinyexr::tinyexr_uint64> offset_table(
  11351. static_cast<size_t>(exr_headers[i]->chunk_count));
  11352. for (size_t c = 0; c < offset_table.size(); c++) {
  11353. tinyexr::tinyexr_uint64 offset;
  11354. memcpy(&offset, marker, 8);
  11355. tinyexr::swap8(&offset);
  11356. if (offset >= size) {
  11357. tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
  11358. err);
  11359. return TINYEXR_ERROR_INVALID_DATA;
  11360. }
  11361. offset_table[c] = offset + 4; // +4 to skip 'part number'
  11362. marker += 8;
  11363. }
  11364. chunk_offset_table_list.push_back(offset_table);
  11365. }
  11366. // Decode image.
  11367. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  11368. std::vector<tinyexr::tinyexr_uint64> &offset_table =
  11369. chunk_offset_table_list[i];
  11370. // First check 'part number' is identitical to 'i'
  11371. for (size_t c = 0; c < offset_table.size(); c++) {
  11372. const unsigned char *part_number_addr =
  11373. memory + offset_table[c] - 4; // -4 to move to 'part number' field.
  11374. unsigned int part_no;
  11375. memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
  11376. tinyexr::swap4(&part_no);
  11377. if (part_no != i) {
  11378. tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
  11379. err);
  11380. return TINYEXR_ERROR_INVALID_DATA;
  11381. }
  11382. }
  11383. std::string e;
  11384. int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table,
  11385. memory, size, &e);
  11386. if (ret != TINYEXR_SUCCESS) {
  11387. if (!e.empty()) {
  11388. tinyexr::SetErrorMessage(e, err);
  11389. }
  11390. return ret;
  11391. }
  11392. }
  11393. return TINYEXR_SUCCESS;
  11394. }
  11395. int LoadEXRMultipartImageFromFile(EXRImage *exr_images,
  11396. const EXRHeader **exr_headers,
  11397. unsigned int num_parts, const char *filename,
  11398. const char **err) {
  11399. if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
  11400. tinyexr::SetErrorMessage(
  11401. "Invalid argument for LoadEXRMultipartImageFromFile", err);
  11402. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11403. }
  11404. #ifdef _WIN32
  11405. FILE *fp = NULL;
  11406. fopen_s(&fp, filename, "rb");
  11407. #else
  11408. FILE *fp = fopen(filename, "rb");
  11409. #endif
  11410. if (!fp) {
  11411. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  11412. return TINYEXR_ERROR_CANT_OPEN_FILE;
  11413. }
  11414. size_t filesize;
  11415. // Compute size
  11416. fseek(fp, 0, SEEK_END);
  11417. filesize = static_cast<size_t>(ftell(fp));
  11418. fseek(fp, 0, SEEK_SET);
  11419. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  11420. {
  11421. size_t ret;
  11422. ret = fread(&buf[0], 1, filesize, fp);
  11423. assert(ret == filesize);
  11424. fclose(fp);
  11425. (void)ret;
  11426. }
  11427. return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
  11428. &buf.at(0), filesize, err);
  11429. }
  11430. int SaveEXR(const float *data, int width, int height, int components,
  11431. const int save_as_fp16, const char *outfilename, const char **err) {
  11432. if ((components == 1) || components == 3 || components == 4) {
  11433. // OK
  11434. } else {
  11435. std::stringstream ss;
  11436. ss << "Unsupported component value : " << components << std::endl;
  11437. tinyexr::SetErrorMessage(ss.str(), err);
  11438. return TINYEXR_ERROR_INVALID_ARGUMENT;
  11439. }
  11440. EXRHeader header;
  11441. InitEXRHeader(&header);
  11442. if ((width < 16) && (height < 16)) {
  11443. // No compression for small image.
  11444. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;
  11445. } else {
  11446. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  11447. }
  11448. EXRImage image;
  11449. InitEXRImage(&image);
  11450. image.num_channels = components;
  11451. std::vector<float> images[4];
  11452. if (components == 1) {
  11453. images[0].resize(static_cast<size_t>(width * height));
  11454. memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
  11455. } else {
  11456. images[0].resize(static_cast<size_t>(width * height));
  11457. images[1].resize(static_cast<size_t>(width * height));
  11458. images[2].resize(static_cast<size_t>(width * height));
  11459. images[3].resize(static_cast<size_t>(width * height));
  11460. // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
  11461. for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
  11462. images[0][i] = data[static_cast<size_t>(components) * i + 0];
  11463. images[1][i] = data[static_cast<size_t>(components) * i + 1];
  11464. images[2][i] = data[static_cast<size_t>(components) * i + 2];
  11465. if (components == 4) {
  11466. images[3][i] = data[static_cast<size_t>(components) * i + 3];
  11467. }
  11468. }
  11469. }
  11470. float *image_ptr[4] = {0, 0, 0, 0};
  11471. if (components == 4) {
  11472. image_ptr[0] = &(images[3].at(0)); // A
  11473. image_ptr[1] = &(images[2].at(0)); // B
  11474. image_ptr[2] = &(images[1].at(0)); // G
  11475. image_ptr[3] = &(images[0].at(0)); // R
  11476. } else if (components == 3) {
  11477. image_ptr[0] = &(images[2].at(0)); // B
  11478. image_ptr[1] = &(images[1].at(0)); // G
  11479. image_ptr[2] = &(images[0].at(0)); // R
  11480. } else if (components == 1) {
  11481. image_ptr[0] = &(images[0].at(0)); // A
  11482. }
  11483. image.images = reinterpret_cast<unsigned char **>(image_ptr);
  11484. image.width = width;
  11485. image.height = height;
  11486. header.num_channels = components;
  11487. header.channels = static_cast<EXRChannelInfo *>(malloc(
  11488. sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
  11489. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  11490. if (components == 4) {
  11491. #ifdef _MSC_VER
  11492. strncpy_s(header.channels[0].name, "A", 255);
  11493. strncpy_s(header.channels[1].name, "B", 255);
  11494. strncpy_s(header.channels[2].name, "G", 255);
  11495. strncpy_s(header.channels[3].name, "R", 255);
  11496. #else
  11497. strncpy(header.channels[0].name, "A", 255);
  11498. strncpy(header.channels[1].name, "B", 255);
  11499. strncpy(header.channels[2].name, "G", 255);
  11500. strncpy(header.channels[3].name, "R", 255);
  11501. #endif
  11502. header.channels[0].name[strlen("A")] = '\0';
  11503. header.channels[1].name[strlen("B")] = '\0';
  11504. header.channels[2].name[strlen("G")] = '\0';
  11505. header.channels[3].name[strlen("R")] = '\0';
  11506. } else if (components == 3) {
  11507. #ifdef _MSC_VER
  11508. strncpy_s(header.channels[0].name, "B", 255);
  11509. strncpy_s(header.channels[1].name, "G", 255);
  11510. strncpy_s(header.channels[2].name, "R", 255);
  11511. #else
  11512. strncpy(header.channels[0].name, "B", 255);
  11513. strncpy(header.channels[1].name, "G", 255);
  11514. strncpy(header.channels[2].name, "R", 255);
  11515. #endif
  11516. header.channels[0].name[strlen("B")] = '\0';
  11517. header.channels[1].name[strlen("G")] = '\0';
  11518. header.channels[2].name[strlen("R")] = '\0';
  11519. } else {
  11520. #ifdef _MSC_VER
  11521. strncpy_s(header.channels[0].name, "A", 255);
  11522. #else
  11523. strncpy(header.channels[0].name, "A", 255);
  11524. #endif
  11525. header.channels[0].name[strlen("A")] = '\0';
  11526. }
  11527. header.pixel_types = static_cast<int *>(
  11528. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11529. header.requested_pixel_types = static_cast<int *>(
  11530. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  11531. for (int i = 0; i < header.num_channels; i++) {
  11532. header.pixel_types[i] =
  11533. TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
  11534. if (save_as_fp16 > 0) {
  11535. header.requested_pixel_types[i] =
  11536. TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
  11537. } else {
  11538. header.requested_pixel_types[i] =
  11539. TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
  11540. // no precision reduction)
  11541. }
  11542. }
  11543. int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
  11544. if (ret != TINYEXR_SUCCESS) {
  11545. return ret;
  11546. }
  11547. free(header.channels);
  11548. free(header.pixel_types);
  11549. free(header.requested_pixel_types);
  11550. return ret;
  11551. }
  11552. #ifdef __clang__
  11553. // zero-as-null-ppinter-constant
  11554. #pragma clang diagnostic pop
  11555. #endif
  11556. #endif // TINYEXR_IMPLEMENTATION_DEIFNED
  11557. #endif // TINYEXR_IMPLEMENTATION