tinyexr.h 264 KB

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