tinyexr.h 266 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601
  1. #ifndef TINYEXR_H_
  2. #define TINYEXR_H_
  3. /*
  4. Copyright (c) 2014 - 2021, Syoyo Fujita and many contributors.
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. * Neither the name of the Syoyo Fujita nor the
  14. names of its contributors may be used to endorse or promote products
  15. derived from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  20. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // TinyEXR contains some OpenEXR code, which is licensed under ------------
  28. ///////////////////////////////////////////////////////////////////////////
  29. //
  30. // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
  31. // Digital Ltd. LLC
  32. //
  33. // All rights reserved.
  34. //
  35. // Redistribution and use in source and binary forms, with or without
  36. // modification, are permitted provided that the following conditions are
  37. // met:
  38. // * Redistributions of source code must retain the above copyright
  39. // notice, this list of conditions and the following disclaimer.
  40. // * Redistributions in binary form must reproduce the above
  41. // copyright notice, this list of conditions and the following disclaimer
  42. // in the documentation and/or other materials provided with the
  43. // distribution.
  44. // * Neither the name of Industrial Light & Magic nor the names of
  45. // its contributors may be used to endorse or promote products derived
  46. // from this software without specific prior written permission.
  47. //
  48. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  49. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  50. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  51. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  52. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  55. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  56. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  57. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  58. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  59. //
  60. ///////////////////////////////////////////////////////////////////////////
  61. // End of OpenEXR license -------------------------------------------------
  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. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
  83. defined(__i386) || defined(__i486__) || defined(__i486) || \
  84. defined(i386) || defined(__ia64__) || defined(__x86_64__)
  85. #define TINYEXR_X86_OR_X64_CPU 1
  86. #else
  87. #define TINYEXR_X86_OR_X64_CPU 0
  88. #endif
  89. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || TINYEXR_X86_OR_X64_CPU
  90. #define TINYEXR_LITTLE_ENDIAN 1
  91. #else
  92. #define TINYEXR_LITTLE_ENDIAN 0
  93. #endif
  94. // Use miniz or not to decode ZIP format pixel. Linking with zlib
  95. // required if this flas is 0.
  96. #ifndef TINYEXR_USE_MINIZ
  97. #define TINYEXR_USE_MINIZ (1)
  98. #endif
  99. // Disable PIZ comporession when applying cpplint.
  100. #ifndef TINYEXR_USE_PIZ
  101. #define TINYEXR_USE_PIZ (1)
  102. #endif
  103. #ifndef TINYEXR_USE_ZFP
  104. #define TINYEXR_USE_ZFP (0) // TinyEXR extension.
  105. // http://computation.llnl.gov/projects/floating-point-compression
  106. #endif
  107. #ifndef TINYEXR_USE_THREAD
  108. #define TINYEXR_USE_THREAD (0) // No threaded loading.
  109. // http://computation.llnl.gov/projects/floating-point-compression
  110. #endif
  111. #ifndef TINYEXR_USE_OPENMP
  112. #ifdef _OPENMP
  113. #define TINYEXR_USE_OPENMP (1)
  114. #else
  115. #define TINYEXR_USE_OPENMP (0)
  116. #endif
  117. #endif
  118. #define TINYEXR_SUCCESS (0)
  119. #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)
  120. #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)
  121. #define TINYEXR_ERROR_INVALID_ARGUMENT (-3)
  122. #define TINYEXR_ERROR_INVALID_DATA (-4)
  123. #define TINYEXR_ERROR_INVALID_FILE (-5)
  124. #define TINYEXR_ERROR_INVALID_PARAMETER (-6)
  125. #define TINYEXR_ERROR_CANT_OPEN_FILE (-7)
  126. #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8)
  127. #define TINYEXR_ERROR_INVALID_HEADER (-9)
  128. #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10)
  129. #define TINYEXR_ERROR_CANT_WRITE_FILE (-11)
  130. #define TINYEXR_ERROR_SERIALZATION_FAILED (-12)
  131. #define TINYEXR_ERROR_LAYER_NOT_FOUND (-13)
  132. // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }
  133. // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
  134. #define TINYEXR_PIXELTYPE_UINT (0)
  135. #define TINYEXR_PIXELTYPE_HALF (1)
  136. #define TINYEXR_PIXELTYPE_FLOAT (2)
  137. #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)
  138. #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)
  139. #define TINYEXR_COMPRESSIONTYPE_NONE (0)
  140. #define TINYEXR_COMPRESSIONTYPE_RLE (1)
  141. #define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
  142. #define TINYEXR_COMPRESSIONTYPE_ZIP (3)
  143. #define TINYEXR_COMPRESSIONTYPE_PIZ (4)
  144. #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension
  145. #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)
  146. #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)
  147. #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)
  148. #define TINYEXR_TILE_ONE_LEVEL (0)
  149. #define TINYEXR_TILE_MIPMAP_LEVELS (1)
  150. #define TINYEXR_TILE_RIPMAP_LEVELS (2)
  151. #define TINYEXR_TILE_ROUND_DOWN (0)
  152. #define TINYEXR_TILE_ROUND_UP (1)
  153. typedef struct _EXRVersion {
  154. int version; // this must be 2
  155. // tile format image;
  156. // not zero for only a single-part "normal" tiled file (according to spec.)
  157. int tiled;
  158. int long_name; // long name attribute
  159. // deep image(EXR 2.0);
  160. // for a multi-part file, indicates that at least one part is of type deep* (according to spec.)
  161. int non_image;
  162. int multipart; // multi-part(EXR 2.0)
  163. } EXRVersion;
  164. typedef struct _EXRAttribute {
  165. char name[256]; // name and type are up to 255 chars long.
  166. char type[256];
  167. unsigned char *value; // uint8_t*
  168. int size;
  169. int pad0;
  170. } EXRAttribute;
  171. typedef struct _EXRChannelInfo {
  172. char name[256]; // less than 255 bytes long
  173. int pixel_type;
  174. int x_sampling;
  175. int y_sampling;
  176. unsigned char p_linear;
  177. unsigned char pad[3];
  178. } EXRChannelInfo;
  179. typedef struct _EXRTile {
  180. int offset_x;
  181. int offset_y;
  182. int level_x;
  183. int level_y;
  184. int width; // actual width in a tile.
  185. int height; // actual height int a tile.
  186. unsigned char **images; // image[channels][pixels]
  187. } EXRTile;
  188. typedef struct _EXRBox2i {
  189. int min_x;
  190. int min_y;
  191. int max_x;
  192. int max_y;
  193. } EXRBox2i;
  194. typedef struct _EXRHeader {
  195. float pixel_aspect_ratio;
  196. int line_order;
  197. EXRBox2i data_window;
  198. EXRBox2i display_window;
  199. float screen_window_center[2];
  200. float screen_window_width;
  201. int chunk_count;
  202. // Properties for tiled format(`tiledesc`).
  203. int tiled;
  204. int tile_size_x;
  205. int tile_size_y;
  206. int tile_level_mode;
  207. int tile_rounding_mode;
  208. int long_name;
  209. // for a single-part file, agree with the version field bit 11
  210. // for a multi-part file, it is consistent with the type of part
  211. int non_image;
  212. int multipart;
  213. unsigned int header_len;
  214. // Custom attributes(exludes required attributes(e.g. `channels`,
  215. // `compression`, etc)
  216. int num_custom_attributes;
  217. EXRAttribute *custom_attributes; // array of EXRAttribute. size =
  218. // `num_custom_attributes`.
  219. EXRChannelInfo *channels; // [num_channels]
  220. int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
  221. // each channel. This is overwritten with `requested_pixel_types` when
  222. // loading.
  223. int num_channels;
  224. int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)
  225. int *requested_pixel_types; // Filled initially by
  226. // ParseEXRHeaderFrom(Meomory|File), then users
  227. // can edit it(only valid for HALF pixel type
  228. // channel)
  229. // name attribute required for multipart files;
  230. // must be unique and non empty (according to spec.);
  231. // use EXRSetNameAttr for setting value;
  232. // max 255 character allowed - excluding terminating zero
  233. char name[256];
  234. } EXRHeader;
  235. typedef struct _EXRMultiPartHeader {
  236. int num_headers;
  237. EXRHeader *headers;
  238. } EXRMultiPartHeader;
  239. typedef struct _EXRImage {
  240. EXRTile *tiles; // Tiled pixel data. The application must reconstruct image
  241. // from tiles manually. NULL if scanline format.
  242. struct _EXRImage* next_level; // NULL if scanline format or image is the last level.
  243. int level_x; // x level index
  244. int level_y; // y level index
  245. unsigned char **images; // image[channels][pixels]. NULL if tiled format.
  246. int width;
  247. int height;
  248. int num_channels;
  249. // Properties for tile format.
  250. int num_tiles;
  251. } EXRImage;
  252. typedef struct _EXRMultiPartImage {
  253. int num_images;
  254. EXRImage *images;
  255. } EXRMultiPartImage;
  256. typedef struct _DeepImage {
  257. const char **channel_names;
  258. float ***image; // image[channels][scanlines][samples]
  259. int **offset_table; // offset_table[scanline][offsets]
  260. int num_channels;
  261. int width;
  262. int height;
  263. int pad0;
  264. } DeepImage;
  265. // @deprecated { For backward compatibility. Not recommended to use. }
  266. // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel
  267. // alpha) or RGB(A) channels.
  268. // Application must free image data as returned by `out_rgba`
  269. // Result image format is: float x RGBA x width x hight
  270. // Returns negative value and may set error string in `err` when there's an
  271. // error
  272. extern int LoadEXR(float **out_rgba, int *width, int *height,
  273. const char *filename, const char **err);
  274. // Loads single-frame OpenEXR image by specifying layer name. Assume EXR image
  275. // contains A(single channel alpha) or RGB(A) channels. Application must free
  276. // image data as returned by `out_rgba` Result image format is: float x RGBA x
  277. // width x hight Returns negative value and may set error string in `err` when
  278. // there's an error When the specified layer name is not found in the EXR file,
  279. // the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`.
  280. extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height,
  281. const char *filename, const char *layer_name,
  282. const char **err);
  283. //
  284. // Get layer infos from EXR file.
  285. //
  286. // @param[out] layer_names List of layer names. Application must free memory
  287. // after using this.
  288. // @param[out] num_layers The number of layers
  289. // @param[out] err Error string(will be filled when the function returns error
  290. // code). Free it using FreeEXRErrorMessage after using this value.
  291. //
  292. // @return TINYEXR_SUCCEES upon success.
  293. //
  294. extern int EXRLayers(const char *filename, const char **layer_names[],
  295. int *num_layers, const char **err);
  296. // @deprecated { to be removed. }
  297. // Simple wrapper API for ParseEXRHeaderFromFile.
  298. // checking given file is a EXR file(by just look up header)
  299. // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for
  300. // others
  301. extern int IsEXR(const char *filename);
  302. // @deprecated { to be removed. }
  303. // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
  304. // components must be 1(Grayscale), 3(RGB) or 4(RGBA).
  305. // Input image format is: `float x width x height`, or `float x RGB(A) x width x
  306. // hight`
  307. // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
  308. // value.
  309. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
  310. // Use ZIP compression by default.
  311. // Returns negative value and may set error string in `err` when there's an
  312. // error
  313. extern int SaveEXR(const float *data, const int width, const int height,
  314. const int components, const int save_as_fp16,
  315. const char *filename, const char **err);
  316. // Returns the number of resolution levels of the image (including the base)
  317. extern int EXRNumLevels(const EXRImage* exr_image);
  318. // Initialize EXRHeader struct
  319. extern void InitEXRHeader(EXRHeader *exr_header);
  320. // Set name attribute of EXRHeader struct (it makes a copy)
  321. extern void EXRSetNameAttr(EXRHeader *exr_header, const char* name);
  322. // Initialize EXRImage struct
  323. extern void InitEXRImage(EXRImage *exr_image);
  324. // Frees internal data of EXRHeader struct
  325. extern int FreeEXRHeader(EXRHeader *exr_header);
  326. // Frees internal data of EXRImage struct
  327. extern int FreeEXRImage(EXRImage *exr_image);
  328. // Frees error message
  329. extern void FreeEXRErrorMessage(const char *msg);
  330. // Parse EXR version header of a file.
  331. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);
  332. // Parse EXR version header from memory-mapped EXR data.
  333. extern int ParseEXRVersionFromMemory(EXRVersion *version,
  334. const unsigned char *memory, size_t size);
  335. // Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
  336. // When there was an error message, Application must free `err` with
  337. // FreeEXRErrorMessage()
  338. extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,
  339. const char *filename, const char **err);
  340. // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
  341. // When there was an error message, Application must free `err` with
  342. // FreeEXRErrorMessage()
  343. extern int ParseEXRHeaderFromMemory(EXRHeader *header,
  344. const EXRVersion *version,
  345. const unsigned char *memory, size_t size,
  346. const char **err);
  347. // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
  348. // array.
  349. // When there was an error message, Application must free `err` with
  350. // FreeEXRErrorMessage()
  351. extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,
  352. int *num_headers,
  353. const EXRVersion *version,
  354. const char *filename,
  355. const char **err);
  356. // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
  357. // array
  358. // When there was an error message, Application must free `err` with
  359. // FreeEXRErrorMessage()
  360. extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,
  361. int *num_headers,
  362. const EXRVersion *version,
  363. const unsigned char *memory,
  364. size_t size, const char **err);
  365. // Loads single-part OpenEXR image from a file.
  366. // Application must setup `ParseEXRHeaderFromFile` before calling this function.
  367. // Application can free EXRImage using `FreeEXRImage`
  368. // Returns negative value and may set error string in `err` when there's an
  369. // error
  370. // When there was an error message, Application must free `err` with
  371. // FreeEXRErrorMessage()
  372. extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,
  373. const char *filename, const char **err);
  374. // Loads single-part OpenEXR image from a memory.
  375. // Application must setup `EXRHeader` with
  376. // `ParseEXRHeaderFromMemory` before calling this function.
  377. // Application can free EXRImage using `FreeEXRImage`
  378. // Returns negative value and may set error string in `err` when there's an
  379. // error
  380. // When there was an error message, Application must free `err` with
  381. // FreeEXRErrorMessage()
  382. extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,
  383. const unsigned char *memory,
  384. const size_t size, const char **err);
  385. // Loads multi-part OpenEXR image from a file.
  386. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
  387. // function.
  388. // Application can free EXRImage using `FreeEXRImage`
  389. // Returns negative value and may set error string in `err` when there's an
  390. // error
  391. // When there was an error message, Application must free `err` with
  392. // FreeEXRErrorMessage()
  393. extern int LoadEXRMultipartImageFromFile(EXRImage *images,
  394. const EXRHeader **headers,
  395. unsigned int num_parts,
  396. const char *filename,
  397. const char **err);
  398. // Loads multi-part OpenEXR image from a memory.
  399. // Application must setup `EXRHeader*` array with
  400. // `ParseEXRMultipartHeaderFromMemory` before calling this function.
  401. // Application can free EXRImage using `FreeEXRImage`
  402. // Returns negative value and may set error string in `err` when there's an
  403. // error
  404. // When there was an error message, Application must free `err` with
  405. // FreeEXRErrorMessage()
  406. extern int LoadEXRMultipartImageFromMemory(EXRImage *images,
  407. const EXRHeader **headers,
  408. unsigned int num_parts,
  409. const unsigned char *memory,
  410. const size_t size, const char **err);
  411. // Saves multi-channel, single-frame OpenEXR image to a file.
  412. // Returns negative value and may set error string in `err` when there's an
  413. // error
  414. // When there was an error message, Application must free `err` with
  415. // FreeEXRErrorMessage()
  416. extern int SaveEXRImageToFile(const EXRImage *image,
  417. const EXRHeader *exr_header, const char *filename,
  418. const char **err);
  419. // Saves multi-channel, single-frame OpenEXR image to a memory.
  420. // Image is compressed using EXRImage.compression value.
  421. // Return the number of bytes if success.
  422. // Return zero and will set error string in `err` when there's an
  423. // error.
  424. // When there was an error message, Application must free `err` with
  425. // FreeEXRErrorMessage()
  426. extern size_t SaveEXRImageToMemory(const EXRImage *image,
  427. const EXRHeader *exr_header,
  428. unsigned char **memory, const char **err);
  429. // Saves multi-channel, multi-frame OpenEXR image to a memory.
  430. // Image is compressed using EXRImage.compression value.
  431. // File global attributes (eg. display_window) must be set in the first header.
  432. // Returns negative value and may set error string in `err` when there's an
  433. // error
  434. // When there was an error message, Application must free `err` with
  435. // FreeEXRErrorMessage()
  436. extern int SaveEXRMultipartImageToFile(const EXRImage *images,
  437. const EXRHeader **exr_headers,
  438. unsigned int num_parts,
  439. const char *filename, const char **err);
  440. // Saves multi-channel, multi-frame OpenEXR image to a memory.
  441. // Image is compressed using EXRImage.compression value.
  442. // File global attributes (eg. display_window) must be set in the first header.
  443. // Return the number of bytes if success.
  444. // Return zero and will set error string in `err` when there's an
  445. // error.
  446. // When there was an error message, Application must free `err` with
  447. // FreeEXRErrorMessage()
  448. extern size_t SaveEXRMultipartImageToMemory(const EXRImage *images,
  449. const EXRHeader **exr_headers,
  450. unsigned int num_parts,
  451. unsigned char **memory, const char **err);
  452. // Loads single-frame OpenEXR deep image.
  453. // Application must free memory of variables in DeepImage(image, offset_table)
  454. // Returns negative value and may set error string in `err` when there's an
  455. // error
  456. // When there was an error message, Application must free `err` with
  457. // FreeEXRErrorMessage()
  458. extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
  459. const char **err);
  460. // NOT YET IMPLEMENTED:
  461. // Saves single-frame OpenEXR deep image.
  462. // Returns negative value and may set error string in `err` when there's an
  463. // error
  464. // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
  465. // const char **err);
  466. // NOT YET IMPLEMENTED:
  467. // Loads multi-part OpenEXR deep image.
  468. // Application must free memory of variables in DeepImage(image, offset_table)
  469. // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
  470. // char *filename,
  471. // const char **err);
  472. // For emscripten.
  473. // Loads single-frame OpenEXR image from memory. Assume EXR image contains
  474. // RGB(A) channels.
  475. // Returns negative value and may set error string in `err` when there's an
  476. // error
  477. // When there was an error message, Application must free `err` with
  478. // FreeEXRErrorMessage()
  479. extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  480. const unsigned char *memory, size_t size,
  481. const char **err);
  482. #ifdef __cplusplus
  483. }
  484. #endif
  485. #endif // TINYEXR_H_
  486. #ifdef TINYEXR_IMPLEMENTATION
  487. #ifndef TINYEXR_IMPLEMENTATION_DEFINED
  488. #define TINYEXR_IMPLEMENTATION_DEFINED
  489. #ifdef _WIN32
  490. #ifndef WIN32_LEAN_AND_MEAN
  491. #define WIN32_LEAN_AND_MEAN
  492. #endif
  493. #ifndef NOMINMAX
  494. #define NOMINMAX
  495. #endif
  496. #include <windows.h> // for UTF-8
  497. #endif
  498. #include <algorithm>
  499. #include <cassert>
  500. #include <cstdio>
  501. #include <cstdlib>
  502. #include <cstring>
  503. #include <sstream>
  504. // #include <iostream> // debug
  505. #include <limits>
  506. #include <string>
  507. #include <vector>
  508. #include <set>
  509. // https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support
  510. #if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900)
  511. #define TINYEXR_HAS_CXX11 (1)
  512. // C++11
  513. #include <cstdint>
  514. #if TINYEXR_USE_THREAD
  515. #include <atomic>
  516. #include <thread>
  517. #endif
  518. #endif // __cplusplus > 199711L
  519. #if TINYEXR_USE_OPENMP
  520. #include <omp.h>
  521. #endif
  522. #if TINYEXR_USE_MINIZ
  523. #include <miniz.h>
  524. #else
  525. // Issue #46. Please include your own zlib-compatible API header before
  526. // including `tinyexr.h`
  527. //#include "zlib.h"
  528. #endif
  529. #if TINYEXR_USE_ZFP
  530. #ifdef __clang__
  531. #pragma clang diagnostic push
  532. #pragma clang diagnostic ignored "-Weverything"
  533. #endif
  534. #include "zfp.h"
  535. #ifdef __clang__
  536. #pragma clang diagnostic pop
  537. #endif
  538. #endif
  539. namespace tinyexr {
  540. #if __cplusplus > 199711L
  541. // C++11
  542. typedef uint64_t tinyexr_uint64;
  543. typedef int64_t tinyexr_int64;
  544. #else
  545. // Although `long long` is not a standard type pre C++11, assume it is defined
  546. // as a compiler's extension.
  547. #ifdef __clang__
  548. #pragma clang diagnostic push
  549. #pragma clang diagnostic ignored "-Wc++11-long-long"
  550. #endif
  551. typedef unsigned long long tinyexr_uint64;
  552. typedef long long tinyexr_int64;
  553. #ifdef __clang__
  554. #pragma clang diagnostic pop
  555. #endif
  556. #endif
  557. // static bool IsBigEndian(void) {
  558. // union {
  559. // unsigned int i;
  560. // char c[4];
  561. // } bint = {0x01020304};
  562. //
  563. // return bint.c[0] == 1;
  564. //}
  565. static void SetErrorMessage(const std::string &msg, const char **err) {
  566. if (err) {
  567. #ifdef _WIN32
  568. (*err) = _strdup(msg.c_str());
  569. #else
  570. (*err) = strdup(msg.c_str());
  571. #endif
  572. }
  573. }
  574. static void SetWarningMessage(const std::string &msg, const char **warn) {
  575. if (warn) {
  576. #ifdef _WIN32
  577. (*warn) = _strdup(msg.c_str());
  578. #else
  579. (*warn) = strdup(msg.c_str());
  580. #endif
  581. }
  582. }
  583. static const int kEXRVersionSize = 8;
  584. static void cpy2(unsigned short *dst_val, const unsigned short *src_val) {
  585. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  586. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  587. dst[0] = src[0];
  588. dst[1] = src[1];
  589. }
  590. static void swap2(unsigned short *val) {
  591. #ifdef TINYEXR_LITTLE_ENDIAN
  592. (void)val;
  593. #else
  594. unsigned short tmp = *val;
  595. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  596. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  597. dst[0] = src[1];
  598. dst[1] = src[0];
  599. #endif
  600. }
  601. #ifdef __clang__
  602. #pragma clang diagnostic push
  603. #pragma clang diagnostic ignored "-Wunused-function"
  604. #endif
  605. #ifdef __GNUC__
  606. #pragma GCC diagnostic push
  607. #pragma GCC diagnostic ignored "-Wunused-function"
  608. #endif
  609. static void cpy4(int *dst_val, const int *src_val) {
  610. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  611. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  612. dst[0] = src[0];
  613. dst[1] = src[1];
  614. dst[2] = src[2];
  615. dst[3] = src[3];
  616. }
  617. static void cpy4(unsigned int *dst_val, const unsigned int *src_val) {
  618. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  619. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  620. dst[0] = src[0];
  621. dst[1] = src[1];
  622. dst[2] = src[2];
  623. dst[3] = src[3];
  624. }
  625. static void cpy4(float *dst_val, const float *src_val) {
  626. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  627. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  628. dst[0] = src[0];
  629. dst[1] = src[1];
  630. dst[2] = src[2];
  631. dst[3] = src[3];
  632. }
  633. #ifdef __clang__
  634. #pragma clang diagnostic pop
  635. #endif
  636. #ifdef __GNUC__
  637. #pragma GCC diagnostic pop
  638. #endif
  639. static void swap4(unsigned int *val) {
  640. #ifdef TINYEXR_LITTLE_ENDIAN
  641. (void)val;
  642. #else
  643. unsigned int tmp = *val;
  644. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  645. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  646. dst[0] = src[3];
  647. dst[1] = src[2];
  648. dst[2] = src[1];
  649. dst[3] = src[0];
  650. #endif
  651. }
  652. static void swap4(int *val) {
  653. #ifdef TINYEXR_LITTLE_ENDIAN
  654. (void)val;
  655. #else
  656. int tmp = *val;
  657. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  658. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  659. dst[0] = src[3];
  660. dst[1] = src[2];
  661. dst[2] = src[1];
  662. dst[3] = src[0];
  663. #endif
  664. }
  665. static void swap4(float *val) {
  666. #ifdef TINYEXR_LITTLE_ENDIAN
  667. (void)val;
  668. #else
  669. float tmp = *val;
  670. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  671. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  672. dst[0] = src[3];
  673. dst[1] = src[2];
  674. dst[2] = src[1];
  675. dst[3] = src[0];
  676. #endif
  677. }
  678. #if 0
  679. static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
  680. unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
  681. const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
  682. dst[0] = src[0];
  683. dst[1] = src[1];
  684. dst[2] = src[2];
  685. dst[3] = src[3];
  686. dst[4] = src[4];
  687. dst[5] = src[5];
  688. dst[6] = src[6];
  689. dst[7] = src[7];
  690. }
  691. #endif
  692. static void swap8(tinyexr::tinyexr_uint64 *val) {
  693. #ifdef TINYEXR_LITTLE_ENDIAN
  694. (void)val;
  695. #else
  696. tinyexr::tinyexr_uint64 tmp = (*val);
  697. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  698. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  699. dst[0] = src[7];
  700. dst[1] = src[6];
  701. dst[2] = src[5];
  702. dst[3] = src[4];
  703. dst[4] = src[3];
  704. dst[5] = src[2];
  705. dst[6] = src[1];
  706. dst[7] = src[0];
  707. #endif
  708. }
  709. // https://gist.github.com/rygorous/2156668
  710. union FP32 {
  711. unsigned int u;
  712. float f;
  713. struct {
  714. #if TINYEXR_LITTLE_ENDIAN
  715. unsigned int Mantissa : 23;
  716. unsigned int Exponent : 8;
  717. unsigned int Sign : 1;
  718. #else
  719. unsigned int Sign : 1;
  720. unsigned int Exponent : 8;
  721. unsigned int Mantissa : 23;
  722. #endif
  723. } s;
  724. };
  725. #ifdef __clang__
  726. #pragma clang diagnostic push
  727. #pragma clang diagnostic ignored "-Wpadded"
  728. #endif
  729. union FP16 {
  730. unsigned short u;
  731. struct {
  732. #if TINYEXR_LITTLE_ENDIAN
  733. unsigned int Mantissa : 10;
  734. unsigned int Exponent : 5;
  735. unsigned int Sign : 1;
  736. #else
  737. unsigned int Sign : 1;
  738. unsigned int Exponent : 5;
  739. unsigned int Mantissa : 10;
  740. #endif
  741. } s;
  742. };
  743. #ifdef __clang__
  744. #pragma clang diagnostic pop
  745. #endif
  746. static FP32 half_to_float(FP16 h) {
  747. static const FP32 magic = {113 << 23};
  748. static const unsigned int shifted_exp = 0x7c00
  749. << 13; // exponent mask after shift
  750. FP32 o;
  751. o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
  752. unsigned int exp_ = shifted_exp & o.u; // just the exponent
  753. o.u += (127 - 15) << 23; // exponent adjust
  754. // handle exponent special cases
  755. if (exp_ == shifted_exp) // Inf/NaN?
  756. o.u += (128 - 16) << 23; // extra exp adjust
  757. else if (exp_ == 0) // Zero/Denormal?
  758. {
  759. o.u += 1 << 23; // extra exp adjust
  760. o.f -= magic.f; // renormalize
  761. }
  762. o.u |= (h.u & 0x8000U) << 16U; // sign bit
  763. return o;
  764. }
  765. static FP16 float_to_half_full(FP32 f) {
  766. FP16 o = {0};
  767. // Based on ISPC reference code (with minor modifications)
  768. if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
  769. o.s.Exponent = 0;
  770. else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
  771. {
  772. o.s.Exponent = 31;
  773. o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
  774. } else // Normalized number
  775. {
  776. // Exponent unbias the single, then bias the halfp
  777. int newexp = f.s.Exponent - 127 + 15;
  778. if (newexp >= 31) // Overflow, return signed infinity
  779. o.s.Exponent = 31;
  780. else if (newexp <= 0) // Underflow
  781. {
  782. if ((14 - newexp) <= 24) // Mantissa might be non-zero
  783. {
  784. unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
  785. o.s.Mantissa = mant >> (14 - newexp);
  786. if ((mant >> (13 - newexp)) & 1) // Check for rounding
  787. o.u++; // Round, might overflow into exp bit, but this is OK
  788. }
  789. } else {
  790. o.s.Exponent = static_cast<unsigned int>(newexp);
  791. o.s.Mantissa = f.s.Mantissa >> 13;
  792. if (f.s.Mantissa & 0x1000) // Check for rounding
  793. o.u++; // Round, might overflow to inf, this is OK
  794. }
  795. }
  796. o.s.Sign = f.s.Sign;
  797. return o;
  798. }
  799. // NOTE: From OpenEXR code
  800. // #define IMF_INCREASING_Y 0
  801. // #define IMF_DECREASING_Y 1
  802. // #define IMF_RAMDOM_Y 2
  803. //
  804. // #define IMF_NO_COMPRESSION 0
  805. // #define IMF_RLE_COMPRESSION 1
  806. // #define IMF_ZIPS_COMPRESSION 2
  807. // #define IMF_ZIP_COMPRESSION 3
  808. // #define IMF_PIZ_COMPRESSION 4
  809. // #define IMF_PXR24_COMPRESSION 5
  810. // #define IMF_B44_COMPRESSION 6
  811. // #define IMF_B44A_COMPRESSION 7
  812. #ifdef __clang__
  813. #pragma clang diagnostic push
  814. #if __has_warning("-Wzero-as-null-pointer-constant")
  815. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  816. #endif
  817. #endif
  818. static const char *ReadString(std::string *s, const char *ptr, size_t len) {
  819. // Read untile NULL(\0).
  820. const char *p = ptr;
  821. const char *q = ptr;
  822. while ((size_t(q - ptr) < len) && (*q) != 0) {
  823. q++;
  824. }
  825. if (size_t(q - ptr) >= len) {
  826. (*s).clear();
  827. return NULL;
  828. }
  829. (*s) = std::string(p, q);
  830. return q + 1; // skip '\0'
  831. }
  832. static bool ReadAttribute(std::string *name, std::string *type,
  833. std::vector<unsigned char> *data, size_t *marker_size,
  834. const char *marker, size_t size) {
  835. size_t name_len = strnlen(marker, size);
  836. if (name_len == size) {
  837. // String does not have a terminating character.
  838. return false;
  839. }
  840. *name = std::string(marker, name_len);
  841. marker += name_len + 1;
  842. size -= name_len + 1;
  843. size_t type_len = strnlen(marker, size);
  844. if (type_len == size) {
  845. return false;
  846. }
  847. *type = std::string(marker, type_len);
  848. marker += type_len + 1;
  849. size -= type_len + 1;
  850. if (size < sizeof(uint32_t)) {
  851. return false;
  852. }
  853. uint32_t data_len;
  854. memcpy(&data_len, marker, sizeof(uint32_t));
  855. tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
  856. if (data_len == 0) {
  857. if ((*type).compare("string") == 0) {
  858. // Accept empty string attribute.
  859. marker += sizeof(uint32_t);
  860. size -= sizeof(uint32_t);
  861. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
  862. data->resize(1);
  863. (*data)[0] = '\0';
  864. return true;
  865. } else {
  866. return false;
  867. }
  868. }
  869. marker += sizeof(uint32_t);
  870. size -= sizeof(uint32_t);
  871. if (size < data_len) {
  872. return false;
  873. }
  874. data->resize(static_cast<size_t>(data_len));
  875. memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
  876. *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
  877. return true;
  878. }
  879. static void WriteAttributeToMemory(std::vector<unsigned char> *out,
  880. const char *name, const char *type,
  881. const unsigned char *data, int len) {
  882. out->insert(out->end(), name, name + strlen(name) + 1);
  883. out->insert(out->end(), type, type + strlen(type) + 1);
  884. int outLen = len;
  885. tinyexr::swap4(&outLen);
  886. out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),
  887. reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
  888. out->insert(out->end(), data, data + len);
  889. }
  890. typedef struct {
  891. std::string name; // less than 255 bytes long
  892. int pixel_type;
  893. int requested_pixel_type;
  894. int x_sampling;
  895. int y_sampling;
  896. unsigned char p_linear;
  897. unsigned char pad[3];
  898. } ChannelInfo;
  899. typedef struct {
  900. int min_x;
  901. int min_y;
  902. int max_x;
  903. int max_y;
  904. } Box2iInfo;
  905. struct HeaderInfo {
  906. std::vector<tinyexr::ChannelInfo> channels;
  907. std::vector<EXRAttribute> attributes;
  908. Box2iInfo data_window;
  909. int line_order;
  910. Box2iInfo display_window;
  911. float screen_window_center[2];
  912. float screen_window_width;
  913. float pixel_aspect_ratio;
  914. int chunk_count;
  915. // Tiled format
  916. int tiled; // Non-zero if the part is tiled.
  917. int tile_size_x;
  918. int tile_size_y;
  919. int tile_level_mode;
  920. int tile_rounding_mode;
  921. unsigned int header_len;
  922. int compression_type;
  923. // required for multi-part or non-image files
  924. std::string name;
  925. // required for multi-part or non-image files
  926. std::string type;
  927. void clear() {
  928. channels.clear();
  929. attributes.clear();
  930. data_window.min_x = 0;
  931. data_window.min_y = 0;
  932. data_window.max_x = 0;
  933. data_window.max_y = 0;
  934. line_order = 0;
  935. display_window.min_x = 0;
  936. display_window.min_y = 0;
  937. display_window.max_x = 0;
  938. display_window.max_y = 0;
  939. screen_window_center[0] = 0.0f;
  940. screen_window_center[1] = 0.0f;
  941. screen_window_width = 0.0f;
  942. pixel_aspect_ratio = 0.0f;
  943. chunk_count = 0;
  944. // Tiled format
  945. tiled = 0;
  946. tile_size_x = 0;
  947. tile_size_y = 0;
  948. tile_level_mode = 0;
  949. tile_rounding_mode = 0;
  950. header_len = 0;
  951. compression_type = 0;
  952. name.clear();
  953. type.clear();
  954. }
  955. };
  956. static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,
  957. const std::vector<unsigned char> &data) {
  958. const char *p = reinterpret_cast<const char *>(&data.at(0));
  959. for (;;) {
  960. if ((*p) == 0) {
  961. break;
  962. }
  963. ChannelInfo info;
  964. tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -
  965. (p - reinterpret_cast<const char *>(data.data()));
  966. if (data_len < 0) {
  967. return false;
  968. }
  969. p = ReadString(&info.name, p, size_t(data_len));
  970. if ((p == NULL) && (info.name.empty())) {
  971. // Buffer overrun. Issue #51.
  972. return false;
  973. }
  974. const unsigned char *data_end =
  975. reinterpret_cast<const unsigned char *>(p) + 16;
  976. if (data_end >= (data.data() + data.size())) {
  977. return false;
  978. }
  979. memcpy(&info.pixel_type, p, sizeof(int));
  980. p += 4;
  981. info.p_linear = static_cast<unsigned char>(p[0]); // uchar
  982. p += 1 + 3; // reserved: uchar[3]
  983. memcpy(&info.x_sampling, p, sizeof(int)); // int
  984. p += 4;
  985. memcpy(&info.y_sampling, p, sizeof(int)); // int
  986. p += 4;
  987. tinyexr::swap4(&info.pixel_type);
  988. tinyexr::swap4(&info.x_sampling);
  989. tinyexr::swap4(&info.y_sampling);
  990. channels.push_back(info);
  991. }
  992. return true;
  993. }
  994. static void WriteChannelInfo(std::vector<unsigned char> &data,
  995. const std::vector<ChannelInfo> &channels) {
  996. size_t sz = 0;
  997. // Calculate total size.
  998. for (size_t c = 0; c < channels.size(); c++) {
  999. sz += channels[c].name.length() + 1; // +1 for \0
  1000. sz += 16; // 4 * int
  1001. }
  1002. data.resize(sz + 1);
  1003. unsigned char *p = &data.at(0);
  1004. for (size_t c = 0; c < channels.size(); c++) {
  1005. memcpy(p, channels[c].name.c_str(), channels[c].name.length());
  1006. p += channels[c].name.length();
  1007. (*p) = '\0';
  1008. p++;
  1009. int pixel_type = channels[c].requested_pixel_type;
  1010. int x_sampling = channels[c].x_sampling;
  1011. int y_sampling = channels[c].y_sampling;
  1012. tinyexr::swap4(&pixel_type);
  1013. tinyexr::swap4(&x_sampling);
  1014. tinyexr::swap4(&y_sampling);
  1015. memcpy(p, &pixel_type, sizeof(int));
  1016. p += sizeof(int);
  1017. (*p) = channels[c].p_linear;
  1018. p += 4;
  1019. memcpy(p, &x_sampling, sizeof(int));
  1020. p += sizeof(int);
  1021. memcpy(p, &y_sampling, sizeof(int));
  1022. p += sizeof(int);
  1023. }
  1024. (*p) = '\0';
  1025. }
  1026. static void CompressZip(unsigned char *dst,
  1027. tinyexr::tinyexr_uint64 &compressedSize,
  1028. const unsigned char *src, unsigned long src_size) {
  1029. std::vector<unsigned char> tmpBuf(src_size);
  1030. //
  1031. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  1032. // ImfZipCompressor.cpp
  1033. //
  1034. //
  1035. // Reorder the pixel data.
  1036. //
  1037. const char *srcPtr = reinterpret_cast<const char *>(src);
  1038. {
  1039. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  1040. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  1041. const char *stop = srcPtr + src_size;
  1042. for (;;) {
  1043. if (srcPtr < stop)
  1044. *(t1++) = *(srcPtr++);
  1045. else
  1046. break;
  1047. if (srcPtr < stop)
  1048. *(t2++) = *(srcPtr++);
  1049. else
  1050. break;
  1051. }
  1052. }
  1053. //
  1054. // Predictor.
  1055. //
  1056. {
  1057. unsigned char *t = &tmpBuf.at(0) + 1;
  1058. unsigned char *stop = &tmpBuf.at(0) + src_size;
  1059. int p = t[-1];
  1060. while (t < stop) {
  1061. int d = int(t[0]) - p + (128 + 256);
  1062. p = t[0];
  1063. t[0] = static_cast<unsigned char>(d);
  1064. ++t;
  1065. }
  1066. }
  1067. #if TINYEXR_USE_MINIZ
  1068. //
  1069. // Compress the data using miniz
  1070. //
  1071. mz_ulong outSize = mz_compressBound(src_size);
  1072. int ret = mz_compress(
  1073. dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),
  1074. src_size);
  1075. assert(ret == MZ_OK);
  1076. (void)ret;
  1077. compressedSize = outSize;
  1078. #else
  1079. uLong outSize = compressBound(static_cast<uLong>(src_size));
  1080. int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),
  1081. src_size);
  1082. assert(ret == Z_OK);
  1083. compressedSize = outSize;
  1084. #endif
  1085. // Use uncompressed data when compressed data is larger than uncompressed.
  1086. // (Issue 40)
  1087. if (compressedSize >= src_size) {
  1088. compressedSize = src_size;
  1089. memcpy(dst, src, src_size);
  1090. }
  1091. }
  1092. static bool DecompressZip(unsigned char *dst,
  1093. unsigned long *uncompressed_size /* inout */,
  1094. const unsigned char *src, unsigned long src_size) {
  1095. if ((*uncompressed_size) == src_size) {
  1096. // Data is not compressed(Issue 40).
  1097. memcpy(dst, src, src_size);
  1098. return true;
  1099. }
  1100. std::vector<unsigned char> tmpBuf(*uncompressed_size);
  1101. #if TINYEXR_USE_MINIZ
  1102. int ret =
  1103. mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  1104. if (MZ_OK != ret) {
  1105. return false;
  1106. }
  1107. #else
  1108. int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
  1109. if (Z_OK != ret) {
  1110. return false;
  1111. }
  1112. #endif
  1113. //
  1114. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  1115. // ImfZipCompressor.cpp
  1116. //
  1117. // Predictor.
  1118. {
  1119. unsigned char *t = &tmpBuf.at(0) + 1;
  1120. unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);
  1121. while (t < stop) {
  1122. int d = int(t[-1]) + int(t[0]) - 128;
  1123. t[0] = static_cast<unsigned char>(d);
  1124. ++t;
  1125. }
  1126. }
  1127. // Reorder the pixel data.
  1128. {
  1129. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  1130. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  1131. (*uncompressed_size + 1) / 2;
  1132. char *s = reinterpret_cast<char *>(dst);
  1133. char *stop = s + (*uncompressed_size);
  1134. for (;;) {
  1135. if (s < stop)
  1136. *(s++) = *(t1++);
  1137. else
  1138. break;
  1139. if (s < stop)
  1140. *(s++) = *(t2++);
  1141. else
  1142. break;
  1143. }
  1144. }
  1145. return true;
  1146. }
  1147. // RLE code from OpenEXR --------------------------------------
  1148. #ifdef __clang__
  1149. #pragma clang diagnostic push
  1150. #pragma clang diagnostic ignored "-Wsign-conversion"
  1151. #if __has_warning("-Wextra-semi-stmt")
  1152. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  1153. #endif
  1154. #endif
  1155. #ifdef _MSC_VER
  1156. #pragma warning(push)
  1157. #pragma warning(disable : 4204) // nonstandard extension used : non-constant
  1158. // aggregate initializer (also supported by GNU
  1159. // C and C99, so no big deal)
  1160. #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
  1161. // 'int', possible loss of data
  1162. #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
  1163. // 'int', possible loss of data
  1164. #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
  1165. // deprecated. Instead, use the ISO C and C++
  1166. // conformant name: _strdup.
  1167. #endif
  1168. const int MIN_RUN_LENGTH = 3;
  1169. const int MAX_RUN_LENGTH = 127;
  1170. //
  1171. // Compress an array of bytes, using run-length encoding,
  1172. // and return the length of the compressed data.
  1173. //
  1174. static int rleCompress(int inLength, const char in[], signed char out[]) {
  1175. const char *inEnd = in + inLength;
  1176. const char *runStart = in;
  1177. const char *runEnd = in + 1;
  1178. signed char *outWrite = out;
  1179. while (runStart < inEnd) {
  1180. while (runEnd < inEnd && *runStart == *runEnd &&
  1181. runEnd - runStart - 1 < MAX_RUN_LENGTH) {
  1182. ++runEnd;
  1183. }
  1184. if (runEnd - runStart >= MIN_RUN_LENGTH) {
  1185. //
  1186. // Compressible run
  1187. //
  1188. *outWrite++ = static_cast<char>(runEnd - runStart) - 1;
  1189. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart));
  1190. runStart = runEnd;
  1191. } else {
  1192. //
  1193. // Uncompressable run
  1194. //
  1195. while (runEnd < inEnd &&
  1196. ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||
  1197. (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&
  1198. runEnd - runStart < MAX_RUN_LENGTH) {
  1199. ++runEnd;
  1200. }
  1201. *outWrite++ = static_cast<char>(runStart - runEnd);
  1202. while (runStart < runEnd) {
  1203. *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));
  1204. }
  1205. }
  1206. ++runEnd;
  1207. }
  1208. return static_cast<int>(outWrite - out);
  1209. }
  1210. //
  1211. // Uncompress an array of bytes compressed with rleCompress().
  1212. // Returns the length of the oncompressed data, or 0 if the
  1213. // length of the uncompressed data would be more than maxLength.
  1214. //
  1215. static int rleUncompress(int inLength, int maxLength, const signed char in[],
  1216. char out[]) {
  1217. char *outStart = out;
  1218. while (inLength > 0) {
  1219. if (*in < 0) {
  1220. int count = -(static_cast<int>(*in++));
  1221. inLength -= count + 1;
  1222. // Fixes #116: Add bounds check to in buffer.
  1223. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0;
  1224. memcpy(out, in, count);
  1225. out += count;
  1226. in += count;
  1227. } else {
  1228. int count = *in++;
  1229. inLength -= 2;
  1230. if (0 > (maxLength -= count + 1)) return 0;
  1231. memset(out, *reinterpret_cast<const char *>(in), count + 1);
  1232. out += count + 1;
  1233. in++;
  1234. }
  1235. }
  1236. return static_cast<int>(out - outStart);
  1237. }
  1238. #ifdef __clang__
  1239. #pragma clang diagnostic pop
  1240. #endif
  1241. // End of RLE code from OpenEXR -----------------------------------
  1242. static void CompressRle(unsigned char *dst,
  1243. tinyexr::tinyexr_uint64 &compressedSize,
  1244. const unsigned char *src, unsigned long src_size) {
  1245. std::vector<unsigned char> tmpBuf(src_size);
  1246. //
  1247. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  1248. // ImfRleCompressor.cpp
  1249. //
  1250. //
  1251. // Reorder the pixel data.
  1252. //
  1253. const char *srcPtr = reinterpret_cast<const char *>(src);
  1254. {
  1255. char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
  1256. char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
  1257. const char *stop = srcPtr + src_size;
  1258. for (;;) {
  1259. if (srcPtr < stop)
  1260. *(t1++) = *(srcPtr++);
  1261. else
  1262. break;
  1263. if (srcPtr < stop)
  1264. *(t2++) = *(srcPtr++);
  1265. else
  1266. break;
  1267. }
  1268. }
  1269. //
  1270. // Predictor.
  1271. //
  1272. {
  1273. unsigned char *t = &tmpBuf.at(0) + 1;
  1274. unsigned char *stop = &tmpBuf.at(0) + src_size;
  1275. int p = t[-1];
  1276. while (t < stop) {
  1277. int d = int(t[0]) - p + (128 + 256);
  1278. p = t[0];
  1279. t[0] = static_cast<unsigned char>(d);
  1280. ++t;
  1281. }
  1282. }
  1283. // outSize will be (srcSiz * 3) / 2 at max.
  1284. int outSize = rleCompress(static_cast<int>(src_size),
  1285. reinterpret_cast<const char *>(&tmpBuf.at(0)),
  1286. reinterpret_cast<signed char *>(dst));
  1287. assert(outSize > 0);
  1288. compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
  1289. // Use uncompressed data when compressed data is larger than uncompressed.
  1290. // (Issue 40)
  1291. if (compressedSize >= src_size) {
  1292. compressedSize = src_size;
  1293. memcpy(dst, src, src_size);
  1294. }
  1295. }
  1296. static bool DecompressRle(unsigned char *dst,
  1297. const unsigned long uncompressed_size,
  1298. const unsigned char *src, unsigned long src_size) {
  1299. if (uncompressed_size == src_size) {
  1300. // Data is not compressed(Issue 40).
  1301. memcpy(dst, src, src_size);
  1302. return true;
  1303. }
  1304. // Workaround for issue #112.
  1305. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.
  1306. if (src_size <= 2) {
  1307. return false;
  1308. }
  1309. std::vector<unsigned char> tmpBuf(uncompressed_size);
  1310. int ret = rleUncompress(static_cast<int>(src_size),
  1311. static_cast<int>(uncompressed_size),
  1312. reinterpret_cast<const signed char *>(src),
  1313. reinterpret_cast<char *>(&tmpBuf.at(0)));
  1314. if (ret != static_cast<int>(uncompressed_size)) {
  1315. return false;
  1316. }
  1317. //
  1318. // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
  1319. // ImfRleCompressor.cpp
  1320. //
  1321. // Predictor.
  1322. {
  1323. unsigned char *t = &tmpBuf.at(0) + 1;
  1324. unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;
  1325. while (t < stop) {
  1326. int d = int(t[-1]) + int(t[0]) - 128;
  1327. t[0] = static_cast<unsigned char>(d);
  1328. ++t;
  1329. }
  1330. }
  1331. // Reorder the pixel data.
  1332. {
  1333. const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
  1334. const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
  1335. (uncompressed_size + 1) / 2;
  1336. char *s = reinterpret_cast<char *>(dst);
  1337. char *stop = s + uncompressed_size;
  1338. for (;;) {
  1339. if (s < stop)
  1340. *(s++) = *(t1++);
  1341. else
  1342. break;
  1343. if (s < stop)
  1344. *(s++) = *(t2++);
  1345. else
  1346. break;
  1347. }
  1348. }
  1349. return true;
  1350. }
  1351. #if TINYEXR_USE_PIZ
  1352. #ifdef __clang__
  1353. #pragma clang diagnostic push
  1354. #pragma clang diagnostic ignored "-Wc++11-long-long"
  1355. #pragma clang diagnostic ignored "-Wold-style-cast"
  1356. #pragma clang diagnostic ignored "-Wpadded"
  1357. #pragma clang diagnostic ignored "-Wsign-conversion"
  1358. #pragma clang diagnostic ignored "-Wc++11-extensions"
  1359. #pragma clang diagnostic ignored "-Wconversion"
  1360. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1361. #if __has_warning("-Wcast-qual")
  1362. #pragma clang diagnostic ignored "-Wcast-qual"
  1363. #endif
  1364. #if __has_warning("-Wextra-semi-stmt")
  1365. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  1366. #endif
  1367. #endif
  1368. //
  1369. // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
  1370. //
  1371. // -----------------------------------------------------------------
  1372. // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
  1373. // Digital Ltd. LLC)
  1374. // (3 clause BSD license)
  1375. //
  1376. struct PIZChannelData {
  1377. unsigned short *start;
  1378. unsigned short *end;
  1379. int nx;
  1380. int ny;
  1381. int ys;
  1382. int size;
  1383. };
  1384. //-----------------------------------------------------------------------------
  1385. //
  1386. // 16-bit Haar Wavelet encoding and decoding
  1387. //
  1388. // The source code in this file is derived from the encoding
  1389. // and decoding routines written by Christian Rouet for his
  1390. // PIZ image file format.
  1391. //
  1392. //-----------------------------------------------------------------------------
  1393. //
  1394. // Wavelet basis functions without modulo arithmetic; they produce
  1395. // the best compression ratios when the wavelet-transformed data are
  1396. // Huffman-encoded, but the wavelet transform works only for 14-bit
  1397. // data (untransformed data values must be less than (1 << 14)).
  1398. //
  1399. inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
  1400. unsigned short &h) {
  1401. short as = static_cast<short>(a);
  1402. short bs = static_cast<short>(b);
  1403. short ms = (as + bs) >> 1;
  1404. short ds = as - bs;
  1405. l = static_cast<unsigned short>(ms);
  1406. h = static_cast<unsigned short>(ds);
  1407. }
  1408. inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
  1409. unsigned short &b) {
  1410. short ls = static_cast<short>(l);
  1411. short hs = static_cast<short>(h);
  1412. int hi = hs;
  1413. int ai = ls + (hi & 1) + (hi >> 1);
  1414. short as = static_cast<short>(ai);
  1415. short bs = static_cast<short>(ai - hi);
  1416. a = static_cast<unsigned short>(as);
  1417. b = static_cast<unsigned short>(bs);
  1418. }
  1419. //
  1420. // Wavelet basis functions with modulo arithmetic; they work with full
  1421. // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
  1422. // compress the data quite as well.
  1423. //
  1424. const int NBITS = 16;
  1425. const int A_OFFSET = 1 << (NBITS - 1);
  1426. const int M_OFFSET = 1 << (NBITS - 1);
  1427. const int MOD_MASK = (1 << NBITS) - 1;
  1428. inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
  1429. unsigned short &h) {
  1430. int ao = (a + A_OFFSET) & MOD_MASK;
  1431. int m = ((ao + b) >> 1);
  1432. int d = ao - b;
  1433. if (d < 0) m = (m + M_OFFSET) & MOD_MASK;
  1434. d &= MOD_MASK;
  1435. l = static_cast<unsigned short>(m);
  1436. h = static_cast<unsigned short>(d);
  1437. }
  1438. inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
  1439. unsigned short &b) {
  1440. int m = l;
  1441. int d = h;
  1442. int bb = (m - (d >> 1)) & MOD_MASK;
  1443. int aa = (d + bb - A_OFFSET) & MOD_MASK;
  1444. b = static_cast<unsigned short>(bb);
  1445. a = static_cast<unsigned short>(aa);
  1446. }
  1447. //
  1448. // 2D Wavelet encoding:
  1449. //
  1450. static void wav2Encode(
  1451. unsigned short *in, // io: values are transformed in place
  1452. int nx, // i : x size
  1453. int ox, // i : x offset
  1454. int ny, // i : y size
  1455. int oy, // i : y offset
  1456. unsigned short mx) // i : maximum in[x][y] value
  1457. {
  1458. bool w14 = (mx < (1 << 14));
  1459. int n = (nx > ny) ? ny : nx;
  1460. int p = 1; // == 1 << level
  1461. int p2 = 2; // == 1 << (level+1)
  1462. //
  1463. // Hierarchical loop on smaller dimension n
  1464. //
  1465. while (p2 <= n) {
  1466. unsigned short *py = in;
  1467. unsigned short *ey = in + oy * (ny - p2);
  1468. int oy1 = oy * p;
  1469. int oy2 = oy * p2;
  1470. int ox1 = ox * p;
  1471. int ox2 = ox * p2;
  1472. unsigned short i00, i01, i10, i11;
  1473. //
  1474. // Y loop
  1475. //
  1476. for (; py <= ey; py += oy2) {
  1477. unsigned short *px = py;
  1478. unsigned short *ex = py + ox * (nx - p2);
  1479. //
  1480. // X loop
  1481. //
  1482. for (; px <= ex; px += ox2) {
  1483. unsigned short *p01 = px + ox1;
  1484. unsigned short *p10 = px + oy1;
  1485. unsigned short *p11 = p10 + ox1;
  1486. //
  1487. // 2D wavelet encoding
  1488. //
  1489. if (w14) {
  1490. wenc14(*px, *p01, i00, i01);
  1491. wenc14(*p10, *p11, i10, i11);
  1492. wenc14(i00, i10, *px, *p10);
  1493. wenc14(i01, i11, *p01, *p11);
  1494. } else {
  1495. wenc16(*px, *p01, i00, i01);
  1496. wenc16(*p10, *p11, i10, i11);
  1497. wenc16(i00, i10, *px, *p10);
  1498. wenc16(i01, i11, *p01, *p11);
  1499. }
  1500. }
  1501. //
  1502. // Encode (1D) odd column (still in Y loop)
  1503. //
  1504. if (nx & p) {
  1505. unsigned short *p10 = px + oy1;
  1506. if (w14)
  1507. wenc14(*px, *p10, i00, *p10);
  1508. else
  1509. wenc16(*px, *p10, i00, *p10);
  1510. *px = i00;
  1511. }
  1512. }
  1513. //
  1514. // Encode (1D) odd line (must loop in X)
  1515. //
  1516. if (ny & p) {
  1517. unsigned short *px = py;
  1518. unsigned short *ex = py + ox * (nx - p2);
  1519. for (; px <= ex; px += ox2) {
  1520. unsigned short *p01 = px + ox1;
  1521. if (w14)
  1522. wenc14(*px, *p01, i00, *p01);
  1523. else
  1524. wenc16(*px, *p01, i00, *p01);
  1525. *px = i00;
  1526. }
  1527. }
  1528. //
  1529. // Next level
  1530. //
  1531. p = p2;
  1532. p2 <<= 1;
  1533. }
  1534. }
  1535. //
  1536. // 2D Wavelet decoding:
  1537. //
  1538. static void wav2Decode(
  1539. unsigned short *in, // io: values are transformed in place
  1540. int nx, // i : x size
  1541. int ox, // i : x offset
  1542. int ny, // i : y size
  1543. int oy, // i : y offset
  1544. unsigned short mx) // i : maximum in[x][y] value
  1545. {
  1546. bool w14 = (mx < (1 << 14));
  1547. int n = (nx > ny) ? ny : nx;
  1548. int p = 1;
  1549. int p2;
  1550. //
  1551. // Search max level
  1552. //
  1553. while (p <= n) p <<= 1;
  1554. p >>= 1;
  1555. p2 = p;
  1556. p >>= 1;
  1557. //
  1558. // Hierarchical loop on smaller dimension n
  1559. //
  1560. while (p >= 1) {
  1561. unsigned short *py = in;
  1562. unsigned short *ey = in + oy * (ny - p2);
  1563. int oy1 = oy * p;
  1564. int oy2 = oy * p2;
  1565. int ox1 = ox * p;
  1566. int ox2 = ox * p2;
  1567. unsigned short i00, i01, i10, i11;
  1568. //
  1569. // Y loop
  1570. //
  1571. for (; py <= ey; py += oy2) {
  1572. unsigned short *px = py;
  1573. unsigned short *ex = py + ox * (nx - p2);
  1574. //
  1575. // X loop
  1576. //
  1577. for (; px <= ex; px += ox2) {
  1578. unsigned short *p01 = px + ox1;
  1579. unsigned short *p10 = px + oy1;
  1580. unsigned short *p11 = p10 + ox1;
  1581. //
  1582. // 2D wavelet decoding
  1583. //
  1584. if (w14) {
  1585. wdec14(*px, *p10, i00, i10);
  1586. wdec14(*p01, *p11, i01, i11);
  1587. wdec14(i00, i01, *px, *p01);
  1588. wdec14(i10, i11, *p10, *p11);
  1589. } else {
  1590. wdec16(*px, *p10, i00, i10);
  1591. wdec16(*p01, *p11, i01, i11);
  1592. wdec16(i00, i01, *px, *p01);
  1593. wdec16(i10, i11, *p10, *p11);
  1594. }
  1595. }
  1596. //
  1597. // Decode (1D) odd column (still in Y loop)
  1598. //
  1599. if (nx & p) {
  1600. unsigned short *p10 = px + oy1;
  1601. if (w14)
  1602. wdec14(*px, *p10, i00, *p10);
  1603. else
  1604. wdec16(*px, *p10, i00, *p10);
  1605. *px = i00;
  1606. }
  1607. }
  1608. //
  1609. // Decode (1D) odd line (must loop in X)
  1610. //
  1611. if (ny & p) {
  1612. unsigned short *px = py;
  1613. unsigned short *ex = py + ox * (nx - p2);
  1614. for (; px <= ex; px += ox2) {
  1615. unsigned short *p01 = px + ox1;
  1616. if (w14)
  1617. wdec14(*px, *p01, i00, *p01);
  1618. else
  1619. wdec16(*px, *p01, i00, *p01);
  1620. *px = i00;
  1621. }
  1622. }
  1623. //
  1624. // Next level
  1625. //
  1626. p2 = p;
  1627. p >>= 1;
  1628. }
  1629. }
  1630. //-----------------------------------------------------------------------------
  1631. //
  1632. // 16-bit Huffman compression and decompression.
  1633. //
  1634. // The source code in this file is derived from the 8-bit
  1635. // Huffman compression and decompression routines written
  1636. // by Christian Rouet for his PIZ image file format.
  1637. //
  1638. //-----------------------------------------------------------------------------
  1639. // Adds some modification for tinyexr.
  1640. const int HUF_ENCBITS = 16; // literal (value) bit length
  1641. const int HUF_DECBITS = 14; // decoding bit size (>= 8)
  1642. const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
  1643. const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  1644. const int HUF_DECMASK = HUF_DECSIZE - 1;
  1645. struct HufDec { // short code long code
  1646. //-------------------------------
  1647. unsigned int len : 8; // code length 0
  1648. unsigned int lit : 24; // lit p size
  1649. unsigned int *p; // 0 lits
  1650. };
  1651. inline long long hufLength(long long code) { return code & 63; }
  1652. inline long long hufCode(long long code) { return code >> 6; }
  1653. inline void outputBits(int nBits, long long bits, long long &c, int &lc,
  1654. char *&out) {
  1655. c <<= nBits;
  1656. lc += nBits;
  1657. c |= bits;
  1658. while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));
  1659. }
  1660. inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
  1661. while (lc < nBits) {
  1662. c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));
  1663. lc += 8;
  1664. }
  1665. lc -= nBits;
  1666. return (c >> lc) & ((1 << nBits) - 1);
  1667. }
  1668. //
  1669. // ENCODING TABLE BUILDING & (UN)PACKING
  1670. //
  1671. //
  1672. // Build a "canonical" Huffman code table:
  1673. // - for each (uncompressed) symbol, hcode contains the length
  1674. // of the corresponding code (in the compressed data)
  1675. // - canonical codes are computed and stored in hcode
  1676. // - the rules for constructing canonical codes are as follows:
  1677. // * shorter codes (if filled with zeroes to the right)
  1678. // have a numerically higher value than longer codes
  1679. // * for codes with the same length, numerical values
  1680. // increase with numerical symbol values
  1681. // - because the canonical code table can be constructed from
  1682. // symbol lengths alone, the code table can be transmitted
  1683. // without sending the actual code values
  1684. // - see http://www.compressconsult.com/huffman/
  1685. //
  1686. static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
  1687. long long n[59];
  1688. //
  1689. // For each i from 0 through 58, count the
  1690. // number of different codes of length i, and
  1691. // store the count in n[i].
  1692. //
  1693. for (int i = 0; i <= 58; ++i) n[i] = 0;
  1694. for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;
  1695. //
  1696. // For each i from 58 through 1, compute the
  1697. // numerically lowest code with length i, and
  1698. // store that code in n[i].
  1699. //
  1700. long long c = 0;
  1701. for (int i = 58; i > 0; --i) {
  1702. long long nc = ((c + n[i]) >> 1);
  1703. n[i] = c;
  1704. c = nc;
  1705. }
  1706. //
  1707. // hcode[i] contains the length, l, of the
  1708. // code for symbol i. Assign the next available
  1709. // code of length l to the symbol and store both
  1710. // l and the code in hcode[i].
  1711. //
  1712. for (int i = 0; i < HUF_ENCSIZE; ++i) {
  1713. int l = static_cast<int>(hcode[i]);
  1714. if (l > 0) hcode[i] = l | (n[l]++ << 6);
  1715. }
  1716. }
  1717. //
  1718. // Compute Huffman codes (based on frq input) and store them in frq:
  1719. // - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
  1720. // - max code length is 58 bits;
  1721. // - codes outside the range [im-iM] have a null length (unused values);
  1722. // - original frequencies are destroyed;
  1723. // - encoding tables are used by hufEncode() and hufBuildDecTable();
  1724. //
  1725. struct FHeapCompare {
  1726. bool operator()(long long *a, long long *b) { return *a > *b; }
  1727. };
  1728. static void hufBuildEncTable(
  1729. long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
  1730. int *im, // o: min frq index
  1731. int *iM) // o: max frq index
  1732. {
  1733. //
  1734. // This function assumes that when it is called, array frq
  1735. // indicates the frequency of all possible symbols in the data
  1736. // that are to be Huffman-encoded. (frq[i] contains the number
  1737. // of occurrences of symbol i in the data.)
  1738. //
  1739. // The loop below does three things:
  1740. //
  1741. // 1) Finds the minimum and maximum indices that point
  1742. // to non-zero entries in frq:
  1743. //
  1744. // frq[im] != 0, and frq[i] == 0 for all i < im
  1745. // frq[iM] != 0, and frq[i] == 0 for all i > iM
  1746. //
  1747. // 2) Fills array fHeap with pointers to all non-zero
  1748. // entries in frq.
  1749. //
  1750. // 3) Initializes array hlink such that hlink[i] == i
  1751. // for all array entries.
  1752. //
  1753. std::vector<int> hlink(HUF_ENCSIZE);
  1754. std::vector<long long *> fHeap(HUF_ENCSIZE);
  1755. *im = 0;
  1756. while (!frq[*im]) (*im)++;
  1757. int nf = 0;
  1758. for (int i = *im; i < HUF_ENCSIZE; i++) {
  1759. hlink[i] = i;
  1760. if (frq[i]) {
  1761. fHeap[nf] = &frq[i];
  1762. nf++;
  1763. *iM = i;
  1764. }
  1765. }
  1766. //
  1767. // Add a pseudo-symbol, with a frequency count of 1, to frq;
  1768. // adjust the fHeap and hlink array accordingly. Function
  1769. // hufEncode() uses the pseudo-symbol for run-length encoding.
  1770. //
  1771. (*iM)++;
  1772. frq[*iM] = 1;
  1773. fHeap[nf] = &frq[*iM];
  1774. nf++;
  1775. //
  1776. // Build an array, scode, such that scode[i] contains the number
  1777. // of bits assigned to symbol i. Conceptually this is done by
  1778. // constructing a tree whose leaves are the symbols with non-zero
  1779. // frequency:
  1780. //
  1781. // Make a heap that contains all symbols with a non-zero frequency,
  1782. // with the least frequent symbol on top.
  1783. //
  1784. // Repeat until only one symbol is left on the heap:
  1785. //
  1786. // Take the two least frequent symbols off the top of the heap.
  1787. // Create a new node that has first two nodes as children, and
  1788. // whose frequency is the sum of the frequencies of the first
  1789. // two nodes. Put the new node back into the heap.
  1790. //
  1791. // The last node left on the heap is the root of the tree. For each
  1792. // leaf node, the distance between the root and the leaf is the length
  1793. // of the code for the corresponding symbol.
  1794. //
  1795. // The loop below doesn't actually build the tree; instead we compute
  1796. // the distances of the leaves from the root on the fly. When a new
  1797. // node is added to the heap, then that node's descendants are linked
  1798. // into a single linear list that starts at the new node, and the code
  1799. // lengths of the descendants (that is, their distance from the root
  1800. // of the tree) are incremented by one.
  1801. //
  1802. std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  1803. std::vector<long long> scode(HUF_ENCSIZE);
  1804. memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
  1805. while (nf > 1) {
  1806. //
  1807. // Find the indices, mm and m, of the two smallest non-zero frq
  1808. // values in fHeap, add the smallest frq to the second-smallest
  1809. // frq, and remove the smallest frq value from fHeap.
  1810. //
  1811. int mm = fHeap[0] - frq;
  1812. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  1813. --nf;
  1814. int m = fHeap[0] - frq;
  1815. std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  1816. frq[m] += frq[mm];
  1817. std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
  1818. //
  1819. // The entries in scode are linked into lists with the
  1820. // entries in hlink serving as "next" pointers and with
  1821. // the end of a list marked by hlink[j] == j.
  1822. //
  1823. // Traverse the lists that start at scode[m] and scode[mm].
  1824. // For each element visited, increment the length of the
  1825. // corresponding code by one bit. (If we visit scode[j]
  1826. // during the traversal, then the code for symbol j becomes
  1827. // one bit longer.)
  1828. //
  1829. // Merge the lists that start at scode[m] and scode[mm]
  1830. // into a single list that starts at scode[m].
  1831. //
  1832. //
  1833. // Add a bit to all codes in the first list.
  1834. //
  1835. for (int j = m;; j = hlink[j]) {
  1836. scode[j]++;
  1837. assert(scode[j] <= 58);
  1838. if (hlink[j] == j) {
  1839. //
  1840. // Merge the two lists.
  1841. //
  1842. hlink[j] = mm;
  1843. break;
  1844. }
  1845. }
  1846. //
  1847. // Add a bit to all codes in the second list
  1848. //
  1849. for (int j = mm;; j = hlink[j]) {
  1850. scode[j]++;
  1851. assert(scode[j] <= 58);
  1852. if (hlink[j] == j) break;
  1853. }
  1854. }
  1855. //
  1856. // Build a canonical Huffman code table, replacing the code
  1857. // lengths in scode with (code, code length) pairs. Copy the
  1858. // code table from scode into frq.
  1859. //
  1860. hufCanonicalCodeTable(scode.data());
  1861. memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
  1862. }
  1863. //
  1864. // Pack an encoding table:
  1865. // - only code lengths, not actual codes, are stored
  1866. // - runs of zeroes are compressed as follows:
  1867. //
  1868. // unpacked packed
  1869. // --------------------------------
  1870. // 1 zero 0 (6 bits)
  1871. // 2 zeroes 59
  1872. // 3 zeroes 60
  1873. // 4 zeroes 61
  1874. // 5 zeroes 62
  1875. // n zeroes (6 or more) 63 n-6 (6 + 8 bits)
  1876. //
  1877. const int SHORT_ZEROCODE_RUN = 59;
  1878. const int LONG_ZEROCODE_RUN = 63;
  1879. const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  1880. const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
  1881. static void hufPackEncTable(
  1882. const long long *hcode, // i : encoding table [HUF_ENCSIZE]
  1883. int im, // i : min hcode index
  1884. int iM, // i : max hcode index
  1885. char **pcode) // o: ptr to packed table (updated)
  1886. {
  1887. char *p = *pcode;
  1888. long long c = 0;
  1889. int lc = 0;
  1890. for (; im <= iM; im++) {
  1891. int l = hufLength(hcode[im]);
  1892. if (l == 0) {
  1893. int zerun = 1;
  1894. while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
  1895. if (hufLength(hcode[im + 1]) > 0) break;
  1896. im++;
  1897. zerun++;
  1898. }
  1899. if (zerun >= 2) {
  1900. if (zerun >= SHORTEST_LONG_RUN) {
  1901. outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
  1902. outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
  1903. } else {
  1904. outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
  1905. }
  1906. continue;
  1907. }
  1908. }
  1909. outputBits(6, l, c, lc, p);
  1910. }
  1911. if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));
  1912. *pcode = p;
  1913. }
  1914. //
  1915. // Unpack an encoding table packed by hufPackEncTable():
  1916. //
  1917. static bool hufUnpackEncTable(
  1918. const char **pcode, // io: ptr to packed table (updated)
  1919. int ni, // i : input size (in bytes)
  1920. int im, // i : min hcode index
  1921. int iM, // i : max hcode index
  1922. long long *hcode) // o: encoding table [HUF_ENCSIZE]
  1923. {
  1924. memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
  1925. const char *p = *pcode;
  1926. long long c = 0;
  1927. int lc = 0;
  1928. for (; im <= iM; im++) {
  1929. if (p - *pcode >= ni) {
  1930. return false;
  1931. }
  1932. long long l = hcode[im] = getBits(6, c, lc, p); // code length
  1933. if (l == (long long)LONG_ZEROCODE_RUN) {
  1934. if (p - *pcode > ni) {
  1935. return false;
  1936. }
  1937. int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
  1938. if (im + zerun > iM + 1) {
  1939. return false;
  1940. }
  1941. while (zerun--) hcode[im++] = 0;
  1942. im--;
  1943. } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
  1944. int zerun = l - SHORT_ZEROCODE_RUN + 2;
  1945. if (im + zerun > iM + 1) {
  1946. return false;
  1947. }
  1948. while (zerun--) hcode[im++] = 0;
  1949. im--;
  1950. }
  1951. }
  1952. *pcode = const_cast<char *>(p);
  1953. hufCanonicalCodeTable(hcode);
  1954. return true;
  1955. }
  1956. //
  1957. // DECODING TABLE BUILDING
  1958. //
  1959. //
  1960. // Clear a newly allocated decoding table so that it contains only zeroes.
  1961. //
  1962. static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
  1963. // decoding table [HUF_DECSIZE]
  1964. {
  1965. for (int i = 0; i < HUF_DECSIZE; i++) {
  1966. hdecod[i].len = 0;
  1967. hdecod[i].lit = 0;
  1968. hdecod[i].p = NULL;
  1969. }
  1970. // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
  1971. }
  1972. //
  1973. // Build a decoding hash table based on the encoding table hcode:
  1974. // - short codes (<= HUF_DECBITS) are resolved with a single table access;
  1975. // - long code entry allocations are not optimized, because long codes are
  1976. // unfrequent;
  1977. // - decoding tables are used by hufDecode();
  1978. //
  1979. static bool hufBuildDecTable(const long long *hcode, // i : encoding table
  1980. int im, // i : min index in hcode
  1981. int iM, // i : max index in hcode
  1982. HufDec *hdecod) // o: (allocated by caller)
  1983. // decoding table [HUF_DECSIZE]
  1984. {
  1985. //
  1986. // Init hashtable & loop on all codes.
  1987. // Assumes that hufClearDecTable(hdecod) has already been called.
  1988. //
  1989. for (; im <= iM; im++) {
  1990. long long c = hufCode(hcode[im]);
  1991. int l = hufLength(hcode[im]);
  1992. if (c >> l) {
  1993. //
  1994. // Error: c is supposed to be an l-bit code,
  1995. // but c contains a value that is greater
  1996. // than the largest l-bit number.
  1997. //
  1998. // invalidTableEntry();
  1999. return false;
  2000. }
  2001. if (l > HUF_DECBITS) {
  2002. //
  2003. // Long code: add a secondary entry
  2004. //
  2005. HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
  2006. if (pl->len) {
  2007. //
  2008. // Error: a short code has already
  2009. // been stored in table entry *pl.
  2010. //
  2011. // invalidTableEntry();
  2012. return false;
  2013. }
  2014. pl->lit++;
  2015. if (pl->p) {
  2016. unsigned int *p = pl->p;
  2017. pl->p = new unsigned int[pl->lit];
  2018. for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i];
  2019. delete[] p;
  2020. } else {
  2021. pl->p = new unsigned int[1];
  2022. }
  2023. pl->p[pl->lit - 1] = im;
  2024. } else if (l) {
  2025. //
  2026. // Short code: init all primary entries
  2027. //
  2028. HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
  2029. for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
  2030. if (pl->len || pl->p) {
  2031. //
  2032. // Error: a short code or a long code has
  2033. // already been stored in table entry *pl.
  2034. //
  2035. // invalidTableEntry();
  2036. return false;
  2037. }
  2038. pl->len = l;
  2039. pl->lit = im;
  2040. }
  2041. }
  2042. }
  2043. return true;
  2044. }
  2045. //
  2046. // Free the long code entries of a decoding table built by hufBuildDecTable()
  2047. //
  2048. static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
  2049. {
  2050. for (int i = 0; i < HUF_DECSIZE; i++) {
  2051. if (hdecod[i].p) {
  2052. delete[] hdecod[i].p;
  2053. hdecod[i].p = 0;
  2054. }
  2055. }
  2056. }
  2057. //
  2058. // ENCODING
  2059. //
  2060. inline void outputCode(long long code, long long &c, int &lc, char *&out) {
  2061. outputBits(hufLength(code), hufCode(code), c, lc, out);
  2062. }
  2063. inline void sendCode(long long sCode, int runCount, long long runCode,
  2064. long long &c, int &lc, char *&out) {
  2065. //
  2066. // Output a run of runCount instances of the symbol sCount.
  2067. // Output the symbols explicitly, or if that is shorter, output
  2068. // the sCode symbol once followed by a runCode symbol and runCount
  2069. // expressed as an 8-bit number.
  2070. //
  2071. if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
  2072. outputCode(sCode, c, lc, out);
  2073. outputCode(runCode, c, lc, out);
  2074. outputBits(8, runCount, c, lc, out);
  2075. } else {
  2076. while (runCount-- >= 0) outputCode(sCode, c, lc, out);
  2077. }
  2078. }
  2079. //
  2080. // Encode (compress) ni values based on the Huffman encoding table hcode:
  2081. //
  2082. static int hufEncode // return: output size (in bits)
  2083. (const long long *hcode, // i : encoding table
  2084. const unsigned short *in, // i : uncompressed input buffer
  2085. const int ni, // i : input buffer size (in bytes)
  2086. int rlc, // i : rl code
  2087. char *out) // o: compressed output buffer
  2088. {
  2089. char *outStart = out;
  2090. long long c = 0; // bits not yet written to out
  2091. int lc = 0; // number of valid bits in c (LSB)
  2092. int s = in[0];
  2093. int cs = 0;
  2094. //
  2095. // Loop on input values
  2096. //
  2097. for (int i = 1; i < ni; i++) {
  2098. //
  2099. // Count same values or send code
  2100. //
  2101. if (s == in[i] && cs < 255) {
  2102. cs++;
  2103. } else {
  2104. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  2105. cs = 0;
  2106. }
  2107. s = in[i];
  2108. }
  2109. //
  2110. // Send remaining code
  2111. //
  2112. sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
  2113. if (lc) *out = (c << (8 - lc)) & 0xff;
  2114. return (out - outStart) * 8 + lc;
  2115. }
  2116. //
  2117. // DECODING
  2118. //
  2119. //
  2120. // In order to force the compiler to inline them,
  2121. // getChar() and getCode() are implemented as macros
  2122. // instead of "inline" functions.
  2123. //
  2124. #define getChar(c, lc, in) \
  2125. { \
  2126. c = (c << 8) | *(unsigned char *)(in++); \
  2127. lc += 8; \
  2128. }
  2129. #if 0
  2130. #define getCode(po, rlc, c, lc, in, out, ob, oe) \
  2131. { \
  2132. if (po == rlc) { \
  2133. if (lc < 8) getChar(c, lc, in); \
  2134. \
  2135. lc -= 8; \
  2136. \
  2137. unsigned char cs = (c >> lc); \
  2138. \
  2139. if (out + cs > oe) return false; \
  2140. \
  2141. /* TinyEXR issue 78 */ \
  2142. unsigned short s = out[-1]; \
  2143. \
  2144. while (cs-- > 0) *out++ = s; \
  2145. } else if (out < oe) { \
  2146. *out++ = po; \
  2147. } else { \
  2148. return false; \
  2149. } \
  2150. }
  2151. #else
  2152. static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,
  2153. const char *in_end, unsigned short *&out,
  2154. const unsigned short *ob, const unsigned short *oe) {
  2155. (void)ob;
  2156. if (po == rlc) {
  2157. if (lc < 8) {
  2158. /* TinyEXR issue 78 */
  2159. /* TinyEXR issue 160. in + 1 -> in */
  2160. if (in >= in_end) {
  2161. return false;
  2162. }
  2163. getChar(c, lc, in);
  2164. }
  2165. lc -= 8;
  2166. unsigned char cs = (c >> lc);
  2167. if (out + cs > oe) return false;
  2168. // Bounds check for safety
  2169. // Issue 100.
  2170. if ((out - 1) < ob) return false;
  2171. unsigned short s = out[-1];
  2172. while (cs-- > 0) *out++ = s;
  2173. } else if (out < oe) {
  2174. *out++ = po;
  2175. } else {
  2176. return false;
  2177. }
  2178. return true;
  2179. }
  2180. #endif
  2181. //
  2182. // Decode (uncompress) ni bits based on encoding & decoding tables:
  2183. //
  2184. static bool hufDecode(const long long *hcode, // i : encoding table
  2185. const HufDec *hdecod, // i : decoding table
  2186. const char *in, // i : compressed input buffer
  2187. int ni, // i : input size (in bits)
  2188. int rlc, // i : run-length code
  2189. int no, // i : expected output size (in bytes)
  2190. unsigned short *out) // o: uncompressed output buffer
  2191. {
  2192. long long c = 0;
  2193. int lc = 0;
  2194. unsigned short *outb = out; // begin
  2195. unsigned short *oe = out + no; // end
  2196. const char *ie = in + (ni + 7) / 8; // input byte size
  2197. //
  2198. // Loop on input bytes
  2199. //
  2200. while (in < ie) {
  2201. getChar(c, lc, in);
  2202. //
  2203. // Access decoding table
  2204. //
  2205. while (lc >= HUF_DECBITS) {
  2206. const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
  2207. if (pl.len) {
  2208. //
  2209. // Get short code
  2210. //
  2211. lc -= pl.len;
  2212. // std::cout << "lit = " << pl.lit << std::endl;
  2213. // std::cout << "rlc = " << rlc << std::endl;
  2214. // std::cout << "c = " << c << std::endl;
  2215. // std::cout << "lc = " << lc << std::endl;
  2216. // std::cout << "in = " << in << std::endl;
  2217. // std::cout << "out = " << out << std::endl;
  2218. // std::cout << "oe = " << oe << std::endl;
  2219. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  2220. return false;
  2221. }
  2222. } else {
  2223. if (!pl.p) {
  2224. return false;
  2225. }
  2226. // invalidCode(); // wrong code
  2227. //
  2228. // Search long code
  2229. //
  2230. int j;
  2231. for (j = 0; j < pl.lit; j++) {
  2232. int l = hufLength(hcode[pl.p[j]]);
  2233. while (lc < l && in < ie) // get more bits
  2234. getChar(c, lc, in);
  2235. if (lc >= l) {
  2236. if (hufCode(hcode[pl.p[j]]) ==
  2237. ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
  2238. //
  2239. // Found : get long code
  2240. //
  2241. lc -= l;
  2242. if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
  2243. return false;
  2244. }
  2245. break;
  2246. }
  2247. }
  2248. }
  2249. if (j == pl.lit) {
  2250. return false;
  2251. // invalidCode(); // Not found
  2252. }
  2253. }
  2254. }
  2255. }
  2256. //
  2257. // Get remaining (short) codes
  2258. //
  2259. int i = (8 - ni) & 7;
  2260. c >>= i;
  2261. lc -= i;
  2262. while (lc > 0) {
  2263. const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
  2264. if (pl.len) {
  2265. lc -= pl.len;
  2266. if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
  2267. return false;
  2268. }
  2269. } else {
  2270. return false;
  2271. // invalidCode(); // wrong (long) code
  2272. }
  2273. }
  2274. if (out - outb != no) {
  2275. return false;
  2276. }
  2277. // notEnoughData ();
  2278. return true;
  2279. }
  2280. static void countFrequencies(std::vector<long long> &freq,
  2281. const unsigned short data[/*n*/], int n) {
  2282. for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;
  2283. for (int i = 0; i < n; ++i) ++freq[data[i]];
  2284. }
  2285. static void writeUInt(char buf[4], unsigned int i) {
  2286. unsigned char *b = (unsigned char *)buf;
  2287. b[0] = i;
  2288. b[1] = i >> 8;
  2289. b[2] = i >> 16;
  2290. b[3] = i >> 24;
  2291. }
  2292. static unsigned int readUInt(const char buf[4]) {
  2293. const unsigned char *b = (const unsigned char *)buf;
  2294. return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
  2295. ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
  2296. }
  2297. //
  2298. // EXTERNAL INTERFACE
  2299. //
  2300. static int hufCompress(const unsigned short raw[], int nRaw,
  2301. char compressed[]) {
  2302. if (nRaw == 0) return 0;
  2303. std::vector<long long> freq(HUF_ENCSIZE);
  2304. countFrequencies(freq, raw, nRaw);
  2305. int im = 0;
  2306. int iM = 0;
  2307. hufBuildEncTable(freq.data(), &im, &iM);
  2308. char *tableStart = compressed + 20;
  2309. char *tableEnd = tableStart;
  2310. hufPackEncTable(freq.data(), im, iM, &tableEnd);
  2311. int tableLength = tableEnd - tableStart;
  2312. char *dataStart = tableEnd;
  2313. int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
  2314. int data_length = (nBits + 7) / 8;
  2315. writeUInt(compressed, im);
  2316. writeUInt(compressed + 4, iM);
  2317. writeUInt(compressed + 8, tableLength);
  2318. writeUInt(compressed + 12, nBits);
  2319. writeUInt(compressed + 16, 0); // room for future extensions
  2320. return dataStart + data_length - compressed;
  2321. }
  2322. static bool hufUncompress(const char compressed[], int nCompressed,
  2323. std::vector<unsigned short> *raw) {
  2324. if (nCompressed == 0) {
  2325. if (raw->size() != 0) return false;
  2326. return false;
  2327. }
  2328. int im = readUInt(compressed);
  2329. int iM = readUInt(compressed + 4);
  2330. // int tableLength = readUInt (compressed + 8);
  2331. int nBits = readUInt(compressed + 12);
  2332. if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;
  2333. const char *ptr = compressed + 20;
  2334. //
  2335. // Fast decoder needs at least 2x64-bits of compressed data, and
  2336. // needs to be run-able on this platform. Otherwise, fall back
  2337. // to the original decoder
  2338. //
  2339. // if (FastHufDecoder::enabled() && nBits > 128)
  2340. //{
  2341. // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
  2342. // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
  2343. //}
  2344. // else
  2345. {
  2346. std::vector<long long> freq(HUF_ENCSIZE);
  2347. std::vector<HufDec> hdec(HUF_DECSIZE);
  2348. hufClearDecTable(&hdec.at(0));
  2349. hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
  2350. &freq.at(0));
  2351. {
  2352. if (nBits > 8 * (nCompressed - (ptr - compressed))) {
  2353. return false;
  2354. }
  2355. hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
  2356. hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
  2357. raw->data());
  2358. }
  2359. // catch (...)
  2360. //{
  2361. // hufFreeDecTable (hdec);
  2362. // throw;
  2363. //}
  2364. hufFreeDecTable(&hdec.at(0));
  2365. }
  2366. return true;
  2367. }
  2368. //
  2369. // Functions to compress the range of values in the pixel data
  2370. //
  2371. const int USHORT_RANGE = (1 << 16);
  2372. const int BITMAP_SIZE = (USHORT_RANGE >> 3);
  2373. static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
  2374. unsigned char bitmap[BITMAP_SIZE],
  2375. unsigned short &minNonZero,
  2376. unsigned short &maxNonZero) {
  2377. for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;
  2378. for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
  2379. bitmap[0] &= ~1; // zero is not explicitly stored in
  2380. // the bitmap; we assume that the
  2381. // data always contain zeroes
  2382. minNonZero = BITMAP_SIZE - 1;
  2383. maxNonZero = 0;
  2384. for (int i = 0; i < BITMAP_SIZE; ++i) {
  2385. if (bitmap[i]) {
  2386. if (minNonZero > i) minNonZero = i;
  2387. if (maxNonZero < i) maxNonZero = i;
  2388. }
  2389. }
  2390. }
  2391. static unsigned short forwardLutFromBitmap(
  2392. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  2393. int k = 0;
  2394. for (int i = 0; i < USHORT_RANGE; ++i) {
  2395. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
  2396. lut[i] = k++;
  2397. else
  2398. lut[i] = 0;
  2399. }
  2400. return k - 1; // maximum value stored in lut[],
  2401. } // i.e. number of ones in bitmap minus 1
  2402. static unsigned short reverseLutFromBitmap(
  2403. const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
  2404. int k = 0;
  2405. for (int i = 0; i < USHORT_RANGE; ++i) {
  2406. if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;
  2407. }
  2408. int n = k - 1;
  2409. while (k < USHORT_RANGE) lut[k++] = 0;
  2410. return n; // maximum k where lut[k] is non-zero,
  2411. } // i.e. number of ones in bitmap minus 1
  2412. static void applyLut(const unsigned short lut[USHORT_RANGE],
  2413. unsigned short data[/*nData*/], int nData) {
  2414. for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];
  2415. }
  2416. #ifdef __clang__
  2417. #pragma clang diagnostic pop
  2418. #endif // __clang__
  2419. #ifdef _MSC_VER
  2420. #pragma warning(pop)
  2421. #endif
  2422. static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,
  2423. const unsigned char *inPtr, size_t inSize,
  2424. const std::vector<ChannelInfo> &channelInfo,
  2425. int data_width, int num_lines) {
  2426. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  2427. unsigned short minNonZero;
  2428. unsigned short maxNonZero;
  2429. #if !TINYEXR_LITTLE_ENDIAN
  2430. // @todo { PIZ compression on BigEndian architecture. }
  2431. assert(0);
  2432. return false;
  2433. #endif
  2434. // Assume `inSize` is multiple of 2 or 4.
  2435. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
  2436. std::vector<PIZChannelData> channelData(channelInfo.size());
  2437. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  2438. for (size_t c = 0; c < channelData.size(); c++) {
  2439. PIZChannelData &cd = channelData[c];
  2440. cd.start = tmpBufferEnd;
  2441. cd.end = cd.start;
  2442. cd.nx = data_width;
  2443. cd.ny = num_lines;
  2444. // cd.ys = c.channel().ySampling;
  2445. size_t pixelSize = sizeof(int); // UINT and FLOAT
  2446. if (channelInfo[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
  2447. pixelSize = sizeof(short);
  2448. }
  2449. cd.size = static_cast<int>(pixelSize / sizeof(short));
  2450. tmpBufferEnd += cd.nx * cd.ny * cd.size;
  2451. }
  2452. const unsigned char *ptr = inPtr;
  2453. for (int y = 0; y < num_lines; ++y) {
  2454. for (size_t i = 0; i < channelData.size(); ++i) {
  2455. PIZChannelData &cd = channelData[i];
  2456. // if (modp (y, cd.ys) != 0)
  2457. // continue;
  2458. size_t n = static_cast<size_t>(cd.nx * cd.size);
  2459. memcpy(cd.end, ptr, n * sizeof(unsigned short));
  2460. ptr += n * sizeof(unsigned short);
  2461. cd.end += n;
  2462. }
  2463. }
  2464. bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
  2465. bitmap.data(), minNonZero, maxNonZero);
  2466. std::vector<unsigned short> lut(USHORT_RANGE);
  2467. unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
  2468. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
  2469. //
  2470. // Store range compression info in _outBuffer
  2471. //
  2472. char *buf = reinterpret_cast<char *>(outPtr);
  2473. memcpy(buf, &minNonZero, sizeof(unsigned short));
  2474. buf += sizeof(unsigned short);
  2475. memcpy(buf, &maxNonZero, sizeof(unsigned short));
  2476. buf += sizeof(unsigned short);
  2477. if (minNonZero <= maxNonZero) {
  2478. memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),
  2479. maxNonZero - minNonZero + 1);
  2480. buf += maxNonZero - minNonZero + 1;
  2481. }
  2482. //
  2483. // Apply wavelet encoding
  2484. //
  2485. for (size_t i = 0; i < channelData.size(); ++i) {
  2486. PIZChannelData &cd = channelData[i];
  2487. for (int j = 0; j < cd.size; ++j) {
  2488. wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  2489. maxValue);
  2490. }
  2491. }
  2492. //
  2493. // Apply Huffman encoding; append the result to _outBuffer
  2494. //
  2495. // length header(4byte), then huff data. Initialize length header with zero,
  2496. // then later fill it by `length`.
  2497. char *lengthPtr = buf;
  2498. int zero = 0;
  2499. memcpy(buf, &zero, sizeof(int));
  2500. buf += sizeof(int);
  2501. int length =
  2502. hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
  2503. memcpy(lengthPtr, &length, sizeof(int));
  2504. (*outSize) = static_cast<unsigned int>(
  2505. (reinterpret_cast<unsigned char *>(buf) - outPtr) +
  2506. static_cast<unsigned int>(length));
  2507. // Use uncompressed data when compressed data is larger than uncompressed.
  2508. // (Issue 40)
  2509. if ((*outSize) >= inSize) {
  2510. (*outSize) = static_cast<unsigned int>(inSize);
  2511. memcpy(outPtr, inPtr, inSize);
  2512. }
  2513. return true;
  2514. }
  2515. static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,
  2516. size_t tmpBufSizeInBytes, size_t inLen, int num_channels,
  2517. const EXRChannelInfo *channels, int data_width,
  2518. int num_lines) {
  2519. if (inLen == tmpBufSizeInBytes) {
  2520. // Data is not compressed(Issue 40).
  2521. memcpy(outPtr, inPtr, inLen);
  2522. return true;
  2523. }
  2524. std::vector<unsigned char> bitmap(BITMAP_SIZE);
  2525. unsigned short minNonZero;
  2526. unsigned short maxNonZero;
  2527. #if !TINYEXR_LITTLE_ENDIAN
  2528. // @todo { PIZ compression on BigEndian architecture. }
  2529. assert(0);
  2530. return false;
  2531. #endif
  2532. memset(bitmap.data(), 0, BITMAP_SIZE);
  2533. const unsigned char *ptr = inPtr;
  2534. // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
  2535. tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));
  2536. // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
  2537. tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));
  2538. ptr += 4;
  2539. if (maxNonZero >= BITMAP_SIZE) {
  2540. return false;
  2541. }
  2542. if (minNonZero <= maxNonZero) {
  2543. memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,
  2544. maxNonZero - minNonZero + 1);
  2545. ptr += maxNonZero - minNonZero + 1;
  2546. }
  2547. std::vector<unsigned short> lut(USHORT_RANGE);
  2548. memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
  2549. unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
  2550. //
  2551. // Huffman decoding
  2552. //
  2553. int length;
  2554. // length = *(reinterpret_cast<const int *>(ptr));
  2555. tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));
  2556. ptr += sizeof(int);
  2557. if (size_t((ptr - inPtr) + length) > inLen) {
  2558. return false;
  2559. }
  2560. std::vector<unsigned short> tmpBuffer(tmpBufSizeInBytes / sizeof(unsigned short));
  2561. hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);
  2562. //
  2563. // Wavelet decoding
  2564. //
  2565. std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
  2566. unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
  2567. for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
  2568. const EXRChannelInfo &chan = channels[i];
  2569. size_t pixelSize = sizeof(int); // UINT and FLOAT
  2570. if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
  2571. pixelSize = sizeof(short);
  2572. }
  2573. channelData[i].start = tmpBufferEnd;
  2574. channelData[i].end = channelData[i].start;
  2575. channelData[i].nx = data_width;
  2576. channelData[i].ny = num_lines;
  2577. // channelData[i].ys = 1;
  2578. channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
  2579. tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
  2580. }
  2581. for (size_t i = 0; i < channelData.size(); ++i) {
  2582. PIZChannelData &cd = channelData[i];
  2583. for (int j = 0; j < cd.size; ++j) {
  2584. wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
  2585. maxValue);
  2586. }
  2587. }
  2588. //
  2589. // Expand the pixel data to their original range
  2590. //
  2591. applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSizeInBytes / sizeof(unsigned short)));
  2592. for (int y = 0; y < num_lines; y++) {
  2593. for (size_t i = 0; i < channelData.size(); ++i) {
  2594. PIZChannelData &cd = channelData[i];
  2595. // if (modp (y, cd.ys) != 0)
  2596. // continue;
  2597. size_t n = static_cast<size_t>(cd.nx * cd.size);
  2598. memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
  2599. outPtr += n * sizeof(unsigned short);
  2600. cd.end += n;
  2601. }
  2602. }
  2603. return true;
  2604. }
  2605. #endif // TINYEXR_USE_PIZ
  2606. #if TINYEXR_USE_ZFP
  2607. struct ZFPCompressionParam {
  2608. double rate;
  2609. unsigned int precision;
  2610. unsigned int __pad0;
  2611. double tolerance;
  2612. int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
  2613. unsigned int __pad1;
  2614. ZFPCompressionParam() {
  2615. type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;
  2616. rate = 2.0;
  2617. precision = 0;
  2618. tolerance = 0.0;
  2619. }
  2620. };
  2621. static bool FindZFPCompressionParam(ZFPCompressionParam *param,
  2622. const EXRAttribute *attributes,
  2623. int num_attributes, std::string *err) {
  2624. bool foundType = false;
  2625. for (int i = 0; i < num_attributes; i++) {
  2626. if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) {
  2627. if (attributes[i].size == 1) {
  2628. param->type = static_cast<int>(attributes[i].value[0]);
  2629. foundType = true;
  2630. break;
  2631. } else {
  2632. if (err) {
  2633. (*err) +=
  2634. "zfpCompressionType attribute must be uchar(1 byte) type.\n";
  2635. }
  2636. return false;
  2637. }
  2638. }
  2639. }
  2640. if (!foundType) {
  2641. if (err) {
  2642. (*err) += "`zfpCompressionType` attribute not found.\n";
  2643. }
  2644. return false;
  2645. }
  2646. if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  2647. for (int i = 0; i < num_attributes; i++) {
  2648. if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&
  2649. (attributes[i].size == 8)) {
  2650. param->rate = *(reinterpret_cast<double *>(attributes[i].value));
  2651. return true;
  2652. }
  2653. }
  2654. if (err) {
  2655. (*err) += "`zfpCompressionRate` attribute not found.\n";
  2656. }
  2657. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  2658. for (int i = 0; i < num_attributes; i++) {
  2659. if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&
  2660. (attributes[i].size == 4)) {
  2661. param->rate = *(reinterpret_cast<int *>(attributes[i].value));
  2662. return true;
  2663. }
  2664. }
  2665. if (err) {
  2666. (*err) += "`zfpCompressionPrecision` attribute not found.\n";
  2667. }
  2668. } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  2669. for (int i = 0; i < num_attributes; i++) {
  2670. if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&
  2671. (attributes[i].size == 8)) {
  2672. param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));
  2673. return true;
  2674. }
  2675. }
  2676. if (err) {
  2677. (*err) += "`zfpCompressionTolerance` attribute not found.\n";
  2678. }
  2679. } else {
  2680. if (err) {
  2681. (*err) += "Unknown value specified for `zfpCompressionType`.\n";
  2682. }
  2683. }
  2684. return false;
  2685. }
  2686. // Assume pixel format is FLOAT for all channels.
  2687. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,
  2688. size_t num_channels, const unsigned char *src,
  2689. unsigned long src_size,
  2690. const ZFPCompressionParam &param) {
  2691. size_t uncompressed_size =
  2692. size_t(dst_width) * size_t(dst_num_lines) * num_channels;
  2693. if (uncompressed_size == src_size) {
  2694. // Data is not compressed(Issue 40).
  2695. memcpy(dst, src, src_size);
  2696. }
  2697. zfp_stream *zfp = NULL;
  2698. zfp_field *field = NULL;
  2699. assert((dst_width % 4) == 0);
  2700. assert((dst_num_lines % 4) == 0);
  2701. if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) {
  2702. return false;
  2703. }
  2704. field =
  2705. zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),
  2706. zfp_type_float, static_cast<unsigned int>(dst_width),
  2707. static_cast<unsigned int>(dst_num_lines) *
  2708. static_cast<unsigned int>(num_channels));
  2709. zfp = zfp_stream_open(NULL);
  2710. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  2711. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2,
  2712. /* write random access */ 0);
  2713. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  2714. zfp_stream_set_precision(zfp, param.precision);
  2715. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  2716. zfp_stream_set_accuracy(zfp, param.tolerance);
  2717. } else {
  2718. assert(0);
  2719. }
  2720. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  2721. std::vector<unsigned char> buf(buf_size);
  2722. memcpy(&buf.at(0), src, src_size);
  2723. bitstream *stream = stream_open(&buf.at(0), buf_size);
  2724. zfp_stream_set_bit_stream(zfp, stream);
  2725. zfp_stream_rewind(zfp);
  2726. size_t image_size = size_t(dst_width) * size_t(dst_num_lines);
  2727. for (size_t c = 0; c < size_t(num_channels); c++) {
  2728. // decompress 4x4 pixel block.
  2729. for (size_t y = 0; y < size_t(dst_num_lines); y += 4) {
  2730. for (size_t x = 0; x < size_t(dst_width); x += 4) {
  2731. float fblock[16];
  2732. zfp_decode_block_float_2(zfp, fblock);
  2733. for (size_t j = 0; j < 4; j++) {
  2734. for (size_t i = 0; i < 4; i++) {
  2735. dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] =
  2736. fblock[j * 4 + i];
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. zfp_field_free(field);
  2743. zfp_stream_close(zfp);
  2744. stream_close(stream);
  2745. return true;
  2746. }
  2747. // Assume pixel format is FLOAT for all channels.
  2748. static bool CompressZfp(std::vector<unsigned char> *outBuf,
  2749. unsigned int *outSize, const float *inPtr, int width,
  2750. int num_lines, int num_channels,
  2751. const ZFPCompressionParam &param) {
  2752. zfp_stream *zfp = NULL;
  2753. zfp_field *field = NULL;
  2754. assert((width % 4) == 0);
  2755. assert((num_lines % 4) == 0);
  2756. if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) {
  2757. return false;
  2758. }
  2759. // create input array.
  2760. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),
  2761. zfp_type_float, static_cast<unsigned int>(width),
  2762. static_cast<unsigned int>(num_lines * num_channels));
  2763. zfp = zfp_stream_open(NULL);
  2764. if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
  2765. zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
  2766. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
  2767. zfp_stream_set_precision(zfp, param.precision);
  2768. } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
  2769. zfp_stream_set_accuracy(zfp, param.tolerance);
  2770. } else {
  2771. assert(0);
  2772. }
  2773. size_t buf_size = zfp_stream_maximum_size(zfp, field);
  2774. outBuf->resize(buf_size);
  2775. bitstream *stream = stream_open(&outBuf->at(0), buf_size);
  2776. zfp_stream_set_bit_stream(zfp, stream);
  2777. zfp_field_free(field);
  2778. size_t image_size = size_t(width) * size_t(num_lines);
  2779. for (size_t c = 0; c < size_t(num_channels); c++) {
  2780. // compress 4x4 pixel block.
  2781. for (size_t y = 0; y < size_t(num_lines); y += 4) {
  2782. for (size_t x = 0; x < size_t(width); x += 4) {
  2783. float fblock[16];
  2784. for (size_t j = 0; j < 4; j++) {
  2785. for (size_t i = 0; i < 4; i++) {
  2786. fblock[j * 4 + i] =
  2787. inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))];
  2788. }
  2789. }
  2790. zfp_encode_block_float_2(zfp, fblock);
  2791. }
  2792. }
  2793. }
  2794. zfp_stream_flush(zfp);
  2795. (*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp));
  2796. zfp_stream_close(zfp);
  2797. return true;
  2798. }
  2799. #endif
  2800. //
  2801. // -----------------------------------------------------------------
  2802. //
  2803. // heuristics
  2804. #define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192)
  2805. // TODO(syoyo): Refactor function arguments.
  2806. static bool DecodePixelData(/* out */ unsigned char **out_images,
  2807. const int *requested_pixel_types,
  2808. const unsigned char *data_ptr, size_t data_len,
  2809. int compression_type, int line_order, int width,
  2810. int height, int x_stride, int y, int line_no,
  2811. int num_lines, size_t pixel_data_size,
  2812. size_t num_attributes,
  2813. const EXRAttribute *attributes, size_t num_channels,
  2814. const EXRChannelInfo *channels,
  2815. const std::vector<size_t> &channel_offset_list) {
  2816. if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
  2817. #if TINYEXR_USE_PIZ
  2818. if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
  2819. // Invalid input #90
  2820. return false;
  2821. }
  2822. // Allocate original data size.
  2823. std::vector<unsigned char> outBuf(static_cast<size_t>(
  2824. static_cast<size_t>(width * num_lines) * pixel_data_size));
  2825. size_t tmpBufLen = outBuf.size();
  2826. bool ret = tinyexr::DecompressPiz(
  2827. reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,
  2828. data_len, static_cast<int>(num_channels), channels, width, num_lines);
  2829. if (!ret) {
  2830. return false;
  2831. }
  2832. // For PIZ_COMPRESSION:
  2833. // pixel sample data for channel 0 for scanline 0
  2834. // pixel sample data for channel 1 for scanline 0
  2835. // pixel sample data for channel ... for scanline 0
  2836. // pixel sample data for channel n for scanline 0
  2837. // pixel sample data for channel 0 for scanline 1
  2838. // pixel sample data for channel 1 for scanline 1
  2839. // pixel sample data for channel ... for scanline 1
  2840. // pixel sample data for channel n for scanline 1
  2841. // ...
  2842. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  2843. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  2844. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  2845. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  2846. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  2847. channel_offset_list[c] * static_cast<size_t>(width)));
  2848. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  2849. FP16 hf;
  2850. // hf.u = line_ptr[u];
  2851. // use `cpy` to avoid unaligned memory access when compiler's
  2852. // optimization is on.
  2853. tinyexr::cpy2(&(hf.u), line_ptr + u);
  2854. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  2855. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  2856. unsigned short *image =
  2857. reinterpret_cast<unsigned short **>(out_images)[c];
  2858. if (line_order == 0) {
  2859. image += (static_cast<size_t>(line_no) + v) *
  2860. static_cast<size_t>(x_stride) +
  2861. u;
  2862. } else {
  2863. image += static_cast<size_t>(
  2864. (height - 1 - (line_no + static_cast<int>(v)))) *
  2865. static_cast<size_t>(x_stride) +
  2866. u;
  2867. }
  2868. *image = hf.u;
  2869. } else { // HALF -> FLOAT
  2870. FP32 f32 = half_to_float(hf);
  2871. float *image = reinterpret_cast<float **>(out_images)[c];
  2872. size_t offset = 0;
  2873. if (line_order == 0) {
  2874. offset = (static_cast<size_t>(line_no) + v) *
  2875. static_cast<size_t>(x_stride) +
  2876. u;
  2877. } else {
  2878. offset = static_cast<size_t>(
  2879. (height - 1 - (line_no + static_cast<int>(v)))) *
  2880. static_cast<size_t>(x_stride) +
  2881. u;
  2882. }
  2883. image += offset;
  2884. *image = f32.f;
  2885. }
  2886. }
  2887. }
  2888. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  2889. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  2890. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  2891. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  2892. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  2893. channel_offset_list[c] * static_cast<size_t>(width)));
  2894. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  2895. unsigned int val;
  2896. // val = line_ptr[u];
  2897. tinyexr::cpy4(&val, line_ptr + u);
  2898. tinyexr::swap4(&val);
  2899. unsigned int *image =
  2900. reinterpret_cast<unsigned int **>(out_images)[c];
  2901. if (line_order == 0) {
  2902. image += (static_cast<size_t>(line_no) + v) *
  2903. static_cast<size_t>(x_stride) +
  2904. u;
  2905. } else {
  2906. image += static_cast<size_t>(
  2907. (height - 1 - (line_no + static_cast<int>(v)))) *
  2908. static_cast<size_t>(x_stride) +
  2909. u;
  2910. }
  2911. *image = val;
  2912. }
  2913. }
  2914. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  2915. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  2916. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  2917. const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(
  2918. v * pixel_data_size * static_cast<size_t>(x_stride) +
  2919. channel_offset_list[c] * static_cast<size_t>(x_stride)));
  2920. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  2921. float val;
  2922. // val = line_ptr[u];
  2923. tinyexr::cpy4(&val, line_ptr + u);
  2924. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  2925. float *image = reinterpret_cast<float **>(out_images)[c];
  2926. if (line_order == 0) {
  2927. image += (static_cast<size_t>(line_no) + v) *
  2928. static_cast<size_t>(x_stride) +
  2929. u;
  2930. } else {
  2931. image += static_cast<size_t>(
  2932. (height - 1 - (line_no + static_cast<int>(v)))) *
  2933. static_cast<size_t>(x_stride) +
  2934. u;
  2935. }
  2936. *image = val;
  2937. }
  2938. }
  2939. } else {
  2940. assert(0);
  2941. }
  2942. }
  2943. #else
  2944. assert(0 && "PIZ is enabled in this build");
  2945. return false;
  2946. #endif
  2947. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||
  2948. compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  2949. // Allocate original data size.
  2950. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  2951. static_cast<size_t>(num_lines) *
  2952. pixel_data_size);
  2953. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  2954. assert(dstLen > 0);
  2955. if (!tinyexr::DecompressZip(
  2956. reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,
  2957. static_cast<unsigned long>(data_len))) {
  2958. return false;
  2959. }
  2960. // For ZIP_COMPRESSION:
  2961. // pixel sample data for channel 0 for scanline 0
  2962. // pixel sample data for channel 1 for scanline 0
  2963. // pixel sample data for channel ... for scanline 0
  2964. // pixel sample data for channel n for scanline 0
  2965. // pixel sample data for channel 0 for scanline 1
  2966. // pixel sample data for channel 1 for scanline 1
  2967. // pixel sample data for channel ... for scanline 1
  2968. // pixel sample data for channel n for scanline 1
  2969. // ...
  2970. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  2971. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  2972. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  2973. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  2974. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  2975. static_cast<size_t>(width) +
  2976. channel_offset_list[c] * static_cast<size_t>(width)));
  2977. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  2978. tinyexr::FP16 hf;
  2979. // hf.u = line_ptr[u];
  2980. tinyexr::cpy2(&(hf.u), line_ptr + u);
  2981. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  2982. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  2983. unsigned short *image =
  2984. reinterpret_cast<unsigned short **>(out_images)[c];
  2985. if (line_order == 0) {
  2986. image += (static_cast<size_t>(line_no) + v) *
  2987. static_cast<size_t>(x_stride) +
  2988. u;
  2989. } else {
  2990. image += (static_cast<size_t>(height) - 1U -
  2991. (static_cast<size_t>(line_no) + v)) *
  2992. static_cast<size_t>(x_stride) +
  2993. u;
  2994. }
  2995. *image = hf.u;
  2996. } else { // HALF -> FLOAT
  2997. tinyexr::FP32 f32 = half_to_float(hf);
  2998. float *image = reinterpret_cast<float **>(out_images)[c];
  2999. size_t offset = 0;
  3000. if (line_order == 0) {
  3001. offset = (static_cast<size_t>(line_no) + v) *
  3002. static_cast<size_t>(x_stride) +
  3003. u;
  3004. } else {
  3005. offset = (static_cast<size_t>(height) - 1U -
  3006. (static_cast<size_t>(line_no) + v)) *
  3007. static_cast<size_t>(x_stride) +
  3008. u;
  3009. }
  3010. image += offset;
  3011. *image = f32.f;
  3012. }
  3013. }
  3014. }
  3015. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  3016. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  3017. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3018. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  3019. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  3020. channel_offset_list[c] * static_cast<size_t>(width)));
  3021. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3022. unsigned int val;
  3023. // val = line_ptr[u];
  3024. tinyexr::cpy4(&val, line_ptr + u);
  3025. tinyexr::swap4(&val);
  3026. unsigned int *image =
  3027. reinterpret_cast<unsigned int **>(out_images)[c];
  3028. if (line_order == 0) {
  3029. image += (static_cast<size_t>(line_no) + v) *
  3030. static_cast<size_t>(x_stride) +
  3031. u;
  3032. } else {
  3033. image += (static_cast<size_t>(height) - 1U -
  3034. (static_cast<size_t>(line_no) + v)) *
  3035. static_cast<size_t>(x_stride) +
  3036. u;
  3037. }
  3038. *image = val;
  3039. }
  3040. }
  3041. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3042. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  3043. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3044. const float *line_ptr = reinterpret_cast<float *>(
  3045. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  3046. channel_offset_list[c] * static_cast<size_t>(width)));
  3047. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3048. float val;
  3049. // val = line_ptr[u];
  3050. tinyexr::cpy4(&val, line_ptr + u);
  3051. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  3052. float *image = reinterpret_cast<float **>(out_images)[c];
  3053. if (line_order == 0) {
  3054. image += (static_cast<size_t>(line_no) + v) *
  3055. static_cast<size_t>(x_stride) +
  3056. u;
  3057. } else {
  3058. image += (static_cast<size_t>(height) - 1U -
  3059. (static_cast<size_t>(line_no) + v)) *
  3060. static_cast<size_t>(x_stride) +
  3061. u;
  3062. }
  3063. *image = val;
  3064. }
  3065. }
  3066. } else {
  3067. assert(0);
  3068. return false;
  3069. }
  3070. }
  3071. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  3072. // Allocate original data size.
  3073. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  3074. static_cast<size_t>(num_lines) *
  3075. pixel_data_size);
  3076. unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
  3077. if (dstLen == 0) {
  3078. return false;
  3079. }
  3080. if (!tinyexr::DecompressRle(
  3081. reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr,
  3082. static_cast<unsigned long>(data_len))) {
  3083. return false;
  3084. }
  3085. // For RLE_COMPRESSION:
  3086. // pixel sample data for channel 0 for scanline 0
  3087. // pixel sample data for channel 1 for scanline 0
  3088. // pixel sample data for channel ... for scanline 0
  3089. // pixel sample data for channel n for scanline 0
  3090. // pixel sample data for channel 0 for scanline 1
  3091. // pixel sample data for channel 1 for scanline 1
  3092. // pixel sample data for channel ... for scanline 1
  3093. // pixel sample data for channel n for scanline 1
  3094. // ...
  3095. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  3096. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  3097. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3098. const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  3099. &outBuf.at(v * static_cast<size_t>(pixel_data_size) *
  3100. static_cast<size_t>(width) +
  3101. channel_offset_list[c] * static_cast<size_t>(width)));
  3102. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3103. tinyexr::FP16 hf;
  3104. // hf.u = line_ptr[u];
  3105. tinyexr::cpy2(&(hf.u), line_ptr + u);
  3106. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  3107. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  3108. unsigned short *image =
  3109. reinterpret_cast<unsigned short **>(out_images)[c];
  3110. if (line_order == 0) {
  3111. image += (static_cast<size_t>(line_no) + v) *
  3112. static_cast<size_t>(x_stride) +
  3113. u;
  3114. } else {
  3115. image += (static_cast<size_t>(height) - 1U -
  3116. (static_cast<size_t>(line_no) + v)) *
  3117. static_cast<size_t>(x_stride) +
  3118. u;
  3119. }
  3120. *image = hf.u;
  3121. } else { // HALF -> FLOAT
  3122. tinyexr::FP32 f32 = half_to_float(hf);
  3123. float *image = reinterpret_cast<float **>(out_images)[c];
  3124. if (line_order == 0) {
  3125. image += (static_cast<size_t>(line_no) + v) *
  3126. static_cast<size_t>(x_stride) +
  3127. u;
  3128. } else {
  3129. image += (static_cast<size_t>(height) - 1U -
  3130. (static_cast<size_t>(line_no) + v)) *
  3131. static_cast<size_t>(x_stride) +
  3132. u;
  3133. }
  3134. *image = f32.f;
  3135. }
  3136. }
  3137. }
  3138. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  3139. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
  3140. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3141. const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
  3142. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  3143. channel_offset_list[c] * static_cast<size_t>(width)));
  3144. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3145. unsigned int val;
  3146. // val = line_ptr[u];
  3147. tinyexr::cpy4(&val, line_ptr + u);
  3148. tinyexr::swap4(&val);
  3149. unsigned int *image =
  3150. reinterpret_cast<unsigned int **>(out_images)[c];
  3151. if (line_order == 0) {
  3152. image += (static_cast<size_t>(line_no) + v) *
  3153. static_cast<size_t>(x_stride) +
  3154. u;
  3155. } else {
  3156. image += (static_cast<size_t>(height) - 1U -
  3157. (static_cast<size_t>(line_no) + v)) *
  3158. static_cast<size_t>(x_stride) +
  3159. u;
  3160. }
  3161. *image = val;
  3162. }
  3163. }
  3164. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3165. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  3166. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3167. const float *line_ptr = reinterpret_cast<float *>(
  3168. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  3169. channel_offset_list[c] * static_cast<size_t>(width)));
  3170. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3171. float val;
  3172. // val = line_ptr[u];
  3173. tinyexr::cpy4(&val, line_ptr + u);
  3174. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  3175. float *image = reinterpret_cast<float **>(out_images)[c];
  3176. if (line_order == 0) {
  3177. image += (static_cast<size_t>(line_no) + v) *
  3178. static_cast<size_t>(x_stride) +
  3179. u;
  3180. } else {
  3181. image += (static_cast<size_t>(height) - 1U -
  3182. (static_cast<size_t>(line_no) + v)) *
  3183. static_cast<size_t>(x_stride) +
  3184. u;
  3185. }
  3186. *image = val;
  3187. }
  3188. }
  3189. } else {
  3190. assert(0);
  3191. return false;
  3192. }
  3193. }
  3194. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  3195. #if TINYEXR_USE_ZFP
  3196. tinyexr::ZFPCompressionParam zfp_compression_param;
  3197. std::string e;
  3198. if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes,
  3199. int(num_attributes), &e)) {
  3200. // This code path should not be reachable.
  3201. assert(0);
  3202. return false;
  3203. }
  3204. // Allocate original data size.
  3205. std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
  3206. static_cast<size_t>(num_lines) *
  3207. pixel_data_size);
  3208. unsigned long dstLen = outBuf.size();
  3209. assert(dstLen > 0);
  3210. tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,
  3211. num_lines, num_channels, data_ptr,
  3212. static_cast<unsigned long>(data_len),
  3213. zfp_compression_param);
  3214. // For ZFP_COMPRESSION:
  3215. // pixel sample data for channel 0 for scanline 0
  3216. // pixel sample data for channel 1 for scanline 0
  3217. // pixel sample data for channel ... for scanline 0
  3218. // pixel sample data for channel n for scanline 0
  3219. // pixel sample data for channel 0 for scanline 1
  3220. // pixel sample data for channel 1 for scanline 1
  3221. // pixel sample data for channel ... for scanline 1
  3222. // pixel sample data for channel n for scanline 1
  3223. // ...
  3224. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  3225. assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT);
  3226. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3227. assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
  3228. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3229. const float *line_ptr = reinterpret_cast<float *>(
  3230. &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
  3231. channel_offset_list[c] * static_cast<size_t>(width)));
  3232. for (size_t u = 0; u < static_cast<size_t>(width); u++) {
  3233. float val;
  3234. tinyexr::cpy4(&val, line_ptr + u);
  3235. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  3236. float *image = reinterpret_cast<float **>(out_images)[c];
  3237. if (line_order == 0) {
  3238. image += (static_cast<size_t>(line_no) + v) *
  3239. static_cast<size_t>(x_stride) +
  3240. u;
  3241. } else {
  3242. image += (static_cast<size_t>(height) - 1U -
  3243. (static_cast<size_t>(line_no) + v)) *
  3244. static_cast<size_t>(x_stride) +
  3245. u;
  3246. }
  3247. *image = val;
  3248. }
  3249. }
  3250. } else {
  3251. assert(0);
  3252. return false;
  3253. }
  3254. }
  3255. #else
  3256. (void)attributes;
  3257. (void)num_attributes;
  3258. (void)num_channels;
  3259. assert(0);
  3260. return false;
  3261. #endif
  3262. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  3263. for (size_t c = 0; c < num_channels; c++) {
  3264. for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
  3265. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  3266. const unsigned short *line_ptr =
  3267. reinterpret_cast<const unsigned short *>(
  3268. data_ptr + v * pixel_data_size * size_t(width) +
  3269. channel_offset_list[c] * static_cast<size_t>(width));
  3270. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  3271. unsigned short *outLine =
  3272. reinterpret_cast<unsigned short *>(out_images[c]);
  3273. if (line_order == 0) {
  3274. outLine += (size_t(y) + v) * size_t(x_stride);
  3275. } else {
  3276. outLine +=
  3277. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  3278. }
  3279. for (int u = 0; u < width; u++) {
  3280. tinyexr::FP16 hf;
  3281. // hf.u = line_ptr[u];
  3282. tinyexr::cpy2(&(hf.u), line_ptr + u);
  3283. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  3284. outLine[u] = hf.u;
  3285. }
  3286. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  3287. float *outLine = reinterpret_cast<float *>(out_images[c]);
  3288. if (line_order == 0) {
  3289. outLine += (size_t(y) + v) * size_t(x_stride);
  3290. } else {
  3291. outLine +=
  3292. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  3293. }
  3294. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  3295. (data_ptr + data_len)) {
  3296. // Insufficient data size
  3297. return false;
  3298. }
  3299. for (int u = 0; u < width; u++) {
  3300. tinyexr::FP16 hf;
  3301. // address may not be aliged. use byte-wise copy for safety.#76
  3302. // hf.u = line_ptr[u];
  3303. tinyexr::cpy2(&(hf.u), line_ptr + u);
  3304. tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
  3305. tinyexr::FP32 f32 = half_to_float(hf);
  3306. outLine[u] = f32.f;
  3307. }
  3308. } else {
  3309. assert(0);
  3310. return false;
  3311. }
  3312. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3313. const float *line_ptr = reinterpret_cast<const float *>(
  3314. data_ptr + v * pixel_data_size * size_t(width) +
  3315. channel_offset_list[c] * static_cast<size_t>(width));
  3316. float *outLine = reinterpret_cast<float *>(out_images[c]);
  3317. if (line_order == 0) {
  3318. outLine += (size_t(y) + v) * size_t(x_stride);
  3319. } else {
  3320. outLine +=
  3321. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  3322. }
  3323. if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
  3324. (data_ptr + data_len)) {
  3325. // Insufficient data size
  3326. return false;
  3327. }
  3328. for (int u = 0; u < width; u++) {
  3329. float val;
  3330. tinyexr::cpy4(&val, line_ptr + u);
  3331. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  3332. outLine[u] = val;
  3333. }
  3334. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  3335. const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(
  3336. data_ptr + v * pixel_data_size * size_t(width) +
  3337. channel_offset_list[c] * static_cast<size_t>(width));
  3338. unsigned int *outLine =
  3339. reinterpret_cast<unsigned int *>(out_images[c]);
  3340. if (line_order == 0) {
  3341. outLine += (size_t(y) + v) * size_t(x_stride);
  3342. } else {
  3343. outLine +=
  3344. (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
  3345. }
  3346. for (int u = 0; u < width; u++) {
  3347. if (reinterpret_cast<const unsigned char *>(line_ptr + u) >=
  3348. (data_ptr + data_len)) {
  3349. // Corrupsed data?
  3350. return false;
  3351. }
  3352. unsigned int val;
  3353. tinyexr::cpy4(&val, line_ptr + u);
  3354. tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
  3355. outLine[u] = val;
  3356. }
  3357. }
  3358. }
  3359. }
  3360. }
  3361. return true;
  3362. }
  3363. static bool DecodeTiledPixelData(
  3364. unsigned char **out_images, int *width, int *height,
  3365. const int *requested_pixel_types, const unsigned char *data_ptr,
  3366. size_t data_len, int compression_type, int line_order, int data_width,
  3367. int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
  3368. int tile_size_y, size_t pixel_data_size, size_t num_attributes,
  3369. const EXRAttribute *attributes, size_t num_channels,
  3370. const EXRChannelInfo *channels,
  3371. const std::vector<size_t> &channel_offset_list) {
  3372. // Here, data_width and data_height are the dimensions of the current (sub)level.
  3373. if (tile_size_x * tile_offset_x > data_width ||
  3374. tile_size_y * tile_offset_y > data_height) {
  3375. return false;
  3376. }
  3377. // Compute actual image size in a tile.
  3378. if ((tile_offset_x + 1) * tile_size_x >= data_width) {
  3379. (*width) = data_width - (tile_offset_x * tile_size_x);
  3380. } else {
  3381. (*width) = tile_size_x;
  3382. }
  3383. if ((tile_offset_y + 1) * tile_size_y >= data_height) {
  3384. (*height) = data_height - (tile_offset_y * tile_size_y);
  3385. } else {
  3386. (*height) = tile_size_y;
  3387. }
  3388. // Image size = tile size.
  3389. return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
  3390. compression_type, line_order, (*width), tile_size_y,
  3391. /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
  3392. (*height), pixel_data_size, num_attributes, attributes,
  3393. num_channels, channels, channel_offset_list);
  3394. }
  3395. static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,
  3396. int *pixel_data_size, size_t *channel_offset,
  3397. int num_channels,
  3398. const EXRChannelInfo *channels) {
  3399. channel_offset_list->resize(static_cast<size_t>(num_channels));
  3400. (*pixel_data_size) = 0;
  3401. (*channel_offset) = 0;
  3402. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  3403. (*channel_offset_list)[c] = (*channel_offset);
  3404. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  3405. (*pixel_data_size) += sizeof(unsigned short);
  3406. (*channel_offset) += sizeof(unsigned short);
  3407. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3408. (*pixel_data_size) += sizeof(float);
  3409. (*channel_offset) += sizeof(float);
  3410. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  3411. (*pixel_data_size) += sizeof(unsigned int);
  3412. (*channel_offset) += sizeof(unsigned int);
  3413. } else {
  3414. // ???
  3415. return false;
  3416. }
  3417. }
  3418. return true;
  3419. }
  3420. static unsigned char **AllocateImage(int num_channels,
  3421. const EXRChannelInfo *channels,
  3422. const int *requested_pixel_types,
  3423. int data_width, int data_height) {
  3424. unsigned char **images =
  3425. reinterpret_cast<unsigned char **>(static_cast<float **>(
  3426. malloc(sizeof(float *) * static_cast<size_t>(num_channels))));
  3427. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  3428. size_t data_len =
  3429. static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
  3430. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  3431. // pixel_data_size += sizeof(unsigned short);
  3432. // channel_offset += sizeof(unsigned short);
  3433. // Alloc internal image for half type.
  3434. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
  3435. images[c] =
  3436. reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(
  3437. malloc(sizeof(unsigned short) * data_len)));
  3438. } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
  3439. images[c] = reinterpret_cast<unsigned char *>(
  3440. static_cast<float *>(malloc(sizeof(float) * data_len)));
  3441. } else {
  3442. assert(0);
  3443. }
  3444. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  3445. // pixel_data_size += sizeof(float);
  3446. // channel_offset += sizeof(float);
  3447. images[c] = reinterpret_cast<unsigned char *>(
  3448. static_cast<float *>(malloc(sizeof(float) * data_len)));
  3449. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  3450. // pixel_data_size += sizeof(unsigned int);
  3451. // channel_offset += sizeof(unsigned int);
  3452. images[c] = reinterpret_cast<unsigned char *>(
  3453. static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));
  3454. } else {
  3455. assert(0);
  3456. }
  3457. }
  3458. return images;
  3459. }
  3460. #ifdef _WIN32
  3461. static inline std::wstring UTF8ToWchar(const std::string &str) {
  3462. int wstr_size =
  3463. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0);
  3464. std::wstring wstr(wstr_size, 0);
  3465. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],
  3466. (int)wstr.size());
  3467. return wstr;
  3468. }
  3469. #endif
  3470. static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,
  3471. const EXRVersion *version, std::string *err,
  3472. const unsigned char *buf, size_t size) {
  3473. const char *marker = reinterpret_cast<const char *>(&buf[0]);
  3474. if (empty_header) {
  3475. (*empty_header) = false;
  3476. }
  3477. if (version->multipart) {
  3478. if (size > 0 && marker[0] == '\0') {
  3479. // End of header list.
  3480. if (empty_header) {
  3481. (*empty_header) = true;
  3482. }
  3483. return TINYEXR_SUCCESS;
  3484. }
  3485. }
  3486. // According to the spec, the header of every OpenEXR file must contain at
  3487. // least the following attributes:
  3488. //
  3489. // channels chlist
  3490. // compression compression
  3491. // dataWindow box2i
  3492. // displayWindow box2i
  3493. // lineOrder lineOrder
  3494. // pixelAspectRatio float
  3495. // screenWindowCenter v2f
  3496. // screenWindowWidth float
  3497. bool has_channels = false;
  3498. bool has_compression = false;
  3499. bool has_data_window = false;
  3500. bool has_display_window = false;
  3501. bool has_line_order = false;
  3502. bool has_pixel_aspect_ratio = false;
  3503. bool has_screen_window_center = false;
  3504. bool has_screen_window_width = false;
  3505. bool has_name = false;
  3506. bool has_type = false;
  3507. info->name.clear();
  3508. info->type.clear();
  3509. info->data_window.min_x = 0;
  3510. info->data_window.min_y = 0;
  3511. info->data_window.max_x = 0;
  3512. info->data_window.max_y = 0;
  3513. info->line_order = 0; // @fixme
  3514. info->display_window.min_x = 0;
  3515. info->display_window.min_y = 0;
  3516. info->display_window.max_x = 0;
  3517. info->display_window.max_y = 0;
  3518. info->screen_window_center[0] = 0.0f;
  3519. info->screen_window_center[1] = 0.0f;
  3520. info->screen_window_width = -1.0f;
  3521. info->pixel_aspect_ratio = -1.0f;
  3522. info->tiled = 0;
  3523. info->tile_size_x = -1;
  3524. info->tile_size_y = -1;
  3525. info->tile_level_mode = -1;
  3526. info->tile_rounding_mode = -1;
  3527. info->attributes.clear();
  3528. // Read attributes
  3529. size_t orig_size = size;
  3530. for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
  3531. if (0 == size) {
  3532. if (err) {
  3533. (*err) += "Insufficient data size for attributes.\n";
  3534. }
  3535. return TINYEXR_ERROR_INVALID_DATA;
  3536. } else if (marker[0] == '\0') {
  3537. size--;
  3538. break;
  3539. }
  3540. std::string attr_name;
  3541. std::string attr_type;
  3542. std::vector<unsigned char> data;
  3543. size_t marker_size;
  3544. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  3545. marker, size)) {
  3546. if (err) {
  3547. (*err) += "Failed to read attribute.\n";
  3548. }
  3549. return TINYEXR_ERROR_INVALID_DATA;
  3550. }
  3551. marker += marker_size;
  3552. size -= marker_size;
  3553. // For a multipart file, the version field 9th bit is 0.
  3554. if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) {
  3555. unsigned int x_size, y_size;
  3556. unsigned char tile_mode;
  3557. if (data.size() != 9) {
  3558. if (err) {
  3559. (*err) += "(ParseEXRHeader) Invalid attribute data size. Attribute data size must be 9.\n";
  3560. }
  3561. return TINYEXR_ERROR_INVALID_DATA;
  3562. }
  3563. assert(data.size() == 9);
  3564. memcpy(&x_size, &data.at(0), sizeof(int));
  3565. memcpy(&y_size, &data.at(4), sizeof(int));
  3566. tile_mode = data[8];
  3567. tinyexr::swap4(&x_size);
  3568. tinyexr::swap4(&y_size);
  3569. if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) ||
  3570. y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) {
  3571. if (err) {
  3572. (*err) = "Tile sizes were invalid.";
  3573. }
  3574. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  3575. }
  3576. info->tile_size_x = static_cast<int>(x_size);
  3577. info->tile_size_y = static_cast<int>(y_size);
  3578. // mode = levelMode + roundingMode * 16
  3579. info->tile_level_mode = tile_mode & 0x3;
  3580. info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
  3581. info->tiled = 1;
  3582. } else if (attr_name.compare("compression") == 0) {
  3583. bool ok = false;
  3584. if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
  3585. ok = true;
  3586. }
  3587. if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
  3588. #if TINYEXR_USE_PIZ
  3589. ok = true;
  3590. #else
  3591. if (err) {
  3592. (*err) = "PIZ compression is not supported.";
  3593. }
  3594. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  3595. #endif
  3596. }
  3597. if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
  3598. #if TINYEXR_USE_ZFP
  3599. ok = true;
  3600. #else
  3601. if (err) {
  3602. (*err) = "ZFP compression is not supported.";
  3603. }
  3604. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  3605. #endif
  3606. }
  3607. if (!ok) {
  3608. if (err) {
  3609. (*err) = "Unknown compression type.";
  3610. }
  3611. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  3612. }
  3613. info->compression_type = static_cast<int>(data[0]);
  3614. has_compression = true;
  3615. } else if (attr_name.compare("channels") == 0) {
  3616. // name: zero-terminated string, from 1 to 255 bytes long
  3617. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  3618. // pLinear: unsigned char, possible values are 0 and 1
  3619. // reserved: three chars, should be zero
  3620. // xSampling: int
  3621. // ySampling: int
  3622. if (!ReadChannelInfo(info->channels, data)) {
  3623. if (err) {
  3624. (*err) += "Failed to parse channel info.\n";
  3625. }
  3626. return TINYEXR_ERROR_INVALID_DATA;
  3627. }
  3628. if (info->channels.size() < 1) {
  3629. if (err) {
  3630. (*err) += "# of channels is zero.\n";
  3631. }
  3632. return TINYEXR_ERROR_INVALID_DATA;
  3633. }
  3634. has_channels = true;
  3635. } else if (attr_name.compare("dataWindow") == 0) {
  3636. if (data.size() >= 16) {
  3637. memcpy(&info->data_window.min_x, &data.at(0), sizeof(int));
  3638. memcpy(&info->data_window.min_y, &data.at(4), sizeof(int));
  3639. memcpy(&info->data_window.max_x, &data.at(8), sizeof(int));
  3640. memcpy(&info->data_window.max_y, &data.at(12), sizeof(int));
  3641. tinyexr::swap4(&info->data_window.min_x);
  3642. tinyexr::swap4(&info->data_window.min_y);
  3643. tinyexr::swap4(&info->data_window.max_x);
  3644. tinyexr::swap4(&info->data_window.max_y);
  3645. has_data_window = true;
  3646. }
  3647. } else if (attr_name.compare("displayWindow") == 0) {
  3648. if (data.size() >= 16) {
  3649. memcpy(&info->display_window.min_x, &data.at(0), sizeof(int));
  3650. memcpy(&info->display_window.min_y, &data.at(4), sizeof(int));
  3651. memcpy(&info->display_window.max_x, &data.at(8), sizeof(int));
  3652. memcpy(&info->display_window.max_y, &data.at(12), sizeof(int));
  3653. tinyexr::swap4(&info->display_window.min_x);
  3654. tinyexr::swap4(&info->display_window.min_y);
  3655. tinyexr::swap4(&info->display_window.max_x);
  3656. tinyexr::swap4(&info->display_window.max_y);
  3657. has_display_window = true;
  3658. }
  3659. } else if (attr_name.compare("lineOrder") == 0) {
  3660. if (data.size() >= 1) {
  3661. info->line_order = static_cast<int>(data[0]);
  3662. has_line_order = true;
  3663. }
  3664. } else if (attr_name.compare("pixelAspectRatio") == 0) {
  3665. if (data.size() >= sizeof(float)) {
  3666. memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
  3667. tinyexr::swap4(&info->pixel_aspect_ratio);
  3668. has_pixel_aspect_ratio = true;
  3669. }
  3670. } else if (attr_name.compare("screenWindowCenter") == 0) {
  3671. if (data.size() >= 8) {
  3672. memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
  3673. memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
  3674. tinyexr::swap4(&info->screen_window_center[0]);
  3675. tinyexr::swap4(&info->screen_window_center[1]);
  3676. has_screen_window_center = true;
  3677. }
  3678. } else if (attr_name.compare("screenWindowWidth") == 0) {
  3679. if (data.size() >= sizeof(float)) {
  3680. memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
  3681. tinyexr::swap4(&info->screen_window_width);
  3682. has_screen_window_width = true;
  3683. }
  3684. } else if (attr_name.compare("chunkCount") == 0) {
  3685. if (data.size() >= sizeof(int)) {
  3686. memcpy(&info->chunk_count, &data.at(0), sizeof(int));
  3687. tinyexr::swap4(&info->chunk_count);
  3688. }
  3689. } else if (attr_name.compare("name") == 0) {
  3690. if (!data.empty() && data[0]) {
  3691. data.push_back(0);
  3692. size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
  3693. info->name.resize(len);
  3694. info->name.assign(reinterpret_cast<const char*>(&data[0]), len);
  3695. has_name = true;
  3696. }
  3697. } else if (attr_name.compare("type") == 0) {
  3698. if (!data.empty() && data[0]) {
  3699. data.push_back(0);
  3700. size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
  3701. info->type.resize(len);
  3702. info->type.assign(reinterpret_cast<const char*>(&data[0]), len);
  3703. has_type = true;
  3704. }
  3705. } else {
  3706. // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
  3707. if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  3708. EXRAttribute attrib;
  3709. #ifdef _MSC_VER
  3710. strncpy_s(attrib.name, attr_name.c_str(), 255);
  3711. strncpy_s(attrib.type, attr_type.c_str(), 255);
  3712. #else
  3713. strncpy(attrib.name, attr_name.c_str(), 255);
  3714. strncpy(attrib.type, attr_type.c_str(), 255);
  3715. #endif
  3716. attrib.name[255] = '\0';
  3717. attrib.type[255] = '\0';
  3718. attrib.size = static_cast<int>(data.size());
  3719. attrib.value = static_cast<unsigned char *>(malloc(data.size()));
  3720. memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),
  3721. data.size());
  3722. info->attributes.push_back(attrib);
  3723. }
  3724. }
  3725. }
  3726. // Check if required attributes exist
  3727. {
  3728. std::stringstream ss_err;
  3729. if (!has_compression) {
  3730. ss_err << "\"compression\" attribute not found in the header."
  3731. << std::endl;
  3732. }
  3733. if (!has_channels) {
  3734. ss_err << "\"channels\" attribute not found in the header." << std::endl;
  3735. }
  3736. if (!has_line_order) {
  3737. ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
  3738. }
  3739. if (!has_display_window) {
  3740. ss_err << "\"displayWindow\" attribute not found in the header."
  3741. << std::endl;
  3742. }
  3743. if (!has_data_window) {
  3744. ss_err << "\"dataWindow\" attribute not found in the header or invalid."
  3745. << std::endl;
  3746. }
  3747. if (!has_pixel_aspect_ratio) {
  3748. ss_err << "\"pixelAspectRatio\" attribute not found in the header."
  3749. << std::endl;
  3750. }
  3751. if (!has_screen_window_width) {
  3752. ss_err << "\"screenWindowWidth\" attribute not found in the header."
  3753. << std::endl;
  3754. }
  3755. if (!has_screen_window_center) {
  3756. ss_err << "\"screenWindowCenter\" attribute not found in the header."
  3757. << std::endl;
  3758. }
  3759. if (version->multipart || version->non_image) {
  3760. if (!has_name) {
  3761. ss_err << "\"name\" attribute not found in the header."
  3762. << std::endl;
  3763. }
  3764. if (!has_type) {
  3765. ss_err << "\"type\" attribute not found in the header."
  3766. << std::endl;
  3767. }
  3768. }
  3769. if (!(ss_err.str().empty())) {
  3770. if (err) {
  3771. (*err) += ss_err.str();
  3772. }
  3773. return TINYEXR_ERROR_INVALID_HEADER;
  3774. }
  3775. }
  3776. info->header_len = static_cast<unsigned int>(orig_size - size);
  3777. return TINYEXR_SUCCESS;
  3778. }
  3779. // C++ HeaderInfo to C EXRHeader conversion.
  3780. static bool ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info, std::string *warn, std::string *err) {
  3781. exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
  3782. exr_header->screen_window_center[0] = info.screen_window_center[0];
  3783. exr_header->screen_window_center[1] = info.screen_window_center[1];
  3784. exr_header->screen_window_width = info.screen_window_width;
  3785. exr_header->chunk_count = info.chunk_count;
  3786. exr_header->display_window.min_x = info.display_window.min_x;
  3787. exr_header->display_window.min_y = info.display_window.min_y;
  3788. exr_header->display_window.max_x = info.display_window.max_x;
  3789. exr_header->display_window.max_y = info.display_window.max_y;
  3790. exr_header->data_window.min_x = info.data_window.min_x;
  3791. exr_header->data_window.min_y = info.data_window.min_y;
  3792. exr_header->data_window.max_x = info.data_window.max_x;
  3793. exr_header->data_window.max_y = info.data_window.max_y;
  3794. exr_header->line_order = info.line_order;
  3795. exr_header->compression_type = info.compression_type;
  3796. exr_header->tiled = info.tiled;
  3797. exr_header->tile_size_x = info.tile_size_x;
  3798. exr_header->tile_size_y = info.tile_size_y;
  3799. exr_header->tile_level_mode = info.tile_level_mode;
  3800. exr_header->tile_rounding_mode = info.tile_rounding_mode;
  3801. EXRSetNameAttr(exr_header, info.name.c_str());
  3802. bool valid = true;
  3803. if (!info.type.empty()) {
  3804. if (info.type == "scanlineimage") {
  3805. if (exr_header->tiled) {
  3806. if (err) {
  3807. (*err) += "(ConvertHeader) tiled bit must be off for `scanlineimage` type.\n";
  3808. }
  3809. valid = false;
  3810. }
  3811. } else if (info.type == "tiledimage") {
  3812. if (!exr_header->tiled) {
  3813. if (err) {
  3814. (*err) += "(ConvertHeader) tiled bit must be on for `tiledimage` type.\n";
  3815. }
  3816. valid = false;
  3817. }
  3818. } else if (info.type == "deeptile") {
  3819. exr_header->non_image = 1;
  3820. if (!exr_header->tiled) {
  3821. if (err) {
  3822. (*err) += "(ConvertHeader) tiled bit must be on for `deeptile` type.\n";
  3823. }
  3824. valid = false;
  3825. }
  3826. } else if (info.type == "deepscanline") {
  3827. exr_header->non_image = 1;
  3828. if (exr_header->tiled) {
  3829. if (err) {
  3830. (*err) += "(ConvertHeader) tiled bit must be off for `deepscanline` type.\n";
  3831. }
  3832. valid = false;
  3833. }
  3834. } else {
  3835. if (warn) {
  3836. std::stringstream ss;
  3837. ss << "(ConvertHeader) Unsupported or unknown info.type: " << info.type << "\n";
  3838. (*warn) += ss.str();
  3839. }
  3840. }
  3841. }
  3842. exr_header->num_channels = static_cast<int>(info.channels.size());
  3843. exr_header->channels = static_cast<EXRChannelInfo *>(malloc(
  3844. sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
  3845. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  3846. #ifdef _MSC_VER
  3847. strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  3848. #else
  3849. strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
  3850. #endif
  3851. // manually add '\0' for safety.
  3852. exr_header->channels[c].name[255] = '\0';
  3853. exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
  3854. exr_header->channels[c].p_linear = info.channels[c].p_linear;
  3855. exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
  3856. exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
  3857. }
  3858. exr_header->pixel_types = static_cast<int *>(
  3859. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  3860. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  3861. exr_header->pixel_types[c] = info.channels[c].pixel_type;
  3862. }
  3863. // Initially fill with values of `pixel_types`
  3864. exr_header->requested_pixel_types = static_cast<int *>(
  3865. malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
  3866. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  3867. exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
  3868. }
  3869. exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
  3870. if (exr_header->num_custom_attributes > 0) {
  3871. // TODO(syoyo): Report warning when # of attributes exceeds
  3872. // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
  3873. if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
  3874. exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;
  3875. }
  3876. exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(
  3877. sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
  3878. for (size_t i = 0; i < info.attributes.size(); i++) {
  3879. memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
  3880. 256);
  3881. memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
  3882. 256);
  3883. exr_header->custom_attributes[i].size = info.attributes[i].size;
  3884. // Just copy pointer
  3885. exr_header->custom_attributes[i].value = info.attributes[i].value;
  3886. }
  3887. } else {
  3888. exr_header->custom_attributes = NULL;
  3889. }
  3890. exr_header->header_len = info.header_len;
  3891. return true;
  3892. }
  3893. struct OffsetData {
  3894. OffsetData() : num_x_levels(0), num_y_levels(0) {}
  3895. std::vector<std::vector<std::vector <tinyexr::tinyexr_uint64> > > offsets;
  3896. int num_x_levels;
  3897. int num_y_levels;
  3898. };
  3899. int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels) {
  3900. switch (tile_level_mode) {
  3901. case TINYEXR_TILE_ONE_LEVEL:
  3902. return 0;
  3903. case TINYEXR_TILE_MIPMAP_LEVELS:
  3904. return lx;
  3905. case TINYEXR_TILE_RIPMAP_LEVELS:
  3906. return lx + ly * num_x_levels;
  3907. default:
  3908. assert(false);
  3909. }
  3910. return 0;
  3911. }
  3912. static int LevelSize(int toplevel_size, int level, int tile_rounding_mode) {
  3913. assert(level >= 0);
  3914. int b = (int)(1u << (unsigned)level);
  3915. int level_size = toplevel_size / b;
  3916. if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size)
  3917. level_size += 1;
  3918. return std::max(level_size, 1);
  3919. }
  3920. static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header,
  3921. const OffsetData& offset_data,
  3922. const std::vector<size_t>& channel_offset_list,
  3923. int pixel_data_size,
  3924. const unsigned char* head, const size_t size,
  3925. std::string* err) {
  3926. int num_channels = exr_header->num_channels;
  3927. int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels);
  3928. int num_y_tiles = (int)offset_data.offsets[level_index].size();
  3929. assert(num_y_tiles);
  3930. int num_x_tiles = (int)offset_data.offsets[level_index][0].size();
  3931. assert(num_x_tiles);
  3932. int num_tiles = num_x_tiles * num_y_tiles;
  3933. int err_code = TINYEXR_SUCCESS;
  3934. enum {
  3935. EF_SUCCESS = 0,
  3936. EF_INVALID_DATA = 1,
  3937. EF_INSUFFICIENT_DATA = 2,
  3938. EF_FAILED_TO_DECODE = 4
  3939. };
  3940. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  3941. std::atomic<unsigned> error_flag(EF_SUCCESS);
  3942. #else
  3943. unsigned error_flag(EF_SUCCESS);
  3944. #endif
  3945. // Although the spec says : "...the data window is subdivided into an array of smaller rectangles...",
  3946. // the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window.
  3947. #if 0
  3948. if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) &&
  3949. exr_image->level_x == 0 && exr_image->level_y == 0) {
  3950. if (err) {
  3951. (*err) += "Failed to decode tile data.\n";
  3952. }
  3953. err_code = TINYEXR_ERROR_INVALID_DATA;
  3954. }
  3955. #endif
  3956. exr_image->tiles = static_cast<EXRTile*>(
  3957. calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles)));
  3958. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  3959. std::vector<std::thread> workers;
  3960. std::atomic<int> tile_count(0);
  3961. int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
  3962. if (num_threads > int(num_tiles)) {
  3963. num_threads = int(num_tiles);
  3964. }
  3965. for (int t = 0; t < num_threads; t++) {
  3966. workers.emplace_back(std::thread([&]()
  3967. {
  3968. int tile_idx = 0;
  3969. while ((tile_idx = tile_count++) < num_tiles) {
  3970. #else
  3971. #if TINYEXR_USE_OPENMP
  3972. #pragma omp parallel for
  3973. #endif
  3974. for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
  3975. #endif
  3976. // Allocate memory for each tile.
  3977. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
  3978. num_channels, exr_header->channels,
  3979. exr_header->requested_pixel_types, exr_header->tile_size_x,
  3980. exr_header->tile_size_y);
  3981. int x_tile = tile_idx % num_x_tiles;
  3982. int y_tile = tile_idx / num_x_tiles;
  3983. // 16 byte: tile coordinates
  3984. // 4 byte : data size
  3985. // ~ : data(uncompressed or compressed)
  3986. tinyexr::tinyexr_uint64 offset = offset_data.offsets[level_index][y_tile][x_tile];
  3987. if (offset + sizeof(int) * 5 > size) {
  3988. // Insufficient data size.
  3989. error_flag |= EF_INSUFFICIENT_DATA;
  3990. continue;
  3991. }
  3992. size_t data_size =
  3993. size_t(size - (offset + sizeof(int) * 5));
  3994. const unsigned char* data_ptr =
  3995. reinterpret_cast<const unsigned char*>(head + offset);
  3996. int tile_coordinates[4];
  3997. memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
  3998. tinyexr::swap4(&tile_coordinates[0]);
  3999. tinyexr::swap4(&tile_coordinates[1]);
  4000. tinyexr::swap4(&tile_coordinates[2]);
  4001. tinyexr::swap4(&tile_coordinates[3]);
  4002. if (tile_coordinates[2] != exr_image->level_x) {
  4003. // Invalid data.
  4004. error_flag |= EF_INVALID_DATA;
  4005. continue;
  4006. }
  4007. if (tile_coordinates[3] != exr_image->level_y) {
  4008. // Invalid data.
  4009. error_flag |= EF_INVALID_DATA;
  4010. continue;
  4011. }
  4012. int data_len;
  4013. memcpy(&data_len, data_ptr + 16,
  4014. sizeof(int)); // 16 = sizeof(tile_coordinates)
  4015. tinyexr::swap4(&data_len);
  4016. if (data_len < 2 || size_t(data_len) > data_size) {
  4017. // Insufficient data size.
  4018. error_flag |= EF_INSUFFICIENT_DATA;
  4019. continue;
  4020. }
  4021. // Move to data addr: 20 = 16 + 4;
  4022. data_ptr += 20;
  4023. bool ret = tinyexr::DecodeTiledPixelData(
  4024. exr_image->tiles[tile_idx].images,
  4025. &(exr_image->tiles[tile_idx].width),
  4026. &(exr_image->tiles[tile_idx].height),
  4027. exr_header->requested_pixel_types, data_ptr,
  4028. static_cast<size_t>(data_len), exr_header->compression_type,
  4029. exr_header->line_order,
  4030. exr_image->width, exr_image->height,
  4031. tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x,
  4032. exr_header->tile_size_y, static_cast<size_t>(pixel_data_size),
  4033. static_cast<size_t>(exr_header->num_custom_attributes),
  4034. exr_header->custom_attributes,
  4035. static_cast<size_t>(exr_header->num_channels),
  4036. exr_header->channels, channel_offset_list);
  4037. if (!ret) {
  4038. // Failed to decode tile data.
  4039. error_flag |= EF_FAILED_TO_DECODE;
  4040. }
  4041. exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
  4042. exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
  4043. exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
  4044. exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
  4045. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  4046. }
  4047. }));
  4048. } // num_thread loop
  4049. for (auto& t : workers) {
  4050. t.join();
  4051. }
  4052. #else
  4053. } // parallel for
  4054. #endif
  4055. // Even in the event of an error, the reserved memory may be freed.
  4056. exr_image->num_channels = num_channels;
  4057. exr_image->num_tiles = static_cast<int>(num_tiles);
  4058. if (error_flag) err_code = TINYEXR_ERROR_INVALID_DATA;
  4059. if (err) {
  4060. if (error_flag & EF_INSUFFICIENT_DATA) {
  4061. (*err) += "Insufficient data length.\n";
  4062. }
  4063. if (error_flag & EF_FAILED_TO_DECODE) {
  4064. (*err) += "Failed to decode tile data.\n";
  4065. }
  4066. }
  4067. return err_code;
  4068. }
  4069. static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
  4070. const OffsetData& offset_data,
  4071. const unsigned char *head, const size_t size,
  4072. std::string *err) {
  4073. int num_channels = exr_header->num_channels;
  4074. int num_scanline_blocks = 1;
  4075. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  4076. num_scanline_blocks = 16;
  4077. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  4078. num_scanline_blocks = 32;
  4079. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  4080. num_scanline_blocks = 16;
  4081. #if TINYEXR_USE_ZFP
  4082. tinyexr::ZFPCompressionParam zfp_compression_param;
  4083. if (!FindZFPCompressionParam(&zfp_compression_param,
  4084. exr_header->custom_attributes,
  4085. int(exr_header->num_custom_attributes), err)) {
  4086. return TINYEXR_ERROR_INVALID_HEADER;
  4087. }
  4088. #endif
  4089. }
  4090. if (exr_header->data_window.max_x < exr_header->data_window.min_x ||
  4091. exr_header->data_window.max_y < exr_header->data_window.min_y) {
  4092. if (err) {
  4093. (*err) += "Invalid data window.\n";
  4094. }
  4095. return TINYEXR_ERROR_INVALID_DATA;
  4096. }
  4097. int data_width =
  4098. exr_header->data_window.max_x - exr_header->data_window.min_x + 1;
  4099. int data_height =
  4100. exr_header->data_window.max_y - exr_header->data_window.min_y + 1;
  4101. // Do not allow too large data_width and data_height. header invalid?
  4102. {
  4103. if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) {
  4104. if (err) {
  4105. std::stringstream ss;
  4106. ss << "data_with or data_height too large. data_width: " << data_width
  4107. << ", "
  4108. << "data_height = " << data_height << std::endl;
  4109. (*err) += ss.str();
  4110. }
  4111. return TINYEXR_ERROR_INVALID_DATA;
  4112. }
  4113. if (exr_header->tiled) {
  4114. if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) {
  4115. if (err) {
  4116. std::stringstream ss;
  4117. ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x
  4118. << ", "
  4119. << "tile height = " << exr_header->tile_size_y << std::endl;
  4120. (*err) += ss.str();
  4121. }
  4122. return TINYEXR_ERROR_INVALID_DATA;
  4123. }
  4124. }
  4125. }
  4126. const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
  4127. size_t num_blocks = offsets.size();
  4128. std::vector<size_t> channel_offset_list;
  4129. int pixel_data_size = 0;
  4130. size_t channel_offset = 0;
  4131. if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
  4132. &channel_offset, num_channels,
  4133. exr_header->channels)) {
  4134. if (err) {
  4135. (*err) += "Failed to compute channel layout.\n";
  4136. }
  4137. return TINYEXR_ERROR_INVALID_DATA;
  4138. }
  4139. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  4140. std::atomic<bool> invalid_data(false);
  4141. #else
  4142. bool invalid_data(false);
  4143. #endif
  4144. if (exr_header->tiled) {
  4145. // value check
  4146. if (exr_header->tile_size_x < 0) {
  4147. if (err) {
  4148. std::stringstream ss;
  4149. ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n";
  4150. (*err) += ss.str();
  4151. }
  4152. return TINYEXR_ERROR_INVALID_HEADER;
  4153. }
  4154. if (exr_header->tile_size_y < 0) {
  4155. if (err) {
  4156. std::stringstream ss;
  4157. ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n";
  4158. (*err) += ss.str();
  4159. }
  4160. return TINYEXR_ERROR_INVALID_HEADER;
  4161. }
  4162. if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) {
  4163. EXRImage* level_image = NULL;
  4164. for (int level = 0; level < offset_data.num_x_levels; ++level) {
  4165. if (!level_image) {
  4166. level_image = exr_image;
  4167. } else {
  4168. level_image->next_level = new EXRImage;
  4169. InitEXRImage(level_image->next_level);
  4170. level_image = level_image->next_level;
  4171. }
  4172. level_image->width =
  4173. LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode);
  4174. level_image->height =
  4175. LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode);
  4176. level_image->level_x = level;
  4177. level_image->level_y = level;
  4178. int ret = DecodeTiledLevel(level_image, exr_header,
  4179. offset_data,
  4180. channel_offset_list,
  4181. pixel_data_size,
  4182. head, size,
  4183. err);
  4184. if (ret != TINYEXR_SUCCESS) return ret;
  4185. }
  4186. } else {
  4187. EXRImage* level_image = NULL;
  4188. for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y)
  4189. for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) {
  4190. if (!level_image) {
  4191. level_image = exr_image;
  4192. } else {
  4193. level_image->next_level = new EXRImage;
  4194. InitEXRImage(level_image->next_level);
  4195. level_image = level_image->next_level;
  4196. }
  4197. level_image->width =
  4198. LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode);
  4199. level_image->height =
  4200. LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode);
  4201. level_image->level_x = level_x;
  4202. level_image->level_y = level_y;
  4203. int ret = DecodeTiledLevel(level_image, exr_header,
  4204. offset_data,
  4205. channel_offset_list,
  4206. pixel_data_size,
  4207. head, size,
  4208. err);
  4209. if (ret != TINYEXR_SUCCESS) return ret;
  4210. }
  4211. }
  4212. } else { // scanline format
  4213. // Don't allow too large image(256GB * pixel_data_size or more). Workaround
  4214. // for #104.
  4215. size_t total_data_len =
  4216. size_t(data_width) * size_t(data_height) * size_t(num_channels);
  4217. const bool total_data_len_overflown =
  4218. sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false;
  4219. if ((total_data_len == 0) || total_data_len_overflown) {
  4220. if (err) {
  4221. std::stringstream ss;
  4222. ss << "Image data size is zero or too large: width = " << data_width
  4223. << ", height = " << data_height << ", channels = " << num_channels
  4224. << std::endl;
  4225. (*err) += ss.str();
  4226. }
  4227. return TINYEXR_ERROR_INVALID_DATA;
  4228. }
  4229. exr_image->images = tinyexr::AllocateImage(
  4230. num_channels, exr_header->channels, exr_header->requested_pixel_types,
  4231. data_width, data_height);
  4232. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  4233. std::vector<std::thread> workers;
  4234. std::atomic<int> y_count(0);
  4235. int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
  4236. if (num_threads > int(num_blocks)) {
  4237. num_threads = int(num_blocks);
  4238. }
  4239. for (int t = 0; t < num_threads; t++) {
  4240. workers.emplace_back(std::thread([&]() {
  4241. int y = 0;
  4242. while ((y = y_count++) < int(num_blocks)) {
  4243. #else
  4244. #if TINYEXR_USE_OPENMP
  4245. #pragma omp parallel for
  4246. #endif
  4247. for (int y = 0; y < static_cast<int>(num_blocks); y++) {
  4248. #endif
  4249. size_t y_idx = static_cast<size_t>(y);
  4250. if (offsets[y_idx] + sizeof(int) * 2 > size) {
  4251. invalid_data = true;
  4252. } else {
  4253. // 4 byte: scan line
  4254. // 4 byte: data size
  4255. // ~ : pixel data(uncompressed or compressed)
  4256. size_t data_size =
  4257. size_t(size - (offsets[y_idx] + sizeof(int) * 2));
  4258. const unsigned char *data_ptr =
  4259. reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);
  4260. int line_no;
  4261. memcpy(&line_no, data_ptr, sizeof(int));
  4262. int data_len;
  4263. memcpy(&data_len, data_ptr + 4, sizeof(int));
  4264. tinyexr::swap4(&line_no);
  4265. tinyexr::swap4(&data_len);
  4266. if (size_t(data_len) > data_size) {
  4267. invalid_data = true;
  4268. } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {
  4269. // Too large value. Assume this is invalid
  4270. // 2**20 = 1048576 = heuristic value.
  4271. invalid_data = true;
  4272. } else if (data_len == 0) {
  4273. // TODO(syoyo): May be ok to raise the threshold for example
  4274. // `data_len < 4`
  4275. invalid_data = true;
  4276. } else {
  4277. // line_no may be negative.
  4278. int end_line_no = (std::min)(line_no + num_scanline_blocks,
  4279. (exr_header->data_window.max_y + 1));
  4280. int num_lines = end_line_no - line_no;
  4281. if (num_lines <= 0) {
  4282. invalid_data = true;
  4283. } else {
  4284. // Move to data addr: 8 = 4 + 4;
  4285. data_ptr += 8;
  4286. // Adjust line_no with data_window.bmin.y
  4287. // overflow check
  4288. tinyexr_int64 lno =
  4289. static_cast<tinyexr_int64>(line_no) -
  4290. static_cast<tinyexr_int64>(exr_header->data_window.min_y);
  4291. if (lno > std::numeric_limits<int>::max()) {
  4292. line_no = -1; // invalid
  4293. } else if (lno < -std::numeric_limits<int>::max()) {
  4294. line_no = -1; // invalid
  4295. } else {
  4296. line_no -= exr_header->data_window.min_y;
  4297. }
  4298. if (line_no < 0) {
  4299. invalid_data = true;
  4300. } else {
  4301. if (!tinyexr::DecodePixelData(
  4302. exr_image->images, exr_header->requested_pixel_types,
  4303. data_ptr, static_cast<size_t>(data_len),
  4304. exr_header->compression_type, exr_header->line_order,
  4305. data_width, data_height, data_width, y, line_no,
  4306. num_lines, static_cast<size_t>(pixel_data_size),
  4307. static_cast<size_t>(
  4308. exr_header->num_custom_attributes),
  4309. exr_header->custom_attributes,
  4310. static_cast<size_t>(exr_header->num_channels),
  4311. exr_header->channels, channel_offset_list)) {
  4312. invalid_data = true;
  4313. }
  4314. }
  4315. }
  4316. }
  4317. }
  4318. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  4319. }
  4320. }));
  4321. }
  4322. for (auto &t : workers) {
  4323. t.join();
  4324. }
  4325. #else
  4326. } // omp parallel
  4327. #endif
  4328. }
  4329. if (invalid_data) {
  4330. if (err) {
  4331. (*err) += "Invalid data found when decoding pixels.\n";
  4332. }
  4333. return TINYEXR_ERROR_INVALID_DATA;
  4334. }
  4335. // Overwrite `pixel_type` with `requested_pixel_type`.
  4336. {
  4337. for (int c = 0; c < exr_header->num_channels; c++) {
  4338. exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
  4339. }
  4340. }
  4341. {
  4342. exr_image->num_channels = num_channels;
  4343. exr_image->width = data_width;
  4344. exr_image->height = data_height;
  4345. }
  4346. return TINYEXR_SUCCESS;
  4347. }
  4348. static bool ReconstructLineOffsets(
  4349. std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,
  4350. const unsigned char *head, const unsigned char *marker, const size_t size) {
  4351. assert(head < marker);
  4352. assert(offsets->size() == n);
  4353. for (size_t i = 0; i < n; i++) {
  4354. size_t offset = static_cast<size_t>(marker - head);
  4355. // Offset should not exceed whole EXR file/data size.
  4356. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
  4357. return false;
  4358. }
  4359. int y;
  4360. unsigned int data_len;
  4361. memcpy(&y, marker, sizeof(int));
  4362. memcpy(&data_len, marker + 4, sizeof(unsigned int));
  4363. if (data_len >= size) {
  4364. return false;
  4365. }
  4366. tinyexr::swap4(&y);
  4367. tinyexr::swap4(&data_len);
  4368. (*offsets)[i] = offset;
  4369. marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
  4370. }
  4371. return true;
  4372. }
  4373. static int FloorLog2(unsigned x) {
  4374. //
  4375. // For x > 0, floorLog2(y) returns floor(log(x)/log(2)).
  4376. //
  4377. int y = 0;
  4378. while (x > 1) {
  4379. y += 1;
  4380. x >>= 1u;
  4381. }
  4382. return y;
  4383. }
  4384. static int CeilLog2(unsigned x) {
  4385. //
  4386. // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)).
  4387. //
  4388. int y = 0;
  4389. int r = 0;
  4390. while (x > 1) {
  4391. if (x & 1)
  4392. r = 1;
  4393. y += 1;
  4394. x >>= 1u;
  4395. }
  4396. return y + r;
  4397. }
  4398. static int RoundLog2(int x, int tile_rounding_mode) {
  4399. return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x));
  4400. }
  4401. static int CalculateNumXLevels(const EXRHeader* exr_header) {
  4402. int min_x = exr_header->data_window.min_x;
  4403. int max_x = exr_header->data_window.max_x;
  4404. int min_y = exr_header->data_window.min_y;
  4405. int max_y = exr_header->data_window.max_y;
  4406. int num = 0;
  4407. switch (exr_header->tile_level_mode) {
  4408. case TINYEXR_TILE_ONE_LEVEL:
  4409. num = 1;
  4410. break;
  4411. case TINYEXR_TILE_MIPMAP_LEVELS:
  4412. {
  4413. int w = max_x - min_x + 1;
  4414. int h = max_y - min_y + 1;
  4415. num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
  4416. }
  4417. break;
  4418. case TINYEXR_TILE_RIPMAP_LEVELS:
  4419. {
  4420. int w = max_x - min_x + 1;
  4421. num = RoundLog2(w, exr_header->tile_rounding_mode) + 1;
  4422. }
  4423. break;
  4424. default:
  4425. assert(false);
  4426. }
  4427. return num;
  4428. }
  4429. static int CalculateNumYLevels(const EXRHeader* exr_header) {
  4430. int min_x = exr_header->data_window.min_x;
  4431. int max_x = exr_header->data_window.max_x;
  4432. int min_y = exr_header->data_window.min_y;
  4433. int max_y = exr_header->data_window.max_y;
  4434. int num = 0;
  4435. switch (exr_header->tile_level_mode) {
  4436. case TINYEXR_TILE_ONE_LEVEL:
  4437. num = 1;
  4438. break;
  4439. case TINYEXR_TILE_MIPMAP_LEVELS:
  4440. {
  4441. int w = max_x - min_x + 1;
  4442. int h = max_y - min_y + 1;
  4443. num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
  4444. }
  4445. break;
  4446. case TINYEXR_TILE_RIPMAP_LEVELS:
  4447. {
  4448. int h = max_y - min_y + 1;
  4449. num = RoundLog2(h, exr_header->tile_rounding_mode) + 1;
  4450. }
  4451. break;
  4452. default:
  4453. assert(false);
  4454. }
  4455. return num;
  4456. }
  4457. static void CalculateNumTiles(std::vector<int>& numTiles,
  4458. int toplevel_size,
  4459. int size,
  4460. int tile_rounding_mode) {
  4461. for (unsigned i = 0; i < numTiles.size(); i++) {
  4462. int l = LevelSize(toplevel_size, i, tile_rounding_mode);
  4463. assert(l <= std::numeric_limits<int>::max() - size + 1);
  4464. numTiles[i] = (l + size - 1) / size;
  4465. }
  4466. }
  4467. static void PrecalculateTileInfo(std::vector<int>& num_x_tiles,
  4468. std::vector<int>& num_y_tiles,
  4469. const EXRHeader* exr_header) {
  4470. int min_x = exr_header->data_window.min_x;
  4471. int max_x = exr_header->data_window.max_x;
  4472. int min_y = exr_header->data_window.min_y;
  4473. int max_y = exr_header->data_window.max_y;
  4474. int num_x_levels = CalculateNumXLevels(exr_header);
  4475. int num_y_levels = CalculateNumYLevels(exr_header);
  4476. num_x_tiles.resize(num_x_levels);
  4477. num_y_tiles.resize(num_y_levels);
  4478. CalculateNumTiles(num_x_tiles,
  4479. max_x - min_x + 1,
  4480. exr_header->tile_size_x,
  4481. exr_header->tile_rounding_mode);
  4482. CalculateNumTiles(num_y_tiles,
  4483. max_y - min_y + 1,
  4484. exr_header->tile_size_y,
  4485. exr_header->tile_rounding_mode);
  4486. }
  4487. static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks) {
  4488. offset_data.offsets.resize(1);
  4489. offset_data.offsets[0].resize(1);
  4490. offset_data.offsets[0][0].resize(num_blocks);
  4491. offset_data.num_x_levels = 1;
  4492. offset_data.num_y_levels = 1;
  4493. }
  4494. // Return sum of tile blocks.
  4495. static int InitTileOffsets(OffsetData& offset_data,
  4496. const EXRHeader* exr_header,
  4497. const std::vector<int>& num_x_tiles,
  4498. const std::vector<int>& num_y_tiles) {
  4499. int num_tile_blocks = 0;
  4500. offset_data.num_x_levels = static_cast<int>(num_x_tiles.size());
  4501. offset_data.num_y_levels = static_cast<int>(num_y_tiles.size());
  4502. switch (exr_header->tile_level_mode) {
  4503. case TINYEXR_TILE_ONE_LEVEL:
  4504. case TINYEXR_TILE_MIPMAP_LEVELS:
  4505. assert(offset_data.num_x_levels == offset_data.num_y_levels);
  4506. offset_data.offsets.resize(offset_data.num_x_levels);
  4507. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
  4508. offset_data.offsets[l].resize(num_y_tiles[l]);
  4509. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
  4510. offset_data.offsets[l][dy].resize(num_x_tiles[l]);
  4511. num_tile_blocks += num_x_tiles[l];
  4512. }
  4513. }
  4514. break;
  4515. case TINYEXR_TILE_RIPMAP_LEVELS:
  4516. offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels));
  4517. for (int ly = 0; ly < offset_data.num_y_levels; ++ly) {
  4518. for (int lx = 0; lx < offset_data.num_x_levels; ++lx) {
  4519. int l = ly * offset_data.num_x_levels + lx;
  4520. offset_data.offsets[l].resize(num_y_tiles[ly]);
  4521. for (size_t dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
  4522. offset_data.offsets[l][dy].resize(num_x_tiles[lx]);
  4523. num_tile_blocks += num_x_tiles[lx];
  4524. }
  4525. }
  4526. }
  4527. break;
  4528. default:
  4529. assert(false);
  4530. }
  4531. return num_tile_blocks;
  4532. }
  4533. static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data) {
  4534. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
  4535. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
  4536. for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx)
  4537. if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0)
  4538. return true;
  4539. return false;
  4540. }
  4541. static bool isValidTile(const EXRHeader* exr_header,
  4542. const OffsetData& offset_data,
  4543. int dx, int dy, int lx, int ly) {
  4544. if (lx < 0 || ly < 0 || dx < 0 || dy < 0) return false;
  4545. int num_x_levels = offset_data.num_x_levels;
  4546. int num_y_levels = offset_data.num_y_levels;
  4547. switch (exr_header->tile_level_mode) {
  4548. case TINYEXR_TILE_ONE_LEVEL:
  4549. if (lx == 0 &&
  4550. ly == 0 &&
  4551. offset_data.offsets.size() > 0 &&
  4552. offset_data.offsets[0].size() > static_cast<size_t>(dy) &&
  4553. offset_data.offsets[0][dy].size() > static_cast<size_t>(dx)) {
  4554. return true;
  4555. }
  4556. break;
  4557. case TINYEXR_TILE_MIPMAP_LEVELS:
  4558. if (lx < num_x_levels &&
  4559. ly < num_y_levels &&
  4560. offset_data.offsets.size() > static_cast<size_t>(lx) &&
  4561. offset_data.offsets[lx].size() > static_cast<size_t>(dy) &&
  4562. offset_data.offsets[lx][dy].size() > static_cast<size_t>(dx)) {
  4563. return true;
  4564. }
  4565. break;
  4566. case TINYEXR_TILE_RIPMAP_LEVELS:
  4567. {
  4568. size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly)* static_cast<size_t>(num_x_levels);
  4569. if (lx < num_x_levels &&
  4570. ly < num_y_levels &&
  4571. (offset_data.offsets.size() > idx) &&
  4572. offset_data.offsets[idx].size() > static_cast<size_t>(dy) &&
  4573. offset_data.offsets[idx][dy].size() > static_cast<size_t>(dx)) {
  4574. return true;
  4575. }
  4576. }
  4577. break;
  4578. default:
  4579. return false;
  4580. }
  4581. return false;
  4582. }
  4583. static void ReconstructTileOffsets(OffsetData& offset_data,
  4584. const EXRHeader* exr_header,
  4585. const unsigned char* head, const unsigned char* marker, const size_t /*size*/,
  4586. bool isMultiPartFile,
  4587. bool isDeep) {
  4588. int numXLevels = offset_data.num_x_levels;
  4589. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
  4590. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
  4591. for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
  4592. tinyexr::tinyexr_uint64 tileOffset = marker - head;
  4593. if (isMultiPartFile) {
  4594. //int partNumber;
  4595. marker += sizeof(int);
  4596. }
  4597. int tileX;
  4598. memcpy(&tileX, marker, sizeof(int));
  4599. tinyexr::swap4(&tileX);
  4600. marker += sizeof(int);
  4601. int tileY;
  4602. memcpy(&tileY, marker, sizeof(int));
  4603. tinyexr::swap4(&tileY);
  4604. marker += sizeof(int);
  4605. int levelX;
  4606. memcpy(&levelX, marker, sizeof(int));
  4607. tinyexr::swap4(&levelX);
  4608. marker += sizeof(int);
  4609. int levelY;
  4610. memcpy(&levelY, marker, sizeof(int));
  4611. tinyexr::swap4(&levelY);
  4612. marker += sizeof(int);
  4613. if (isDeep) {
  4614. tinyexr::tinyexr_int64 packed_offset_table_size;
  4615. memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64));
  4616. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size));
  4617. marker += sizeof(tinyexr::tinyexr_int64);
  4618. tinyexr::tinyexr_int64 packed_sample_size;
  4619. memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64));
  4620. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size));
  4621. marker += sizeof(tinyexr::tinyexr_int64);
  4622. // next Int64 is unpacked sample size - skip that too
  4623. marker += packed_offset_table_size + packed_sample_size + 8;
  4624. } else {
  4625. int dataSize;
  4626. memcpy(&dataSize, marker, sizeof(int));
  4627. tinyexr::swap4(&dataSize);
  4628. marker += sizeof(int);
  4629. marker += dataSize;
  4630. }
  4631. if (!isValidTile(exr_header, offset_data,
  4632. tileX, tileY, levelX, levelY))
  4633. return;
  4634. int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels);
  4635. offset_data.offsets[level_idx][tileY][tileX] = tileOffset;
  4636. }
  4637. }
  4638. }
  4639. }
  4640. // marker output is also
  4641. static int ReadOffsets(OffsetData& offset_data,
  4642. const unsigned char* head,
  4643. const unsigned char*& marker,
  4644. const size_t size,
  4645. const char** err) {
  4646. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
  4647. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
  4648. for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
  4649. tinyexr::tinyexr_uint64 offset;
  4650. if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
  4651. tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
  4652. return TINYEXR_ERROR_INVALID_DATA;
  4653. }
  4654. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  4655. tinyexr::swap8(&offset);
  4656. if (offset >= size) {
  4657. tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
  4658. return TINYEXR_ERROR_INVALID_DATA;
  4659. }
  4660. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  4661. offset_data.offsets[l][dy][dx] = offset;
  4662. }
  4663. }
  4664. }
  4665. return TINYEXR_SUCCESS;
  4666. }
  4667. static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,
  4668. const unsigned char *head,
  4669. const unsigned char *marker, const size_t size,
  4670. const char **err) {
  4671. if (exr_image == NULL || exr_header == NULL || head == NULL ||
  4672. marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
  4673. tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
  4674. return TINYEXR_ERROR_INVALID_ARGUMENT;
  4675. }
  4676. int num_scanline_blocks = 1;
  4677. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  4678. num_scanline_blocks = 16;
  4679. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  4680. num_scanline_blocks = 32;
  4681. } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  4682. num_scanline_blocks = 16;
  4683. }
  4684. if (exr_header->data_window.max_x < exr_header->data_window.min_x ||
  4685. exr_header->data_window.max_x - exr_header->data_window.min_x ==
  4686. std::numeric_limits<int>::max()) {
  4687. // Issue 63
  4688. tinyexr::SetErrorMessage("Invalid data width value", err);
  4689. return TINYEXR_ERROR_INVALID_DATA;
  4690. }
  4691. int data_width =
  4692. exr_header->data_window.max_x - exr_header->data_window.min_x + 1;
  4693. if (exr_header->data_window.max_y < exr_header->data_window.min_y ||
  4694. exr_header->data_window.max_y - exr_header->data_window.min_y ==
  4695. std::numeric_limits<int>::max()) {
  4696. tinyexr::SetErrorMessage("Invalid data height value", err);
  4697. return TINYEXR_ERROR_INVALID_DATA;
  4698. }
  4699. int data_height =
  4700. exr_header->data_window.max_y - exr_header->data_window.min_y + 1;
  4701. // Do not allow too large data_width and data_height. header invalid?
  4702. {
  4703. if (data_width > TINYEXR_DIMENSION_THRESHOLD) {
  4704. tinyexr::SetErrorMessage("data width too large.", err);
  4705. return TINYEXR_ERROR_INVALID_DATA;
  4706. }
  4707. if (data_height > TINYEXR_DIMENSION_THRESHOLD) {
  4708. tinyexr::SetErrorMessage("data height too large.", err);
  4709. return TINYEXR_ERROR_INVALID_DATA;
  4710. }
  4711. }
  4712. if (exr_header->tiled) {
  4713. if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) {
  4714. tinyexr::SetErrorMessage("tile width too large.", err);
  4715. return TINYEXR_ERROR_INVALID_DATA;
  4716. }
  4717. if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) {
  4718. tinyexr::SetErrorMessage("tile height too large.", err);
  4719. return TINYEXR_ERROR_INVALID_DATA;
  4720. }
  4721. }
  4722. // Read offset tables.
  4723. OffsetData offset_data;
  4724. size_t num_blocks = 0;
  4725. // For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header.
  4726. // If chunk_count > 0 then chunk_count must be equal to the calculated tile count.
  4727. if (exr_header->tiled) {
  4728. {
  4729. std::vector<int> num_x_tiles, num_y_tiles;
  4730. PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header);
  4731. num_blocks = InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles);
  4732. if (exr_header->chunk_count > 0) {
  4733. if (exr_header->chunk_count != static_cast<int>(num_blocks)) {
  4734. tinyexr::SetErrorMessage("Invalid offset table size.", err);
  4735. return TINYEXR_ERROR_INVALID_DATA;
  4736. }
  4737. }
  4738. }
  4739. int ret = ReadOffsets(offset_data, head, marker, size, err);
  4740. if (ret != TINYEXR_SUCCESS) return ret;
  4741. if (IsAnyOffsetsAreInvalid(offset_data)) {
  4742. ReconstructTileOffsets(offset_data, exr_header,
  4743. head, marker, size,
  4744. exr_header->multipart, exr_header->non_image);
  4745. }
  4746. } else if (exr_header->chunk_count > 0) {
  4747. // Use `chunkCount` attribute.
  4748. num_blocks = static_cast<size_t>(exr_header->chunk_count);
  4749. InitSingleResolutionOffsets(offset_data, num_blocks);
  4750. } else {
  4751. num_blocks = static_cast<size_t>(data_height) /
  4752. static_cast<size_t>(num_scanline_blocks);
  4753. if (num_blocks * static_cast<size_t>(num_scanline_blocks) <
  4754. static_cast<size_t>(data_height)) {
  4755. num_blocks++;
  4756. }
  4757. InitSingleResolutionOffsets(offset_data, num_blocks);
  4758. }
  4759. if (!exr_header->tiled) {
  4760. std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
  4761. for (size_t y = 0; y < num_blocks; y++) {
  4762. tinyexr::tinyexr_uint64 offset;
  4763. // Issue #81
  4764. if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
  4765. tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
  4766. return TINYEXR_ERROR_INVALID_DATA;
  4767. }
  4768. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  4769. tinyexr::swap8(&offset);
  4770. if (offset >= size) {
  4771. tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
  4772. return TINYEXR_ERROR_INVALID_DATA;
  4773. }
  4774. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  4775. offsets[y] = offset;
  4776. }
  4777. // If line offsets are invalid, we try to reconstruct it.
  4778. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
  4779. for (size_t y = 0; y < num_blocks; y++) {
  4780. if (offsets[y] <= 0) {
  4781. // TODO(syoyo) Report as warning?
  4782. // if (err) {
  4783. // stringstream ss;
  4784. // ss << "Incomplete lineOffsets." << std::endl;
  4785. // (*err) += ss.str();
  4786. //}
  4787. bool ret =
  4788. ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
  4789. if (ret) {
  4790. // OK
  4791. break;
  4792. } else {
  4793. tinyexr::SetErrorMessage(
  4794. "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
  4795. return TINYEXR_ERROR_INVALID_DATA;
  4796. }
  4797. }
  4798. }
  4799. }
  4800. {
  4801. std::string e;
  4802. int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e);
  4803. if (ret != TINYEXR_SUCCESS) {
  4804. if (!e.empty()) {
  4805. tinyexr::SetErrorMessage(e, err);
  4806. }
  4807. #if 1
  4808. FreeEXRImage(exr_image);
  4809. #else
  4810. // release memory(if exists)
  4811. if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
  4812. for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
  4813. if (exr_image->images[c]) {
  4814. free(exr_image->images[c]);
  4815. exr_image->images[c] = NULL;
  4816. }
  4817. }
  4818. free(exr_image->images);
  4819. exr_image->images = NULL;
  4820. }
  4821. #endif
  4822. }
  4823. return ret;
  4824. }
  4825. }
  4826. static void GetLayers(const EXRHeader &exr_header,
  4827. std::vector<std::string> &layer_names) {
  4828. // Naive implementation
  4829. // Group channels by layers
  4830. // go over all channel names, split by periods
  4831. // collect unique names
  4832. layer_names.clear();
  4833. for (int c = 0; c < exr_header.num_channels; c++) {
  4834. std::string full_name(exr_header.channels[c].name);
  4835. const size_t pos = full_name.find_last_of('.');
  4836. if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) {
  4837. full_name.erase(pos);
  4838. if (std::find(layer_names.begin(), layer_names.end(), full_name) ==
  4839. layer_names.end())
  4840. layer_names.push_back(full_name);
  4841. }
  4842. }
  4843. }
  4844. struct LayerChannel {
  4845. explicit LayerChannel(size_t i, std::string n) : index(i), name(n) {}
  4846. size_t index;
  4847. std::string name;
  4848. };
  4849. static void ChannelsInLayer(const EXRHeader &exr_header,
  4850. const std::string &layer_name,
  4851. std::vector<LayerChannel> &channels) {
  4852. channels.clear();
  4853. for (int c = 0; c < exr_header.num_channels; c++) {
  4854. std::string ch_name(exr_header.channels[c].name);
  4855. if (layer_name.empty()) {
  4856. const size_t pos = ch_name.find_last_of('.');
  4857. if (pos != std::string::npos && pos < ch_name.size()) {
  4858. ch_name = ch_name.substr(pos + 1);
  4859. }
  4860. } else {
  4861. const size_t pos = ch_name.find(layer_name + '.');
  4862. if (pos == std::string::npos) continue;
  4863. if (pos == 0) {
  4864. ch_name = ch_name.substr(layer_name.size() + 1);
  4865. }
  4866. }
  4867. LayerChannel ch(size_t(c), ch_name);
  4868. channels.push_back(ch);
  4869. }
  4870. }
  4871. } // namespace tinyexr
  4872. int EXRLayers(const char *filename, const char **layer_names[], int *num_layers,
  4873. const char **err) {
  4874. EXRVersion exr_version;
  4875. EXRHeader exr_header;
  4876. InitEXRHeader(&exr_header);
  4877. {
  4878. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  4879. if (ret != TINYEXR_SUCCESS) {
  4880. tinyexr::SetErrorMessage("Invalid EXR header.", err);
  4881. return ret;
  4882. }
  4883. if (exr_version.multipart || exr_version.non_image) {
  4884. tinyexr::SetErrorMessage(
  4885. "Loading multipart or DeepImage is not supported in LoadEXR() API",
  4886. err);
  4887. return TINYEXR_ERROR_INVALID_DATA; // @fixme.
  4888. }
  4889. }
  4890. int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
  4891. if (ret != TINYEXR_SUCCESS) {
  4892. FreeEXRHeader(&exr_header);
  4893. return ret;
  4894. }
  4895. std::vector<std::string> layer_vec;
  4896. tinyexr::GetLayers(exr_header, layer_vec);
  4897. (*num_layers) = int(layer_vec.size());
  4898. (*layer_names) = static_cast<const char **>(
  4899. malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size())));
  4900. for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) {
  4901. #ifdef _MSC_VER
  4902. (*layer_names)[c] = _strdup(layer_vec[c].c_str());
  4903. #else
  4904. (*layer_names)[c] = strdup(layer_vec[c].c_str());
  4905. #endif
  4906. }
  4907. FreeEXRHeader(&exr_header);
  4908. return TINYEXR_SUCCESS;
  4909. }
  4910. int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
  4911. const char **err) {
  4912. return LoadEXRWithLayer(out_rgba, width, height, filename,
  4913. /* layername */ NULL, err);
  4914. }
  4915. int LoadEXRWithLayer(float **out_rgba, int *width, int *height,
  4916. const char *filename, const char *layername,
  4917. const char **err) {
  4918. if (out_rgba == NULL) {
  4919. tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
  4920. return TINYEXR_ERROR_INVALID_ARGUMENT;
  4921. }
  4922. EXRVersion exr_version;
  4923. EXRImage exr_image;
  4924. EXRHeader exr_header;
  4925. InitEXRHeader(&exr_header);
  4926. InitEXRImage(&exr_image);
  4927. {
  4928. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  4929. if (ret != TINYEXR_SUCCESS) {
  4930. std::stringstream ss;
  4931. ss << "Failed to open EXR file or read version info from EXR file. code("
  4932. << ret << ")";
  4933. tinyexr::SetErrorMessage(ss.str(), err);
  4934. return ret;
  4935. }
  4936. if (exr_version.multipart || exr_version.non_image) {
  4937. tinyexr::SetErrorMessage(
  4938. "Loading multipart or DeepImage is not supported in LoadEXR() API",
  4939. err);
  4940. return TINYEXR_ERROR_INVALID_DATA; // @fixme.
  4941. }
  4942. }
  4943. {
  4944. int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
  4945. if (ret != TINYEXR_SUCCESS) {
  4946. FreeEXRHeader(&exr_header);
  4947. return ret;
  4948. }
  4949. }
  4950. // Read HALF channel as FLOAT.
  4951. for (int i = 0; i < exr_header.num_channels; i++) {
  4952. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  4953. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  4954. }
  4955. }
  4956. // TODO: Probably limit loading to layers (channels) selected by layer index
  4957. {
  4958. int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
  4959. if (ret != TINYEXR_SUCCESS) {
  4960. FreeEXRHeader(&exr_header);
  4961. return ret;
  4962. }
  4963. }
  4964. // RGBA
  4965. int idxR = -1;
  4966. int idxG = -1;
  4967. int idxB = -1;
  4968. int idxA = -1;
  4969. std::vector<std::string> layer_names;
  4970. tinyexr::GetLayers(exr_header, layer_names);
  4971. std::vector<tinyexr::LayerChannel> channels;
  4972. tinyexr::ChannelsInLayer(
  4973. exr_header, layername == NULL ? "" : std::string(layername), channels);
  4974. if (channels.size() < 1) {
  4975. tinyexr::SetErrorMessage("Layer Not Found", err);
  4976. FreeEXRHeader(&exr_header);
  4977. FreeEXRImage(&exr_image);
  4978. return TINYEXR_ERROR_LAYER_NOT_FOUND;
  4979. }
  4980. size_t ch_count = channels.size() < 4 ? channels.size() : 4;
  4981. for (size_t c = 0; c < ch_count; c++) {
  4982. const tinyexr::LayerChannel &ch = channels[c];
  4983. if (ch.name == "R") {
  4984. idxR = int(ch.index);
  4985. } else if (ch.name == "G") {
  4986. idxG = int(ch.index);
  4987. } else if (ch.name == "B") {
  4988. idxB = int(ch.index);
  4989. } else if (ch.name == "A") {
  4990. idxA = int(ch.index);
  4991. }
  4992. }
  4993. if (channels.size() == 1) {
  4994. int chIdx = int(channels.front().index);
  4995. // Grayscale channel only.
  4996. (*out_rgba) = reinterpret_cast<float *>(
  4997. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  4998. static_cast<size_t>(exr_image.height)));
  4999. if (exr_header.tiled) {
  5000. for (int it = 0; it < exr_image.num_tiles; it++) {
  5001. for (int j = 0; j < exr_header.tile_size_y; j++) {
  5002. for (int i = 0; i < exr_header.tile_size_x; i++) {
  5003. const int ii = exr_image.tiles[it].offset_x *
  5004. static_cast<int>(exr_header.tile_size_x) +
  5005. i;
  5006. const int jj = exr_image.tiles[it].offset_y *
  5007. static_cast<int>(exr_header.tile_size_y) +
  5008. j;
  5009. const int idx = ii + jj * static_cast<int>(exr_image.width);
  5010. // out of region check.
  5011. if (ii >= exr_image.width) {
  5012. continue;
  5013. }
  5014. if (jj >= exr_image.height) {
  5015. continue;
  5016. }
  5017. const int srcIdx = i + j * exr_header.tile_size_x;
  5018. unsigned char **src = exr_image.tiles[it].images;
  5019. (*out_rgba)[4 * idx + 0] =
  5020. reinterpret_cast<float **>(src)[chIdx][srcIdx];
  5021. (*out_rgba)[4 * idx + 1] =
  5022. reinterpret_cast<float **>(src)[chIdx][srcIdx];
  5023. (*out_rgba)[4 * idx + 2] =
  5024. reinterpret_cast<float **>(src)[chIdx][srcIdx];
  5025. (*out_rgba)[4 * idx + 3] =
  5026. reinterpret_cast<float **>(src)[chIdx][srcIdx];
  5027. }
  5028. }
  5029. }
  5030. } else {
  5031. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  5032. const float val =
  5033. reinterpret_cast<float **>(exr_image.images)[chIdx][i];
  5034. (*out_rgba)[4 * i + 0] = val;
  5035. (*out_rgba)[4 * i + 1] = val;
  5036. (*out_rgba)[4 * i + 2] = val;
  5037. (*out_rgba)[4 * i + 3] = val;
  5038. }
  5039. }
  5040. } else {
  5041. // Assume RGB(A)
  5042. if (idxR == -1) {
  5043. tinyexr::SetErrorMessage("R channel not found", err);
  5044. FreeEXRHeader(&exr_header);
  5045. FreeEXRImage(&exr_image);
  5046. return TINYEXR_ERROR_INVALID_DATA;
  5047. }
  5048. if (idxG == -1) {
  5049. tinyexr::SetErrorMessage("G channel not found", err);
  5050. FreeEXRHeader(&exr_header);
  5051. FreeEXRImage(&exr_image);
  5052. return TINYEXR_ERROR_INVALID_DATA;
  5053. }
  5054. if (idxB == -1) {
  5055. tinyexr::SetErrorMessage("B channel not found", err);
  5056. FreeEXRHeader(&exr_header);
  5057. FreeEXRImage(&exr_image);
  5058. return TINYEXR_ERROR_INVALID_DATA;
  5059. }
  5060. (*out_rgba) = reinterpret_cast<float *>(
  5061. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  5062. static_cast<size_t>(exr_image.height)));
  5063. if (exr_header.tiled) {
  5064. for (int it = 0; it < exr_image.num_tiles; it++) {
  5065. for (int j = 0; j < exr_header.tile_size_y; j++) {
  5066. for (int i = 0; i < exr_header.tile_size_x; i++) {
  5067. const int ii =
  5068. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  5069. const int jj =
  5070. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  5071. const int idx = ii + jj * exr_image.width;
  5072. // out of region check.
  5073. if (ii >= exr_image.width) {
  5074. continue;
  5075. }
  5076. if (jj >= exr_image.height) {
  5077. continue;
  5078. }
  5079. const int srcIdx = i + j * exr_header.tile_size_x;
  5080. unsigned char **src = exr_image.tiles[it].images;
  5081. (*out_rgba)[4 * idx + 0] =
  5082. reinterpret_cast<float **>(src)[idxR][srcIdx];
  5083. (*out_rgba)[4 * idx + 1] =
  5084. reinterpret_cast<float **>(src)[idxG][srcIdx];
  5085. (*out_rgba)[4 * idx + 2] =
  5086. reinterpret_cast<float **>(src)[idxB][srcIdx];
  5087. if (idxA != -1) {
  5088. (*out_rgba)[4 * idx + 3] =
  5089. reinterpret_cast<float **>(src)[idxA][srcIdx];
  5090. } else {
  5091. (*out_rgba)[4 * idx + 3] = 1.0;
  5092. }
  5093. }
  5094. }
  5095. }
  5096. } else {
  5097. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  5098. (*out_rgba)[4 * i + 0] =
  5099. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  5100. (*out_rgba)[4 * i + 1] =
  5101. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  5102. (*out_rgba)[4 * i + 2] =
  5103. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  5104. if (idxA != -1) {
  5105. (*out_rgba)[4 * i + 3] =
  5106. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  5107. } else {
  5108. (*out_rgba)[4 * i + 3] = 1.0;
  5109. }
  5110. }
  5111. }
  5112. }
  5113. (*width) = exr_image.width;
  5114. (*height) = exr_image.height;
  5115. FreeEXRHeader(&exr_header);
  5116. FreeEXRImage(&exr_image);
  5117. return TINYEXR_SUCCESS;
  5118. }
  5119. int IsEXR(const char *filename) {
  5120. EXRVersion exr_version;
  5121. int ret = ParseEXRVersionFromFile(&exr_version, filename);
  5122. if (ret != TINYEXR_SUCCESS) {
  5123. return ret;
  5124. }
  5125. return TINYEXR_SUCCESS;
  5126. }
  5127. int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,
  5128. const unsigned char *memory, size_t size,
  5129. const char **err) {
  5130. if (memory == NULL || exr_header == NULL) {
  5131. tinyexr::SetErrorMessage(
  5132. "Invalid argument. `memory` or `exr_header` argument is null in "
  5133. "ParseEXRHeaderFromMemory()",
  5134. err);
  5135. // Invalid argument
  5136. return TINYEXR_ERROR_INVALID_ARGUMENT;
  5137. }
  5138. if (size < tinyexr::kEXRVersionSize) {
  5139. tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
  5140. return TINYEXR_ERROR_INVALID_DATA;
  5141. }
  5142. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  5143. size_t marker_size = size - tinyexr::kEXRVersionSize;
  5144. tinyexr::HeaderInfo info;
  5145. info.clear();
  5146. int ret;
  5147. {
  5148. std::string err_str;
  5149. ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
  5150. if (ret != TINYEXR_SUCCESS) {
  5151. if (err && !err_str.empty()) {
  5152. tinyexr::SetErrorMessage(err_str, err);
  5153. }
  5154. }
  5155. }
  5156. {
  5157. std::string warn;
  5158. std::string err_str;
  5159. if (!ConvertHeader(exr_header, info, &warn, &err_str)) {
  5160. if (err && !err_str.empty()) {
  5161. tinyexr::SetErrorMessage(err_str, err);
  5162. }
  5163. ret = TINYEXR_ERROR_INVALID_HEADER;
  5164. }
  5165. }
  5166. exr_header->multipart = version->multipart ? 1 : 0;
  5167. exr_header->non_image = version->non_image ? 1 : 0;
  5168. return ret;
  5169. }
  5170. int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
  5171. const unsigned char *memory, size_t size,
  5172. const char **err) {
  5173. if (out_rgba == NULL || memory == NULL) {
  5174. tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
  5175. return TINYEXR_ERROR_INVALID_ARGUMENT;
  5176. }
  5177. EXRVersion exr_version;
  5178. EXRImage exr_image;
  5179. EXRHeader exr_header;
  5180. InitEXRHeader(&exr_header);
  5181. int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
  5182. if (ret != TINYEXR_SUCCESS) {
  5183. std::stringstream ss;
  5184. ss << "Failed to parse EXR version. code(" << ret << ")";
  5185. tinyexr::SetErrorMessage(ss.str(), err);
  5186. return ret;
  5187. }
  5188. ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
  5189. if (ret != TINYEXR_SUCCESS) {
  5190. return ret;
  5191. }
  5192. // Read HALF channel as FLOAT.
  5193. for (int i = 0; i < exr_header.num_channels; i++) {
  5194. if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
  5195. exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  5196. }
  5197. }
  5198. InitEXRImage(&exr_image);
  5199. ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
  5200. if (ret != TINYEXR_SUCCESS) {
  5201. return ret;
  5202. }
  5203. // RGBA
  5204. int idxR = -1;
  5205. int idxG = -1;
  5206. int idxB = -1;
  5207. int idxA = -1;
  5208. for (int c = 0; c < exr_header.num_channels; c++) {
  5209. if (strcmp(exr_header.channels[c].name, "R") == 0) {
  5210. idxR = c;
  5211. } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
  5212. idxG = c;
  5213. } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
  5214. idxB = c;
  5215. } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
  5216. idxA = c;
  5217. }
  5218. }
  5219. // TODO(syoyo): Refactor removing same code as used in LoadEXR().
  5220. if (exr_header.num_channels == 1) {
  5221. // Grayscale channel only.
  5222. (*out_rgba) = reinterpret_cast<float *>(
  5223. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  5224. static_cast<size_t>(exr_image.height)));
  5225. if (exr_header.tiled) {
  5226. for (int it = 0; it < exr_image.num_tiles; it++) {
  5227. for (int j = 0; j < exr_header.tile_size_y; j++) {
  5228. for (int i = 0; i < exr_header.tile_size_x; i++) {
  5229. const int ii =
  5230. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  5231. const int jj =
  5232. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  5233. const int idx = ii + jj * exr_image.width;
  5234. // out of region check.
  5235. if (ii >= exr_image.width) {
  5236. continue;
  5237. }
  5238. if (jj >= exr_image.height) {
  5239. continue;
  5240. }
  5241. const int srcIdx = i + j * exr_header.tile_size_x;
  5242. unsigned char **src = exr_image.tiles[it].images;
  5243. (*out_rgba)[4 * idx + 0] =
  5244. reinterpret_cast<float **>(src)[0][srcIdx];
  5245. (*out_rgba)[4 * idx + 1] =
  5246. reinterpret_cast<float **>(src)[0][srcIdx];
  5247. (*out_rgba)[4 * idx + 2] =
  5248. reinterpret_cast<float **>(src)[0][srcIdx];
  5249. (*out_rgba)[4 * idx + 3] =
  5250. reinterpret_cast<float **>(src)[0][srcIdx];
  5251. }
  5252. }
  5253. }
  5254. } else {
  5255. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  5256. const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
  5257. (*out_rgba)[4 * i + 0] = val;
  5258. (*out_rgba)[4 * i + 1] = val;
  5259. (*out_rgba)[4 * i + 2] = val;
  5260. (*out_rgba)[4 * i + 3] = val;
  5261. }
  5262. }
  5263. } else {
  5264. // TODO(syoyo): Support non RGBA image.
  5265. if (idxR == -1) {
  5266. tinyexr::SetErrorMessage("R channel not found", err);
  5267. // @todo { free exr_image }
  5268. return TINYEXR_ERROR_INVALID_DATA;
  5269. }
  5270. if (idxG == -1) {
  5271. tinyexr::SetErrorMessage("G channel not found", err);
  5272. // @todo { free exr_image }
  5273. return TINYEXR_ERROR_INVALID_DATA;
  5274. }
  5275. if (idxB == -1) {
  5276. tinyexr::SetErrorMessage("B channel not found", err);
  5277. // @todo { free exr_image }
  5278. return TINYEXR_ERROR_INVALID_DATA;
  5279. }
  5280. (*out_rgba) = reinterpret_cast<float *>(
  5281. malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
  5282. static_cast<size_t>(exr_image.height)));
  5283. if (exr_header.tiled) {
  5284. for (int it = 0; it < exr_image.num_tiles; it++) {
  5285. for (int j = 0; j < exr_header.tile_size_y; j++)
  5286. for (int i = 0; i < exr_header.tile_size_x; i++) {
  5287. const int ii =
  5288. exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
  5289. const int jj =
  5290. exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
  5291. const int idx = ii + jj * exr_image.width;
  5292. // out of region check.
  5293. if (ii >= exr_image.width) {
  5294. continue;
  5295. }
  5296. if (jj >= exr_image.height) {
  5297. continue;
  5298. }
  5299. const int srcIdx = i + j * exr_header.tile_size_x;
  5300. unsigned char **src = exr_image.tiles[it].images;
  5301. (*out_rgba)[4 * idx + 0] =
  5302. reinterpret_cast<float **>(src)[idxR][srcIdx];
  5303. (*out_rgba)[4 * idx + 1] =
  5304. reinterpret_cast<float **>(src)[idxG][srcIdx];
  5305. (*out_rgba)[4 * idx + 2] =
  5306. reinterpret_cast<float **>(src)[idxB][srcIdx];
  5307. if (idxA != -1) {
  5308. (*out_rgba)[4 * idx + 3] =
  5309. reinterpret_cast<float **>(src)[idxA][srcIdx];
  5310. } else {
  5311. (*out_rgba)[4 * idx + 3] = 1.0;
  5312. }
  5313. }
  5314. }
  5315. } else {
  5316. for (int i = 0; i < exr_image.width * exr_image.height; i++) {
  5317. (*out_rgba)[4 * i + 0] =
  5318. reinterpret_cast<float **>(exr_image.images)[idxR][i];
  5319. (*out_rgba)[4 * i + 1] =
  5320. reinterpret_cast<float **>(exr_image.images)[idxG][i];
  5321. (*out_rgba)[4 * i + 2] =
  5322. reinterpret_cast<float **>(exr_image.images)[idxB][i];
  5323. if (idxA != -1) {
  5324. (*out_rgba)[4 * i + 3] =
  5325. reinterpret_cast<float **>(exr_image.images)[idxA][i];
  5326. } else {
  5327. (*out_rgba)[4 * i + 3] = 1.0;
  5328. }
  5329. }
  5330. }
  5331. }
  5332. (*width) = exr_image.width;
  5333. (*height) = exr_image.height;
  5334. FreeEXRHeader(&exr_header);
  5335. FreeEXRImage(&exr_image);
  5336. return TINYEXR_SUCCESS;
  5337. }
  5338. int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,
  5339. const char *filename, const char **err) {
  5340. if (exr_image == NULL) {
  5341. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
  5342. return TINYEXR_ERROR_INVALID_ARGUMENT;
  5343. }
  5344. FILE *fp = NULL;
  5345. #ifdef _WIN32
  5346. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  5347. errno_t errcode =
  5348. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  5349. if (errcode != 0) {
  5350. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  5351. // TODO(syoyo): return wfopen_s erro code
  5352. return TINYEXR_ERROR_CANT_OPEN_FILE;
  5353. }
  5354. #else
  5355. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  5356. fp = fopen(filename, "rb");
  5357. #endif
  5358. #else
  5359. fp = fopen(filename, "rb");
  5360. #endif
  5361. if (!fp) {
  5362. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  5363. return TINYEXR_ERROR_CANT_OPEN_FILE;
  5364. }
  5365. size_t filesize;
  5366. // Compute size
  5367. fseek(fp, 0, SEEK_END);
  5368. filesize = static_cast<size_t>(ftell(fp));
  5369. fseek(fp, 0, SEEK_SET);
  5370. if (filesize < 16) {
  5371. tinyexr::SetErrorMessage("File size too short " + std::string(filename),
  5372. err);
  5373. return TINYEXR_ERROR_INVALID_FILE;
  5374. }
  5375. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  5376. {
  5377. size_t ret;
  5378. ret = fread(&buf[0], 1, filesize, fp);
  5379. assert(ret == filesize);
  5380. fclose(fp);
  5381. (void)ret;
  5382. }
  5383. return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize,
  5384. err);
  5385. }
  5386. int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,
  5387. const unsigned char *memory, const size_t size,
  5388. const char **err) {
  5389. if (exr_image == NULL || memory == NULL ||
  5390. (size < tinyexr::kEXRVersionSize)) {
  5391. tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
  5392. err);
  5393. return TINYEXR_ERROR_INVALID_ARGUMENT;
  5394. }
  5395. if (exr_header->header_len == 0) {
  5396. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  5397. return TINYEXR_ERROR_INVALID_ARGUMENT;
  5398. }
  5399. const unsigned char *head = memory;
  5400. const unsigned char *marker = reinterpret_cast<const unsigned char *>(
  5401. memory + exr_header->header_len +
  5402. 8); // +8 for magic number + version header.
  5403. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
  5404. err);
  5405. }
  5406. namespace tinyexr
  5407. {
  5408. // out_data must be allocated initially with the block-header size
  5409. // of the current image(-part) type
  5410. static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data,
  5411. const unsigned char* const* images,
  5412. int compression_type,
  5413. int /*line_order*/,
  5414. int width, // for tiled : tile.width
  5415. int /*height*/, // for tiled : header.tile_size_y
  5416. int x_stride, // for tiled : header.tile_size_x
  5417. int line_no, // for tiled : 0
  5418. int num_lines, // for tiled : tile.height
  5419. size_t pixel_data_size,
  5420. const std::vector<ChannelInfo>& channels,
  5421. const std::vector<size_t>& channel_offset_list,
  5422. const void* compression_param = 0) // zfp compression param
  5423. {
  5424. size_t buf_size = static_cast<size_t>(width) *
  5425. static_cast<size_t>(num_lines) *
  5426. static_cast<size_t>(pixel_data_size);
  5427. //int last2bit = (buf_size & 3);
  5428. // buf_size must be multiple of four
  5429. //if(last2bit) buf_size += 4 - last2bit;
  5430. std::vector<unsigned char> buf(buf_size);
  5431. size_t start_y = static_cast<size_t>(line_no);
  5432. for (size_t c = 0; c < channels.size(); c++) {
  5433. if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
  5434. if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  5435. for (int y = 0; y < num_lines; y++) {
  5436. // Assume increasing Y
  5437. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  5438. static_cast<size_t>(pixel_data_size * y * width) +
  5439. channel_offset_list[c] *
  5440. static_cast<size_t>(width)));
  5441. for (int x = 0; x < width; x++) {
  5442. tinyexr::FP16 h16;
  5443. h16.u = reinterpret_cast<const unsigned short * const *>(
  5444. images)[c][(y + start_y) * x_stride + x];
  5445. tinyexr::FP32 f32 = half_to_float(h16);
  5446. tinyexr::swap4(&f32.f);
  5447. // line_ptr[x] = f32.f;
  5448. tinyexr::cpy4(line_ptr + x, &(f32.f));
  5449. }
  5450. }
  5451. } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
  5452. for (int y = 0; y < num_lines; y++) {
  5453. // Assume increasing Y
  5454. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  5455. &buf.at(static_cast<size_t>(pixel_data_size * y *
  5456. width) +
  5457. channel_offset_list[c] *
  5458. static_cast<size_t>(width)));
  5459. for (int x = 0; x < width; x++) {
  5460. unsigned short val = reinterpret_cast<const unsigned short * const *>(
  5461. images)[c][(y + start_y) * x_stride + x];
  5462. tinyexr::swap2(&val);
  5463. // line_ptr[x] = val;
  5464. tinyexr::cpy2(line_ptr + x, &val);
  5465. }
  5466. }
  5467. } else {
  5468. assert(0);
  5469. }
  5470. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  5471. if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
  5472. for (int y = 0; y < num_lines; y++) {
  5473. // Assume increasing Y
  5474. unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
  5475. &buf.at(static_cast<size_t>(pixel_data_size * y *
  5476. width) +
  5477. channel_offset_list[c] *
  5478. static_cast<size_t>(width)));
  5479. for (int x = 0; x < width; x++) {
  5480. tinyexr::FP32 f32;
  5481. f32.f = reinterpret_cast<const float * const *>(
  5482. images)[c][(y + start_y) * x_stride + x];
  5483. tinyexr::FP16 h16;
  5484. h16 = float_to_half_full(f32);
  5485. tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));
  5486. // line_ptr[x] = h16.u;
  5487. tinyexr::cpy2(line_ptr + x, &(h16.u));
  5488. }
  5489. }
  5490. } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
  5491. for (int y = 0; y < num_lines; y++) {
  5492. // Assume increasing Y
  5493. float *line_ptr = reinterpret_cast<float *>(&buf.at(
  5494. static_cast<size_t>(pixel_data_size * y * width) +
  5495. channel_offset_list[c] *
  5496. static_cast<size_t>(width)));
  5497. for (int x = 0; x < width; x++) {
  5498. float val = reinterpret_cast<const float * const *>(
  5499. images)[c][(y + start_y) * x_stride + x];
  5500. tinyexr::swap4(&val);
  5501. // line_ptr[x] = val;
  5502. tinyexr::cpy4(line_ptr + x, &val);
  5503. }
  5504. }
  5505. } else {
  5506. assert(0);
  5507. }
  5508. } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
  5509. for (int y = 0; y < num_lines; y++) {
  5510. // Assume increasing Y
  5511. unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(
  5512. static_cast<size_t>(pixel_data_size * y * width) +
  5513. channel_offset_list[c] * static_cast<size_t>(width)));
  5514. for (int x = 0; x < width; x++) {
  5515. unsigned int val = reinterpret_cast<const unsigned int * const *>(
  5516. images)[c][(y + start_y) * x_stride + x];
  5517. tinyexr::swap4(&val);
  5518. // line_ptr[x] = val;
  5519. tinyexr::cpy4(line_ptr + x, &val);
  5520. }
  5521. }
  5522. }
  5523. }
  5524. if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
  5525. // 4 byte: scan line
  5526. // 4 byte: data size
  5527. // ~ : pixel data(uncompressed)
  5528. out_data.insert(out_data.end(), buf.begin(), buf.end());
  5529. } else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  5530. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  5531. #if TINYEXR_USE_MINIZ
  5532. std::vector<unsigned char> block(mz_compressBound(
  5533. static_cast<unsigned long>(buf.size())));
  5534. #else
  5535. std::vector<unsigned char> block(
  5536. compressBound(static_cast<uLong>(buf.size())));
  5537. #endif
  5538. tinyexr::tinyexr_uint64 outSize = block.size();
  5539. tinyexr::CompressZip(&block.at(0), outSize,
  5540. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  5541. static_cast<unsigned long>(buf.size()));
  5542. // 4 byte: scan line
  5543. // 4 byte: data size
  5544. // ~ : pixel data(compressed)
  5545. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  5546. out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
  5547. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
  5548. // (buf.size() * 3) / 2 would be enough.
  5549. std::vector<unsigned char> block((buf.size() * 3) / 2);
  5550. tinyexr::tinyexr_uint64 outSize = block.size();
  5551. tinyexr::CompressRle(&block.at(0), outSize,
  5552. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  5553. static_cast<unsigned long>(buf.size()));
  5554. // 4 byte: scan line
  5555. // 4 byte: data size
  5556. // ~ : pixel data(compressed)
  5557. unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
  5558. out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
  5559. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  5560. #if TINYEXR_USE_PIZ
  5561. unsigned int bufLen =
  5562. 8192 + static_cast<unsigned int>(
  5563. 2 * static_cast<unsigned int>(
  5564. buf.size())); // @fixme { compute good bound. }
  5565. std::vector<unsigned char> block(bufLen);
  5566. unsigned int outSize = static_cast<unsigned int>(block.size());
  5567. CompressPiz(&block.at(0), &outSize,
  5568. reinterpret_cast<const unsigned char *>(&buf.at(0)),
  5569. buf.size(), channels, width, num_lines);
  5570. // 4 byte: scan line
  5571. // 4 byte: data size
  5572. // ~ : pixel data(compressed)
  5573. unsigned int data_len = outSize;
  5574. out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
  5575. #else
  5576. assert(0);
  5577. #endif
  5578. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  5579. #if TINYEXR_USE_ZFP
  5580. const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param);
  5581. std::vector<unsigned char> block;
  5582. unsigned int outSize;
  5583. tinyexr::CompressZfp(
  5584. &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),
  5585. width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param);
  5586. // 4 byte: scan line
  5587. // 4 byte: data size
  5588. // ~ : pixel data(compressed)
  5589. unsigned int data_len = outSize;
  5590. out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
  5591. #else
  5592. (void)compression_param;
  5593. assert(0);
  5594. #endif
  5595. } else {
  5596. assert(0);
  5597. return false;
  5598. }
  5599. return true;
  5600. }
  5601. static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header,
  5602. const std::vector<tinyexr::ChannelInfo>& channels,
  5603. std::vector<std::vector<unsigned char> >& data_list,
  5604. size_t start_index, // for data_list
  5605. int num_x_tiles, int num_y_tiles,
  5606. const std::vector<size_t>& channel_offset_list,
  5607. int pixel_data_size,
  5608. const void* compression_param, // must be set if zfp compression is enabled
  5609. std::string* err) {
  5610. int num_tiles = num_x_tiles * num_y_tiles;
  5611. assert(num_tiles == level_image->num_tiles);
  5612. if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) &&
  5613. level_image->level_x == 0 && level_image->level_y == 0) {
  5614. if (err) {
  5615. (*err) += "Failed to encode tile data.\n";
  5616. }
  5617. return TINYEXR_ERROR_INVALID_DATA;
  5618. }
  5619. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  5620. std::atomic<bool> invalid_data(false);
  5621. #else
  5622. bool invalid_data(false);
  5623. #endif
  5624. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  5625. std::vector<std::thread> workers;
  5626. std::atomic<int> tile_count(0);
  5627. int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
  5628. if (num_threads > int(num_tiles)) {
  5629. num_threads = int(num_tiles);
  5630. }
  5631. for (int t = 0; t < num_threads; t++) {
  5632. workers.emplace_back(std::thread([&]() {
  5633. int i = 0;
  5634. while ((i = tile_count++) < num_tiles) {
  5635. #else
  5636. // Use signed int since some OpenMP compiler doesn't allow unsigned type for
  5637. // `parallel for`
  5638. #if TINYEXR_USE_OPENMP
  5639. #pragma omp parallel for
  5640. #endif
  5641. for (int i = 0; i < num_tiles; i++) {
  5642. #endif
  5643. size_t tile_idx = static_cast<size_t>(i);
  5644. size_t data_idx = tile_idx + start_index;
  5645. int x_tile = i % num_x_tiles;
  5646. int y_tile = i / num_x_tiles;
  5647. EXRTile& tile = level_image->tiles[tile_idx];
  5648. const unsigned char* const* images =
  5649. static_cast<const unsigned char* const*>(tile.images);
  5650. data_list[data_idx].resize(5*sizeof(int));
  5651. size_t data_header_size = data_list[data_idx].size();
  5652. bool ret = EncodePixelData(data_list[data_idx],
  5653. images,
  5654. exr_header->compression_type,
  5655. 0, // increasing y
  5656. tile.width,
  5657. exr_header->tile_size_y,
  5658. exr_header->tile_size_x,
  5659. 0,
  5660. tile.height,
  5661. pixel_data_size,
  5662. channels,
  5663. channel_offset_list,
  5664. compression_param);
  5665. if (!ret) {
  5666. invalid_data = true;
  5667. continue;
  5668. }
  5669. assert(data_list[data_idx].size() > data_header_size);
  5670. int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size);
  5671. //tileX, tileY, levelX, levelY // pixel_data_size(int)
  5672. memcpy(&data_list[data_idx][0], &x_tile, sizeof(int));
  5673. memcpy(&data_list[data_idx][4], &y_tile, sizeof(int));
  5674. memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int));
  5675. memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int));
  5676. memcpy(&data_list[data_idx][16], &data_len, sizeof(int));
  5677. swap4(reinterpret_cast<int*>(&data_list[data_idx][0]));
  5678. swap4(reinterpret_cast<int*>(&data_list[data_idx][4]));
  5679. swap4(reinterpret_cast<int*>(&data_list[data_idx][8]));
  5680. swap4(reinterpret_cast<int*>(&data_list[data_idx][12]));
  5681. swap4(reinterpret_cast<int*>(&data_list[data_idx][16]));
  5682. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  5683. }
  5684. }));
  5685. }
  5686. for (auto &t : workers) {
  5687. t.join();
  5688. }
  5689. #else
  5690. } // omp parallel
  5691. #endif
  5692. if (invalid_data) {
  5693. if (err) {
  5694. (*err) += "Failed to encode tile data.\n";
  5695. }
  5696. return TINYEXR_ERROR_INVALID_DATA;
  5697. }
  5698. return TINYEXR_SUCCESS;
  5699. }
  5700. static int NumScanlines(int compression_type) {
  5701. int num_scanlines = 1;
  5702. if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  5703. num_scanlines = 16;
  5704. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  5705. num_scanlines = 32;
  5706. } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  5707. num_scanlines = 16;
  5708. }
  5709. return num_scanlines;
  5710. }
  5711. static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header,
  5712. const std::vector<ChannelInfo>& channels,
  5713. int num_blocks,
  5714. tinyexr_uint64 chunk_offset, // starting offset of current chunk
  5715. bool is_multipart,
  5716. OffsetData& offset_data, // output block offsets, must be initialized
  5717. std::vector<std::vector<unsigned char> >& data_list, // output
  5718. tinyexr_uint64& total_size, // output: ending offset of current chunk
  5719. std::string* err) {
  5720. int num_scanlines = NumScanlines(exr_header->compression_type);
  5721. data_list.resize(num_blocks);
  5722. std::vector<size_t> channel_offset_list(
  5723. static_cast<size_t>(exr_header->num_channels));
  5724. int pixel_data_size = 0;
  5725. {
  5726. size_t channel_offset = 0;
  5727. for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
  5728. channel_offset_list[c] = channel_offset;
  5729. if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
  5730. pixel_data_size += sizeof(unsigned short);
  5731. channel_offset += sizeof(unsigned short);
  5732. } else if (channels[c].requested_pixel_type ==
  5733. TINYEXR_PIXELTYPE_FLOAT) {
  5734. pixel_data_size += sizeof(float);
  5735. channel_offset += sizeof(float);
  5736. } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_UINT) {
  5737. pixel_data_size += sizeof(unsigned int);
  5738. channel_offset += sizeof(unsigned int);
  5739. } else {
  5740. assert(0);
  5741. }
  5742. }
  5743. }
  5744. const void* compression_param = 0;
  5745. #if TINYEXR_USE_ZFP
  5746. tinyexr::ZFPCompressionParam zfp_compression_param;
  5747. // Use ZFP compression parameter from custom attributes(if such a parameter
  5748. // exists)
  5749. {
  5750. std::string e;
  5751. bool ret = tinyexr::FindZFPCompressionParam(
  5752. &zfp_compression_param, exr_header->custom_attributes,
  5753. exr_header->num_custom_attributes, &e);
  5754. if (!ret) {
  5755. // Use predefined compression parameter.
  5756. zfp_compression_param.type = 0;
  5757. zfp_compression_param.rate = 2;
  5758. }
  5759. compression_param = &zfp_compression_param;
  5760. }
  5761. #endif
  5762. tinyexr_uint64 offset = chunk_offset;
  5763. tinyexr_uint64 doffset = is_multipart ? 4u : 0u;
  5764. if (exr_image->tiles) {
  5765. const EXRImage* level_image = exr_image;
  5766. size_t block_idx = 0;
  5767. tinyexr::tinyexr_uint64 block_data_size = 0;
  5768. int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?
  5769. offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels);
  5770. for (int level_index = 0; level_index < num_levels; ++level_index) {
  5771. if (!level_image) {
  5772. if (err) {
  5773. (*err) += "Invalid number of tiled levels for EncodeChunk\n";
  5774. }
  5775. return TINYEXR_ERROR_INVALID_DATA;
  5776. }
  5777. int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y,
  5778. exr_header->tile_level_mode, offset_data.num_x_levels);
  5779. if (level_index_from_image != level_index) {
  5780. if (err) {
  5781. (*err) += "Incorrect level ordering in tiled image\n";
  5782. }
  5783. return TINYEXR_ERROR_INVALID_DATA;
  5784. }
  5785. int num_y_tiles = (int)offset_data.offsets[level_index].size();
  5786. assert(num_y_tiles);
  5787. int num_x_tiles = (int)offset_data.offsets[level_index][0].size();
  5788. assert(num_x_tiles);
  5789. std::string e;
  5790. int ret = EncodeTiledLevel(level_image,
  5791. exr_header,
  5792. channels,
  5793. data_list,
  5794. block_idx,
  5795. num_x_tiles,
  5796. num_y_tiles,
  5797. channel_offset_list,
  5798. pixel_data_size,
  5799. compression_param,
  5800. &e);
  5801. if (ret != TINYEXR_SUCCESS) {
  5802. if (!e.empty() && err) {
  5803. (*err) += e;
  5804. }
  5805. return ret;
  5806. }
  5807. for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j)
  5808. for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) {
  5809. offset_data.offsets[level_index][j][i] = offset;
  5810. swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i]));
  5811. offset += data_list[block_idx].size() + doffset;
  5812. block_data_size += data_list[block_idx].size();
  5813. ++block_idx;
  5814. }
  5815. level_image = level_image->next_level;
  5816. }
  5817. assert(static_cast<int>(block_idx) == num_blocks);
  5818. total_size = offset;
  5819. } else { // scanlines
  5820. std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
  5821. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  5822. std::atomic<bool> invalid_data(false);
  5823. std::vector<std::thread> workers;
  5824. std::atomic<int> block_count(0);
  5825. int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks);
  5826. for (int t = 0; t < num_threads; t++) {
  5827. workers.emplace_back(std::thread([&]() {
  5828. int i = 0;
  5829. while ((i = block_count++) < num_blocks) {
  5830. #else
  5831. bool invalid_data(false);
  5832. #if TINYEXR_USE_OPENMP
  5833. #pragma omp parallel for
  5834. #endif
  5835. for (int i = 0; i < num_blocks; i++) {
  5836. #endif
  5837. int start_y = num_scanlines * i;
  5838. int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height);
  5839. int num_lines = end_Y - start_y;
  5840. const unsigned char* const* images =
  5841. static_cast<const unsigned char* const*>(exr_image->images);
  5842. data_list[i].resize(2*sizeof(int));
  5843. size_t data_header_size = data_list[i].size();
  5844. bool ret = EncodePixelData(data_list[i],
  5845. images,
  5846. exr_header->compression_type,
  5847. 0, // increasing y
  5848. exr_image->width,
  5849. exr_image->height,
  5850. exr_image->width,
  5851. start_y,
  5852. num_lines,
  5853. pixel_data_size,
  5854. channels,
  5855. channel_offset_list,
  5856. compression_param);
  5857. if (!ret) {
  5858. invalid_data = true;
  5859. continue; // "break" cannot be used with OpenMP
  5860. }
  5861. assert(data_list[i].size() > data_header_size);
  5862. int data_len = static_cast<int>(data_list[i].size() - data_header_size);
  5863. memcpy(&data_list[i][0], &start_y, sizeof(int));
  5864. memcpy(&data_list[i][4], &data_len, sizeof(int));
  5865. swap4(reinterpret_cast<int*>(&data_list[i][0]));
  5866. swap4(reinterpret_cast<int*>(&data_list[i][4]));
  5867. #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
  5868. }
  5869. }));
  5870. }
  5871. for (auto &t : workers) {
  5872. t.join();
  5873. }
  5874. #else
  5875. } // omp parallel
  5876. #endif
  5877. if (invalid_data) {
  5878. if (err) {
  5879. (*err) += "Failed to encode scanline data.\n";
  5880. }
  5881. return TINYEXR_ERROR_INVALID_DATA;
  5882. }
  5883. for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
  5884. offsets[i] = offset;
  5885. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));
  5886. offset += data_list[i].size() + doffset;
  5887. }
  5888. total_size = static_cast<size_t>(offset);
  5889. }
  5890. return TINYEXR_SUCCESS;
  5891. }
  5892. // can save a single or multi-part image (no deep* formats)
  5893. static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images,
  5894. const EXRHeader** exr_headers,
  5895. unsigned int num_parts,
  5896. unsigned char** memory_out, const char** err) {
  5897. if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
  5898. memory_out == NULL) {
  5899. SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
  5900. err);
  5901. return 0;
  5902. }
  5903. {
  5904. for (unsigned int i = 0; i < num_parts; ++i) {
  5905. if (exr_headers[i]->compression_type < 0) {
  5906. SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
  5907. err);
  5908. return 0;
  5909. }
  5910. #if !TINYEXR_USE_PIZ
  5911. if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  5912. SetErrorMessage("PIZ compression is not supported in this build",
  5913. err);
  5914. return 0;
  5915. }
  5916. #endif
  5917. #if !TINYEXR_USE_ZFP
  5918. if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  5919. SetErrorMessage("ZFP compression is not supported in this build",
  5920. err);
  5921. return 0;
  5922. }
  5923. #else
  5924. for (int c = 0; c < exr_header->num_channels; ++c) {
  5925. if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) {
  5926. SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
  5927. err);
  5928. return 0;
  5929. }
  5930. }
  5931. #endif
  5932. }
  5933. }
  5934. std::vector<unsigned char> memory;
  5935. // Header
  5936. {
  5937. const char header[] = { 0x76, 0x2f, 0x31, 0x01 };
  5938. memory.insert(memory.end(), header, header + 4);
  5939. }
  5940. // Version
  5941. // using value from the first header
  5942. int long_name = exr_headers[0]->long_name;
  5943. {
  5944. char marker[] = { 2, 0, 0, 0 };
  5945. /* @todo
  5946. if (exr_header->non_image) {
  5947. marker[1] |= 0x8;
  5948. }
  5949. */
  5950. // tiled
  5951. if (num_parts == 1 && exr_images[0].tiles) {
  5952. marker[1] |= 0x2;
  5953. }
  5954. // long_name
  5955. if (long_name) {
  5956. marker[1] |= 0x4;
  5957. }
  5958. // multipart
  5959. if (num_parts > 1) {
  5960. marker[1] |= 0x10;
  5961. }
  5962. memory.insert(memory.end(), marker, marker + 4);
  5963. }
  5964. int total_chunk_count = 0;
  5965. std::vector<int> chunk_count(num_parts);
  5966. std::vector<OffsetData> offset_data(num_parts);
  5967. for (unsigned int i = 0; i < num_parts; ++i) {
  5968. if (!exr_images[i].tiles) {
  5969. int num_scanlines = NumScanlines(exr_headers[i]->compression_type);
  5970. chunk_count[i] =
  5971. (exr_images[i].height + num_scanlines - 1) / num_scanlines;
  5972. InitSingleResolutionOffsets(offset_data[i], chunk_count[i]);
  5973. total_chunk_count += chunk_count[i];
  5974. } else {
  5975. {
  5976. std::vector<int> num_x_tiles, num_y_tiles;
  5977. PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]);
  5978. chunk_count[i] =
  5979. InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles);
  5980. total_chunk_count += chunk_count[i];
  5981. }
  5982. }
  5983. }
  5984. // Write attributes to memory buffer.
  5985. std::vector< std::vector<tinyexr::ChannelInfo> > channels(num_parts);
  5986. {
  5987. std::set<std::string> partnames;
  5988. for (unsigned int i = 0; i < num_parts; ++i) {
  5989. //channels
  5990. {
  5991. std::vector<unsigned char> data;
  5992. for (int c = 0; c < exr_headers[i]->num_channels; c++) {
  5993. tinyexr::ChannelInfo info;
  5994. info.p_linear = 0;
  5995. info.pixel_type = exr_headers[i]->pixel_types[c];
  5996. info.requested_pixel_type = exr_headers[i]->requested_pixel_types[c];
  5997. info.x_sampling = 1;
  5998. info.y_sampling = 1;
  5999. info.name = std::string(exr_headers[i]->channels[c].name);
  6000. channels[i].push_back(info);
  6001. }
  6002. tinyexr::WriteChannelInfo(data, channels[i]);
  6003. tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
  6004. static_cast<int>(data.size()));
  6005. }
  6006. {
  6007. int comp = exr_headers[i]->compression_type;
  6008. swap4(&comp);
  6009. WriteAttributeToMemory(
  6010. &memory, "compression", "compression",
  6011. reinterpret_cast<const unsigned char*>(&comp), 1);
  6012. }
  6013. {
  6014. int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 };
  6015. swap4(&data[0]);
  6016. swap4(&data[1]);
  6017. swap4(&data[2]);
  6018. swap4(&data[3]);
  6019. WriteAttributeToMemory(
  6020. &memory, "dataWindow", "box2i",
  6021. reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4);
  6022. int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 };
  6023. swap4(&data0[0]);
  6024. swap4(&data0[1]);
  6025. swap4(&data0[2]);
  6026. swap4(&data0[3]);
  6027. // Note: must be the same across parts (currently, using value from the first header)
  6028. WriteAttributeToMemory(
  6029. &memory, "displayWindow", "box2i",
  6030. reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4);
  6031. }
  6032. {
  6033. unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
  6034. WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
  6035. &line_order, 1);
  6036. }
  6037. {
  6038. // Note: must be the same across parts
  6039. float aspectRatio = 1.0f;
  6040. swap4(&aspectRatio);
  6041. WriteAttributeToMemory(
  6042. &memory, "pixelAspectRatio", "float",
  6043. reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float));
  6044. }
  6045. {
  6046. float center[2] = { 0.0f, 0.0f };
  6047. swap4(&center[0]);
  6048. swap4(&center[1]);
  6049. WriteAttributeToMemory(
  6050. &memory, "screenWindowCenter", "v2f",
  6051. reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float));
  6052. }
  6053. {
  6054. float w = 1.0f;
  6055. swap4(&w);
  6056. WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
  6057. reinterpret_cast<const unsigned char*>(&w),
  6058. sizeof(float));
  6059. }
  6060. if (exr_images[i].tiles) {
  6061. unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3);
  6062. if (exr_headers[i]->tile_rounding_mode) tile_mode |= (1u << 4u);
  6063. //unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  6064. unsigned int datai[3] = { 0, 0, 0 };
  6065. unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]);
  6066. datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x);
  6067. datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y);
  6068. data[8] = tile_mode;
  6069. swap4(reinterpret_cast<unsigned int*>(&data[0]));
  6070. swap4(reinterpret_cast<unsigned int*>(&data[4]));
  6071. WriteAttributeToMemory(
  6072. &memory, "tiles", "tiledesc",
  6073. reinterpret_cast<const unsigned char*>(data), 9);
  6074. }
  6075. // must be present for multi-part files - according to spec.
  6076. if (num_parts > 1) {
  6077. // name
  6078. {
  6079. size_t len = 0;
  6080. if ((len = strlen(exr_headers[i]->name)) > 0) {
  6081. partnames.emplace(exr_headers[i]->name);
  6082. if (partnames.size() != i + 1) {
  6083. SetErrorMessage("'name' attributes must be unique for a multi-part file", err);
  6084. return 0;
  6085. }
  6086. WriteAttributeToMemory(
  6087. &memory, "name", "string",
  6088. reinterpret_cast<const unsigned char*>(exr_headers[i]->name),
  6089. static_cast<int>(len));
  6090. } else {
  6091. SetErrorMessage("Invalid 'name' attribute for a multi-part file", err);
  6092. return 0;
  6093. }
  6094. }
  6095. // type
  6096. {
  6097. const char* type = "scanlineimage";
  6098. if (exr_images[i].tiles) type = "tiledimage";
  6099. WriteAttributeToMemory(
  6100. &memory, "type", "string",
  6101. reinterpret_cast<const unsigned char*>(type),
  6102. static_cast<int>(strlen(type)));
  6103. }
  6104. // chunkCount
  6105. {
  6106. WriteAttributeToMemory(
  6107. &memory, "chunkCount", "int",
  6108. reinterpret_cast<const unsigned char*>(&chunk_count[i]),
  6109. 4);
  6110. }
  6111. }
  6112. // Custom attributes
  6113. if (exr_headers[i]->num_custom_attributes > 0) {
  6114. for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) {
  6115. tinyexr::WriteAttributeToMemory(
  6116. &memory, exr_headers[i]->custom_attributes[j].name,
  6117. exr_headers[i]->custom_attributes[j].type,
  6118. reinterpret_cast<const unsigned char*>(
  6119. exr_headers[i]->custom_attributes[j].value),
  6120. exr_headers[i]->custom_attributes[j].size);
  6121. }
  6122. }
  6123. { // end of header
  6124. memory.push_back(0);
  6125. }
  6126. }
  6127. }
  6128. if (num_parts > 1) {
  6129. // end of header list
  6130. memory.push_back(0);
  6131. }
  6132. tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64);
  6133. tinyexr_uint64 total_size = 0;
  6134. std::vector< std::vector< std::vector<unsigned char> > > data_lists(num_parts);
  6135. for (unsigned int i = 0; i < num_parts; ++i) {
  6136. std::string e;
  6137. int ret = EncodeChunk(&exr_images[i], exr_headers[i],
  6138. channels[i],
  6139. chunk_count[i],
  6140. // starting offset of current chunk after part-number
  6141. chunk_offset,
  6142. num_parts > 1,
  6143. offset_data[i], // output: block offsets, must be initialized
  6144. data_lists[i], // output
  6145. total_size, // output
  6146. &e);
  6147. if (ret != TINYEXR_SUCCESS) {
  6148. if (!e.empty()) {
  6149. tinyexr::SetErrorMessage(e, err);
  6150. }
  6151. return 0;
  6152. }
  6153. chunk_offset = total_size;
  6154. }
  6155. // Allocating required memory
  6156. if (total_size == 0) { // something went wrong
  6157. tinyexr::SetErrorMessage("Output memory size is zero", err);
  6158. return 0;
  6159. }
  6160. (*memory_out) = static_cast<unsigned char*>(malloc(total_size));
  6161. // Writing header
  6162. memcpy((*memory_out), &memory[0], memory.size());
  6163. unsigned char* memory_ptr = *memory_out + memory.size();
  6164. size_t sum = memory.size();
  6165. // Writing offset data for chunks
  6166. for (unsigned int i = 0; i < num_parts; ++i) {
  6167. if (exr_images[i].tiles) {
  6168. const EXRImage* level_image = &exr_images[i];
  6169. int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?
  6170. offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels);
  6171. for (int level_index = 0; level_index < num_levels; ++level_index) {
  6172. for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) {
  6173. size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size();
  6174. sum += num_bytes;
  6175. assert(sum <= total_size);
  6176. memcpy(memory_ptr,
  6177. reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]),
  6178. num_bytes);
  6179. memory_ptr += num_bytes;
  6180. }
  6181. level_image = level_image->next_level;
  6182. }
  6183. } else {
  6184. size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]);
  6185. sum += num_bytes;
  6186. assert(sum <= total_size);
  6187. std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0];
  6188. memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes);
  6189. memory_ptr += num_bytes;
  6190. }
  6191. }
  6192. // Writing chunk data
  6193. for (unsigned int i = 0; i < num_parts; ++i) {
  6194. for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) {
  6195. if (num_parts > 1) {
  6196. sum += 4;
  6197. assert(sum <= total_size);
  6198. unsigned int part_number = i;
  6199. swap4(&part_number);
  6200. memcpy(memory_ptr, &part_number, 4);
  6201. memory_ptr += 4;
  6202. }
  6203. sum += data_lists[i][j].size();
  6204. assert(sum <= total_size);
  6205. memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size());
  6206. memory_ptr += data_lists[i][j].size();
  6207. }
  6208. }
  6209. assert(sum == total_size);
  6210. return total_size; // OK
  6211. }
  6212. } // tinyexr
  6213. size_t SaveEXRImageToMemory(const EXRImage* exr_image,
  6214. const EXRHeader* exr_header,
  6215. unsigned char** memory_out, const char** err) {
  6216. return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err);
  6217. }
  6218. int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,
  6219. const char *filename, const char **err) {
  6220. if (exr_image == NULL || filename == NULL ||
  6221. exr_header->compression_type < 0) {
  6222. tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
  6223. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6224. }
  6225. #if !TINYEXR_USE_PIZ
  6226. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
  6227. tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
  6228. err);
  6229. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  6230. }
  6231. #endif
  6232. #if !TINYEXR_USE_ZFP
  6233. if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
  6234. tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
  6235. err);
  6236. return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
  6237. }
  6238. #endif
  6239. FILE *fp = NULL;
  6240. #ifdef _WIN32
  6241. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang
  6242. errno_t errcode =
  6243. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
  6244. if (errcode != 0) {
  6245. tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
  6246. err);
  6247. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6248. }
  6249. #else
  6250. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  6251. fp = fopen(filename, "wb");
  6252. #endif
  6253. #else
  6254. fp = fopen(filename, "wb");
  6255. #endif
  6256. if (!fp) {
  6257. tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
  6258. err);
  6259. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6260. }
  6261. unsigned char *mem = NULL;
  6262. size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
  6263. if (mem_size == 0) {
  6264. return TINYEXR_ERROR_SERIALZATION_FAILED;
  6265. }
  6266. size_t written_size = 0;
  6267. if ((mem_size > 0) && mem) {
  6268. written_size = fwrite(mem, 1, mem_size, fp);
  6269. }
  6270. free(mem);
  6271. fclose(fp);
  6272. if (written_size != mem_size) {
  6273. tinyexr::SetErrorMessage("Cannot write a file", err);
  6274. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6275. }
  6276. return TINYEXR_SUCCESS;
  6277. }
  6278. size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images,
  6279. const EXRHeader** exr_headers,
  6280. unsigned int num_parts,
  6281. unsigned char** memory_out, const char** err) {
  6282. if (exr_images == NULL || exr_headers == NULL || num_parts < 2 ||
  6283. memory_out == NULL) {
  6284. tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
  6285. err);
  6286. return 0;
  6287. }
  6288. return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err);
  6289. }
  6290. int SaveEXRMultipartImageToFile(const EXRImage* exr_images,
  6291. const EXRHeader** exr_headers,
  6292. unsigned int num_parts,
  6293. const char* filename,
  6294. const char** err) {
  6295. if (exr_images == NULL || exr_headers == NULL || num_parts < 2) {
  6296. tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile",
  6297. err);
  6298. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6299. }
  6300. FILE *fp = NULL;
  6301. #ifdef _WIN32
  6302. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  6303. errno_t errcode =
  6304. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
  6305. if (errcode != 0) {
  6306. tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
  6307. err);
  6308. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6309. }
  6310. #else
  6311. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  6312. fp = fopen(filename, "wb");
  6313. #endif
  6314. #else
  6315. fp = fopen(filename, "wb");
  6316. #endif
  6317. if (!fp) {
  6318. tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
  6319. err);
  6320. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6321. }
  6322. unsigned char *mem = NULL;
  6323. size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err);
  6324. if (mem_size == 0) {
  6325. return TINYEXR_ERROR_SERIALZATION_FAILED;
  6326. }
  6327. size_t written_size = 0;
  6328. if ((mem_size > 0) && mem) {
  6329. written_size = fwrite(mem, 1, mem_size, fp);
  6330. }
  6331. free(mem);
  6332. fclose(fp);
  6333. if (written_size != mem_size) {
  6334. tinyexr::SetErrorMessage("Cannot write a file", err);
  6335. return TINYEXR_ERROR_CANT_WRITE_FILE;
  6336. }
  6337. return TINYEXR_SUCCESS;
  6338. }
  6339. int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {
  6340. if (deep_image == NULL) {
  6341. tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
  6342. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6343. }
  6344. #ifdef _WIN32
  6345. FILE *fp = NULL;
  6346. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  6347. errno_t errcode =
  6348. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  6349. if (errcode != 0) {
  6350. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  6351. err);
  6352. return TINYEXR_ERROR_CANT_OPEN_FILE;
  6353. }
  6354. #else
  6355. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  6356. fp = fopen(filename, "rb");
  6357. #endif
  6358. if (!fp) {
  6359. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  6360. err);
  6361. return TINYEXR_ERROR_CANT_OPEN_FILE;
  6362. }
  6363. #else
  6364. FILE *fp = fopen(filename, "rb");
  6365. if (!fp) {
  6366. tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
  6367. err);
  6368. return TINYEXR_ERROR_CANT_OPEN_FILE;
  6369. }
  6370. #endif
  6371. size_t filesize;
  6372. // Compute size
  6373. fseek(fp, 0, SEEK_END);
  6374. filesize = static_cast<size_t>(ftell(fp));
  6375. fseek(fp, 0, SEEK_SET);
  6376. if (filesize == 0) {
  6377. fclose(fp);
  6378. tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
  6379. err);
  6380. return TINYEXR_ERROR_INVALID_FILE;
  6381. }
  6382. std::vector<char> buf(filesize); // @todo { use mmap }
  6383. {
  6384. size_t ret;
  6385. ret = fread(&buf[0], 1, filesize, fp);
  6386. assert(ret == filesize);
  6387. (void)ret;
  6388. }
  6389. fclose(fp);
  6390. const char *head = &buf[0];
  6391. const char *marker = &buf[0];
  6392. // Header check.
  6393. {
  6394. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  6395. if (memcmp(marker, header, 4) != 0) {
  6396. tinyexr::SetErrorMessage("Invalid magic number", err);
  6397. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  6398. }
  6399. marker += 4;
  6400. }
  6401. // Version, scanline.
  6402. {
  6403. // ver 2.0, scanline, deep bit on(0x800)
  6404. // must be [2, 0, 0, 0]
  6405. if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
  6406. tinyexr::SetErrorMessage("Unsupported version or scanline", err);
  6407. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  6408. }
  6409. marker += 4;
  6410. }
  6411. int dx = -1;
  6412. int dy = -1;
  6413. int dw = -1;
  6414. int dh = -1;
  6415. int num_scanline_blocks = 1; // 16 for ZIP compression.
  6416. int compression_type = -1;
  6417. int num_channels = -1;
  6418. std::vector<tinyexr::ChannelInfo> channels;
  6419. // Read attributes
  6420. size_t size = filesize - tinyexr::kEXRVersionSize;
  6421. for (;;) {
  6422. if (0 == size) {
  6423. return TINYEXR_ERROR_INVALID_DATA;
  6424. } else if (marker[0] == '\0') {
  6425. marker++;
  6426. size--;
  6427. break;
  6428. }
  6429. std::string attr_name;
  6430. std::string attr_type;
  6431. std::vector<unsigned char> data;
  6432. size_t marker_size;
  6433. if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
  6434. marker, size)) {
  6435. std::stringstream ss;
  6436. ss << "Failed to parse attribute\n";
  6437. tinyexr::SetErrorMessage(ss.str(), err);
  6438. return TINYEXR_ERROR_INVALID_DATA;
  6439. }
  6440. marker += marker_size;
  6441. size -= marker_size;
  6442. if (attr_name.compare("compression") == 0) {
  6443. compression_type = data[0];
  6444. if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
  6445. std::stringstream ss;
  6446. ss << "Unsupported compression type : " << compression_type;
  6447. tinyexr::SetErrorMessage(ss.str(), err);
  6448. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  6449. }
  6450. if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
  6451. num_scanline_blocks = 16;
  6452. }
  6453. } else if (attr_name.compare("channels") == 0) {
  6454. // name: zero-terminated string, from 1 to 255 bytes long
  6455. // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
  6456. // pLinear: unsigned char, possible values are 0 and 1
  6457. // reserved: three chars, should be zero
  6458. // xSampling: int
  6459. // ySampling: int
  6460. if (!tinyexr::ReadChannelInfo(channels, data)) {
  6461. tinyexr::SetErrorMessage("Failed to parse channel info", err);
  6462. return TINYEXR_ERROR_INVALID_DATA;
  6463. }
  6464. num_channels = static_cast<int>(channels.size());
  6465. if (num_channels < 1) {
  6466. tinyexr::SetErrorMessage("Invalid channels format", err);
  6467. return TINYEXR_ERROR_INVALID_DATA;
  6468. }
  6469. } else if (attr_name.compare("dataWindow") == 0) {
  6470. memcpy(&dx, &data.at(0), sizeof(int));
  6471. memcpy(&dy, &data.at(4), sizeof(int));
  6472. memcpy(&dw, &data.at(8), sizeof(int));
  6473. memcpy(&dh, &data.at(12), sizeof(int));
  6474. tinyexr::swap4(&dx);
  6475. tinyexr::swap4(&dy);
  6476. tinyexr::swap4(&dw);
  6477. tinyexr::swap4(&dh);
  6478. } else if (attr_name.compare("displayWindow") == 0) {
  6479. int x;
  6480. int y;
  6481. int w;
  6482. int h;
  6483. memcpy(&x, &data.at(0), sizeof(int));
  6484. memcpy(&y, &data.at(4), sizeof(int));
  6485. memcpy(&w, &data.at(8), sizeof(int));
  6486. memcpy(&h, &data.at(12), sizeof(int));
  6487. tinyexr::swap4(&x);
  6488. tinyexr::swap4(&y);
  6489. tinyexr::swap4(&w);
  6490. tinyexr::swap4(&h);
  6491. }
  6492. }
  6493. assert(dx >= 0);
  6494. assert(dy >= 0);
  6495. assert(dw >= 0);
  6496. assert(dh >= 0);
  6497. assert(num_channels >= 1);
  6498. int data_width = dw - dx + 1;
  6499. int data_height = dh - dy + 1;
  6500. // Read offset tables.
  6501. int num_blocks = data_height / num_scanline_blocks;
  6502. if (num_blocks * num_scanline_blocks < data_height) {
  6503. num_blocks++;
  6504. }
  6505. std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
  6506. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  6507. tinyexr::tinyexr_int64 offset;
  6508. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
  6509. tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));
  6510. marker += sizeof(tinyexr::tinyexr_int64); // = 8
  6511. offsets[y] = offset;
  6512. }
  6513. #if TINYEXR_USE_PIZ
  6514. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  6515. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  6516. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  6517. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||
  6518. (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
  6519. #else
  6520. if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
  6521. (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
  6522. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
  6523. (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
  6524. #endif
  6525. // OK
  6526. } else {
  6527. tinyexr::SetErrorMessage("Unsupported compression format", err);
  6528. return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
  6529. }
  6530. deep_image->image = static_cast<float ***>(
  6531. malloc(sizeof(float **) * static_cast<size_t>(num_channels)));
  6532. for (int c = 0; c < num_channels; c++) {
  6533. deep_image->image[c] = static_cast<float **>(
  6534. malloc(sizeof(float *) * static_cast<size_t>(data_height)));
  6535. for (int y = 0; y < data_height; y++) {
  6536. }
  6537. }
  6538. deep_image->offset_table = static_cast<int **>(
  6539. malloc(sizeof(int *) * static_cast<size_t>(data_height)));
  6540. for (int y = 0; y < data_height; y++) {
  6541. deep_image->offset_table[y] = static_cast<int *>(
  6542. malloc(sizeof(int) * static_cast<size_t>(data_width)));
  6543. }
  6544. for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
  6545. const unsigned char *data_ptr =
  6546. reinterpret_cast<const unsigned char *>(head + offsets[y]);
  6547. // int: y coordinate
  6548. // int64: packed size of pixel offset table
  6549. // int64: packed size of sample data
  6550. // int64: unpacked size of sample data
  6551. // compressed pixel offset table
  6552. // compressed sample data
  6553. int line_no;
  6554. tinyexr::tinyexr_int64 packedOffsetTableSize;
  6555. tinyexr::tinyexr_int64 packedSampleDataSize;
  6556. tinyexr::tinyexr_int64 unpackedSampleDataSize;
  6557. memcpy(&line_no, data_ptr, sizeof(int));
  6558. memcpy(&packedOffsetTableSize, data_ptr + 4,
  6559. sizeof(tinyexr::tinyexr_int64));
  6560. memcpy(&packedSampleDataSize, data_ptr + 12,
  6561. sizeof(tinyexr::tinyexr_int64));
  6562. memcpy(&unpackedSampleDataSize, data_ptr + 20,
  6563. sizeof(tinyexr::tinyexr_int64));
  6564. tinyexr::swap4(&line_no);
  6565. tinyexr::swap8(
  6566. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));
  6567. tinyexr::swap8(
  6568. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));
  6569. tinyexr::swap8(
  6570. reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));
  6571. std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
  6572. // decode pixel offset table.
  6573. {
  6574. unsigned long dstLen =
  6575. static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
  6576. if (!tinyexr::DecompressZip(
  6577. reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
  6578. &dstLen, data_ptr + 28,
  6579. static_cast<unsigned long>(packedOffsetTableSize))) {
  6580. return false;
  6581. }
  6582. assert(dstLen == pixelOffsetTable.size() * sizeof(int));
  6583. for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
  6584. deep_image->offset_table[y][i] = pixelOffsetTable[i];
  6585. }
  6586. }
  6587. std::vector<unsigned char> sample_data(
  6588. static_cast<size_t>(unpackedSampleDataSize));
  6589. // decode sample data.
  6590. {
  6591. unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
  6592. if (dstLen) {
  6593. if (!tinyexr::DecompressZip(
  6594. reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,
  6595. data_ptr + 28 + packedOffsetTableSize,
  6596. static_cast<unsigned long>(packedSampleDataSize))) {
  6597. return false;
  6598. }
  6599. assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize));
  6600. }
  6601. }
  6602. // decode sample
  6603. int sampleSize = -1;
  6604. std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
  6605. {
  6606. int channel_offset = 0;
  6607. for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
  6608. channel_offset_list[i] = channel_offset;
  6609. if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
  6610. channel_offset += 4;
  6611. } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
  6612. channel_offset += 2;
  6613. } else if (channels[i].pixel_type ==
  6614. TINYEXR_PIXELTYPE_FLOAT) { // float
  6615. channel_offset += 4;
  6616. } else {
  6617. assert(0);
  6618. }
  6619. }
  6620. sampleSize = channel_offset;
  6621. }
  6622. assert(sampleSize >= 2);
  6623. assert(static_cast<size_t>(
  6624. pixelOffsetTable[static_cast<size_t>(data_width - 1)] *
  6625. sampleSize) == sample_data.size());
  6626. int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
  6627. //
  6628. // Alloc memory
  6629. //
  6630. //
  6631. // pixel data is stored as image[channels][pixel_samples]
  6632. //
  6633. {
  6634. tinyexr::tinyexr_uint64 data_offset = 0;
  6635. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  6636. deep_image->image[c][y] = static_cast<float *>(
  6637. malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
  6638. if (channels[c].pixel_type == 0) { // UINT
  6639. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  6640. unsigned int ui;
  6641. unsigned int *src_ptr = reinterpret_cast<unsigned int *>(
  6642. &sample_data.at(size_t(data_offset) + x * sizeof(int)));
  6643. tinyexr::cpy4(&ui, src_ptr);
  6644. deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
  6645. }
  6646. data_offset +=
  6647. sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
  6648. } else if (channels[c].pixel_type == 1) { // half
  6649. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  6650. tinyexr::FP16 f16;
  6651. const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(
  6652. &sample_data.at(size_t(data_offset) + x * sizeof(short)));
  6653. tinyexr::cpy2(&(f16.u), src_ptr);
  6654. tinyexr::FP32 f32 = half_to_float(f16);
  6655. deep_image->image[c][y][x] = f32.f;
  6656. }
  6657. data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
  6658. } else { // float
  6659. for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
  6660. float f;
  6661. const float *src_ptr = reinterpret_cast<float *>(
  6662. &sample_data.at(size_t(data_offset) + x * sizeof(float)));
  6663. tinyexr::cpy4(&f, src_ptr);
  6664. deep_image->image[c][y][x] = f;
  6665. }
  6666. data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
  6667. }
  6668. }
  6669. }
  6670. } // y
  6671. deep_image->width = data_width;
  6672. deep_image->height = data_height;
  6673. deep_image->channel_names = static_cast<const char **>(
  6674. malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));
  6675. for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
  6676. #ifdef _WIN32
  6677. deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
  6678. #else
  6679. deep_image->channel_names[c] = strdup(channels[c].name.c_str());
  6680. #endif
  6681. }
  6682. deep_image->num_channels = num_channels;
  6683. return TINYEXR_SUCCESS;
  6684. }
  6685. void InitEXRImage(EXRImage *exr_image) {
  6686. if (exr_image == NULL) {
  6687. return;
  6688. }
  6689. exr_image->width = 0;
  6690. exr_image->height = 0;
  6691. exr_image->num_channels = 0;
  6692. exr_image->images = NULL;
  6693. exr_image->tiles = NULL;
  6694. exr_image->next_level = NULL;
  6695. exr_image->level_x = 0;
  6696. exr_image->level_y = 0;
  6697. exr_image->num_tiles = 0;
  6698. }
  6699. void FreeEXRErrorMessage(const char *msg) {
  6700. if (msg) {
  6701. free(reinterpret_cast<void *>(const_cast<char *>(msg)));
  6702. }
  6703. return;
  6704. }
  6705. void InitEXRHeader(EXRHeader *exr_header) {
  6706. if (exr_header == NULL) {
  6707. return;
  6708. }
  6709. memset(exr_header, 0, sizeof(EXRHeader));
  6710. }
  6711. int FreeEXRHeader(EXRHeader *exr_header) {
  6712. if (exr_header == NULL) {
  6713. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6714. }
  6715. if (exr_header->channels) {
  6716. free(exr_header->channels);
  6717. }
  6718. if (exr_header->pixel_types) {
  6719. free(exr_header->pixel_types);
  6720. }
  6721. if (exr_header->requested_pixel_types) {
  6722. free(exr_header->requested_pixel_types);
  6723. }
  6724. for (int i = 0; i < exr_header->num_custom_attributes; i++) {
  6725. if (exr_header->custom_attributes[i].value) {
  6726. free(exr_header->custom_attributes[i].value);
  6727. }
  6728. }
  6729. if (exr_header->custom_attributes) {
  6730. free(exr_header->custom_attributes);
  6731. }
  6732. EXRSetNameAttr(exr_header, NULL);
  6733. return TINYEXR_SUCCESS;
  6734. }
  6735. void EXRSetNameAttr(EXRHeader* exr_header, const char* name) {
  6736. if (exr_header == NULL) {
  6737. return;
  6738. }
  6739. memset(exr_header->name, 0, 256);
  6740. if (name != NULL) {
  6741. size_t len = std::min(strlen(name), (size_t)255);
  6742. if (len) {
  6743. memcpy(exr_header->name, name, len);
  6744. }
  6745. }
  6746. }
  6747. int EXRNumLevels(const EXRImage* exr_image) {
  6748. if (exr_image == NULL) return 0;
  6749. if(exr_image->images) return 1; // scanlines
  6750. int levels = 1;
  6751. const EXRImage* level_image = exr_image;
  6752. while((level_image = level_image->next_level)) ++levels;
  6753. return levels;
  6754. }
  6755. int FreeEXRImage(EXRImage *exr_image) {
  6756. if (exr_image == NULL) {
  6757. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6758. }
  6759. if (exr_image->next_level) {
  6760. FreeEXRImage(exr_image->next_level);
  6761. delete exr_image->next_level;
  6762. }
  6763. for (int i = 0; i < exr_image->num_channels; i++) {
  6764. if (exr_image->images && exr_image->images[i]) {
  6765. free(exr_image->images[i]);
  6766. }
  6767. }
  6768. if (exr_image->images) {
  6769. free(exr_image->images);
  6770. }
  6771. if (exr_image->tiles) {
  6772. for (int tid = 0; tid < exr_image->num_tiles; tid++) {
  6773. for (int i = 0; i < exr_image->num_channels; i++) {
  6774. if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
  6775. free(exr_image->tiles[tid].images[i]);
  6776. }
  6777. }
  6778. if (exr_image->tiles[tid].images) {
  6779. free(exr_image->tiles[tid].images);
  6780. }
  6781. }
  6782. free(exr_image->tiles);
  6783. }
  6784. return TINYEXR_SUCCESS;
  6785. }
  6786. int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,
  6787. const char *filename, const char **err) {
  6788. if (exr_header == NULL || exr_version == NULL || filename == NULL) {
  6789. tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
  6790. err);
  6791. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6792. }
  6793. FILE *fp = NULL;
  6794. #ifdef _WIN32
  6795. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  6796. errno_t errcode =
  6797. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  6798. if (errcode != 0) {
  6799. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  6800. return TINYEXR_ERROR_INVALID_FILE;
  6801. }
  6802. #else
  6803. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  6804. fp = fopen(filename, "rb");
  6805. #endif
  6806. #else
  6807. fp = fopen(filename, "rb");
  6808. #endif
  6809. if (!fp) {
  6810. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  6811. return TINYEXR_ERROR_CANT_OPEN_FILE;
  6812. }
  6813. size_t filesize;
  6814. // Compute size
  6815. fseek(fp, 0, SEEK_END);
  6816. filesize = static_cast<size_t>(ftell(fp));
  6817. fseek(fp, 0, SEEK_SET);
  6818. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  6819. {
  6820. size_t ret;
  6821. ret = fread(&buf[0], 1, filesize, fp);
  6822. assert(ret == filesize);
  6823. fclose(fp);
  6824. if (ret != filesize) {
  6825. tinyexr::SetErrorMessage("fread() error on " + std::string(filename),
  6826. err);
  6827. return TINYEXR_ERROR_INVALID_FILE;
  6828. }
  6829. }
  6830. return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize,
  6831. err);
  6832. }
  6833. int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,
  6834. int *num_headers,
  6835. const EXRVersion *exr_version,
  6836. const unsigned char *memory, size_t size,
  6837. const char **err) {
  6838. if (memory == NULL || exr_headers == NULL || num_headers == NULL ||
  6839. exr_version == NULL) {
  6840. // Invalid argument
  6841. tinyexr::SetErrorMessage(
  6842. "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
  6843. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6844. }
  6845. if (size < tinyexr::kEXRVersionSize) {
  6846. tinyexr::SetErrorMessage("Data size too short", err);
  6847. return TINYEXR_ERROR_INVALID_DATA;
  6848. }
  6849. const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
  6850. size_t marker_size = size - tinyexr::kEXRVersionSize;
  6851. std::vector<tinyexr::HeaderInfo> infos;
  6852. for (;;) {
  6853. tinyexr::HeaderInfo info;
  6854. info.clear();
  6855. std::string err_str;
  6856. bool empty_header = false;
  6857. int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
  6858. marker, marker_size);
  6859. if (ret != TINYEXR_SUCCESS) {
  6860. tinyexr::SetErrorMessage(err_str, err);
  6861. return ret;
  6862. }
  6863. if (empty_header) {
  6864. marker += 1; // skip '\0'
  6865. break;
  6866. }
  6867. // `chunkCount` must exist in the header.
  6868. if (info.chunk_count == 0) {
  6869. tinyexr::SetErrorMessage(
  6870. "`chunkCount' attribute is not found in the header.", err);
  6871. return TINYEXR_ERROR_INVALID_DATA;
  6872. }
  6873. infos.push_back(info);
  6874. // move to next header.
  6875. marker += info.header_len;
  6876. size -= info.header_len;
  6877. }
  6878. // allocate memory for EXRHeader and create array of EXRHeader pointers.
  6879. (*exr_headers) =
  6880. static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));
  6881. int retcode = TINYEXR_SUCCESS;
  6882. for (size_t i = 0; i < infos.size(); i++) {
  6883. EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));
  6884. memset(exr_header, 0, sizeof(EXRHeader));
  6885. std::string warn;
  6886. std::string _err;
  6887. if (!ConvertHeader(exr_header, infos[i], &warn, &_err)) {
  6888. if (!_err.empty()) {
  6889. tinyexr::SetErrorMessage(
  6890. _err, err);
  6891. }
  6892. // continue to converting headers
  6893. retcode = TINYEXR_ERROR_INVALID_HEADER;
  6894. }
  6895. exr_header->multipart = exr_version->multipart ? 1 : 0;
  6896. (*exr_headers)[i] = exr_header;
  6897. }
  6898. (*num_headers) = static_cast<int>(infos.size());
  6899. return retcode;
  6900. }
  6901. int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,
  6902. const EXRVersion *exr_version,
  6903. const char *filename, const char **err) {
  6904. if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||
  6905. filename == NULL) {
  6906. tinyexr::SetErrorMessage(
  6907. "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
  6908. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6909. }
  6910. FILE *fp = NULL;
  6911. #ifdef _WIN32
  6912. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  6913. errno_t errcode =
  6914. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  6915. if (errcode != 0) {
  6916. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  6917. return TINYEXR_ERROR_INVALID_FILE;
  6918. }
  6919. #else
  6920. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  6921. fp = fopen(filename, "rb");
  6922. #endif
  6923. #else
  6924. fp = fopen(filename, "rb");
  6925. #endif
  6926. if (!fp) {
  6927. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  6928. return TINYEXR_ERROR_CANT_OPEN_FILE;
  6929. }
  6930. size_t filesize;
  6931. // Compute size
  6932. fseek(fp, 0, SEEK_END);
  6933. filesize = static_cast<size_t>(ftell(fp));
  6934. fseek(fp, 0, SEEK_SET);
  6935. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  6936. {
  6937. size_t ret;
  6938. ret = fread(&buf[0], 1, filesize, fp);
  6939. assert(ret == filesize);
  6940. fclose(fp);
  6941. if (ret != filesize) {
  6942. tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err);
  6943. return TINYEXR_ERROR_INVALID_FILE;
  6944. }
  6945. }
  6946. return ParseEXRMultipartHeaderFromMemory(
  6947. exr_headers, num_headers, exr_version, &buf.at(0), filesize, err);
  6948. }
  6949. int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,
  6950. size_t size) {
  6951. if (version == NULL || memory == NULL) {
  6952. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6953. }
  6954. if (size < tinyexr::kEXRVersionSize) {
  6955. return TINYEXR_ERROR_INVALID_DATA;
  6956. }
  6957. const unsigned char *marker = memory;
  6958. // Header check.
  6959. {
  6960. const char header[] = {0x76, 0x2f, 0x31, 0x01};
  6961. if (memcmp(marker, header, 4) != 0) {
  6962. return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
  6963. }
  6964. marker += 4;
  6965. }
  6966. version->tiled = false;
  6967. version->long_name = false;
  6968. version->non_image = false;
  6969. version->multipart = false;
  6970. // Parse version header.
  6971. {
  6972. // must be 2
  6973. if (marker[0] != 2) {
  6974. return TINYEXR_ERROR_INVALID_EXR_VERSION;
  6975. }
  6976. if (version == NULL) {
  6977. return TINYEXR_SUCCESS; // May OK
  6978. }
  6979. version->version = 2;
  6980. if (marker[1] & 0x2) { // 9th bit
  6981. version->tiled = true;
  6982. }
  6983. if (marker[1] & 0x4) { // 10th bit
  6984. version->long_name = true;
  6985. }
  6986. if (marker[1] & 0x8) { // 11th bit
  6987. version->non_image = true; // (deep image)
  6988. }
  6989. if (marker[1] & 0x10) { // 12th bit
  6990. version->multipart = true;
  6991. }
  6992. }
  6993. return TINYEXR_SUCCESS;
  6994. }
  6995. int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {
  6996. if (filename == NULL) {
  6997. return TINYEXR_ERROR_INVALID_ARGUMENT;
  6998. }
  6999. FILE *fp = NULL;
  7000. #ifdef _WIN32
  7001. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  7002. errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  7003. if (err != 0) {
  7004. // TODO(syoyo): return wfopen_s erro code
  7005. return TINYEXR_ERROR_CANT_OPEN_FILE;
  7006. }
  7007. #else
  7008. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  7009. fp = fopen(filename, "rb");
  7010. #endif
  7011. #else
  7012. fp = fopen(filename, "rb");
  7013. #endif
  7014. if (!fp) {
  7015. return TINYEXR_ERROR_CANT_OPEN_FILE;
  7016. }
  7017. size_t file_size;
  7018. // Compute size
  7019. fseek(fp, 0, SEEK_END);
  7020. file_size = static_cast<size_t>(ftell(fp));
  7021. fseek(fp, 0, SEEK_SET);
  7022. if (file_size < tinyexr::kEXRVersionSize) {
  7023. return TINYEXR_ERROR_INVALID_FILE;
  7024. }
  7025. unsigned char buf[tinyexr::kEXRVersionSize];
  7026. size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
  7027. fclose(fp);
  7028. if (ret != tinyexr::kEXRVersionSize) {
  7029. return TINYEXR_ERROR_INVALID_FILE;
  7030. }
  7031. return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
  7032. }
  7033. int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,
  7034. const EXRHeader **exr_headers,
  7035. unsigned int num_parts,
  7036. const unsigned char *memory,
  7037. const size_t size, const char **err) {
  7038. if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
  7039. memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
  7040. tinyexr::SetErrorMessage(
  7041. "Invalid argument for LoadEXRMultipartImageFromMemory()", err);
  7042. return TINYEXR_ERROR_INVALID_ARGUMENT;
  7043. }
  7044. // compute total header size.
  7045. size_t total_header_size = 0;
  7046. for (unsigned int i = 0; i < num_parts; i++) {
  7047. if (exr_headers[i]->header_len == 0) {
  7048. tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
  7049. return TINYEXR_ERROR_INVALID_ARGUMENT;
  7050. }
  7051. total_header_size += exr_headers[i]->header_len;
  7052. }
  7053. const char *marker = reinterpret_cast<const char *>(
  7054. memory + total_header_size + 4 +
  7055. 4); // +8 for magic number and version header.
  7056. marker += 1; // Skip empty header.
  7057. // NOTE 1:
  7058. // In multipart image, There is 'part number' before chunk data.
  7059. // 4 byte : part number
  7060. // 4+ : chunk
  7061. //
  7062. // NOTE 2:
  7063. // EXR spec says 'part number' is 'unsigned long' but actually this is
  7064. // 'unsigned int(4 bytes)' in OpenEXR implementation...
  7065. // http://www.openexr.com/openexrfilelayout.pdf
  7066. // Load chunk offset table.
  7067. std::vector<tinyexr::OffsetData> chunk_offset_table_list;
  7068. chunk_offset_table_list.reserve(num_parts);
  7069. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  7070. chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1);
  7071. tinyexr::OffsetData& offset_data = chunk_offset_table_list.back();
  7072. if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) {
  7073. tinyexr::InitSingleResolutionOffsets(offset_data, exr_headers[i]->chunk_count);
  7074. std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0];
  7075. for (size_t c = 0; c < offset_table.size(); c++) {
  7076. tinyexr::tinyexr_uint64 offset;
  7077. memcpy(&offset, marker, 8);
  7078. tinyexr::swap8(&offset);
  7079. if (offset >= size) {
  7080. tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
  7081. err);
  7082. return TINYEXR_ERROR_INVALID_DATA;
  7083. }
  7084. offset_table[c] = offset + 4; // +4 to skip 'part number'
  7085. marker += 8;
  7086. }
  7087. } else {
  7088. {
  7089. std::vector<int> num_x_tiles, num_y_tiles;
  7090. tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]);
  7091. int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles);
  7092. if (num_blocks != exr_headers[i]->chunk_count) {
  7093. tinyexr::SetErrorMessage("Invalid offset table size.", err);
  7094. return TINYEXR_ERROR_INVALID_DATA;
  7095. }
  7096. }
  7097. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
  7098. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
  7099. for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
  7100. tinyexr::tinyexr_uint64 offset;
  7101. memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
  7102. tinyexr::swap8(&offset);
  7103. if (offset >= size) {
  7104. tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
  7105. err);
  7106. return TINYEXR_ERROR_INVALID_DATA;
  7107. }
  7108. offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number'
  7109. marker += sizeof(tinyexr::tinyexr_uint64); // = 8
  7110. }
  7111. }
  7112. }
  7113. }
  7114. }
  7115. // Decode image.
  7116. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
  7117. tinyexr::OffsetData &offset_data = chunk_offset_table_list[i];
  7118. // First check 'part number' is identitical to 'i'
  7119. for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
  7120. for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
  7121. for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
  7122. const unsigned char *part_number_addr =
  7123. memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field.
  7124. unsigned int part_no;
  7125. memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
  7126. tinyexr::swap4(&part_no);
  7127. if (part_no != i) {
  7128. tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
  7129. err);
  7130. return TINYEXR_ERROR_INVALID_DATA;
  7131. }
  7132. }
  7133. std::string e;
  7134. int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data,
  7135. memory, size, &e);
  7136. if (ret != TINYEXR_SUCCESS) {
  7137. if (!e.empty()) {
  7138. tinyexr::SetErrorMessage(e, err);
  7139. }
  7140. return ret;
  7141. }
  7142. }
  7143. return TINYEXR_SUCCESS;
  7144. }
  7145. int LoadEXRMultipartImageFromFile(EXRImage *exr_images,
  7146. const EXRHeader **exr_headers,
  7147. unsigned int num_parts, const char *filename,
  7148. const char **err) {
  7149. if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
  7150. tinyexr::SetErrorMessage(
  7151. "Invalid argument for LoadEXRMultipartImageFromFile", err);
  7152. return TINYEXR_ERROR_INVALID_ARGUMENT;
  7153. }
  7154. FILE *fp = NULL;
  7155. #ifdef _WIN32
  7156. #if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
  7157. errno_t errcode =
  7158. _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
  7159. if (errcode != 0) {
  7160. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  7161. return TINYEXR_ERROR_CANT_OPEN_FILE;
  7162. }
  7163. #else
  7164. // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
  7165. fp = fopen(filename, "rb");
  7166. #endif
  7167. #else
  7168. fp = fopen(filename, "rb");
  7169. #endif
  7170. if (!fp) {
  7171. tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
  7172. return TINYEXR_ERROR_CANT_OPEN_FILE;
  7173. }
  7174. size_t filesize;
  7175. // Compute size
  7176. fseek(fp, 0, SEEK_END);
  7177. filesize = static_cast<size_t>(ftell(fp));
  7178. fseek(fp, 0, SEEK_SET);
  7179. std::vector<unsigned char> buf(filesize); // @todo { use mmap }
  7180. {
  7181. size_t ret;
  7182. ret = fread(&buf[0], 1, filesize, fp);
  7183. assert(ret == filesize);
  7184. fclose(fp);
  7185. (void)ret;
  7186. }
  7187. return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
  7188. &buf.at(0), filesize, err);
  7189. }
  7190. int SaveEXR(const float *data, int width, int height, int components,
  7191. const int save_as_fp16, const char *outfilename, const char **err) {
  7192. if ((components == 1) || components == 3 || components == 4) {
  7193. // OK
  7194. } else {
  7195. std::stringstream ss;
  7196. ss << "Unsupported component value : " << components << std::endl;
  7197. tinyexr::SetErrorMessage(ss.str(), err);
  7198. return TINYEXR_ERROR_INVALID_ARGUMENT;
  7199. }
  7200. EXRHeader header;
  7201. InitEXRHeader(&header);
  7202. if ((width < 16) && (height < 16)) {
  7203. // No compression for small image.
  7204. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;
  7205. } else {
  7206. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  7207. }
  7208. EXRImage image;
  7209. InitEXRImage(&image);
  7210. image.num_channels = components;
  7211. std::vector<float> images[4];
  7212. if (components == 1) {
  7213. images[0].resize(static_cast<size_t>(width * height));
  7214. memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
  7215. } else {
  7216. images[0].resize(static_cast<size_t>(width * height));
  7217. images[1].resize(static_cast<size_t>(width * height));
  7218. images[2].resize(static_cast<size_t>(width * height));
  7219. images[3].resize(static_cast<size_t>(width * height));
  7220. // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
  7221. for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
  7222. images[0][i] = data[static_cast<size_t>(components) * i + 0];
  7223. images[1][i] = data[static_cast<size_t>(components) * i + 1];
  7224. images[2][i] = data[static_cast<size_t>(components) * i + 2];
  7225. if (components == 4) {
  7226. images[3][i] = data[static_cast<size_t>(components) * i + 3];
  7227. }
  7228. }
  7229. }
  7230. float *image_ptr[4] = {0, 0, 0, 0};
  7231. if (components == 4) {
  7232. image_ptr[0] = &(images[3].at(0)); // A
  7233. image_ptr[1] = &(images[2].at(0)); // B
  7234. image_ptr[2] = &(images[1].at(0)); // G
  7235. image_ptr[3] = &(images[0].at(0)); // R
  7236. } else if (components == 3) {
  7237. image_ptr[0] = &(images[2].at(0)); // B
  7238. image_ptr[1] = &(images[1].at(0)); // G
  7239. image_ptr[2] = &(images[0].at(0)); // R
  7240. } else if (components == 1) {
  7241. image_ptr[0] = &(images[0].at(0)); // A
  7242. }
  7243. image.images = reinterpret_cast<unsigned char **>(image_ptr);
  7244. image.width = width;
  7245. image.height = height;
  7246. header.num_channels = components;
  7247. header.channels = static_cast<EXRChannelInfo *>(malloc(
  7248. sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
  7249. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  7250. if (components == 4) {
  7251. #ifdef _MSC_VER
  7252. strncpy_s(header.channels[0].name, "A", 255);
  7253. strncpy_s(header.channels[1].name, "B", 255);
  7254. strncpy_s(header.channels[2].name, "G", 255);
  7255. strncpy_s(header.channels[3].name, "R", 255);
  7256. #else
  7257. strncpy(header.channels[0].name, "A", 255);
  7258. strncpy(header.channels[1].name, "B", 255);
  7259. strncpy(header.channels[2].name, "G", 255);
  7260. strncpy(header.channels[3].name, "R", 255);
  7261. #endif
  7262. header.channels[0].name[strlen("A")] = '\0';
  7263. header.channels[1].name[strlen("B")] = '\0';
  7264. header.channels[2].name[strlen("G")] = '\0';
  7265. header.channels[3].name[strlen("R")] = '\0';
  7266. } else if (components == 3) {
  7267. #ifdef _MSC_VER
  7268. strncpy_s(header.channels[0].name, "B", 255);
  7269. strncpy_s(header.channels[1].name, "G", 255);
  7270. strncpy_s(header.channels[2].name, "R", 255);
  7271. #else
  7272. strncpy(header.channels[0].name, "B", 255);
  7273. strncpy(header.channels[1].name, "G", 255);
  7274. strncpy(header.channels[2].name, "R", 255);
  7275. #endif
  7276. header.channels[0].name[strlen("B")] = '\0';
  7277. header.channels[1].name[strlen("G")] = '\0';
  7278. header.channels[2].name[strlen("R")] = '\0';
  7279. } else {
  7280. #ifdef _MSC_VER
  7281. strncpy_s(header.channels[0].name, "A", 255);
  7282. #else
  7283. strncpy(header.channels[0].name, "A", 255);
  7284. #endif
  7285. header.channels[0].name[strlen("A")] = '\0';
  7286. }
  7287. header.pixel_types = static_cast<int *>(
  7288. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  7289. header.requested_pixel_types = static_cast<int *>(
  7290. malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
  7291. for (int i = 0; i < header.num_channels; i++) {
  7292. header.pixel_types[i] =
  7293. TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
  7294. if (save_as_fp16 > 0) {
  7295. header.requested_pixel_types[i] =
  7296. TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
  7297. } else {
  7298. header.requested_pixel_types[i] =
  7299. TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
  7300. // no precision reduction)
  7301. }
  7302. }
  7303. int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
  7304. if (ret != TINYEXR_SUCCESS) {
  7305. return ret;
  7306. }
  7307. free(header.channels);
  7308. free(header.pixel_types);
  7309. free(header.requested_pixel_types);
  7310. return ret;
  7311. }
  7312. #ifdef __clang__
  7313. // zero-as-null-ppinter-constant
  7314. #pragma clang diagnostic pop
  7315. #endif
  7316. #endif // TINYEXR_IMPLEMENTATION_DEFINED
  7317. #endif // TINYEXR_IMPLEMENTATION