basisu_enc.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980
  1. // basisu_enc.cpp
  2. // Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include "basisu_enc.h"
  16. #include "basisu_resampler.h"
  17. #include "basisu_resampler_filters.h"
  18. #include "basisu_etc.h"
  19. #include "../transcoder/basisu_transcoder.h"
  20. #include "basisu_bc7enc.h"
  21. #include "jpgd.h"
  22. #include "pvpngreader.h"
  23. #include "basisu_opencl.h"
  24. #include "basisu_uastc_hdr_4x4_enc.h"
  25. #include "basisu_astc_hdr_6x6_enc.h"
  26. #include <vector>
  27. #ifndef TINYEXR_USE_ZFP
  28. #define TINYEXR_USE_ZFP (1)
  29. #endif
  30. #include <tinyexr.h>
  31. #ifndef MINIZ_HEADER_FILE_ONLY
  32. #define MINIZ_HEADER_FILE_ONLY
  33. #endif
  34. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  35. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  36. #endif
  37. #include "basisu_miniz.h"
  38. #if defined(_WIN32)
  39. // For QueryPerformanceCounter/QueryPerformanceFrequency
  40. #define WIN32_LEAN_AND_MEAN
  41. #include <windows.h>
  42. #endif
  43. namespace basisu
  44. {
  45. uint64_t interval_timer::g_init_ticks, interval_timer::g_freq;
  46. double interval_timer::g_timer_freq;
  47. #if BASISU_SUPPORT_SSE
  48. bool g_cpu_supports_sse41;
  49. #endif
  50. fast_linear_to_srgb g_fast_linear_to_srgb;
  51. uint8_t g_hamming_dist[256] =
  52. {
  53. 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  54. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  55. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  56. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  57. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  58. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  59. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  60. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  61. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  62. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  63. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  64. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  65. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  66. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  67. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  68. 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
  69. };
  70. // This is a Public Domain 8x8 font from here:
  71. // https://github.com/dhepper/font8x8/blob/master/font8x8_basic.h
  72. const uint8_t g_debug_font8x8_basic[127 - 32 + 1][8] =
  73. {
  74. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 ( )
  75. { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!)
  76. { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (")
  77. { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#)
  78. { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($)
  79. { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%)
  80. { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&)
  81. { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (')
  82. { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (()
  83. { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ())
  84. { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*)
  85. { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+)
  86. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,)
  87. { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-)
  88. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.)
  89. { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/)
  90. { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0)
  91. { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1)
  92. { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2)
  93. { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3)
  94. { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4)
  95. { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5)
  96. { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6)
  97. { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7)
  98. { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8)
  99. { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9)
  100. { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:)
  101. { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (;)
  102. { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<)
  103. { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=)
  104. { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>)
  105. { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?)
  106. { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@)
  107. { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A)
  108. { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B)
  109. { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C)
  110. { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D)
  111. { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E)
  112. { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F)
  113. { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G)
  114. { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H)
  115. { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I)
  116. { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J)
  117. { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K)
  118. { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L)
  119. { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M)
  120. { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N)
  121. { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O)
  122. { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P)
  123. { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q)
  124. { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R)
  125. { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S)
  126. { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T)
  127. { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U)
  128. { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V)
  129. { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W)
  130. { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X)
  131. { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y)
  132. { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z)
  133. { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([)
  134. { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\)
  135. { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (])
  136. { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^)
  137. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_)
  138. { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`)
  139. { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a)
  140. { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b)
  141. { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c)
  142. { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d)
  143. { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e)
  144. { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f)
  145. { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g)
  146. { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h)
  147. { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i)
  148. { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j)
  149. { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k)
  150. { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l)
  151. { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m)
  152. { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n)
  153. { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o)
  154. { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p)
  155. { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q)
  156. { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r)
  157. { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s)
  158. { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t)
  159. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u)
  160. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v)
  161. { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w)
  162. { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x)
  163. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y)
  164. { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z)
  165. { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({)
  166. { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|)
  167. { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (})
  168. { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~)
  169. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F
  170. };
  171. bool g_library_initialized;
  172. std::mutex g_encoder_init_mutex;
  173. // Encoder library initialization (just call once at startup)
  174. bool basisu_encoder_init(bool use_opencl, bool opencl_force_serialization)
  175. {
  176. std::lock_guard<std::mutex> lock(g_encoder_init_mutex);
  177. if (g_library_initialized)
  178. return true;
  179. detect_sse41();
  180. basist::basisu_transcoder_init();
  181. pack_etc1_solid_color_init();
  182. //uastc_init();
  183. bc7enc_compress_block_init(); // must be after uastc_init()
  184. // Don't bother initializing the OpenCL module at all if it's been completely disabled.
  185. if (use_opencl)
  186. {
  187. opencl_init(opencl_force_serialization);
  188. }
  189. interval_timer::init(); // make sure interval_timer globals are initialized from main thread to avoid TSAN reports
  190. astc_hdr_enc_init();
  191. basist::bc6h_enc_init();
  192. astc_6x6_hdr::global_init();
  193. g_library_initialized = true;
  194. return true;
  195. }
  196. void basisu_encoder_deinit()
  197. {
  198. opencl_deinit();
  199. g_library_initialized = false;
  200. }
  201. void error_vprintf(const char* pFmt, va_list args)
  202. {
  203. const uint32_t BUF_SIZE = 256;
  204. char buf[BUF_SIZE];
  205. va_list args_copy;
  206. va_copy(args_copy, args);
  207. int total_chars = vsnprintf(buf, sizeof(buf), pFmt, args_copy);
  208. va_end(args_copy);
  209. if (total_chars < 0)
  210. {
  211. assert(0);
  212. return;
  213. }
  214. if (total_chars >= (int)BUF_SIZE)
  215. {
  216. basisu::vector<char> var_buf(total_chars + 1);
  217. va_copy(args_copy, args);
  218. int total_chars_retry = vsnprintf(var_buf.data(), var_buf.size(), pFmt, args_copy);
  219. va_end(args_copy);
  220. if (total_chars_retry < 0)
  221. {
  222. assert(0);
  223. return;
  224. }
  225. fprintf(stderr, "ERROR: %s", var_buf.data());
  226. }
  227. else
  228. {
  229. fprintf(stderr, "ERROR: %s", buf);
  230. }
  231. }
  232. void error_printf(const char *pFmt, ...)
  233. {
  234. va_list args;
  235. va_start(args, pFmt);
  236. error_vprintf(pFmt, args);
  237. va_end(args);
  238. }
  239. #if defined(_WIN32)
  240. void platform_sleep(uint32_t ms)
  241. {
  242. Sleep(ms);
  243. }
  244. #else
  245. void platform_sleep(uint32_t ms)
  246. {
  247. // TODO
  248. }
  249. #endif
  250. #if defined(_WIN32)
  251. inline void query_counter(timer_ticks* pTicks)
  252. {
  253. QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(pTicks));
  254. }
  255. inline void query_counter_frequency(timer_ticks* pTicks)
  256. {
  257. QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(pTicks));
  258. }
  259. #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
  260. #include <sys/time.h>
  261. inline void query_counter(timer_ticks* pTicks)
  262. {
  263. struct timeval cur_time;
  264. gettimeofday(&cur_time, NULL);
  265. *pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
  266. }
  267. inline void query_counter_frequency(timer_ticks* pTicks)
  268. {
  269. *pTicks = 1000000;
  270. }
  271. #elif defined(__GNUC__)
  272. #include <sys/timex.h>
  273. inline void query_counter(timer_ticks* pTicks)
  274. {
  275. struct timeval cur_time;
  276. gettimeofday(&cur_time, NULL);
  277. *pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
  278. }
  279. inline void query_counter_frequency(timer_ticks* pTicks)
  280. {
  281. *pTicks = 1000000;
  282. }
  283. #else
  284. #error TODO
  285. #endif
  286. interval_timer::interval_timer() : m_start_time(0), m_stop_time(0), m_started(false), m_stopped(false)
  287. {
  288. if (!g_timer_freq)
  289. init();
  290. }
  291. void interval_timer::start()
  292. {
  293. query_counter(&m_start_time);
  294. m_started = true;
  295. m_stopped = false;
  296. }
  297. void interval_timer::stop()
  298. {
  299. assert(m_started);
  300. query_counter(&m_stop_time);
  301. m_stopped = true;
  302. }
  303. double interval_timer::get_elapsed_secs() const
  304. {
  305. assert(m_started);
  306. if (!m_started)
  307. return 0;
  308. timer_ticks stop_time = m_stop_time;
  309. if (!m_stopped)
  310. query_counter(&stop_time);
  311. timer_ticks delta = stop_time - m_start_time;
  312. return delta * g_timer_freq;
  313. }
  314. void interval_timer::init()
  315. {
  316. if (!g_timer_freq)
  317. {
  318. query_counter_frequency(&g_freq);
  319. g_timer_freq = 1.0f / g_freq;
  320. query_counter(&g_init_ticks);
  321. }
  322. }
  323. timer_ticks interval_timer::get_ticks()
  324. {
  325. if (!g_timer_freq)
  326. init();
  327. timer_ticks ticks;
  328. query_counter(&ticks);
  329. return ticks - g_init_ticks;
  330. }
  331. double interval_timer::ticks_to_secs(timer_ticks ticks)
  332. {
  333. if (!g_timer_freq)
  334. init();
  335. return ticks * g_timer_freq;
  336. }
  337. // Note this is linear<->sRGB, NOT REC709 which uses slightly different equations/transfer functions.
  338. // However the gamuts/white points of REC709 and sRGB are the same.
  339. float linear_to_srgb(float l)
  340. {
  341. assert(l >= 0.0f && l <= 1.0f);
  342. if (l < .0031308f)
  343. return saturate(l * 12.92f);
  344. else
  345. return saturate(1.055f * powf(l, 1.0f / 2.4f) - .055f);
  346. }
  347. float srgb_to_linear(float s)
  348. {
  349. assert(s >= 0.0f && s <= 1.0f);
  350. if (s < .04045f)
  351. return saturate(s * (1.0f / 12.92f));
  352. else
  353. return saturate(powf((s + .055f) * (1.0f / 1.055f), 2.4f));
  354. }
  355. const uint32_t MAX_32BIT_ALLOC_SIZE = 250000000;
  356. bool load_tga(const char* pFilename, image& img)
  357. {
  358. int w = 0, h = 0, n_chans = 0;
  359. uint8_t* pImage_data = read_tga(pFilename, w, h, n_chans);
  360. if ((!pImage_data) || (!w) || (!h) || ((n_chans != 3) && (n_chans != 4)))
  361. {
  362. error_printf("Failed loading .TGA image \"%s\"!\n", pFilename);
  363. if (pImage_data)
  364. free(pImage_data);
  365. return false;
  366. }
  367. if (sizeof(void *) == sizeof(uint32_t))
  368. {
  369. if (((uint64_t)w * h * n_chans) > MAX_32BIT_ALLOC_SIZE)
  370. {
  371. error_printf("Image \"%s\" is too large (%ux%u) to process in a 32-bit build!\n", pFilename, w, h);
  372. if (pImage_data)
  373. free(pImage_data);
  374. return false;
  375. }
  376. }
  377. img.resize(w, h);
  378. const uint8_t *pSrc = pImage_data;
  379. for (int y = 0; y < h; y++)
  380. {
  381. color_rgba *pDst = &img(0, y);
  382. for (int x = 0; x < w; x++)
  383. {
  384. pDst->r = pSrc[0];
  385. pDst->g = pSrc[1];
  386. pDst->b = pSrc[2];
  387. pDst->a = (n_chans == 3) ? 255 : pSrc[3];
  388. pSrc += n_chans;
  389. ++pDst;
  390. }
  391. }
  392. free(pImage_data);
  393. return true;
  394. }
  395. bool load_qoi(const char* pFilename, image& img)
  396. {
  397. return false;
  398. }
  399. bool load_png(const uint8_t *pBuf, size_t buf_size, image &img, const char *pFilename)
  400. {
  401. interval_timer tm;
  402. tm.start();
  403. if (!buf_size)
  404. return false;
  405. uint32_t width = 0, height = 0, num_chans = 0;
  406. void* pImage = pv_png::load_png(pBuf, buf_size, 4, width, height, num_chans);
  407. if (!pImage)
  408. {
  409. error_printf("pv_png::load_png failed while loading image \"%s\"\n", pFilename);
  410. return false;
  411. }
  412. img.grant_ownership(reinterpret_cast<color_rgba*>(pImage), width, height);
  413. //debug_printf("Total load_png() time: %3.3f secs\n", tm.get_elapsed_secs());
  414. return true;
  415. }
  416. bool load_png(const char* pFilename, image& img)
  417. {
  418. uint8_vec buffer;
  419. if (!read_file_to_vec(pFilename, buffer))
  420. {
  421. error_printf("load_png: Failed reading file \"%s\"!\n", pFilename);
  422. return false;
  423. }
  424. return load_png(buffer.data(), buffer.size(), img, pFilename);
  425. }
  426. bool load_jpg(const char *pFilename, image& img)
  427. {
  428. int width = 0, height = 0, actual_comps = 0;
  429. uint8_t *pImage_data = jpgd::decompress_jpeg_image_from_file(pFilename, &width, &height, &actual_comps, 4, jpgd::jpeg_decoder::cFlagLinearChromaFiltering);
  430. if (!pImage_data)
  431. return false;
  432. img.init(pImage_data, width, height, 4);
  433. free(pImage_data);
  434. return true;
  435. }
  436. bool load_jpg(const uint8_t* pBuf, size_t buf_size, image& img)
  437. {
  438. if (buf_size > INT_MAX)
  439. {
  440. assert(0);
  441. return false;
  442. }
  443. int width = 0, height = 0, actual_comps = 0;
  444. uint8_t* pImage_data = jpgd::decompress_jpeg_image_from_memory(pBuf, (int)buf_size, &width, &height, &actual_comps, 4, jpgd::jpeg_decoder::cFlagLinearChromaFiltering);
  445. if (!pImage_data)
  446. return false;
  447. img.init(pImage_data, width, height, 4);
  448. free(pImage_data);
  449. return true;
  450. }
  451. bool load_image(const char* pFilename, image& img)
  452. {
  453. std::string ext(string_get_extension(std::string(pFilename)));
  454. if (ext.length() == 0)
  455. return false;
  456. const char *pExt = ext.c_str();
  457. if (strcasecmp(pExt, "png") == 0)
  458. return load_png(pFilename, img);
  459. if (strcasecmp(pExt, "tga") == 0)
  460. return load_tga(pFilename, img);
  461. if (strcasecmp(pExt, "qoi") == 0)
  462. return load_qoi(pFilename, img);
  463. if ( (strcasecmp(pExt, "jpg") == 0) || (strcasecmp(pExt, "jfif") == 0) || (strcasecmp(pExt, "jpeg") == 0) )
  464. return load_jpg(pFilename, img);
  465. return false;
  466. }
  467. static void convert_ldr_to_hdr_image(imagef &img, const image &ldr_img, bool ldr_srgb_to_linear, float linear_nit_multiplier = 1.0f, float ldr_black_bias = 0.0f)
  468. {
  469. img.resize(ldr_img.get_width(), ldr_img.get_height());
  470. for (uint32_t y = 0; y < ldr_img.get_height(); y++)
  471. {
  472. for (uint32_t x = 0; x < ldr_img.get_width(); x++)
  473. {
  474. const color_rgba& c = ldr_img(x, y);
  475. vec4F& d = img(x, y);
  476. if (ldr_srgb_to_linear)
  477. {
  478. float r = (float)c[0];
  479. float g = (float)c[1];
  480. float b = (float)c[2];
  481. if (ldr_black_bias > 0.0f)
  482. {
  483. // ASTC HDR is noticeably weaker dealing with blocks containing some pixels with components set to 0.
  484. // Add a very slight bias less than .5 to avoid this difficulity. When the HDR image is mapped to SDR sRGB and rounded back to 8-bits, this bias will still result in zero.
  485. // (FWIW, in reality, a physical monitor would be unlikely to have a perfectly zero black level.)
  486. // This is purely optional and on most images it doesn't matter visually.
  487. if (r == 0.0f)
  488. r = ldr_black_bias;
  489. if (g == 0.0f)
  490. g = ldr_black_bias;
  491. if (b == 0.0f)
  492. b = ldr_black_bias;
  493. }
  494. // Compute how much linear light would be emitted by a SDR 80-100 nit monitor.
  495. d[0] = srgb_to_linear(r * (1.0f / 255.0f)) * linear_nit_multiplier;
  496. d[1] = srgb_to_linear(g * (1.0f / 255.0f)) * linear_nit_multiplier;
  497. d[2] = srgb_to_linear(b * (1.0f / 255.0f)) * linear_nit_multiplier;
  498. }
  499. else
  500. {
  501. d[0] = c[0] * (1.0f / 255.0f) * linear_nit_multiplier;
  502. d[1] = c[1] * (1.0f / 255.0f) * linear_nit_multiplier;
  503. d[2] = c[2] * (1.0f / 255.0f) * linear_nit_multiplier;
  504. }
  505. d[3] = c[3] * (1.0f / 255.0f);
  506. }
  507. }
  508. }
  509. bool load_image_hdr(const void* pMem, size_t mem_size, imagef& img, uint32_t width, uint32_t height, hdr_image_type img_type, bool ldr_srgb_to_linear, float linear_nit_multiplier, float ldr_black_bias)
  510. {
  511. if ((!pMem) || (!mem_size))
  512. {
  513. assert(0);
  514. return false;
  515. }
  516. switch (img_type)
  517. {
  518. case hdr_image_type::cHITRGBAHalfFloat:
  519. {
  520. if (mem_size != width * height * sizeof(basist::half_float) * 4)
  521. {
  522. assert(0);
  523. return false;
  524. }
  525. if ((!width) || (!height))
  526. {
  527. assert(0);
  528. return false;
  529. }
  530. const basist::half_float* pSrc_image_h = static_cast<const basist::half_float *>(pMem);
  531. img.resize(width, height);
  532. for (uint32_t y = 0; y < height; y++)
  533. {
  534. for (uint32_t x = 0; x < width; x++)
  535. {
  536. const basist::half_float* pSrc_pixel = &pSrc_image_h[x * 4];
  537. vec4F& dst = img(x, y);
  538. dst[0] = basist::half_to_float(pSrc_pixel[0]);
  539. dst[1] = basist::half_to_float(pSrc_pixel[1]);
  540. dst[2] = basist::half_to_float(pSrc_pixel[2]);
  541. dst[3] = basist::half_to_float(pSrc_pixel[3]);
  542. }
  543. pSrc_image_h += (width * 4);
  544. }
  545. break;
  546. }
  547. case hdr_image_type::cHITRGBAFloat:
  548. {
  549. if (mem_size != width * height * sizeof(float) * 4)
  550. {
  551. assert(0);
  552. return false;
  553. }
  554. if ((!width) || (!height))
  555. {
  556. assert(0);
  557. return false;
  558. }
  559. img.resize(width, height);
  560. memcpy((void *)img.get_ptr(), pMem, width * height * sizeof(float) * 4);
  561. break;
  562. }
  563. case hdr_image_type::cHITJPGImage:
  564. {
  565. image ldr_img;
  566. if (!load_jpg(static_cast<const uint8_t*>(pMem), mem_size, ldr_img))
  567. return false;
  568. convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
  569. break;
  570. }
  571. case hdr_image_type::cHITPNGImage:
  572. {
  573. image ldr_img;
  574. if (!load_png(static_cast<const uint8_t *>(pMem), mem_size, ldr_img))
  575. return false;
  576. convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
  577. break;
  578. }
  579. case hdr_image_type::cHITEXRImage:
  580. {
  581. if (!read_exr(pMem, mem_size, img))
  582. return false;
  583. break;
  584. }
  585. case hdr_image_type::cHITHDRImage:
  586. {
  587. uint8_vec buf(mem_size);
  588. memcpy(buf.get_ptr(), pMem, mem_size);
  589. rgbe_header_info hdr;
  590. if (!read_rgbe(buf, img, hdr))
  591. return false;
  592. break;
  593. }
  594. default:
  595. assert(0);
  596. return false;
  597. }
  598. return true;
  599. }
  600. bool is_image_filename_hdr(const char *pFilename)
  601. {
  602. std::string ext(string_get_extension(std::string(pFilename)));
  603. if (ext.length() == 0)
  604. return false;
  605. const char* pExt = ext.c_str();
  606. return ((strcasecmp(pExt, "hdr") == 0) || (strcasecmp(pExt, "exr") == 0));
  607. }
  608. // TODO: move parameters to struct, add a HDR clean flag to eliminate NaN's/Inf's
  609. bool load_image_hdr(const char* pFilename, imagef& img, bool ldr_srgb_to_linear, float linear_nit_multiplier, float ldr_black_bias)
  610. {
  611. std::string ext(string_get_extension(std::string(pFilename)));
  612. if (ext.length() == 0)
  613. return false;
  614. const char* pExt = ext.c_str();
  615. if (strcasecmp(pExt, "hdr") == 0)
  616. {
  617. rgbe_header_info rgbe_info;
  618. if (!read_rgbe(pFilename, img, rgbe_info))
  619. return false;
  620. return true;
  621. }
  622. if (strcasecmp(pExt, "exr") == 0)
  623. {
  624. int n_chans = 0;
  625. if (!read_exr(pFilename, img, n_chans))
  626. return false;
  627. return true;
  628. }
  629. // Try loading image as LDR, then optionally convert to linear light.
  630. {
  631. image ldr_img;
  632. if (!load_image(pFilename, ldr_img))
  633. return false;
  634. convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear, linear_nit_multiplier, ldr_black_bias);
  635. }
  636. return true;
  637. }
  638. bool save_png(const char* pFilename, const image &img, uint32_t image_save_flags, uint32_t grayscale_comp)
  639. {
  640. if (!img.get_total_pixels())
  641. return false;
  642. void* pPNG_data = nullptr;
  643. size_t PNG_data_size = 0;
  644. if (image_save_flags & cImageSaveGrayscale)
  645. {
  646. uint8_vec g_pixels(img.get_total_pixels());
  647. uint8_t* pDst = &g_pixels[0];
  648. for (uint32_t y = 0; y < img.get_height(); y++)
  649. for (uint32_t x = 0; x < img.get_width(); x++)
  650. *pDst++ = img(x, y)[grayscale_comp];
  651. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(g_pixels.data(), img.get_width(), img.get_height(), 1, &PNG_data_size, 1, false);
  652. }
  653. else
  654. {
  655. bool has_alpha = false;
  656. if ((image_save_flags & cImageSaveIgnoreAlpha) == 0)
  657. has_alpha = img.has_alpha();
  658. if (!has_alpha)
  659. {
  660. uint8_vec rgb_pixels(img.get_total_pixels() * 3);
  661. uint8_t* pDst = &rgb_pixels[0];
  662. for (uint32_t y = 0; y < img.get_height(); y++)
  663. {
  664. const color_rgba* pSrc = &img(0, y);
  665. for (uint32_t x = 0; x < img.get_width(); x++)
  666. {
  667. pDst[0] = pSrc->r;
  668. pDst[1] = pSrc->g;
  669. pDst[2] = pSrc->b;
  670. pSrc++;
  671. pDst += 3;
  672. }
  673. }
  674. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(rgb_pixels.data(), img.get_width(), img.get_height(), 3, &PNG_data_size, 1, false);
  675. }
  676. else
  677. {
  678. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(img.get_ptr(), img.get_width(), img.get_height(), 4, &PNG_data_size, 1, false);
  679. }
  680. }
  681. if (!pPNG_data)
  682. return false;
  683. bool status = write_data_to_file(pFilename, pPNG_data, PNG_data_size);
  684. if (!status)
  685. {
  686. error_printf("save_png: Failed writing to filename \"%s\"!\n", pFilename);
  687. }
  688. free(pPNG_data);
  689. return status;
  690. }
  691. bool read_file_to_vec(const char* pFilename, uint8_vec& data)
  692. {
  693. FILE* pFile = nullptr;
  694. #ifdef _WIN32
  695. fopen_s(&pFile, pFilename, "rb");
  696. #else
  697. pFile = fopen(pFilename, "rb");
  698. #endif
  699. if (!pFile)
  700. return false;
  701. fseek(pFile, 0, SEEK_END);
  702. #ifdef _WIN32
  703. int64_t filesize = _ftelli64(pFile);
  704. #else
  705. int64_t filesize = ftello(pFile);
  706. #endif
  707. if (filesize < 0)
  708. {
  709. fclose(pFile);
  710. return false;
  711. }
  712. fseek(pFile, 0, SEEK_SET);
  713. if (sizeof(size_t) == sizeof(uint32_t))
  714. {
  715. if (filesize > 0x70000000)
  716. {
  717. // File might be too big to load safely in one alloc
  718. fclose(pFile);
  719. return false;
  720. }
  721. }
  722. if (!data.try_resize((size_t)filesize))
  723. {
  724. fclose(pFile);
  725. return false;
  726. }
  727. if (filesize)
  728. {
  729. if (fread(&data[0], 1, (size_t)filesize, pFile) != (size_t)filesize)
  730. {
  731. fclose(pFile);
  732. return false;
  733. }
  734. }
  735. fclose(pFile);
  736. return true;
  737. }
  738. bool read_file_to_data(const char* pFilename, void *pData, size_t len)
  739. {
  740. assert(pData && len);
  741. if ((!pData) || (!len))
  742. return false;
  743. FILE* pFile = nullptr;
  744. #ifdef _WIN32
  745. fopen_s(&pFile, pFilename, "rb");
  746. #else
  747. pFile = fopen(pFilename, "rb");
  748. #endif
  749. if (!pFile)
  750. return false;
  751. fseek(pFile, 0, SEEK_END);
  752. #ifdef _WIN32
  753. int64_t filesize = _ftelli64(pFile);
  754. #else
  755. int64_t filesize = ftello(pFile);
  756. #endif
  757. if ((filesize < 0) || ((size_t)filesize < len))
  758. {
  759. fclose(pFile);
  760. return false;
  761. }
  762. fseek(pFile, 0, SEEK_SET);
  763. if (fread(pData, 1, (size_t)len, pFile) != (size_t)len)
  764. {
  765. fclose(pFile);
  766. return false;
  767. }
  768. fclose(pFile);
  769. return true;
  770. }
  771. bool write_data_to_file(const char* pFilename, const void* pData, size_t len)
  772. {
  773. FILE* pFile = nullptr;
  774. #ifdef _WIN32
  775. fopen_s(&pFile, pFilename, "wb");
  776. #else
  777. pFile = fopen(pFilename, "wb");
  778. #endif
  779. if (!pFile)
  780. return false;
  781. if (len)
  782. {
  783. if (fwrite(pData, 1, len, pFile) != len)
  784. {
  785. fclose(pFile);
  786. return false;
  787. }
  788. }
  789. return fclose(pFile) != EOF;
  790. }
  791. bool image_resample(const image &src, image &dst, bool srgb,
  792. const char *pFilter, float filter_scale,
  793. bool wrapping,
  794. uint32_t first_comp, uint32_t num_comps)
  795. {
  796. assert((first_comp + num_comps) <= 4);
  797. const int cMaxComps = 4;
  798. const uint32_t src_w = src.get_width(), src_h = src.get_height();
  799. const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
  800. if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
  801. {
  802. printf("Image is too large!\n");
  803. return false;
  804. }
  805. if (!src_w || !src_h || !dst_w || !dst_h)
  806. return false;
  807. if ((num_comps < 1) || (num_comps > cMaxComps))
  808. return false;
  809. if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
  810. {
  811. printf("Image is too large!\n");
  812. return false;
  813. }
  814. if ((src_w == dst_w) && (src_h == dst_h))
  815. {
  816. dst = src;
  817. return true;
  818. }
  819. float srgb_to_linear_table[256];
  820. if (srgb)
  821. {
  822. for (int i = 0; i < 256; ++i)
  823. srgb_to_linear_table[i] = srgb_to_linear((float)i * (1.0f/255.0f));
  824. }
  825. const int LINEAR_TO_SRGB_TABLE_SIZE = 8192;
  826. uint8_t linear_to_srgb_table[LINEAR_TO_SRGB_TABLE_SIZE];
  827. if (srgb)
  828. {
  829. for (int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i)
  830. linear_to_srgb_table[i] = (uint8_t)clamp<int>((int)(255.0f * linear_to_srgb((float)i * (1.0f / (LINEAR_TO_SRGB_TABLE_SIZE - 1))) + .5f), 0, 255);
  831. }
  832. std::vector<float> samples[cMaxComps];
  833. Resampler *resamplers[cMaxComps];
  834. resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
  835. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
  836. pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
  837. samples[0].resize(src_w);
  838. for (uint32_t i = 1; i < num_comps; ++i)
  839. {
  840. resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
  841. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
  842. pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
  843. samples[i].resize(src_w);
  844. }
  845. uint32_t dst_y = 0;
  846. for (uint32_t src_y = 0; src_y < src_h; ++src_y)
  847. {
  848. const color_rgba *pSrc = &src(0, src_y);
  849. // Put source lines into resampler(s)
  850. for (uint32_t x = 0; x < src_w; ++x)
  851. {
  852. for (uint32_t c = 0; c < num_comps; ++c)
  853. {
  854. const uint32_t comp_index = first_comp + c;
  855. const uint32_t v = (*pSrc)[comp_index];
  856. if (!srgb || (comp_index == 3))
  857. samples[c][x] = v * (1.0f / 255.0f);
  858. else
  859. samples[c][x] = srgb_to_linear_table[v];
  860. }
  861. pSrc++;
  862. }
  863. for (uint32_t c = 0; c < num_comps; ++c)
  864. {
  865. if (!resamplers[c]->put_line(&samples[c][0]))
  866. {
  867. for (uint32_t i = 0; i < num_comps; i++)
  868. delete resamplers[i];
  869. return false;
  870. }
  871. }
  872. // Now retrieve any output lines
  873. for (;;)
  874. {
  875. uint32_t c;
  876. for (c = 0; c < num_comps; ++c)
  877. {
  878. const uint32_t comp_index = first_comp + c;
  879. const float *pOutput_samples = resamplers[c]->get_line();
  880. if (!pOutput_samples)
  881. break;
  882. const bool linear_flag = !srgb || (comp_index == 3);
  883. color_rgba *pDst = &dst(0, dst_y);
  884. for (uint32_t x = 0; x < dst_w; x++)
  885. {
  886. // TODO: Add dithering
  887. if (linear_flag)
  888. {
  889. int j = (int)(255.0f * pOutput_samples[x] + .5f);
  890. (*pDst)[comp_index] = (uint8_t)clamp<int>(j, 0, 255);
  891. }
  892. else
  893. {
  894. int j = (int)((LINEAR_TO_SRGB_TABLE_SIZE - 1) * pOutput_samples[x] + .5f);
  895. (*pDst)[comp_index] = linear_to_srgb_table[clamp<int>(j, 0, LINEAR_TO_SRGB_TABLE_SIZE - 1)];
  896. }
  897. pDst++;
  898. }
  899. }
  900. if (c < num_comps)
  901. break;
  902. ++dst_y;
  903. }
  904. }
  905. for (uint32_t i = 0; i < num_comps; ++i)
  906. delete resamplers[i];
  907. return true;
  908. }
  909. bool image_resample(const imagef& src, imagef& dst,
  910. const char* pFilter, float filter_scale,
  911. bool wrapping,
  912. uint32_t first_comp, uint32_t num_comps)
  913. {
  914. assert((first_comp + num_comps) <= 4);
  915. const int cMaxComps = 4;
  916. const uint32_t src_w = src.get_width(), src_h = src.get_height();
  917. const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
  918. if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
  919. {
  920. printf("Image is too large!\n");
  921. return false;
  922. }
  923. if (!src_w || !src_h || !dst_w || !dst_h)
  924. return false;
  925. if ((num_comps < 1) || (num_comps > cMaxComps))
  926. return false;
  927. if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
  928. {
  929. printf("Image is too large!\n");
  930. return false;
  931. }
  932. if ((src_w == dst_w) && (src_h == dst_h) && (filter_scale == 1.0f))
  933. {
  934. dst = src;
  935. return true;
  936. }
  937. std::vector<float> samples[cMaxComps];
  938. Resampler* resamplers[cMaxComps];
  939. resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
  940. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
  941. pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
  942. samples[0].resize(src_w);
  943. for (uint32_t i = 1; i < num_comps; ++i)
  944. {
  945. resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
  946. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
  947. pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
  948. samples[i].resize(src_w);
  949. }
  950. uint32_t dst_y = 0;
  951. for (uint32_t src_y = 0; src_y < src_h; ++src_y)
  952. {
  953. const vec4F* pSrc = &src(0, src_y);
  954. // Put source lines into resampler(s)
  955. for (uint32_t x = 0; x < src_w; ++x)
  956. {
  957. for (uint32_t c = 0; c < num_comps; ++c)
  958. {
  959. const uint32_t comp_index = first_comp + c;
  960. const float v = (*pSrc)[comp_index];
  961. samples[c][x] = v;
  962. }
  963. pSrc++;
  964. }
  965. for (uint32_t c = 0; c < num_comps; ++c)
  966. {
  967. if (!resamplers[c]->put_line(&samples[c][0]))
  968. {
  969. for (uint32_t i = 0; i < num_comps; i++)
  970. delete resamplers[i];
  971. return false;
  972. }
  973. }
  974. // Now retrieve any output lines
  975. for (;;)
  976. {
  977. uint32_t c;
  978. for (c = 0; c < num_comps; ++c)
  979. {
  980. const uint32_t comp_index = first_comp + c;
  981. const float* pOutput_samples = resamplers[c]->get_line();
  982. if (!pOutput_samples)
  983. break;
  984. vec4F* pDst = &dst(0, dst_y);
  985. for (uint32_t x = 0; x < dst_w; x++)
  986. {
  987. (*pDst)[comp_index] = pOutput_samples[x];
  988. pDst++;
  989. }
  990. }
  991. if (c < num_comps)
  992. break;
  993. ++dst_y;
  994. }
  995. }
  996. for (uint32_t i = 0; i < num_comps; ++i)
  997. delete resamplers[i];
  998. return true;
  999. }
  1000. void canonical_huffman_calculate_minimum_redundancy(sym_freq *A, int num_syms)
  1001. {
  1002. // See the paper "In-Place Calculation of Minimum Redundancy Codes" by Moffat and Katajainen
  1003. if (!num_syms)
  1004. return;
  1005. if (1 == num_syms)
  1006. {
  1007. A[0].m_key = 1;
  1008. return;
  1009. }
  1010. A[0].m_key += A[1].m_key;
  1011. int s = 2, r = 0, next;
  1012. for (next = 1; next < (num_syms - 1); ++next)
  1013. {
  1014. if ((s >= num_syms) || (A[r].m_key < A[s].m_key))
  1015. {
  1016. A[next].m_key = A[r].m_key;
  1017. A[r].m_key = next;
  1018. ++r;
  1019. }
  1020. else
  1021. {
  1022. A[next].m_key = A[s].m_key;
  1023. ++s;
  1024. }
  1025. if ((s >= num_syms) || ((r < next) && A[r].m_key < A[s].m_key))
  1026. {
  1027. A[next].m_key = A[next].m_key + A[r].m_key;
  1028. A[r].m_key = next;
  1029. ++r;
  1030. }
  1031. else
  1032. {
  1033. A[next].m_key = A[next].m_key + A[s].m_key;
  1034. ++s;
  1035. }
  1036. }
  1037. A[num_syms - 2].m_key = 0;
  1038. for (next = num_syms - 3; next >= 0; --next)
  1039. {
  1040. A[next].m_key = 1 + A[A[next].m_key].m_key;
  1041. }
  1042. int num_avail = 1, num_used = 0, depth = 0;
  1043. r = num_syms - 2;
  1044. next = num_syms - 1;
  1045. while (num_avail > 0)
  1046. {
  1047. for ( ; (r >= 0) && ((int)A[r].m_key == depth); ++num_used, --r )
  1048. ;
  1049. for ( ; num_avail > num_used; --next, --num_avail)
  1050. A[next].m_key = depth;
  1051. num_avail = 2 * num_used;
  1052. num_used = 0;
  1053. ++depth;
  1054. }
  1055. }
  1056. void canonical_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  1057. {
  1058. int i;
  1059. uint32_t total = 0;
  1060. if (code_list_len <= 1)
  1061. return;
  1062. for (i = max_code_size + 1; i <= cHuffmanMaxSupportedInternalCodeSize; i++)
  1063. pNum_codes[max_code_size] += pNum_codes[i];
  1064. for (i = max_code_size; i > 0; i--)
  1065. total += (((uint32_t)pNum_codes[i]) << (max_code_size - i));
  1066. while (total != (1UL << max_code_size))
  1067. {
  1068. pNum_codes[max_code_size]--;
  1069. for (i = max_code_size - 1; i > 0; i--)
  1070. {
  1071. if (pNum_codes[i])
  1072. {
  1073. pNum_codes[i]--;
  1074. pNum_codes[i + 1] += 2;
  1075. break;
  1076. }
  1077. }
  1078. total--;
  1079. }
  1080. }
  1081. sym_freq *canonical_huffman_radix_sort_syms(uint32_t num_syms, sym_freq *pSyms0, sym_freq *pSyms1)
  1082. {
  1083. uint32_t total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  1084. sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  1085. clear_obj(hist);
  1086. for (i = 0; i < num_syms; i++)
  1087. {
  1088. uint32_t freq = pSyms0[i].m_key;
  1089. // We scale all input frequencies to 16-bits.
  1090. assert(freq <= UINT16_MAX);
  1091. hist[freq & 0xFF]++;
  1092. hist[256 + ((freq >> 8) & 0xFF)]++;
  1093. }
  1094. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  1095. total_passes--;
  1096. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1097. {
  1098. const uint32_t *pHist = &hist[pass << 8];
  1099. uint32_t offsets[256], cur_ofs = 0;
  1100. for (i = 0; i < 256; i++)
  1101. {
  1102. offsets[i] = cur_ofs;
  1103. cur_ofs += pHist[i];
  1104. }
  1105. for (i = 0; i < num_syms; i++)
  1106. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1107. sym_freq *t = pCur_syms;
  1108. pCur_syms = pNew_syms;
  1109. pNew_syms = t;
  1110. }
  1111. return pCur_syms;
  1112. }
  1113. bool huffman_encoding_table::init(uint32_t num_syms, const uint16_t *pFreq, uint32_t max_code_size)
  1114. {
  1115. if (max_code_size > cHuffmanMaxSupportedCodeSize)
  1116. return false;
  1117. if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
  1118. return false;
  1119. uint32_t total_used_syms = 0;
  1120. for (uint32_t i = 0; i < num_syms; i++)
  1121. if (pFreq[i])
  1122. total_used_syms++;
  1123. if (!total_used_syms)
  1124. return false;
  1125. std::vector<sym_freq> sym_freq0(total_used_syms), sym_freq1(total_used_syms);
  1126. for (uint32_t i = 0, j = 0; i < num_syms; i++)
  1127. {
  1128. if (pFreq[i])
  1129. {
  1130. sym_freq0[j].m_key = pFreq[i];
  1131. sym_freq0[j++].m_sym_index = static_cast<uint16_t>(i);
  1132. }
  1133. }
  1134. sym_freq *pSym_freq = canonical_huffman_radix_sort_syms(total_used_syms, &sym_freq0[0], &sym_freq1[0]);
  1135. canonical_huffman_calculate_minimum_redundancy(pSym_freq, total_used_syms);
  1136. int num_codes[cHuffmanMaxSupportedInternalCodeSize + 1];
  1137. clear_obj(num_codes);
  1138. for (uint32_t i = 0; i < total_used_syms; i++)
  1139. {
  1140. if (pSym_freq[i].m_key > cHuffmanMaxSupportedInternalCodeSize)
  1141. return false;
  1142. num_codes[pSym_freq[i].m_key]++;
  1143. }
  1144. canonical_huffman_enforce_max_code_size(num_codes, total_used_syms, max_code_size);
  1145. m_code_sizes.resize(0);
  1146. m_code_sizes.resize(num_syms);
  1147. m_codes.resize(0);
  1148. m_codes.resize(num_syms);
  1149. for (uint32_t i = 1, j = total_used_syms; i <= max_code_size; i++)
  1150. for (uint32_t l = num_codes[i]; l > 0; l--)
  1151. m_code_sizes[pSym_freq[--j].m_sym_index] = static_cast<uint8_t>(i);
  1152. uint32_t next_code[cHuffmanMaxSupportedInternalCodeSize + 1];
  1153. next_code[1] = 0;
  1154. for (uint32_t j = 0, i = 2; i <= max_code_size; i++)
  1155. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1156. for (uint32_t i = 0; i < num_syms; i++)
  1157. {
  1158. uint32_t rev_code = 0, code, code_size;
  1159. if ((code_size = m_code_sizes[i]) == 0)
  1160. continue;
  1161. if (code_size > cHuffmanMaxSupportedInternalCodeSize)
  1162. return false;
  1163. code = next_code[code_size]++;
  1164. for (uint32_t l = code_size; l > 0; l--, code >>= 1)
  1165. rev_code = (rev_code << 1) | (code & 1);
  1166. m_codes[i] = static_cast<uint16_t>(rev_code);
  1167. }
  1168. return true;
  1169. }
  1170. bool huffman_encoding_table::init(uint32_t num_syms, const uint32_t *pSym_freq, uint32_t max_code_size)
  1171. {
  1172. if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
  1173. return false;
  1174. uint16_vec sym_freq(num_syms);
  1175. uint32_t max_freq = 0;
  1176. for (uint32_t i = 0; i < num_syms; i++)
  1177. max_freq = maximum(max_freq, pSym_freq[i]);
  1178. if (max_freq < UINT16_MAX)
  1179. {
  1180. for (uint32_t i = 0; i < num_syms; i++)
  1181. sym_freq[i] = static_cast<uint16_t>(pSym_freq[i]);
  1182. }
  1183. else
  1184. {
  1185. for (uint32_t i = 0; i < num_syms; i++)
  1186. {
  1187. if (pSym_freq[i])
  1188. {
  1189. uint32_t f = static_cast<uint32_t>((static_cast<uint64_t>(pSym_freq[i]) * 65534U + (max_freq >> 1)) / max_freq);
  1190. sym_freq[i] = static_cast<uint16_t>(clamp<uint32_t>(f, 1, 65534));
  1191. }
  1192. }
  1193. }
  1194. return init(num_syms, &sym_freq[0], max_code_size);
  1195. }
  1196. void bitwise_coder::end_nonzero_run(uint16_vec &syms, uint32_t &run_size, uint32_t len)
  1197. {
  1198. if (run_size)
  1199. {
  1200. if (run_size < cHuffmanSmallRepeatSizeMin)
  1201. {
  1202. while (run_size--)
  1203. syms.push_back(static_cast<uint16_t>(len));
  1204. }
  1205. else if (run_size <= cHuffmanSmallRepeatSizeMax)
  1206. {
  1207. syms.push_back(static_cast<uint16_t>(cHuffmanSmallRepeatCode | ((run_size - cHuffmanSmallRepeatSizeMin) << 6)));
  1208. }
  1209. else
  1210. {
  1211. assert((run_size >= cHuffmanBigRepeatSizeMin) && (run_size <= cHuffmanBigRepeatSizeMax));
  1212. syms.push_back(static_cast<uint16_t>(cHuffmanBigRepeatCode | ((run_size - cHuffmanBigRepeatSizeMin) << 6)));
  1213. }
  1214. }
  1215. run_size = 0;
  1216. }
  1217. void bitwise_coder::end_zero_run(uint16_vec &syms, uint32_t &run_size)
  1218. {
  1219. if (run_size)
  1220. {
  1221. if (run_size < cHuffmanSmallZeroRunSizeMin)
  1222. {
  1223. while (run_size--)
  1224. syms.push_back(0);
  1225. }
  1226. else if (run_size <= cHuffmanSmallZeroRunSizeMax)
  1227. {
  1228. syms.push_back(static_cast<uint16_t>(cHuffmanSmallZeroRunCode | ((run_size - cHuffmanSmallZeroRunSizeMin) << 6)));
  1229. }
  1230. else
  1231. {
  1232. assert((run_size >= cHuffmanBigZeroRunSizeMin) && (run_size <= cHuffmanBigZeroRunSizeMax));
  1233. syms.push_back(static_cast<uint16_t>(cHuffmanBigZeroRunCode | ((run_size - cHuffmanBigZeroRunSizeMin) << 6)));
  1234. }
  1235. }
  1236. run_size = 0;
  1237. }
  1238. uint32_t bitwise_coder::emit_huffman_table(const huffman_encoding_table &tab)
  1239. {
  1240. const uint64_t start_bits = m_total_bits;
  1241. const uint8_vec &code_sizes = tab.get_code_sizes();
  1242. uint32_t total_used = tab.get_total_used_codes();
  1243. put_bits(total_used, cHuffmanMaxSymsLog2);
  1244. if (!total_used)
  1245. return 0;
  1246. uint16_vec syms;
  1247. syms.reserve(total_used + 16);
  1248. uint32_t prev_code_len = UINT_MAX, zero_run_size = 0, nonzero_run_size = 0;
  1249. for (uint32_t i = 0; i <= total_used; ++i)
  1250. {
  1251. const uint32_t code_len = (i == total_used) ? 0xFF : code_sizes[i];
  1252. assert((code_len == 0xFF) || (code_len <= 16));
  1253. if (code_len)
  1254. {
  1255. end_zero_run(syms, zero_run_size);
  1256. if (code_len != prev_code_len)
  1257. {
  1258. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1259. if (code_len != 0xFF)
  1260. syms.push_back(static_cast<uint16_t>(code_len));
  1261. }
  1262. else if (++nonzero_run_size == cHuffmanBigRepeatSizeMax)
  1263. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1264. }
  1265. else
  1266. {
  1267. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1268. if (++zero_run_size == cHuffmanBigZeroRunSizeMax)
  1269. end_zero_run(syms, zero_run_size);
  1270. }
  1271. prev_code_len = code_len;
  1272. }
  1273. histogram h(cHuffmanTotalCodelengthCodes);
  1274. for (uint32_t i = 0; i < syms.size(); i++)
  1275. h.inc(syms[i] & 63);
  1276. huffman_encoding_table ct;
  1277. if (!ct.init(h, 7))
  1278. return 0;
  1279. assert(cHuffmanTotalSortedCodelengthCodes == cHuffmanTotalCodelengthCodes);
  1280. uint32_t total_codelength_codes;
  1281. for (total_codelength_codes = cHuffmanTotalSortedCodelengthCodes; total_codelength_codes > 0; total_codelength_codes--)
  1282. if (ct.get_code_sizes()[g_huffman_sorted_codelength_codes[total_codelength_codes - 1]])
  1283. break;
  1284. assert(total_codelength_codes);
  1285. put_bits(total_codelength_codes, 5);
  1286. for (uint32_t i = 0; i < total_codelength_codes; i++)
  1287. put_bits(ct.get_code_sizes()[g_huffman_sorted_codelength_codes[i]], 3);
  1288. for (uint32_t i = 0; i < syms.size(); ++i)
  1289. {
  1290. const uint32_t l = syms[i] & 63, e = syms[i] >> 6;
  1291. put_code(l, ct);
  1292. if (l == cHuffmanSmallZeroRunCode)
  1293. put_bits(e, cHuffmanSmallZeroRunExtraBits);
  1294. else if (l == cHuffmanBigZeroRunCode)
  1295. put_bits(e, cHuffmanBigZeroRunExtraBits);
  1296. else if (l == cHuffmanSmallRepeatCode)
  1297. put_bits(e, cHuffmanSmallRepeatExtraBits);
  1298. else if (l == cHuffmanBigRepeatCode)
  1299. put_bits(e, cHuffmanBigRepeatExtraBits);
  1300. }
  1301. return (uint32_t)(m_total_bits - start_bits);
  1302. }
  1303. bool huffman_test(int rand_seed)
  1304. {
  1305. histogram h(19);
  1306. // Feed in a fibonacci sequence to force large codesizes
  1307. h[0] += 1; h[1] += 1; h[2] += 2; h[3] += 3;
  1308. h[4] += 5; h[5] += 8; h[6] += 13; h[7] += 21;
  1309. h[8] += 34; h[9] += 55; h[10] += 89; h[11] += 144;
  1310. h[12] += 233; h[13] += 377; h[14] += 610; h[15] += 987;
  1311. h[16] += 1597; h[17] += 2584; h[18] += 4181;
  1312. huffman_encoding_table etab;
  1313. etab.init(h, 16);
  1314. {
  1315. bitwise_coder c;
  1316. c.init(1024);
  1317. c.emit_huffman_table(etab);
  1318. for (int i = 0; i < 19; i++)
  1319. c.put_code(i, etab);
  1320. c.flush();
  1321. basist::bitwise_decoder d;
  1322. d.init(&c.get_bytes()[0], static_cast<uint32_t>(c.get_bytes().size()));
  1323. basist::huffman_decoding_table dtab;
  1324. bool success = d.read_huffman_table(dtab);
  1325. if (!success)
  1326. {
  1327. assert(0);
  1328. printf("Failure 5\n");
  1329. return false;
  1330. }
  1331. for (uint32_t i = 0; i < 19; i++)
  1332. {
  1333. uint32_t s = d.decode_huffman(dtab);
  1334. if (s != i)
  1335. {
  1336. assert(0);
  1337. printf("Failure 5\n");
  1338. return false;
  1339. }
  1340. }
  1341. }
  1342. basisu::rand r;
  1343. r.seed(rand_seed);
  1344. for (int iter = 0; iter < 500000; iter++)
  1345. {
  1346. printf("%u\n", iter);
  1347. uint32_t max_sym = r.irand(0, 8193);
  1348. uint32_t num_codes = r.irand(1, 10000);
  1349. uint_vec syms(num_codes);
  1350. for (uint32_t i = 0; i < num_codes; i++)
  1351. {
  1352. if (r.bit())
  1353. syms[i] = r.irand(0, max_sym);
  1354. else
  1355. {
  1356. int s = (int)(r.gaussian((float)max_sym / 2, (float)maximum<int>(1, max_sym / 2)) + .5f);
  1357. s = basisu::clamp<int>(s, 0, max_sym);
  1358. syms[i] = s;
  1359. }
  1360. }
  1361. histogram h1(max_sym + 1);
  1362. for (uint32_t i = 0; i < num_codes; i++)
  1363. h1[syms[i]]++;
  1364. huffman_encoding_table etab2;
  1365. if (!etab2.init(h1, 16))
  1366. {
  1367. assert(0);
  1368. printf("Failed 0\n");
  1369. return false;
  1370. }
  1371. bitwise_coder c;
  1372. c.init(1024);
  1373. c.emit_huffman_table(etab2);
  1374. for (uint32_t i = 0; i < num_codes; i++)
  1375. c.put_code(syms[i], etab2);
  1376. c.flush();
  1377. basist::bitwise_decoder d;
  1378. d.init(&c.get_bytes()[0], (uint32_t)c.get_bytes().size());
  1379. basist::huffman_decoding_table dtab;
  1380. bool success = d.read_huffman_table(dtab);
  1381. if (!success)
  1382. {
  1383. assert(0);
  1384. printf("Failed 2\n");
  1385. return false;
  1386. }
  1387. for (uint32_t i = 0; i < num_codes; i++)
  1388. {
  1389. uint32_t s = d.decode_huffman(dtab);
  1390. if (s != syms[i])
  1391. {
  1392. assert(0);
  1393. printf("Failed 4\n");
  1394. return false;
  1395. }
  1396. }
  1397. }
  1398. return true;
  1399. }
  1400. void palette_index_reorderer::init(uint32_t num_indices, const uint32_t *pIndices, uint32_t num_syms, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1401. {
  1402. assert((num_syms > 0) && (num_indices > 0));
  1403. assert((dist_func_weight >= 0.0f) && (dist_func_weight <= 1.0f));
  1404. clear();
  1405. m_remap_table.resize(num_syms);
  1406. m_entries_picked.reserve(num_syms);
  1407. m_total_count_to_picked.resize(num_syms);
  1408. if (num_indices <= 1)
  1409. return;
  1410. prepare_hist(num_syms, num_indices, pIndices);
  1411. find_initial(num_syms);
  1412. while (m_entries_to_do.size())
  1413. {
  1414. // Find the best entry to move into the picked list.
  1415. uint32_t best_entry;
  1416. double best_count;
  1417. find_next_entry(best_entry, best_count, pDist_func, pCtx, dist_func_weight);
  1418. // We now have chosen an entry to place in the picked list, now determine which side it goes on.
  1419. const uint32_t entry_to_move = m_entries_to_do[best_entry];
  1420. float side = pick_side(num_syms, entry_to_move, pDist_func, pCtx, dist_func_weight);
  1421. // Put entry_to_move either on the "left" or "right" side of the picked entries
  1422. if (side <= 0)
  1423. m_entries_picked.push_back(entry_to_move);
  1424. else
  1425. m_entries_picked.insert(m_entries_picked.begin(), entry_to_move);
  1426. // Erase best_entry from the todo list
  1427. m_entries_to_do.erase(m_entries_to_do.begin() + best_entry);
  1428. // We've just moved best_entry to the picked list, so now we need to update m_total_count_to_picked[] to factor the additional count to best_entry
  1429. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1430. m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], entry_to_move, num_syms);
  1431. }
  1432. for (uint32_t i = 0; i < num_syms; i++)
  1433. m_remap_table[m_entries_picked[i]] = i;
  1434. }
  1435. void palette_index_reorderer::prepare_hist(uint32_t num_syms, uint32_t num_indices, const uint32_t *pIndices)
  1436. {
  1437. m_hist.resize(0);
  1438. m_hist.resize(num_syms * num_syms);
  1439. for (uint32_t i = 0; i < num_indices; i++)
  1440. {
  1441. const uint32_t idx = pIndices[i];
  1442. inc_hist(idx, (i < (num_indices - 1)) ? pIndices[i + 1] : -1, num_syms);
  1443. inc_hist(idx, (i > 0) ? pIndices[i - 1] : -1, num_syms);
  1444. }
  1445. }
  1446. void palette_index_reorderer::find_initial(uint32_t num_syms)
  1447. {
  1448. uint32_t max_count = 0, max_index = 0;
  1449. for (uint32_t i = 0; i < num_syms * num_syms; i++)
  1450. if (m_hist[i] > max_count)
  1451. max_count = m_hist[i], max_index = i;
  1452. uint32_t a = max_index / num_syms, b = max_index % num_syms;
  1453. const size_t ofs = m_entries_picked.size();
  1454. m_entries_picked.push_back(a);
  1455. m_entries_picked.push_back(b);
  1456. for (uint32_t i = 0; i < num_syms; i++)
  1457. if ((i != m_entries_picked[ofs + 1]) && (i != m_entries_picked[ofs]))
  1458. m_entries_to_do.push_back(i);
  1459. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1460. for (uint32_t j = 0; j < m_entries_picked.size(); j++)
  1461. m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], m_entries_picked[j], num_syms);
  1462. }
  1463. void palette_index_reorderer::find_next_entry(uint32_t &best_entry, double &best_count, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1464. {
  1465. best_entry = 0;
  1466. best_count = 0;
  1467. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1468. {
  1469. const uint32_t u = m_entries_to_do[i];
  1470. double total_count = m_total_count_to_picked[u];
  1471. if (pDist_func)
  1472. {
  1473. float w = maximum<float>((*pDist_func)(u, m_entries_picked.front(), pCtx), (*pDist_func)(u, m_entries_picked.back(), pCtx));
  1474. assert((w >= 0.0f) && (w <= 1.0f));
  1475. total_count = (total_count + 1.0f) * lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, w);
  1476. }
  1477. if (total_count <= best_count)
  1478. continue;
  1479. best_entry = i;
  1480. best_count = total_count;
  1481. }
  1482. }
  1483. float palette_index_reorderer::pick_side(uint32_t num_syms, uint32_t entry_to_move, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1484. {
  1485. float which_side = 0;
  1486. int l_count = 0, r_count = 0;
  1487. for (uint32_t j = 0; j < m_entries_picked.size(); j++)
  1488. {
  1489. const int count = get_hist(entry_to_move, m_entries_picked[j], num_syms), r = ((int)m_entries_picked.size() + 1 - 2 * (j + 1));
  1490. which_side += static_cast<float>(r * count);
  1491. if (r >= 0)
  1492. l_count += r * count;
  1493. else
  1494. r_count += -r * count;
  1495. }
  1496. if (pDist_func)
  1497. {
  1498. float w_left = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.front(), pCtx));
  1499. float w_right = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.back(), pCtx));
  1500. which_side = w_left * l_count - w_right * r_count;
  1501. }
  1502. return which_side;
  1503. }
  1504. void image_metrics::calc(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool log)
  1505. {
  1506. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1507. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1508. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1509. double max_e = -1e+30f;
  1510. double sum = 0.0f, sum_sqr = 0.0f;
  1511. m_has_neg = false;
  1512. m_any_abnormal = false;
  1513. m_hf_mag_overflow = false;
  1514. for (uint32_t y = 0; y < height; y++)
  1515. {
  1516. for (uint32_t x = 0; x < width; x++)
  1517. {
  1518. const vec4F& ca = a(x, y), &cb = b(x, y);
  1519. if (total_chans)
  1520. {
  1521. for (uint32_t c = 0; c < total_chans; c++)
  1522. {
  1523. float fa = ca[first_chan + c], fb = cb[first_chan + c];
  1524. if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
  1525. m_hf_mag_overflow = true;
  1526. if ((fa < 0.0f) || (fb < 0.0f))
  1527. m_has_neg = true;
  1528. if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
  1529. m_any_abnormal = true;
  1530. const double delta = fabs(fa - fb);
  1531. max_e = basisu::maximum<double>(max_e, delta);
  1532. if (log)
  1533. {
  1534. double log2_delta = log2f(basisu::maximum(0.0f, fa) + 1.0f) - log2f(basisu::maximum(0.0f, fb) + 1.0f);
  1535. sum += fabs(log2_delta);
  1536. sum_sqr += log2_delta * log2_delta;
  1537. }
  1538. else
  1539. {
  1540. sum += fabs(delta);
  1541. sum_sqr += delta * delta;
  1542. }
  1543. }
  1544. }
  1545. else
  1546. {
  1547. for (uint32_t c = 0; c < 3; c++)
  1548. {
  1549. float fa = ca[c], fb = cb[c];
  1550. if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
  1551. m_hf_mag_overflow = true;
  1552. if ((fa < 0.0f) || (fb < 0.0f))
  1553. m_has_neg = true;
  1554. if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
  1555. m_any_abnormal = true;
  1556. }
  1557. double ca_l = get_luminance(ca), cb_l = get_luminance(cb);
  1558. double delta = fabs(ca_l - cb_l);
  1559. max_e = basisu::maximum(max_e, delta);
  1560. if (log)
  1561. {
  1562. double log2_delta = log2(basisu::maximum<double>(0.0f, ca_l) + 1.0f) - log2(basisu::maximum<double>(0.0f, cb_l) + 1.0f);
  1563. sum += fabs(log2_delta);
  1564. sum_sqr += log2_delta * log2_delta;
  1565. }
  1566. else
  1567. {
  1568. sum += delta;
  1569. sum_sqr += delta * delta;
  1570. }
  1571. }
  1572. }
  1573. }
  1574. m_max = (double)(max_e);
  1575. double total_values = (double)width * (double)height;
  1576. if (avg_comp_error)
  1577. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1578. m_mean = (float)(sum / total_values);
  1579. m_mean_squared = (float)(sum_sqr / total_values);
  1580. m_rms = (float)sqrt(sum_sqr / total_values);
  1581. const double max_val = 1.0f;
  1582. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1583. }
  1584. void image_metrics::calc_half(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
  1585. {
  1586. assert(total_chans);
  1587. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1588. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1589. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1590. m_has_neg = false;
  1591. m_hf_mag_overflow = false;
  1592. m_any_abnormal = false;
  1593. uint_vec hist(65536);
  1594. for (uint32_t y = 0; y < height; y++)
  1595. {
  1596. for (uint32_t x = 0; x < width; x++)
  1597. {
  1598. const vec4F& ca = a(x, y), &cb = b(x, y);
  1599. for (uint32_t i = 0; i < 4; i++)
  1600. {
  1601. if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
  1602. m_has_neg = true;
  1603. if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
  1604. m_hf_mag_overflow = true;
  1605. if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
  1606. m_any_abnormal = true;
  1607. }
  1608. int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
  1609. int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
  1610. for (uint32_t c = 0; c < total_chans; c++)
  1611. hist[iabs(cah[first_chan + c] - cbh[first_chan + c]) & 65535]++;
  1612. } // x
  1613. } // y
  1614. m_max = 0;
  1615. double sum = 0.0f, sum2 = 0.0f;
  1616. for (uint32_t i = 0; i < 65536; i++)
  1617. {
  1618. if (hist[i])
  1619. {
  1620. m_max = basisu::maximum<double>(m_max, (double)i);
  1621. double v = (double)i * (double)hist[i];
  1622. sum += v;
  1623. sum2 += (double)i * v;
  1624. }
  1625. }
  1626. double total_values = (double)width * (double)height;
  1627. if (avg_comp_error)
  1628. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1629. const float max_val = 65535.0f;
  1630. m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
  1631. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
  1632. m_rms = (float)sqrt(m_mean_squared);
  1633. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1634. }
  1635. // Alt. variant, same as calc_half(), for validation.
  1636. void image_metrics::calc_half2(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
  1637. {
  1638. assert(total_chans);
  1639. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1640. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1641. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1642. m_has_neg = false;
  1643. m_hf_mag_overflow = false;
  1644. m_any_abnormal = false;
  1645. double sum = 0.0f, sum2 = 0.0f;
  1646. m_max = 0;
  1647. for (uint32_t y = 0; y < height; y++)
  1648. {
  1649. for (uint32_t x = 0; x < width; x++)
  1650. {
  1651. const vec4F& ca = a(x, y), & cb = b(x, y);
  1652. for (uint32_t i = 0; i < 4; i++)
  1653. {
  1654. if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
  1655. m_has_neg = true;
  1656. if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
  1657. m_hf_mag_overflow = true;
  1658. if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
  1659. m_any_abnormal = true;
  1660. }
  1661. int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
  1662. int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
  1663. for (uint32_t c = 0; c < total_chans; c++)
  1664. {
  1665. int diff = iabs(cah[first_chan + c] - cbh[first_chan + c]);
  1666. if (diff)
  1667. m_max = std::max<double>(m_max, (double)diff);
  1668. sum += diff;
  1669. sum2 += squarei(cah[first_chan + c] - cbh[first_chan + c]);
  1670. }
  1671. } // x
  1672. } // y
  1673. double total_values = (double)width * (double)height;
  1674. if (avg_comp_error)
  1675. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1676. const float max_val = 65535.0f;
  1677. m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
  1678. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
  1679. m_rms = (float)sqrt(m_mean_squared);
  1680. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1681. }
  1682. void image_metrics::calc(const image &a, const image &b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool use_601_luma)
  1683. {
  1684. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1685. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1686. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1687. double hist[256];
  1688. clear_obj(hist);
  1689. m_has_neg = false;
  1690. m_any_abnormal = false;
  1691. m_hf_mag_overflow = false;
  1692. for (uint32_t y = 0; y < height; y++)
  1693. {
  1694. for (uint32_t x = 0; x < width; x++)
  1695. {
  1696. const color_rgba &ca = a(x, y), &cb = b(x, y);
  1697. if (total_chans)
  1698. {
  1699. for (uint32_t c = 0; c < total_chans; c++)
  1700. hist[iabs(ca[first_chan + c] - cb[first_chan + c])]++;
  1701. }
  1702. else
  1703. {
  1704. if (use_601_luma)
  1705. hist[iabs(ca.get_601_luma() - cb.get_601_luma())]++;
  1706. else
  1707. hist[iabs(ca.get_709_luma() - cb.get_709_luma())]++;
  1708. }
  1709. }
  1710. }
  1711. m_max = 0;
  1712. double sum = 0.0f, sum2 = 0.0f;
  1713. for (uint32_t i = 0; i < 256; i++)
  1714. {
  1715. if (hist[i])
  1716. {
  1717. m_max = basisu::maximum<double>(m_max, (double)i);
  1718. double v = i * hist[i];
  1719. sum += v;
  1720. sum2 += i * v;
  1721. }
  1722. }
  1723. double total_values = (double)width * (double)height;
  1724. if (avg_comp_error)
  1725. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1726. m_mean = (float)clamp<double>(sum / total_values, 0.0f, 255.0);
  1727. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, 255.0f * 255.0f);
  1728. m_rms = (float)sqrt(m_mean_squared);
  1729. m_psnr = m_rms ? (float)clamp<double>(log10(255.0 / m_rms) * 20.0f, 0.0f, 100.0f) : 100.0f;
  1730. }
  1731. void print_image_metrics(const image& a, const image& b)
  1732. {
  1733. image_metrics im;
  1734. im.calc(a, b, 0, 3);
  1735. im.print("RGB ");
  1736. im.calc(a, b, 0, 4);
  1737. im.print("RGBA ");
  1738. im.calc(a, b, 0, 1);
  1739. im.print("R ");
  1740. im.calc(a, b, 1, 1);
  1741. im.print("G ");
  1742. im.calc(a, b, 2, 1);
  1743. im.print("B ");
  1744. im.calc(a, b, 3, 1);
  1745. im.print("A ");
  1746. im.calc(a, b, 0, 0);
  1747. im.print("Y 709 ");
  1748. im.calc(a, b, 0, 0, true, true);
  1749. im.print("Y 601 ");
  1750. }
  1751. void fill_buffer_with_random_bytes(void *pBuf, size_t size, uint32_t seed)
  1752. {
  1753. rand r(seed);
  1754. uint8_t *pDst = static_cast<uint8_t *>(pBuf);
  1755. while (size >= sizeof(uint32_t))
  1756. {
  1757. *(uint32_t *)pDst = r.urand32();
  1758. pDst += sizeof(uint32_t);
  1759. size -= sizeof(uint32_t);
  1760. }
  1761. while (size)
  1762. {
  1763. *pDst++ = r.byte();
  1764. size--;
  1765. }
  1766. }
  1767. uint32_t hash_hsieh(const uint8_t *pBuf, size_t len)
  1768. {
  1769. if (!pBuf || !len)
  1770. return 0;
  1771. uint32_t h = static_cast<uint32_t>(len);
  1772. const uint32_t bytes_left = len & 3;
  1773. len >>= 2;
  1774. while (len--)
  1775. {
  1776. const uint16_t *pWords = reinterpret_cast<const uint16_t *>(pBuf);
  1777. h += pWords[0];
  1778. const uint32_t t = (pWords[1] << 11) ^ h;
  1779. h = (h << 16) ^ t;
  1780. pBuf += sizeof(uint32_t);
  1781. h += h >> 11;
  1782. }
  1783. switch (bytes_left)
  1784. {
  1785. case 1:
  1786. h += *reinterpret_cast<const signed char*>(pBuf);
  1787. h ^= h << 10;
  1788. h += h >> 1;
  1789. break;
  1790. case 2:
  1791. h += *reinterpret_cast<const uint16_t *>(pBuf);
  1792. h ^= h << 11;
  1793. h += h >> 17;
  1794. break;
  1795. case 3:
  1796. h += *reinterpret_cast<const uint16_t *>(pBuf);
  1797. h ^= h << 16;
  1798. h ^= (static_cast<signed char>(pBuf[sizeof(uint16_t)])) << 18;
  1799. h += h >> 11;
  1800. break;
  1801. default:
  1802. break;
  1803. }
  1804. h ^= h << 3;
  1805. h += h >> 5;
  1806. h ^= h << 4;
  1807. h += h >> 17;
  1808. h ^= h << 25;
  1809. h += h >> 6;
  1810. return h;
  1811. }
  1812. job_pool::job_pool(uint32_t num_threads) :
  1813. m_num_active_jobs(0)
  1814. {
  1815. m_kill_flag.store(false);
  1816. m_num_active_workers.store(0);
  1817. assert(num_threads >= 1U);
  1818. debug_printf("job_pool::job_pool: %u total threads\n", num_threads);
  1819. if (num_threads > 1)
  1820. {
  1821. m_threads.resize(num_threads - 1);
  1822. for (int i = 0; i < ((int)num_threads - 1); i++)
  1823. m_threads[i] = std::thread([this, i] { job_thread(i); });
  1824. }
  1825. }
  1826. job_pool::~job_pool()
  1827. {
  1828. debug_printf("job_pool::~job_pool\n");
  1829. // Notify all workers that they need to die right now.
  1830. {
  1831. std::lock_guard<std::mutex> lk(m_mutex);
  1832. m_kill_flag.store(true);
  1833. }
  1834. m_has_work.notify_all();
  1835. #ifdef __EMSCRIPTEN__
  1836. for ( ; ; )
  1837. {
  1838. if (m_num_active_workers.load() <= 0)
  1839. break;
  1840. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  1841. }
  1842. // At this point all worker threads should be exiting or exited.
  1843. // We could call detach(), but this seems to just call join() anyway.
  1844. #endif
  1845. // Wait for all worker threads to exit.
  1846. for (uint32_t i = 0; i < m_threads.size(); i++)
  1847. m_threads[i].join();
  1848. }
  1849. void job_pool::add_job(const std::function<void()>& job)
  1850. {
  1851. std::unique_lock<std::mutex> lock(m_mutex);
  1852. m_queue.emplace_back(job);
  1853. const size_t queue_size = m_queue.size();
  1854. lock.unlock();
  1855. if (queue_size > 1)
  1856. m_has_work.notify_one();
  1857. }
  1858. void job_pool::add_job(std::function<void()>&& job)
  1859. {
  1860. std::unique_lock<std::mutex> lock(m_mutex);
  1861. m_queue.emplace_back(std::move(job));
  1862. const size_t queue_size = m_queue.size();
  1863. lock.unlock();
  1864. if (queue_size > 1)
  1865. {
  1866. m_has_work.notify_one();
  1867. }
  1868. }
  1869. void job_pool::wait_for_all()
  1870. {
  1871. std::unique_lock<std::mutex> lock(m_mutex);
  1872. // Drain the job queue on the calling thread.
  1873. while (!m_queue.empty())
  1874. {
  1875. std::function<void()> job(m_queue.back());
  1876. m_queue.pop_back();
  1877. lock.unlock();
  1878. job();
  1879. lock.lock();
  1880. }
  1881. // The queue is empty, now wait for all active jobs to finish up.
  1882. #ifndef __EMSCRIPTEN__
  1883. m_no_more_jobs.wait(lock, [this]{ return !m_num_active_jobs; } );
  1884. #else
  1885. // Avoid infinite blocking
  1886. for (; ; )
  1887. {
  1888. if (m_no_more_jobs.wait_for(lock, std::chrono::milliseconds(50), [this] { return !m_num_active_jobs; }))
  1889. {
  1890. break;
  1891. }
  1892. }
  1893. #endif
  1894. }
  1895. void job_pool::job_thread(uint32_t index)
  1896. {
  1897. BASISU_NOTE_UNUSED(index);
  1898. //debug_printf("job_pool::job_thread: starting %u\n", index);
  1899. m_num_active_workers.fetch_add(1);
  1900. while (!m_kill_flag)
  1901. {
  1902. std::unique_lock<std::mutex> lock(m_mutex);
  1903. // Wait for any jobs to be issued.
  1904. #if 0
  1905. m_has_work.wait(lock, [this] { return m_kill_flag || m_queue.size(); } );
  1906. #else
  1907. // For more safety vs. buggy RTL's. Worse case we stall for a second vs. locking up forever if something goes wrong.
  1908. m_has_work.wait_for(lock, std::chrono::milliseconds(1000), [this] {
  1909. return m_kill_flag || !m_queue.empty();
  1910. });
  1911. #endif
  1912. // Check to see if we're supposed to exit.
  1913. if (m_kill_flag)
  1914. break;
  1915. if (m_queue.empty())
  1916. continue;
  1917. // Get the job and execute it.
  1918. std::function<void()> job(m_queue.back());
  1919. m_queue.pop_back();
  1920. ++m_num_active_jobs;
  1921. lock.unlock();
  1922. job();
  1923. lock.lock();
  1924. --m_num_active_jobs;
  1925. // Now check if there are no more jobs remaining.
  1926. const bool all_done = m_queue.empty() && !m_num_active_jobs;
  1927. lock.unlock();
  1928. if (all_done)
  1929. m_no_more_jobs.notify_all();
  1930. }
  1931. m_num_active_workers.fetch_add(-1);
  1932. //debug_printf("job_pool::job_thread: exiting\n");
  1933. }
  1934. // .TGA image loading
  1935. #pragma pack(push)
  1936. #pragma pack(1)
  1937. struct tga_header
  1938. {
  1939. uint8_t m_id_len;
  1940. uint8_t m_cmap;
  1941. uint8_t m_type;
  1942. packed_uint<2> m_cmap_first;
  1943. packed_uint<2> m_cmap_len;
  1944. uint8_t m_cmap_bpp;
  1945. packed_uint<2> m_x_org;
  1946. packed_uint<2> m_y_org;
  1947. packed_uint<2> m_width;
  1948. packed_uint<2> m_height;
  1949. uint8_t m_depth;
  1950. uint8_t m_desc;
  1951. };
  1952. #pragma pack(pop)
  1953. const uint32_t MAX_TGA_IMAGE_SIZE = 16384;
  1954. enum tga_image_type
  1955. {
  1956. cITPalettized = 1,
  1957. cITRGB = 2,
  1958. cITGrayscale = 3
  1959. };
  1960. uint8_t *read_tga(const uint8_t *pBuf, uint32_t buf_size, int &width, int &height, int &n_chans)
  1961. {
  1962. width = 0;
  1963. height = 0;
  1964. n_chans = 0;
  1965. if (buf_size <= sizeof(tga_header))
  1966. return nullptr;
  1967. const tga_header &hdr = *reinterpret_cast<const tga_header *>(pBuf);
  1968. if ((!hdr.m_width) || (!hdr.m_height) || (hdr.m_width > MAX_TGA_IMAGE_SIZE) || (hdr.m_height > MAX_TGA_IMAGE_SIZE))
  1969. return nullptr;
  1970. if (hdr.m_desc >> 6)
  1971. return nullptr;
  1972. // Simple validation
  1973. if ((hdr.m_cmap != 0) && (hdr.m_cmap != 1))
  1974. return nullptr;
  1975. if (hdr.m_cmap)
  1976. {
  1977. if ((hdr.m_cmap_bpp == 0) || (hdr.m_cmap_bpp > 32))
  1978. return nullptr;
  1979. // Nobody implements CMapFirst correctly, so we're not supporting it. Never seen it used, either.
  1980. if (hdr.m_cmap_first != 0)
  1981. return nullptr;
  1982. }
  1983. const bool x_flipped = (hdr.m_desc & 0x10) != 0;
  1984. const bool y_flipped = (hdr.m_desc & 0x20) == 0;
  1985. bool rle_flag = false;
  1986. int file_image_type = hdr.m_type;
  1987. if (file_image_type > 8)
  1988. {
  1989. file_image_type -= 8;
  1990. rle_flag = true;
  1991. }
  1992. const tga_image_type image_type = static_cast<tga_image_type>(file_image_type);
  1993. switch (file_image_type)
  1994. {
  1995. case cITRGB:
  1996. if (hdr.m_depth == 8)
  1997. return nullptr;
  1998. break;
  1999. case cITPalettized:
  2000. if ((hdr.m_depth != 8) || (hdr.m_cmap != 1) || (hdr.m_cmap_len == 0))
  2001. return nullptr;
  2002. break;
  2003. case cITGrayscale:
  2004. if ((hdr.m_cmap != 0) || (hdr.m_cmap_len != 0))
  2005. return nullptr;
  2006. if ((hdr.m_depth != 8) && (hdr.m_depth != 16))
  2007. return nullptr;
  2008. break;
  2009. default:
  2010. return nullptr;
  2011. }
  2012. uint32_t tga_bytes_per_pixel = 0;
  2013. switch (hdr.m_depth)
  2014. {
  2015. case 32:
  2016. tga_bytes_per_pixel = 4;
  2017. n_chans = 4;
  2018. break;
  2019. case 24:
  2020. tga_bytes_per_pixel = 3;
  2021. n_chans = 3;
  2022. break;
  2023. case 16:
  2024. case 15:
  2025. tga_bytes_per_pixel = 2;
  2026. // For compatibility with stb_image_write.h
  2027. n_chans = ((file_image_type == cITGrayscale) && (hdr.m_depth == 16)) ? 4 : 3;
  2028. break;
  2029. case 8:
  2030. tga_bytes_per_pixel = 1;
  2031. // For palettized RGBA support, which both FreeImage and stb_image support.
  2032. n_chans = ((file_image_type == cITPalettized) && (hdr.m_cmap_bpp == 32)) ? 4 : 3;
  2033. break;
  2034. default:
  2035. return nullptr;
  2036. }
  2037. //const uint32_t bytes_per_line = hdr.m_width * tga_bytes_per_pixel;
  2038. const uint8_t *pSrc = pBuf + sizeof(tga_header);
  2039. uint32_t bytes_remaining = buf_size - sizeof(tga_header);
  2040. if (hdr.m_id_len)
  2041. {
  2042. if (bytes_remaining < hdr.m_id_len)
  2043. return nullptr;
  2044. pSrc += hdr.m_id_len;
  2045. bytes_remaining += hdr.m_id_len;
  2046. }
  2047. color_rgba pal[256];
  2048. for (uint32_t i = 0; i < 256; i++)
  2049. pal[i].set(0, 0, 0, 255);
  2050. if ((hdr.m_cmap) && (hdr.m_cmap_len))
  2051. {
  2052. if (image_type == cITPalettized)
  2053. {
  2054. // Note I cannot find any files using 32bpp palettes in the wild (never seen any in ~30 years).
  2055. if ( ((hdr.m_cmap_bpp != 32) && (hdr.m_cmap_bpp != 24) && (hdr.m_cmap_bpp != 15) && (hdr.m_cmap_bpp != 16)) || (hdr.m_cmap_len > 256) )
  2056. return nullptr;
  2057. if (hdr.m_cmap_bpp == 32)
  2058. {
  2059. const uint32_t pal_size = hdr.m_cmap_len * 4;
  2060. if (bytes_remaining < pal_size)
  2061. return nullptr;
  2062. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  2063. {
  2064. pal[i].r = pSrc[i * 4 + 2];
  2065. pal[i].g = pSrc[i * 4 + 1];
  2066. pal[i].b = pSrc[i * 4 + 0];
  2067. pal[i].a = pSrc[i * 4 + 3];
  2068. }
  2069. bytes_remaining -= pal_size;
  2070. pSrc += pal_size;
  2071. }
  2072. else if (hdr.m_cmap_bpp == 24)
  2073. {
  2074. const uint32_t pal_size = hdr.m_cmap_len * 3;
  2075. if (bytes_remaining < pal_size)
  2076. return nullptr;
  2077. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  2078. {
  2079. pal[i].r = pSrc[i * 3 + 2];
  2080. pal[i].g = pSrc[i * 3 + 1];
  2081. pal[i].b = pSrc[i * 3 + 0];
  2082. pal[i].a = 255;
  2083. }
  2084. bytes_remaining -= pal_size;
  2085. pSrc += pal_size;
  2086. }
  2087. else
  2088. {
  2089. const uint32_t pal_size = hdr.m_cmap_len * 2;
  2090. if (bytes_remaining < pal_size)
  2091. return nullptr;
  2092. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  2093. {
  2094. const uint32_t v = pSrc[i * 2 + 0] | (pSrc[i * 2 + 1] << 8);
  2095. pal[i].r = (((v >> 10) & 31) * 255 + 15) / 31;
  2096. pal[i].g = (((v >> 5) & 31) * 255 + 15) / 31;
  2097. pal[i].b = ((v & 31) * 255 + 15) / 31;
  2098. pal[i].a = 255;
  2099. }
  2100. bytes_remaining -= pal_size;
  2101. pSrc += pal_size;
  2102. }
  2103. }
  2104. else
  2105. {
  2106. const uint32_t bytes_to_skip = (hdr.m_cmap_bpp >> 3) * hdr.m_cmap_len;
  2107. if (bytes_remaining < bytes_to_skip)
  2108. return nullptr;
  2109. pSrc += bytes_to_skip;
  2110. bytes_remaining += bytes_to_skip;
  2111. }
  2112. }
  2113. width = hdr.m_width;
  2114. height = hdr.m_height;
  2115. const uint32_t source_pitch = width * tga_bytes_per_pixel;
  2116. const uint32_t dest_pitch = width * n_chans;
  2117. uint8_t *pImage = (uint8_t *)malloc(dest_pitch * height);
  2118. if (!pImage)
  2119. return nullptr;
  2120. std::vector<uint8_t> input_line_buf;
  2121. if (rle_flag)
  2122. input_line_buf.resize(source_pitch);
  2123. int run_type = 0, run_remaining = 0;
  2124. uint8_t run_pixel[4];
  2125. memset(run_pixel, 0, sizeof(run_pixel));
  2126. for (int y = 0; y < height; y++)
  2127. {
  2128. const uint8_t *pLine_data;
  2129. if (rle_flag)
  2130. {
  2131. int pixels_remaining = width;
  2132. uint8_t *pDst = &input_line_buf[0];
  2133. do
  2134. {
  2135. if (!run_remaining)
  2136. {
  2137. if (bytes_remaining < 1)
  2138. {
  2139. free(pImage);
  2140. return nullptr;
  2141. }
  2142. int v = *pSrc++;
  2143. bytes_remaining--;
  2144. run_type = v & 0x80;
  2145. run_remaining = (v & 0x7F) + 1;
  2146. if (run_type)
  2147. {
  2148. if (bytes_remaining < tga_bytes_per_pixel)
  2149. {
  2150. free(pImage);
  2151. return nullptr;
  2152. }
  2153. memcpy(run_pixel, pSrc, tga_bytes_per_pixel);
  2154. pSrc += tga_bytes_per_pixel;
  2155. bytes_remaining -= tga_bytes_per_pixel;
  2156. }
  2157. }
  2158. const uint32_t n = basisu::minimum<uint32_t>(pixels_remaining, run_remaining);
  2159. pixels_remaining -= n;
  2160. run_remaining -= n;
  2161. if (run_type)
  2162. {
  2163. for (uint32_t i = 0; i < n; i++)
  2164. for (uint32_t j = 0; j < tga_bytes_per_pixel; j++)
  2165. *pDst++ = run_pixel[j];
  2166. }
  2167. else
  2168. {
  2169. const uint32_t bytes_wanted = n * tga_bytes_per_pixel;
  2170. if (bytes_remaining < bytes_wanted)
  2171. {
  2172. free(pImage);
  2173. return nullptr;
  2174. }
  2175. memcpy(pDst, pSrc, bytes_wanted);
  2176. pDst += bytes_wanted;
  2177. pSrc += bytes_wanted;
  2178. bytes_remaining -= bytes_wanted;
  2179. }
  2180. } while (pixels_remaining);
  2181. assert((pDst - &input_line_buf[0]) == (int)(width * tga_bytes_per_pixel));
  2182. pLine_data = &input_line_buf[0];
  2183. }
  2184. else
  2185. {
  2186. if (bytes_remaining < source_pitch)
  2187. {
  2188. free(pImage);
  2189. return nullptr;
  2190. }
  2191. pLine_data = pSrc;
  2192. bytes_remaining -= source_pitch;
  2193. pSrc += source_pitch;
  2194. }
  2195. // Convert to 24bpp RGB or 32bpp RGBA.
  2196. uint8_t *pDst = pImage + (y_flipped ? (height - 1 - y) : y) * dest_pitch + (x_flipped ? (width - 1) * n_chans : 0);
  2197. const int dst_stride = x_flipped ? -((int)n_chans) : n_chans;
  2198. switch (hdr.m_depth)
  2199. {
  2200. case 32:
  2201. assert(tga_bytes_per_pixel == 4 && n_chans == 4);
  2202. for (int i = 0; i < width; i++, pLine_data += 4, pDst += dst_stride)
  2203. {
  2204. pDst[0] = pLine_data[2];
  2205. pDst[1] = pLine_data[1];
  2206. pDst[2] = pLine_data[0];
  2207. pDst[3] = pLine_data[3];
  2208. }
  2209. break;
  2210. case 24:
  2211. assert(tga_bytes_per_pixel == 3 && n_chans == 3);
  2212. for (int i = 0; i < width; i++, pLine_data += 3, pDst += dst_stride)
  2213. {
  2214. pDst[0] = pLine_data[2];
  2215. pDst[1] = pLine_data[1];
  2216. pDst[2] = pLine_data[0];
  2217. }
  2218. break;
  2219. case 16:
  2220. case 15:
  2221. if (image_type == cITRGB)
  2222. {
  2223. assert(tga_bytes_per_pixel == 2 && n_chans == 3);
  2224. for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
  2225. {
  2226. const uint32_t v = pLine_data[0] | (pLine_data[1] << 8);
  2227. pDst[0] = (((v >> 10) & 31) * 255 + 15) / 31;
  2228. pDst[1] = (((v >> 5) & 31) * 255 + 15) / 31;
  2229. pDst[2] = ((v & 31) * 255 + 15) / 31;
  2230. }
  2231. }
  2232. else
  2233. {
  2234. assert(image_type == cITGrayscale && tga_bytes_per_pixel == 2 && n_chans == 4);
  2235. for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
  2236. {
  2237. pDst[0] = pLine_data[0];
  2238. pDst[1] = pLine_data[0];
  2239. pDst[2] = pLine_data[0];
  2240. pDst[3] = pLine_data[1];
  2241. }
  2242. }
  2243. break;
  2244. case 8:
  2245. assert(tga_bytes_per_pixel == 1);
  2246. if (image_type == cITPalettized)
  2247. {
  2248. if (hdr.m_cmap_bpp == 32)
  2249. {
  2250. assert(n_chans == 4);
  2251. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2252. {
  2253. const uint32_t c = *pLine_data;
  2254. pDst[0] = pal[c].r;
  2255. pDst[1] = pal[c].g;
  2256. pDst[2] = pal[c].b;
  2257. pDst[3] = pal[c].a;
  2258. }
  2259. }
  2260. else
  2261. {
  2262. assert(n_chans == 3);
  2263. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2264. {
  2265. const uint32_t c = *pLine_data;
  2266. pDst[0] = pal[c].r;
  2267. pDst[1] = pal[c].g;
  2268. pDst[2] = pal[c].b;
  2269. }
  2270. }
  2271. }
  2272. else
  2273. {
  2274. assert(n_chans == 3);
  2275. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2276. {
  2277. const uint8_t c = *pLine_data;
  2278. pDst[0] = c;
  2279. pDst[1] = c;
  2280. pDst[2] = c;
  2281. }
  2282. }
  2283. break;
  2284. default:
  2285. assert(0);
  2286. break;
  2287. }
  2288. } // y
  2289. return pImage;
  2290. }
  2291. uint8_t *read_tga(const char *pFilename, int &width, int &height, int &n_chans)
  2292. {
  2293. width = height = n_chans = 0;
  2294. uint8_vec filedata;
  2295. if (!read_file_to_vec(pFilename, filedata))
  2296. return nullptr;
  2297. if (!filedata.size() || (filedata.size() > UINT32_MAX))
  2298. return nullptr;
  2299. return read_tga(&filedata[0], (uint32_t)filedata.size(), width, height, n_chans);
  2300. }
  2301. static inline void hdr_convert(const color_rgba& rgbe, vec4F& c)
  2302. {
  2303. if (rgbe[3] != 0)
  2304. {
  2305. float scale = ldexp(1.0f, rgbe[3] - 128 - 8);
  2306. c.set((float)rgbe[0] * scale, (float)rgbe[1] * scale, (float)rgbe[2] * scale, 1.0f);
  2307. }
  2308. else
  2309. {
  2310. c.set(0.0f, 0.0f, 0.0f, 1.0f);
  2311. }
  2312. }
  2313. bool string_begins_with(const std::string& str, const char* pPhrase)
  2314. {
  2315. const size_t str_len = str.size();
  2316. const size_t phrase_len = strlen(pPhrase);
  2317. assert(phrase_len);
  2318. if (str_len >= phrase_len)
  2319. {
  2320. #ifdef _MSC_VER
  2321. if (_strnicmp(pPhrase, str.c_str(), phrase_len) == 0)
  2322. #else
  2323. if (strncasecmp(pPhrase, str.c_str(), phrase_len) == 0)
  2324. #endif
  2325. return true;
  2326. }
  2327. return false;
  2328. }
  2329. // Radiance RGBE (.HDR) image reading.
  2330. // This code tries to preserve the original logic in Radiance's ray/src/common/color.c code:
  2331. // https://www.radiance-online.org/cgi-bin/viewcvs.cgi/ray/src/common/color.c?revision=2.26&view=markup&sortby=log
  2332. // Also see: https://flipcode.com/archives/HDR_Image_Reader.shtml.
  2333. // https://github.com/LuminanceHDR/LuminanceHDR/blob/master/src/Libpfs/io/rgbereader.cpp.
  2334. // https://radsite.lbl.gov/radiance/refer/filefmts.pdf
  2335. // Buggy readers:
  2336. // stb_image.h: appears to be a clone of rgbe.c, but with goto's (doesn't support old format files, doesn't support mixture of RLE/non-RLE scanlines)
  2337. // http://www.graphics.cornell.edu/~bjw/rgbe.html - rgbe.c/h
  2338. // http://www.graphics.cornell.edu/online/formats/rgbe/ - rgbe.c/.h - buggy
  2339. bool read_rgbe(const uint8_vec &filedata, imagef& img, rgbe_header_info& hdr_info)
  2340. {
  2341. hdr_info.clear();
  2342. const uint32_t MAX_SUPPORTED_DIM = 65536;
  2343. if (filedata.size() < 4)
  2344. return false;
  2345. // stb_image.h checks for the string "#?RADIANCE" or "#?RGBE" in the header.
  2346. // The original Radiance header code doesn't care about the specific string.
  2347. // opencv's reader only checks for "#?", so that's what we're going to do.
  2348. if ((filedata[0] != '#') || (filedata[1] != '?'))
  2349. return false;
  2350. //uint32_t width = 0, height = 0;
  2351. bool is_rgbe = false;
  2352. size_t cur_ofs = 0;
  2353. // Parse the lines until we encounter a blank line.
  2354. std::string cur_line;
  2355. for (; ; )
  2356. {
  2357. if (cur_ofs >= filedata.size())
  2358. return false;
  2359. const uint32_t HEADER_TOO_BIG_SIZE = 4096;
  2360. if (cur_ofs >= HEADER_TOO_BIG_SIZE)
  2361. {
  2362. // Header seems too large - something is likely wrong. Return failure.
  2363. return false;
  2364. }
  2365. uint8_t c = filedata[cur_ofs++];
  2366. if (c == '\n')
  2367. {
  2368. if (!cur_line.size())
  2369. break;
  2370. if ((cur_line[0] == '#') && (!string_begins_with(cur_line, "#?")) && (!hdr_info.m_program.size()))
  2371. {
  2372. cur_line.erase(0, 1);
  2373. while (cur_line.size() && (cur_line[0] == ' '))
  2374. cur_line.erase(0, 1);
  2375. hdr_info.m_program = cur_line;
  2376. }
  2377. else if (string_begins_with(cur_line, "EXPOSURE=") && (cur_line.size() > 9))
  2378. {
  2379. hdr_info.m_exposure = atof(cur_line.c_str() + 9);
  2380. hdr_info.m_has_exposure = true;
  2381. }
  2382. else if (string_begins_with(cur_line, "GAMMA=") && (cur_line.size() > 6))
  2383. {
  2384. hdr_info.m_exposure = atof(cur_line.c_str() + 6);
  2385. hdr_info.m_has_gamma = true;
  2386. }
  2387. else if (cur_line == "FORMAT=32-bit_rle_rgbe")
  2388. {
  2389. is_rgbe = true;
  2390. }
  2391. cur_line.resize(0);
  2392. }
  2393. else
  2394. cur_line.push_back((char)c);
  2395. }
  2396. if (!is_rgbe)
  2397. return false;
  2398. // Assume and require the final line to have the image's dimensions. We're not supporting flipping.
  2399. for (; ; )
  2400. {
  2401. if (cur_ofs >= filedata.size())
  2402. return false;
  2403. uint8_t c = filedata[cur_ofs++];
  2404. if (c == '\n')
  2405. break;
  2406. cur_line.push_back((char)c);
  2407. }
  2408. int comp[2] = { 1, 0 }; // y, x (major, minor)
  2409. int dir[2] = { -1, 1 }; // -1, 1, (major, minor), for y -1=up
  2410. uint32_t major_dim = 0, minor_dim = 0;
  2411. // Parse the dimension string, normally it'll be "-Y # +X #" (major, minor), rarely it differs
  2412. for (uint32_t d = 0; d < 2; d++) // 0=major, 1=minor
  2413. {
  2414. const bool is_neg_x = (strncmp(&cur_line[0], "-X ", 3) == 0);
  2415. const bool is_pos_x = (strncmp(&cur_line[0], "+X ", 3) == 0);
  2416. const bool is_x = is_neg_x || is_pos_x;
  2417. const bool is_neg_y = (strncmp(&cur_line[0], "-Y ", 3) == 0);
  2418. const bool is_pos_y = (strncmp(&cur_line[0], "+Y ", 3) == 0);
  2419. const bool is_y = is_neg_y || is_pos_y;
  2420. if (cur_line.size() < 3)
  2421. return false;
  2422. if (!is_x && !is_y)
  2423. return false;
  2424. comp[d] = is_x ? 0 : 1;
  2425. dir[d] = (is_neg_x || is_neg_y) ? -1 : 1;
  2426. uint32_t& dim = d ? minor_dim : major_dim;
  2427. cur_line.erase(0, 3);
  2428. while (cur_line.size())
  2429. {
  2430. char c = cur_line[0];
  2431. if (c != ' ')
  2432. break;
  2433. cur_line.erase(0, 1);
  2434. }
  2435. bool has_digits = false;
  2436. while (cur_line.size())
  2437. {
  2438. char c = cur_line[0];
  2439. cur_line.erase(0, 1);
  2440. if (c == ' ')
  2441. break;
  2442. if ((c < '0') || (c > '9'))
  2443. return false;
  2444. const uint32_t prev_dim = dim;
  2445. dim = dim * 10 + (c - '0');
  2446. if (dim < prev_dim)
  2447. return false;
  2448. has_digits = true;
  2449. }
  2450. if (!has_digits)
  2451. return false;
  2452. if ((dim < 1) || (dim > MAX_SUPPORTED_DIM))
  2453. return false;
  2454. }
  2455. // temp image: width=minor, height=major
  2456. img.resize(minor_dim, major_dim);
  2457. std::vector<color_rgba> temp_scanline(minor_dim);
  2458. // Read the scanlines.
  2459. for (uint32_t y = 0; y < major_dim; y++)
  2460. {
  2461. vec4F* pDst = &img(0, y);
  2462. if ((filedata.size() - cur_ofs) < 4)
  2463. return false;
  2464. // Determine if the line uses the new or old format. See the logic in color.c.
  2465. bool old_decrunch = false;
  2466. if ((minor_dim < 8) || (minor_dim > 0x7FFF))
  2467. {
  2468. // Line is too short or long; must be old format.
  2469. old_decrunch = true;
  2470. }
  2471. else if (filedata[cur_ofs] != 2)
  2472. {
  2473. // R is not 2, must be old format
  2474. old_decrunch = true;
  2475. }
  2476. else
  2477. {
  2478. // c[0]/red is 2.Check GB and E for validity.
  2479. color_rgba c;
  2480. memcpy(&c, &filedata[cur_ofs], 4);
  2481. if ((c[1] != 2) || (c[2] & 0x80))
  2482. {
  2483. // G isn't 2, or the high bit of B is set which is impossible (image's > 0x7FFF pixels can't get here). Use old format.
  2484. old_decrunch = true;
  2485. }
  2486. else
  2487. {
  2488. // Check B and E. If this isn't the minor_dim in network order, something is wrong. The pixel would also be denormalized, and invalid.
  2489. uint32_t w = (c[2] << 8) | c[3];
  2490. if (w != minor_dim)
  2491. return false;
  2492. cur_ofs += 4;
  2493. }
  2494. }
  2495. if (old_decrunch)
  2496. {
  2497. uint32_t rshift = 0, x = 0;
  2498. while (x < minor_dim)
  2499. {
  2500. if ((filedata.size() - cur_ofs) < 4)
  2501. return false;
  2502. color_rgba c;
  2503. memcpy(&c, &filedata[cur_ofs], 4);
  2504. cur_ofs += 4;
  2505. if ((c[0] == 1) && (c[1] == 1) && (c[2] == 1))
  2506. {
  2507. // We'll allow RLE matches to cross scanlines, but not on the very first pixel.
  2508. if ((!x) && (!y))
  2509. return false;
  2510. const uint32_t run_len = c[3] << rshift;
  2511. const vec4F run_color(pDst[-1]);
  2512. if ((x + run_len) > minor_dim)
  2513. return false;
  2514. for (uint32_t i = 0; i < run_len; i++)
  2515. *pDst++ = run_color;
  2516. rshift += 8;
  2517. x += run_len;
  2518. }
  2519. else
  2520. {
  2521. rshift = 0;
  2522. hdr_convert(c, *pDst);
  2523. pDst++;
  2524. x++;
  2525. }
  2526. }
  2527. continue;
  2528. }
  2529. // New format
  2530. for (uint32_t s = 0; s < 4; s++)
  2531. {
  2532. uint32_t x_ofs = 0;
  2533. while (x_ofs < minor_dim)
  2534. {
  2535. uint32_t num_remaining = minor_dim - x_ofs;
  2536. if (cur_ofs >= filedata.size())
  2537. return false;
  2538. uint8_t count = filedata[cur_ofs++];
  2539. if (count > 128)
  2540. {
  2541. count -= 128;
  2542. if (count > num_remaining)
  2543. return false;
  2544. if (cur_ofs >= filedata.size())
  2545. return false;
  2546. const uint8_t val = filedata[cur_ofs++];
  2547. for (uint32_t i = 0; i < count; i++)
  2548. temp_scanline[x_ofs + i][s] = val;
  2549. x_ofs += count;
  2550. }
  2551. else
  2552. {
  2553. if ((!count) || (count > num_remaining))
  2554. return false;
  2555. for (uint32_t i = 0; i < count; i++)
  2556. {
  2557. if (cur_ofs >= filedata.size())
  2558. return false;
  2559. const uint8_t val = filedata[cur_ofs++];
  2560. temp_scanline[x_ofs + i][s] = val;
  2561. }
  2562. x_ofs += count;
  2563. }
  2564. } // while (x_ofs < minor_dim)
  2565. } // c
  2566. // Convert all the RGBE pixels to float now
  2567. for (uint32_t x = 0; x < minor_dim; x++, pDst++)
  2568. hdr_convert(temp_scanline[x], *pDst);
  2569. assert((pDst - &img(0, y)) == (int)minor_dim);
  2570. } // y
  2571. // at here:
  2572. // img(width,height)=image pixels as read from file, x=minor axis, y=major axis
  2573. // width=minor axis dimension
  2574. // height=major axis dimension
  2575. // in file, pixels are emitted in minor order, them major (so major=scanlines in the file)
  2576. imagef final_img;
  2577. if (comp[0] == 0) // if major axis is X
  2578. final_img.resize(major_dim, minor_dim);
  2579. else // major axis is Y, minor is X
  2580. final_img.resize(minor_dim, major_dim);
  2581. // TODO: optimize the identity case
  2582. for (uint32_t major_iter = 0; major_iter < major_dim; major_iter++)
  2583. {
  2584. for (uint32_t minor_iter = 0; minor_iter < minor_dim; minor_iter++)
  2585. {
  2586. const vec4F& p = img(minor_iter, major_iter);
  2587. uint32_t dst_x = 0, dst_y = 0;
  2588. // is the minor dim output x?
  2589. if (comp[1] == 0)
  2590. {
  2591. // minor axis is x, major is y
  2592. // is minor axis (which is output x) flipped?
  2593. if (dir[1] < 0)
  2594. dst_x = minor_dim - 1 - minor_iter;
  2595. else
  2596. dst_x = minor_iter;
  2597. // is major axis (which is output y) flipped? -1=down in raster order, 1=up
  2598. if (dir[0] < 0)
  2599. dst_y = major_iter;
  2600. else
  2601. dst_y = major_dim - 1 - major_iter;
  2602. }
  2603. else
  2604. {
  2605. // minor axis is output y, major is output x
  2606. // is minor axis (which is output y) flipped?
  2607. if (dir[1] < 0)
  2608. dst_y = minor_iter;
  2609. else
  2610. dst_y = minor_dim - 1 - minor_iter;
  2611. // is major axis (which is output x) flipped?
  2612. if (dir[0] < 0)
  2613. dst_x = major_dim - 1 - major_iter;
  2614. else
  2615. dst_x = major_iter;
  2616. }
  2617. final_img(dst_x, dst_y) = p;
  2618. }
  2619. }
  2620. final_img.swap(img);
  2621. return true;
  2622. }
  2623. bool read_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
  2624. {
  2625. uint8_vec filedata;
  2626. if (!read_file_to_vec(pFilename, filedata))
  2627. return false;
  2628. return read_rgbe(filedata, img, hdr_info);
  2629. }
  2630. static uint8_vec& append_string(uint8_vec& buf, const char* pStr)
  2631. {
  2632. const size_t str_len = strlen(pStr);
  2633. if (!str_len)
  2634. return buf;
  2635. const size_t ofs = buf.size();
  2636. buf.resize(ofs + str_len);
  2637. memcpy(&buf[ofs], pStr, str_len);
  2638. return buf;
  2639. }
  2640. static uint8_vec& append_string(uint8_vec& buf, const std::string& str)
  2641. {
  2642. if (!str.size())
  2643. return buf;
  2644. return append_string(buf, str.c_str());
  2645. }
  2646. static inline void float2rgbe(color_rgba &rgbe, const vec4F &c)
  2647. {
  2648. const float red = c[0], green = c[1], blue = c[2];
  2649. assert(red >= 0.0f && green >= 0.0f && blue >= 0.0f);
  2650. const float max_v = basisu::maximumf(basisu::maximumf(red, green), blue);
  2651. if (max_v < 1e-32f)
  2652. rgbe.clear();
  2653. else
  2654. {
  2655. int e;
  2656. const float scale = frexp(max_v, &e) * 256.0f / max_v;
  2657. rgbe[0] = (uint8_t)(clamp<int>((int)(red * scale), 0, 255));
  2658. rgbe[1] = (uint8_t)(clamp<int>((int)(green * scale), 0, 255));
  2659. rgbe[2] = (uint8_t)(clamp<int>((int)(blue * scale), 0, 255));
  2660. rgbe[3] = (uint8_t)(e + 128);
  2661. }
  2662. }
  2663. const bool RGBE_FORCE_RAW = false;
  2664. const bool RGBE_FORCE_OLD_CRUNCH = false; // note must readers (particularly stb_image.h's) don't properly support this, when they should
  2665. bool write_rgbe(uint8_vec &file_data, imagef& img, rgbe_header_info& hdr_info)
  2666. {
  2667. if (!img.get_width() || !img.get_height())
  2668. return false;
  2669. const uint32_t width = img.get_width(), height = img.get_height();
  2670. file_data.resize(0);
  2671. file_data.reserve(1024 + img.get_width() * img.get_height() * 4);
  2672. append_string(file_data, "#?RADIANCE\n");
  2673. if (hdr_info.m_has_exposure)
  2674. append_string(file_data, string_format("EXPOSURE=%g\n", hdr_info.m_exposure));
  2675. if (hdr_info.m_has_gamma)
  2676. append_string(file_data, string_format("GAMMA=%g\n", hdr_info.m_gamma));
  2677. append_string(file_data, "FORMAT=32-bit_rle_rgbe\n\n");
  2678. append_string(file_data, string_format("-Y %u +X %u\n", height, width));
  2679. if (((width < 8) || (width > 0x7FFF)) || (RGBE_FORCE_RAW))
  2680. {
  2681. for (uint32_t y = 0; y < height; y++)
  2682. {
  2683. for (uint32_t x = 0; x < width; x++)
  2684. {
  2685. color_rgba rgbe;
  2686. float2rgbe(rgbe, img(x, y));
  2687. append_vector(file_data, (const uint8_t *)&rgbe, sizeof(rgbe));
  2688. }
  2689. }
  2690. }
  2691. else if (RGBE_FORCE_OLD_CRUNCH)
  2692. {
  2693. for (uint32_t y = 0; y < height; y++)
  2694. {
  2695. int prev_r = -1, prev_g = -1, prev_b = -1, prev_e = -1;
  2696. uint32_t cur_run_len = 0;
  2697. for (uint32_t x = 0; x < width; x++)
  2698. {
  2699. color_rgba rgbe;
  2700. float2rgbe(rgbe, img(x, y));
  2701. if ((rgbe[0] == prev_r) && (rgbe[1] == prev_g) && (rgbe[2] == prev_b) && (rgbe[3] == prev_e))
  2702. {
  2703. if (++cur_run_len == 255)
  2704. {
  2705. // this ensures rshift stays 0, it's lame but this path is only for testing readers
  2706. color_rgba f(1, 1, 1, cur_run_len - 1);
  2707. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2708. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2709. cur_run_len = 0;
  2710. }
  2711. }
  2712. else
  2713. {
  2714. if (cur_run_len > 0)
  2715. {
  2716. color_rgba f(1, 1, 1, cur_run_len);
  2717. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2718. cur_run_len = 0;
  2719. }
  2720. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2721. prev_r = rgbe[0];
  2722. prev_g = rgbe[1];
  2723. prev_b = rgbe[2];
  2724. prev_e = rgbe[3];
  2725. }
  2726. } // x
  2727. if (cur_run_len > 0)
  2728. {
  2729. color_rgba f(1, 1, 1, cur_run_len);
  2730. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2731. }
  2732. } // y
  2733. }
  2734. else
  2735. {
  2736. uint8_vec temp[4];
  2737. for (uint32_t c = 0; c < 4; c++)
  2738. temp[c].resize(width);
  2739. for (uint32_t y = 0; y < height; y++)
  2740. {
  2741. color_rgba rgbe(2, 2, width >> 8, width & 0xFF);
  2742. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2743. for (uint32_t x = 0; x < width; x++)
  2744. {
  2745. float2rgbe(rgbe, img(x, y));
  2746. for (uint32_t c = 0; c < 4; c++)
  2747. temp[c][x] = rgbe[c];
  2748. }
  2749. for (uint32_t c = 0; c < 4; c++)
  2750. {
  2751. int raw_ofs = -1;
  2752. uint32_t x = 0;
  2753. while (x < width)
  2754. {
  2755. const uint32_t num_bytes_remaining = width - x;
  2756. const uint32_t max_run_len = basisu::minimum<uint32_t>(num_bytes_remaining, 127);
  2757. const uint8_t cur_byte = temp[c][x];
  2758. uint32_t run_len = 1;
  2759. while (run_len < max_run_len)
  2760. {
  2761. if (temp[c][x + run_len] != cur_byte)
  2762. break;
  2763. run_len++;
  2764. }
  2765. const uint32_t cost_to_keep_raw = ((raw_ofs != -1) ? 0 : 1) + run_len; // 0 or 1 bytes to start a raw run, then the repeated bytes issued as raw
  2766. const uint32_t cost_to_take_run = 2 + 1; // 2 bytes to issue the RLE, then 1 bytes to start whatever follows it (raw or RLE)
  2767. if ((run_len >= 3) && (cost_to_take_run < cost_to_keep_raw))
  2768. {
  2769. file_data.push_back((uint8_t)(128 + run_len));
  2770. file_data.push_back(cur_byte);
  2771. x += run_len;
  2772. raw_ofs = -1;
  2773. }
  2774. else
  2775. {
  2776. if (raw_ofs < 0)
  2777. {
  2778. raw_ofs = (int)file_data.size();
  2779. file_data.push_back(0);
  2780. }
  2781. if (++file_data[raw_ofs] == 128)
  2782. raw_ofs = -1;
  2783. file_data.push_back(cur_byte);
  2784. x++;
  2785. }
  2786. } // x
  2787. } // c
  2788. } // y
  2789. }
  2790. return true;
  2791. }
  2792. bool write_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
  2793. {
  2794. uint8_vec file_data;
  2795. if (!write_rgbe(file_data, img, hdr_info))
  2796. return false;
  2797. return write_vec_to_file(pFilename, file_data);
  2798. }
  2799. bool read_exr(const char* pFilename, imagef& img, int& n_chans)
  2800. {
  2801. n_chans = 0;
  2802. int width = 0, height = 0;
  2803. float* out_rgba = nullptr;
  2804. const char* err = nullptr;
  2805. int status = LoadEXRWithLayer(&out_rgba, &width, &height, pFilename, nullptr, &err);
  2806. n_chans = 4;
  2807. if (status != 0)
  2808. {
  2809. error_printf("Failed loading .EXR image \"%s\"! (TinyEXR error: %s)\n", pFilename, err ? err : "?");
  2810. FreeEXRErrorMessage(err);
  2811. free(out_rgba);
  2812. return false;
  2813. }
  2814. const uint32_t MAX_SUPPORTED_DIM = 65536;
  2815. if ((width < 1) || (height < 1) || (width > (int)MAX_SUPPORTED_DIM) || (height > (int)MAX_SUPPORTED_DIM))
  2816. {
  2817. error_printf("Invalid dimensions of .EXR image \"%s\"!\n", pFilename);
  2818. free(out_rgba);
  2819. return false;
  2820. }
  2821. img.resize(width, height);
  2822. if (n_chans == 1)
  2823. {
  2824. const float* pSrc = out_rgba;
  2825. vec4F* pDst = img.get_ptr();
  2826. for (int y = 0; y < height; y++)
  2827. {
  2828. for (int x = 0; x < width; x++)
  2829. {
  2830. (*pDst)[0] = pSrc[0];
  2831. (*pDst)[1] = pSrc[1];
  2832. (*pDst)[2] = pSrc[2];
  2833. (*pDst)[3] = 1.0f;
  2834. pSrc += 4;
  2835. ++pDst;
  2836. }
  2837. }
  2838. }
  2839. else
  2840. {
  2841. memcpy((void *)img.get_ptr(), out_rgba, static_cast<size_t>(sizeof(float) * 4 * img.get_total_pixels()));
  2842. }
  2843. free(out_rgba);
  2844. return true;
  2845. }
  2846. bool read_exr(const void* pMem, size_t mem_size, imagef& img)
  2847. {
  2848. float* out_rgba = nullptr;
  2849. int width = 0, height = 0;
  2850. const char* pErr = nullptr;
  2851. int res = LoadEXRFromMemory(&out_rgba, &width, &height, (const uint8_t*)pMem, mem_size, &pErr);
  2852. if (res < 0)
  2853. {
  2854. error_printf("Failed loading .EXR image from memory! (TinyEXR error: %s)\n", pErr ? pErr : "?");
  2855. FreeEXRErrorMessage(pErr);
  2856. free(out_rgba);
  2857. return false;
  2858. }
  2859. img.resize(width, height);
  2860. memcpy((void *)img.get_ptr(), out_rgba, width * height * sizeof(float) * 4);
  2861. free(out_rgba);
  2862. return true;
  2863. }
  2864. bool write_exr(const char* pFilename, const imagef& img, uint32_t n_chans, uint32_t flags)
  2865. {
  2866. assert((n_chans == 1) || (n_chans == 3) || (n_chans == 4));
  2867. const bool linear_hint = (flags & WRITE_EXR_LINEAR_HINT) != 0,
  2868. store_float = (flags & WRITE_EXR_STORE_FLOATS) != 0,
  2869. no_compression = (flags & WRITE_EXR_NO_COMPRESSION) != 0;
  2870. const uint32_t width = img.get_width(), height = img.get_height();
  2871. assert(width && height);
  2872. if (!width || !height)
  2873. return false;
  2874. float_vec layers[4];
  2875. float* image_ptrs[4];
  2876. for (uint32_t c = 0; c < n_chans; c++)
  2877. {
  2878. layers[c].resize(width * height);
  2879. image_ptrs[c] = layers[c].get_ptr();
  2880. }
  2881. // ABGR
  2882. int chan_order[4] = { 3, 2, 1, 0 };
  2883. if (n_chans == 1)
  2884. {
  2885. // Y
  2886. chan_order[0] = 0;
  2887. }
  2888. else if (n_chans == 3)
  2889. {
  2890. // BGR
  2891. chan_order[0] = 2;
  2892. chan_order[1] = 1;
  2893. chan_order[2] = 0;
  2894. }
  2895. else if (n_chans != 4)
  2896. {
  2897. assert(0);
  2898. return false;
  2899. }
  2900. for (uint32_t y = 0; y < height; y++)
  2901. {
  2902. for (uint32_t x = 0; x < width; x++)
  2903. {
  2904. const vec4F& p = img(x, y);
  2905. for (uint32_t c = 0; c < n_chans; c++)
  2906. layers[c][x + y * width] = p[chan_order[c]];
  2907. } // x
  2908. } // y
  2909. EXRHeader header;
  2910. InitEXRHeader(&header);
  2911. EXRImage image;
  2912. InitEXRImage(&image);
  2913. image.num_channels = n_chans;
  2914. image.images = (unsigned char**)image_ptrs;
  2915. image.width = width;
  2916. image.height = height;
  2917. header.num_channels = n_chans;
  2918. header.channels = (EXRChannelInfo*)calloc(header.num_channels, sizeof(EXRChannelInfo));
  2919. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  2920. for (uint32_t i = 0; i < n_chans; i++)
  2921. {
  2922. char c = 'Y';
  2923. if (n_chans == 3)
  2924. c = "BGR"[i];
  2925. else if (n_chans == 4)
  2926. c = "ABGR"[i];
  2927. header.channels[i].name[0] = c;
  2928. header.channels[i].name[1] = '\0';
  2929. header.channels[i].p_linear = linear_hint;
  2930. }
  2931. header.pixel_types = (int*)calloc(header.num_channels, sizeof(int));
  2932. header.requested_pixel_types = (int*)calloc(header.num_channels, sizeof(int));
  2933. if (!no_compression)
  2934. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  2935. for (int i = 0; i < header.num_channels; i++)
  2936. {
  2937. // pixel type of input image
  2938. header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  2939. // pixel type of output image to be stored in .EXR
  2940. header.requested_pixel_types[i] = store_float ? TINYEXR_PIXELTYPE_FLOAT : TINYEXR_PIXELTYPE_HALF;
  2941. }
  2942. const char* pErr_msg = nullptr;
  2943. int ret = SaveEXRImageToFile(&image, &header, pFilename, &pErr_msg);
  2944. if (ret != TINYEXR_SUCCESS)
  2945. {
  2946. error_printf("Save EXR err: %s\n", pErr_msg);
  2947. FreeEXRErrorMessage(pErr_msg);
  2948. }
  2949. free(header.channels);
  2950. free(header.pixel_types);
  2951. free(header.requested_pixel_types);
  2952. return (ret == TINYEXR_SUCCESS);
  2953. }
  2954. void image::debug_text(uint32_t x_ofs, uint32_t y_ofs, uint32_t scale_x, uint32_t scale_y, const color_rgba& fg, const color_rgba* pBG, bool alpha_only, const char* pFmt, ...)
  2955. {
  2956. char buf[2048];
  2957. va_list args;
  2958. va_start(args, pFmt);
  2959. #ifdef _WIN32
  2960. vsprintf_s(buf, sizeof(buf), pFmt, args);
  2961. #else
  2962. vsnprintf(buf, sizeof(buf), pFmt, args);
  2963. #endif
  2964. va_end(args);
  2965. const char* p = buf;
  2966. const uint32_t orig_x_ofs = x_ofs;
  2967. while (*p)
  2968. {
  2969. uint8_t c = *p++;
  2970. if ((c < 32) || (c > 127))
  2971. c = '.';
  2972. const uint8_t* pGlpyh = &g_debug_font8x8_basic[c - 32][0];
  2973. for (uint32_t y = 0; y < 8; y++)
  2974. {
  2975. uint32_t row_bits = pGlpyh[y];
  2976. for (uint32_t x = 0; x < 8; x++)
  2977. {
  2978. const uint32_t q = row_bits & (1 << x);
  2979. const color_rgba* pColor = q ? &fg : pBG;
  2980. if (!pColor)
  2981. continue;
  2982. if (alpha_only)
  2983. fill_box_alpha(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
  2984. else
  2985. fill_box(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
  2986. }
  2987. }
  2988. x_ofs += 8 * scale_x;
  2989. if ((x_ofs + 8 * scale_x) > m_width)
  2990. {
  2991. x_ofs = orig_x_ofs;
  2992. y_ofs += 8 * scale_y;
  2993. }
  2994. }
  2995. }
  2996. // Very basic global Reinhard tone mapping, output converted to sRGB with no dithering, alpha is carried through unchanged.
  2997. // Only used for debugging/development.
  2998. void tonemap_image_reinhard(image &ldr_img, const imagef &hdr_img, float exposure, bool add_noise, bool per_component, bool luma_scaling)
  2999. {
  3000. uint32_t width = hdr_img.get_width(), height = hdr_img.get_height();
  3001. ldr_img.resize(width, height);
  3002. rand r;
  3003. r.seed(128);
  3004. for (uint32_t y = 0; y < height; y++)
  3005. {
  3006. for (uint32_t x = 0; x < width; x++)
  3007. {
  3008. vec4F c(hdr_img(x, y));
  3009. if (per_component)
  3010. {
  3011. for (uint32_t t = 0; t < 3; t++)
  3012. {
  3013. if (c[t] <= 0.0f)
  3014. {
  3015. c[t] = 0.0f;
  3016. }
  3017. else
  3018. {
  3019. c[t] *= exposure;
  3020. c[t] = c[t] / (1.0f + c[t]);
  3021. }
  3022. }
  3023. }
  3024. else
  3025. {
  3026. c[0] *= exposure;
  3027. c[1] *= exposure;
  3028. c[2] *= exposure;
  3029. const float L = 0.2126f * c[0] + 0.7152f * c[1] + 0.0722f * c[2];
  3030. float Lmapped = 0.0f;
  3031. if (L > 0.0f)
  3032. {
  3033. //Lmapped = L / (1.0f + L);
  3034. //Lmapped /= L;
  3035. Lmapped = 1.0f / (1.0f + L);
  3036. }
  3037. c[0] = c[0] * Lmapped;
  3038. c[1] = c[1] * Lmapped;
  3039. c[2] = c[2] * Lmapped;
  3040. if (luma_scaling)
  3041. {
  3042. // Keeps the ratio of r/g/b intact
  3043. float m = maximum(c[0], c[1], c[2]);
  3044. if (m > 1.0f)
  3045. {
  3046. c /= m;
  3047. }
  3048. }
  3049. }
  3050. c.clamp(0.0f, 1.0f);
  3051. c[3] = c[3] * 255.0f;
  3052. color_rgba& o = ldr_img(x, y);
  3053. if (add_noise)
  3054. {
  3055. c[0] = linear_to_srgb(c[0]) * 255.0f;
  3056. c[1] = linear_to_srgb(c[1]) * 255.0f;
  3057. c[2] = linear_to_srgb(c[2]) * 255.0f;
  3058. const float NOISE_AMP = .5f;
  3059. c[0] += r.frand(-NOISE_AMP, NOISE_AMP);
  3060. c[1] += r.frand(-NOISE_AMP, NOISE_AMP);
  3061. c[2] += r.frand(-NOISE_AMP, NOISE_AMP);
  3062. c.clamp(0.0f, 255.0f);
  3063. o[0] = (uint8_t)fast_roundf_int(c[0]);
  3064. o[1] = (uint8_t)fast_roundf_int(c[1]);
  3065. o[2] = (uint8_t)fast_roundf_int(c[2]);
  3066. o[3] = (uint8_t)fast_roundf_int(c[3]);
  3067. }
  3068. else
  3069. {
  3070. o[0] = g_fast_linear_to_srgb.convert(c[0]);
  3071. o[1] = g_fast_linear_to_srgb.convert(c[1]);
  3072. o[2] = g_fast_linear_to_srgb.convert(c[2]);
  3073. o[3] = (uint8_t)fast_roundf_int(c[3]);
  3074. }
  3075. }
  3076. }
  3077. }
  3078. bool tonemap_image_compressive(image& dst_img, const imagef& hdr_test_img)
  3079. {
  3080. const uint32_t width = hdr_test_img.get_width();
  3081. const uint32_t height = hdr_test_img.get_height();
  3082. uint16_vec orig_half_img(width * 3 * height);
  3083. uint16_vec half_img(width * 3 * height);
  3084. int max_shift = 32;
  3085. for (uint32_t y = 0; y < height; y++)
  3086. {
  3087. for (uint32_t x = 0; x < width; x++)
  3088. {
  3089. const vec4F& p = hdr_test_img(x, y);
  3090. for (uint32_t i = 0; i < 3; i++)
  3091. {
  3092. if (p[i] < 0.0f)
  3093. return false;
  3094. if (p[i] > basist::MAX_HALF_FLOAT)
  3095. return false;
  3096. uint32_t h = basist::float_to_half(p[i]);
  3097. //uint32_t orig_h = h;
  3098. orig_half_img[(x + y * width) * 3 + i] = (uint16_t)h;
  3099. // Rotate sign bit into LSB
  3100. //h = rot_left16((uint16_t)h, 1);
  3101. //assert(rot_right16((uint16_t)h, 1) == orig_h);
  3102. h <<= 1;
  3103. half_img[(x + y * width) * 3 + i] = (uint16_t)h;
  3104. // Determine # of leading zero bits, ignoring the sign bit
  3105. if (h)
  3106. {
  3107. int lz = clz(h) - 16;
  3108. assert(lz >= 0 && lz <= 16);
  3109. assert((h << lz) <= 0xFFFF);
  3110. max_shift = basisu::minimum<int>(max_shift, lz);
  3111. }
  3112. } // i
  3113. } // x
  3114. } // y
  3115. //printf("tonemap_image_compressive: Max leading zeros: %i\n", max_shift);
  3116. uint32_t high_hist[256];
  3117. clear_obj(high_hist);
  3118. for (uint32_t y = 0; y < height; y++)
  3119. {
  3120. for (uint32_t x = 0; x < width; x++)
  3121. {
  3122. for (uint32_t i = 0; i < 3; i++)
  3123. {
  3124. uint16_t& hf = half_img[(x + y * width) * 3 + i];
  3125. assert(((uint32_t)hf << max_shift) <= 65535);
  3126. hf <<= max_shift;
  3127. uint32_t h = (uint8_t)(hf >> 8);
  3128. high_hist[h]++;
  3129. }
  3130. } // x
  3131. } // y
  3132. uint32_t total_vals_used = 0;
  3133. int remap_old_to_new[256];
  3134. for (uint32_t i = 0; i < 256; i++)
  3135. remap_old_to_new[i] = -1;
  3136. for (uint32_t i = 0; i < 256; i++)
  3137. {
  3138. if (high_hist[i] != 0)
  3139. {
  3140. remap_old_to_new[i] = total_vals_used;
  3141. total_vals_used++;
  3142. }
  3143. }
  3144. assert(total_vals_used >= 1);
  3145. //printf("tonemap_image_compressive: Total used high byte values: %u, unused: %u\n", total_vals_used, 256 - total_vals_used);
  3146. bool val_used[256];
  3147. clear_obj(val_used);
  3148. int remap_new_to_old[256];
  3149. for (uint32_t i = 0; i < 256; i++)
  3150. remap_new_to_old[i] = -1;
  3151. BASISU_NOTE_UNUSED(remap_new_to_old);
  3152. int prev_c = -1;
  3153. BASISU_NOTE_UNUSED(prev_c);
  3154. for (uint32_t i = 0; i < 256; i++)
  3155. {
  3156. if (remap_old_to_new[i] >= 0)
  3157. {
  3158. int c;
  3159. if (total_vals_used <= 1)
  3160. c = remap_old_to_new[i];
  3161. else
  3162. {
  3163. c = (remap_old_to_new[i] * 255 + ((total_vals_used - 1) / 2)) / (total_vals_used - 1);
  3164. assert(c > prev_c);
  3165. }
  3166. assert(!val_used[c]);
  3167. remap_new_to_old[c] = i;
  3168. remap_old_to_new[i] = c;
  3169. prev_c = c;
  3170. //printf("%u ", c);
  3171. val_used[c] = true;
  3172. }
  3173. } // i
  3174. //printf("\n");
  3175. dst_img.resize(width, height);
  3176. for (uint32_t y = 0; y < height; y++)
  3177. {
  3178. for (uint32_t x = 0; x < width; x++)
  3179. {
  3180. for (uint32_t c = 0; c < 3; c++)
  3181. {
  3182. uint16_t& v16 = half_img[(x + y * width) * 3 + c];
  3183. uint32_t hb = v16 >> 8;
  3184. //uint32_t lb = v16 & 0xFF;
  3185. assert(remap_old_to_new[hb] != -1);
  3186. assert(remap_old_to_new[hb] <= 255);
  3187. assert(remap_new_to_old[remap_old_to_new[hb]] == (int)hb);
  3188. hb = remap_old_to_new[hb];
  3189. //v16 = (uint16_t)((hb << 8) | lb);
  3190. dst_img(x, y)[c] = (uint8_t)hb;
  3191. }
  3192. } // x
  3193. } // y
  3194. return true;
  3195. }
  3196. bool tonemap_image_compressive2(image& dst_img, const imagef& hdr_test_img)
  3197. {
  3198. const uint32_t width = hdr_test_img.get_width();
  3199. const uint32_t height = hdr_test_img.get_height();
  3200. dst_img.resize(width, height);
  3201. dst_img.set_all(color_rgba(0, 0, 0, 255));
  3202. basisu::vector<basist::half_float> half_img(width * 3 * height);
  3203. uint32_t low_h = UINT32_MAX, high_h = 0;
  3204. for (uint32_t y = 0; y < height; y++)
  3205. {
  3206. for (uint32_t x = 0; x < width; x++)
  3207. {
  3208. const vec4F& p = hdr_test_img(x, y);
  3209. for (uint32_t i = 0; i < 3; i++)
  3210. {
  3211. float f = p[i];
  3212. if (std::isnan(f) || std::isinf(f))
  3213. f = 0.0f;
  3214. else if (f < 0.0f)
  3215. f = 0.0f;
  3216. else if (f > basist::MAX_HALF_FLOAT)
  3217. f = basist::MAX_HALF_FLOAT;
  3218. uint32_t h = basist::float_to_half(f);
  3219. low_h = minimum(low_h, h);
  3220. high_h = maximum(high_h, h);
  3221. half_img[(x + y * width) * 3 + i] = (basist::half_float)h;
  3222. } // i
  3223. } // x
  3224. } // y
  3225. if (low_h == high_h)
  3226. return false;
  3227. for (uint32_t y = 0; y < height; y++)
  3228. {
  3229. for (uint32_t x = 0; x < width; x++)
  3230. {
  3231. for (uint32_t i = 0; i < 3; i++)
  3232. {
  3233. basist::half_float h = half_img[(x + y * width) * 3 + i];
  3234. float f = (float)(h - low_h) / (float)(high_h - low_h);
  3235. int iv = basisu::clamp<int>((int)std::round(f * 255.0f), 0, 255);
  3236. dst_img(x, y)[i] = (uint8_t)iv;
  3237. } // i
  3238. } // x
  3239. } // y
  3240. return true;
  3241. }
  3242. } // namespace basisu