basisu_comp.cpp 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334
  1. // basisu_comp.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_comp.h"
  16. #include "basisu_enc.h"
  17. #include <unordered_set>
  18. #include <atomic>
  19. #include <map>
  20. //#define UASTC_HDR_DEBUG_SAVE_CATEGORIZED_BLOCKS
  21. // basisu_transcoder.cpp is where basisu_miniz lives now, we just need the declarations here.
  22. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  23. #include "basisu_miniz.h"
  24. #include "basisu_opencl.h"
  25. #include "../transcoder/basisu_astc_hdr_core.h"
  26. #if !BASISD_SUPPORT_KTX2
  27. #error BASISD_SUPPORT_KTX2 must be enabled (set to 1).
  28. #endif
  29. #if BASISD_SUPPORT_KTX2_ZSTD
  30. #include <zstd.h>
  31. #endif
  32. // Set to 1 to disable the mipPadding alignment workaround (which only seems to be needed when no key-values are written at all)
  33. #define BASISU_DISABLE_KTX2_ALIGNMENT_WORKAROUND (0)
  34. // Set to 1 to disable writing all KTX2 key values, triggering an early validator bug.
  35. #define BASISU_DISABLE_KTX2_KEY_VALUES (0)
  36. using namespace buminiz;
  37. #define BASISU_USE_STB_IMAGE_RESIZE_FOR_MIPMAP_GEN 0
  38. #define DEBUG_CROP_TEXTURE_TO_64x64 (0)
  39. #define DEBUG_RESIZE_TEXTURE (0)
  40. namespace basisu
  41. {
  42. basis_compressor::basis_compressor() :
  43. m_pOpenCL_context(nullptr),
  44. m_fmt_mode(basist::basis_tex_format::cETC1S),
  45. m_basis_file_size(0),
  46. m_basis_bits_per_texel(0.0f),
  47. m_total_blocks(0),
  48. m_hdr_image_scale(1.0f),
  49. m_ldr_to_hdr_upconversion_nit_multiplier(1.0f),
  50. m_upconverted_any_ldr_images(false),
  51. m_any_source_image_has_alpha(false),
  52. m_opencl_failed(false)
  53. {
  54. debug_printf("basis_compressor::basis_compressor\n");
  55. assert(g_library_initialized);
  56. }
  57. basis_compressor::~basis_compressor()
  58. {
  59. if (m_pOpenCL_context)
  60. {
  61. opencl_destroy_context(m_pOpenCL_context);
  62. m_pOpenCL_context = nullptr;
  63. }
  64. }
  65. void basis_compressor::check_for_hdr_inputs()
  66. {
  67. if ((!m_params.m_source_filenames.size()) && (!m_params.m_source_images.size()))
  68. {
  69. if (m_params.m_source_images_hdr.size())
  70. {
  71. // Assume they want UASTC HDR if they've specified any HDR source images.
  72. m_params.m_hdr = true;
  73. }
  74. }
  75. if (!m_params.m_hdr)
  76. {
  77. // See if any files are .EXR or .HDR, if so switch the compressor to UASTC HDR mode.
  78. for (uint32_t i = 0; i < m_params.m_source_filenames.size(); i++)
  79. {
  80. std::string filename;
  81. string_get_filename(m_params.m_source_filenames[i].c_str(), filename);
  82. std::string ext(string_get_extension(filename));
  83. string_tolower(ext);
  84. if ((ext == "exr") || (ext == "hdr"))
  85. {
  86. m_params.m_hdr = true;
  87. break;
  88. }
  89. }
  90. }
  91. if (m_params.m_hdr)
  92. {
  93. if (m_params.m_source_alpha_filenames.size())
  94. {
  95. debug_printf("Warning: Alpha channel image filenames are not yet supported in UASTC HDR/ASTC HDR modes.\n");
  96. m_params.m_source_alpha_filenames.clear();
  97. }
  98. }
  99. if (m_params.m_hdr)
  100. m_params.m_uastc = true;
  101. }
  102. bool basis_compressor::sanity_check_input_params()
  103. {
  104. // Check for no source filenames specified.
  105. if ((m_params.m_read_source_images) && (!m_params.m_source_filenames.size()))
  106. {
  107. assert(0);
  108. return false;
  109. }
  110. // See if they've specified any source filenames, but didn't tell us to read them.
  111. if ((!m_params.m_read_source_images) && (m_params.m_source_filenames.size()))
  112. {
  113. assert(0);
  114. return false;
  115. }
  116. // Sanity check the input image parameters.
  117. if (m_params.m_read_source_images)
  118. {
  119. // Caller can't specify their own images if they want us to read source images from files.
  120. if (m_params.m_source_images.size() || m_params.m_source_images_hdr.size())
  121. {
  122. assert(0);
  123. return false;
  124. }
  125. if (m_params.m_source_mipmap_images.size() || m_params.m_source_mipmap_images_hdr.size())
  126. {
  127. assert(0);
  128. return false;
  129. }
  130. }
  131. else
  132. {
  133. // They didn't tell us to read any source files, so check for no LDR/HDR source images.
  134. if (!m_params.m_source_images.size() && !m_params.m_source_images_hdr.size())
  135. {
  136. assert(0);
  137. return false;
  138. }
  139. // Now we know we've been supplied LDR and/or HDR source images, check for LDR vs. HDR conflicts.
  140. if (m_params.m_source_images.size())
  141. {
  142. // They've supplied LDR images, so make sure they also haven't specified HDR input images.
  143. if (m_params.m_source_images_hdr.size() || m_params.m_source_mipmap_images_hdr.size())
  144. {
  145. assert(0);
  146. return false;
  147. }
  148. }
  149. else
  150. {
  151. // No LDR images, so make sure they haven't specified any LDR mipmaps.
  152. if (m_params.m_source_mipmap_images.size())
  153. {
  154. assert(0);
  155. return false;
  156. }
  157. // No LDR images, so ensure they've supplied some HDR images to process.
  158. if (!m_params.m_source_images_hdr.size())
  159. {
  160. assert(0);
  161. return false;
  162. }
  163. }
  164. }
  165. return true;
  166. }
  167. bool basis_compressor::init(const basis_compressor_params &params)
  168. {
  169. debug_printf("basis_compressor::init\n");
  170. if (!g_library_initialized)
  171. {
  172. error_printf("basis_compressor::init: basisu_encoder_init() MUST be called before using any encoder functionality!\n");
  173. return false;
  174. }
  175. if (!params.m_pJob_pool)
  176. {
  177. error_printf("basis_compressor::init: A non-null job_pool pointer must be specified\n");
  178. return false;
  179. }
  180. m_params = params;
  181. if ((m_params.m_compute_stats) && (!m_params.m_validate_output_data))
  182. m_params.m_validate_output_data = true;
  183. m_hdr_image_scale = 1.0f;
  184. m_ldr_to_hdr_upconversion_nit_multiplier = 1.0f;
  185. m_upconverted_any_ldr_images = false;
  186. check_for_hdr_inputs();
  187. if (m_params.m_debug)
  188. {
  189. debug_printf("basis_compressor::init:\n");
  190. #define PRINT_BOOL_VALUE(v) fmt_debug_printf("{}: {} {}\n", BASISU_STRINGIZE2(v), static_cast<bool>(m_params.v), m_params.v.was_changed());
  191. #define PRINT_INT_VALUE(v) fmt_debug_printf("{}: {} {}\n", BASISU_STRINGIZE2(v), static_cast<int>(m_params.v), m_params.v.was_changed());
  192. #define PRINT_UINT_VALUE(v) fmt_debug_printf("{}: {} {}\n", BASISU_STRINGIZE2(v), static_cast<uint32_t>(m_params.v), m_params.v.was_changed());
  193. #define PRINT_FLOAT_VALUE(v) fmt_debug_printf("{}: {} {}\n", BASISU_STRINGIZE2(v), static_cast<float>(m_params.v), m_params.v.was_changed());
  194. fmt_debug_printf("Source LDR images: {}, HDR images: {}, filenames: {}, alpha filenames: {}, LDR mipmap images: {}, HDR mipmap images: {}\n",
  195. (uint64_t)m_params.m_source_images.size(), (uint64_t)m_params.m_source_images_hdr.size(),
  196. (uint64_t)m_params.m_source_filenames.size(), (uint64_t)m_params.m_source_alpha_filenames.size(),
  197. (uint64_t)m_params.m_source_mipmap_images.size(), (uint64_t)m_params.m_source_mipmap_images_hdr.size());
  198. if (m_params.m_source_mipmap_images.size())
  199. {
  200. debug_printf("m_source_mipmap_images array sizes:\n");
  201. for (uint32_t i = 0; i < m_params.m_source_mipmap_images.size(); i++)
  202. debug_printf("%u ", m_params.m_source_mipmap_images[i].size());
  203. debug_printf("\n");
  204. }
  205. if (m_params.m_source_mipmap_images_hdr.size())
  206. {
  207. debug_printf("m_source_mipmap_images_hdr array sizes:\n");
  208. for (uint32_t i = 0; i < m_params.m_source_mipmap_images_hdr.size(); i++)
  209. debug_printf("%u ", m_params.m_source_mipmap_images_hdr[i].size());
  210. debug_printf("\n");
  211. }
  212. PRINT_BOOL_VALUE(m_hdr);
  213. switch (m_params.m_hdr_mode)
  214. {
  215. case hdr_modes::cUASTC_HDR_4X4:
  216. {
  217. fmt_debug_printf("m_hdr_mode: cUASTC_HDR_4X4\n");
  218. break;
  219. }
  220. case hdr_modes::cASTC_HDR_6X6:
  221. {
  222. fmt_debug_printf("m_hdr_mode: cASTC_HDR_6X6\n");
  223. break;
  224. }
  225. case hdr_modes::cASTC_HDR_6X6_INTERMEDIATE:
  226. {
  227. fmt_debug_printf("m_hdr_mode: cASTC_HDR_6X6_INTERMEDIATE\n");
  228. break;
  229. }
  230. default:
  231. assert(false);
  232. return false;
  233. }
  234. PRINT_BOOL_VALUE(m_uastc);
  235. PRINT_BOOL_VALUE(m_use_opencl);
  236. PRINT_BOOL_VALUE(m_y_flip);
  237. PRINT_BOOL_VALUE(m_debug);
  238. PRINT_BOOL_VALUE(m_validate_etc1s);
  239. PRINT_BOOL_VALUE(m_debug_images);
  240. PRINT_INT_VALUE(m_compression_level);
  241. PRINT_BOOL_VALUE(m_perceptual);
  242. PRINT_BOOL_VALUE(m_no_endpoint_rdo);
  243. PRINT_BOOL_VALUE(m_no_selector_rdo);
  244. PRINT_BOOL_VALUE(m_read_source_images);
  245. PRINT_BOOL_VALUE(m_write_output_basis_or_ktx2_files);
  246. PRINT_BOOL_VALUE(m_compute_stats);
  247. PRINT_BOOL_VALUE(m_check_for_alpha);
  248. PRINT_BOOL_VALUE(m_force_alpha);
  249. debug_printf("swizzle: %d,%d,%d,%d\n",
  250. m_params.m_swizzle[0],
  251. m_params.m_swizzle[1],
  252. m_params.m_swizzle[2],
  253. m_params.m_swizzle[3]);
  254. PRINT_BOOL_VALUE(m_renormalize);
  255. PRINT_BOOL_VALUE(m_multithreading);
  256. PRINT_BOOL_VALUE(m_disable_hierarchical_endpoint_codebooks);
  257. PRINT_FLOAT_VALUE(m_endpoint_rdo_thresh);
  258. PRINT_FLOAT_VALUE(m_selector_rdo_thresh);
  259. PRINT_BOOL_VALUE(m_mip_gen);
  260. PRINT_BOOL_VALUE(m_mip_renormalize);
  261. PRINT_BOOL_VALUE(m_mip_wrapping);
  262. PRINT_BOOL_VALUE(m_mip_fast);
  263. PRINT_BOOL_VALUE(m_mip_srgb);
  264. PRINT_FLOAT_VALUE(m_mip_premultiplied);
  265. PRINT_FLOAT_VALUE(m_mip_scale);
  266. PRINT_INT_VALUE(m_mip_smallest_dimension);
  267. debug_printf("m_mip_filter: %s\n", m_params.m_mip_filter.c_str());
  268. debug_printf("m_max_endpoint_clusters: %u\n", m_params.m_etc1s_max_endpoint_clusters);
  269. debug_printf("m_max_selector_clusters: %u\n", m_params.m_etc1s_max_selector_clusters);
  270. debug_printf("m_etc1s_quality_level: %i\n", m_params.m_etc1s_quality_level);
  271. debug_printf("UASTC HDR 4x4 quality level: %u\n", m_params.m_uastc_hdr_4x4_options.m_level);
  272. debug_printf("m_tex_type: %u\n", m_params.m_tex_type);
  273. debug_printf("m_userdata0: 0x%X, m_userdata1: 0x%X\n", m_params.m_userdata0, m_params.m_userdata1);
  274. debug_printf("m_us_per_frame: %i (%f fps)\n", m_params.m_us_per_frame, m_params.m_us_per_frame ? 1.0f / (m_params.m_us_per_frame / 1000000.0f) : 0);
  275. debug_printf("m_pack_uastc_ldr_4x4_flags: 0x%X\n", m_params.m_pack_uastc_ldr_4x4_flags);
  276. PRINT_BOOL_VALUE(m_rdo_uastc_ldr_4x4);
  277. PRINT_FLOAT_VALUE(m_rdo_uastc_ldr_4x4_quality_scalar);
  278. PRINT_INT_VALUE(m_rdo_uastc_ldr_4x4_dict_size);
  279. PRINT_FLOAT_VALUE(m_rdo_uastc_ldr_4x4_max_allowed_rms_increase_ratio);
  280. PRINT_FLOAT_VALUE(m_rdo_uastc_ldr_4x4_skip_block_rms_thresh);
  281. PRINT_FLOAT_VALUE(m_rdo_uastc_ldr_4x4_max_smooth_block_error_scale);
  282. PRINT_FLOAT_VALUE(m_rdo_uastc_ldr_4x4_smooth_block_max_std_dev);
  283. PRINT_BOOL_VALUE(m_rdo_uastc_ldr_4x4_favor_simpler_modes_in_rdo_mode)
  284. PRINT_BOOL_VALUE(m_rdo_uastc_ldr_4x4_multithreading);
  285. PRINT_INT_VALUE(m_resample_width);
  286. PRINT_INT_VALUE(m_resample_height);
  287. PRINT_FLOAT_VALUE(m_resample_factor);
  288. debug_printf("Has global codebooks: %u\n", m_params.m_pGlobal_codebooks ? 1 : 0);
  289. if (m_params.m_pGlobal_codebooks)
  290. {
  291. debug_printf("Global codebook endpoints: %u selectors: %u\n", m_params.m_pGlobal_codebooks->get_endpoints().size(), m_params.m_pGlobal_codebooks->get_selectors().size());
  292. }
  293. PRINT_BOOL_VALUE(m_create_ktx2_file);
  294. debug_printf("KTX2 UASTC supercompression: %u\n", m_params.m_ktx2_uastc_supercompression);
  295. debug_printf("KTX2 Zstd supercompression level: %i\n", (int)m_params.m_ktx2_zstd_supercompression_level);
  296. debug_printf("KTX2 sRGB transfer func: %u\n", (int)m_params.m_ktx2_srgb_transfer_func);
  297. debug_printf("Total KTX2 key values: %u\n", m_params.m_ktx2_key_values.size());
  298. for (uint32_t i = 0; i < m_params.m_ktx2_key_values.size(); i++)
  299. {
  300. debug_printf("Key: \"%s\"\n", m_params.m_ktx2_key_values[i].m_key.data());
  301. debug_printf("Value size: %u\n", m_params.m_ktx2_key_values[i].m_value.size());
  302. }
  303. PRINT_BOOL_VALUE(m_validate_output_data);
  304. PRINT_BOOL_VALUE(m_ldr_hdr_upconversion_srgb_to_linear);
  305. PRINT_FLOAT_VALUE(m_ldr_hdr_upconversion_nit_multiplier);
  306. debug_printf("Allow UASTC HDR 4x4 uber mode: %u\n", m_params.m_uastc_hdr_4x4_options.m_allow_uber_mode);
  307. debug_printf("UASTC HDR 4x4 ultra quant: %u\n", m_params.m_uastc_hdr_4x4_options.m_ultra_quant);
  308. PRINT_BOOL_VALUE(m_hdr_favor_astc);
  309. #undef PRINT_BOOL_VALUE
  310. #undef PRINT_INT_VALUE
  311. #undef PRINT_UINT_VALUE
  312. #undef PRINT_FLOAT_VALUE
  313. }
  314. if (!sanity_check_input_params())
  315. return false;
  316. if ((m_params.m_use_opencl) && opencl_is_available() && !m_pOpenCL_context && !m_opencl_failed)
  317. {
  318. m_pOpenCL_context = opencl_create_context();
  319. if (!m_pOpenCL_context)
  320. m_opencl_failed = true;
  321. }
  322. return true;
  323. }
  324. void basis_compressor::pick_format_mode()
  325. {
  326. // Unfortunately due to the legacy of this code and backwards compat this is more complex than I would like.
  327. m_fmt_mode = basist::basis_tex_format::cETC1S;
  328. if (m_params.m_hdr)
  329. {
  330. assert(m_params.m_uastc);
  331. switch (m_params.m_hdr_mode)
  332. {
  333. case hdr_modes::cUASTC_HDR_4X4:
  334. m_fmt_mode = basist::basis_tex_format::cUASTC_HDR_4x4;
  335. break;
  336. case hdr_modes::cASTC_HDR_6X6:
  337. m_fmt_mode = basist::basis_tex_format::cASTC_HDR_6x6;
  338. break;
  339. case hdr_modes::cASTC_HDR_6X6_INTERMEDIATE:
  340. m_fmt_mode = basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE;
  341. break;
  342. default:
  343. assert(0);
  344. break;
  345. }
  346. }
  347. else if (m_params.m_uastc)
  348. {
  349. m_fmt_mode = basist::basis_tex_format::cUASTC4x4;
  350. }
  351. if (m_params.m_debug)
  352. {
  353. switch (m_fmt_mode)
  354. {
  355. case basist::basis_tex_format::cETC1S:
  356. fmt_debug_printf("Format Mode: cETC1S\n");
  357. break;
  358. case basist::basis_tex_format::cUASTC4x4:
  359. fmt_debug_printf("Format Mode: cUASTC4x4\n");
  360. break;
  361. case basist::basis_tex_format::cUASTC_HDR_4x4:
  362. fmt_debug_printf("Format Mode: cUASTC_HDR_4x4\n");
  363. break;
  364. case basist::basis_tex_format::cASTC_HDR_6x6:
  365. fmt_debug_printf("Format Mode: cASTC_HDR_6x6\n");
  366. break;
  367. case basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE:
  368. fmt_debug_printf("Format Mode: cASTC_HDR_6x6_INTERMEDIATE\n");
  369. break;
  370. default:
  371. assert(0);
  372. break;
  373. }
  374. }
  375. }
  376. basis_compressor::error_code basis_compressor::process()
  377. {
  378. debug_printf("basis_compressor::process\n");
  379. if (!read_dds_source_images())
  380. return cECFailedReadingSourceImages;
  381. // Note: After here m_params.m_hdr, m_params.m_uastc and m_fmt_mode cannot be changed.
  382. pick_format_mode();
  383. if (!read_source_images())
  384. return cECFailedReadingSourceImages;
  385. if (!validate_texture_type_constraints())
  386. return cECFailedValidating;
  387. if (m_params.m_create_ktx2_file)
  388. {
  389. if (!validate_ktx2_constraints())
  390. {
  391. error_printf("Inputs do not satisfy .KTX2 texture constraints: all source images must be the same resolution and have the same number of mipmap levels.\n");
  392. return cECFailedValidating;
  393. }
  394. }
  395. if (!extract_source_blocks())
  396. return cECFailedFrontEnd;
  397. if (m_params.m_hdr)
  398. {
  399. if (m_params.m_hdr_mode == hdr_modes::cUASTC_HDR_4X4)
  400. {
  401. // UASTC 4x4 HDR
  402. if (m_params.m_status_output)
  403. printf("Mode: UASTC 4x4 HDR Level %u\n", m_params.m_uastc_hdr_4x4_options.m_level);
  404. error_code ec = encode_slices_to_uastc_4x4_hdr();
  405. if (ec != cECSuccess)
  406. return ec;
  407. }
  408. else
  409. {
  410. assert((m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6) || (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE));
  411. // ASTC 6x6 HDR
  412. if (m_params.m_status_output)
  413. {
  414. fmt_printf("Mode: ASTC 6x6 HDR {}, Base Level: {}, Highest Level: {}, Lambda: {}, REC 2020: {}\n",
  415. (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE) ? "Intermediate" : "",
  416. m_params.m_astc_hdr_6x6_options.m_master_comp_level, m_params.m_astc_hdr_6x6_options.m_highest_comp_level,
  417. m_params.m_astc_hdr_6x6_options.m_lambda, m_params.m_astc_hdr_6x6_options.m_rec2020_bt2100_color_gamut);
  418. }
  419. error_code ec = encode_slices_to_astc_6x6_hdr();
  420. if (ec != cECSuccess)
  421. return ec;
  422. }
  423. }
  424. else if (m_params.m_uastc)
  425. {
  426. // UASTC 4x4 LDR
  427. if (m_params.m_status_output)
  428. printf("Mode: UASTC LDR 4x4 Level %u\n", m_params.m_pack_uastc_ldr_4x4_flags & cPackUASTCLevelMask);
  429. error_code ec = encode_slices_to_uastc_4x4_ldr();
  430. if (ec != cECSuccess)
  431. return ec;
  432. }
  433. else
  434. {
  435. // ETC1S
  436. if (m_params.m_status_output)
  437. printf("Mode: ETC1S Quality %i, Level %i\n", m_params.m_etc1s_quality_level, (int)m_params.m_compression_level);
  438. if (!process_frontend())
  439. return cECFailedFrontEnd;
  440. if (!extract_frontend_texture_data())
  441. return cECFailedFontendExtract;
  442. if (!process_backend())
  443. return cECFailedBackend;
  444. }
  445. if (!create_basis_file_and_transcode())
  446. return cECFailedCreateBasisFile;
  447. if (m_params.m_create_ktx2_file)
  448. {
  449. if (!create_ktx2_file())
  450. return cECFailedCreateKTX2File;
  451. }
  452. if (!write_output_files_and_compute_stats())
  453. return cECFailedWritingOutput;
  454. return cECSuccess;
  455. }
  456. basis_compressor::error_code basis_compressor::encode_slices_to_astc_6x6_hdr()
  457. {
  458. debug_printf("basis_compressor::encode_slices_to_astc_6x6_hdr\n");
  459. interval_timer tm;
  460. tm.start();
  461. m_uastc_slice_textures.resize(m_slice_descs.size());
  462. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  463. m_uastc_slice_textures[slice_index].init(texture_format::cASTC_HDR_6x6, m_slice_descs[slice_index].m_orig_width, m_slice_descs[slice_index].m_orig_height);
  464. if (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6)
  465. m_uastc_backend_output.m_tex_format = basist::basis_tex_format::cASTC_HDR_6x6;
  466. else if (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE)
  467. m_uastc_backend_output.m_tex_format = basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE;
  468. else
  469. {
  470. assert(0);
  471. return cECFailedEncodeUASTC;
  472. }
  473. m_uastc_backend_output.m_etc1s = false;
  474. m_uastc_backend_output.m_srgb = false;
  475. m_uastc_backend_output.m_slice_desc = m_slice_descs;
  476. m_uastc_backend_output.m_slice_image_data.resize(m_slice_descs.size());
  477. m_uastc_backend_output.m_slice_image_crcs.resize(m_slice_descs.size());
  478. astc_6x6_hdr::astc_hdr_6x6_global_config global_cfg(m_params.m_astc_hdr_6x6_options);
  479. global_cfg.m_image_stats = m_params.m_compute_stats;
  480. global_cfg.m_debug_images = m_params.m_debug_images;
  481. global_cfg.m_output_images = m_params.m_debug_images;
  482. global_cfg.m_debug_output = m_params.m_debug;
  483. global_cfg.m_status_output = m_params.m_status_output || m_params.m_debug;
  484. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  485. {
  486. gpu_image& dst_tex = m_uastc_slice_textures[slice_index];
  487. uint8_vec &dst_buf = m_uastc_backend_output.m_slice_image_data[slice_index];
  488. basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  489. (void)slice_desc;
  490. const imagef& source_image = m_slice_images_hdr[slice_index];
  491. assert(source_image.get_width() && source_image.get_height());
  492. uint8_vec intermediate_tex_data, astc_tex_data;
  493. global_cfg.m_debug_image_prefix = m_params.m_astc_hdr_6x6_options.m_debug_image_prefix;
  494. global_cfg.m_debug_image_prefix += fmt_string("slice_{}_", slice_index);
  495. global_cfg.m_output_image_prefix = m_params.m_astc_hdr_6x6_options.m_output_image_prefix;
  496. global_cfg.m_output_image_prefix += fmt_string("slice_{}_", slice_index);
  497. if (m_params.m_debug)
  498. fmt_debug_printf("----------------------------------------------------------------------------\n");
  499. astc_6x6_hdr::result_metrics metrics;
  500. bool status = astc_6x6_hdr::compress_photo(source_image, global_cfg, m_params.m_pJob_pool, intermediate_tex_data, astc_tex_data, metrics);
  501. if (!status)
  502. return cECFailedEncodeUASTC;
  503. if (m_params.m_debug)
  504. fmt_debug_printf("----------------------------------------------------------------------------\n");
  505. // Currently it always gives us both intermediate and RDO
  506. assert(intermediate_tex_data.size());
  507. assert(astc_tex_data.size());
  508. assert((astc_tex_data.size() & 15) == 0);
  509. assert(dst_tex.get_size_in_bytes() == astc_tex_data.size_in_bytes());
  510. memcpy(dst_tex.get_ptr(), astc_tex_data.data(), astc_tex_data.size_in_bytes());
  511. if (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6)
  512. {
  513. dst_buf.resize(dst_tex.get_size_in_bytes());
  514. memcpy(&dst_buf[0], dst_tex.get_ptr(), dst_tex.get_size_in_bytes());
  515. }
  516. else
  517. {
  518. assert(m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE);
  519. dst_buf.resize(intermediate_tex_data.size_in_bytes());
  520. memcpy(&dst_buf[0], intermediate_tex_data.get_ptr(), intermediate_tex_data.size_in_bytes());
  521. }
  522. m_uastc_backend_output.m_slice_image_crcs[slice_index] = basist::crc16(dst_buf.get_ptr(), dst_buf.size_in_bytes(), 0);
  523. }
  524. return cECSuccess;
  525. }
  526. basis_compressor::error_code basis_compressor::encode_slices_to_uastc_4x4_hdr()
  527. {
  528. debug_printf("basis_compressor::encode_slices_to_uastc_4x4_hdr\n");
  529. interval_timer tm;
  530. tm.start();
  531. m_uastc_slice_textures.resize(m_slice_descs.size());
  532. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  533. m_uastc_slice_textures[slice_index].init(texture_format::cUASTC_HDR_4x4, m_slice_descs[slice_index].m_orig_width, m_slice_descs[slice_index].m_orig_height);
  534. m_uastc_backend_output.m_tex_format = basist::basis_tex_format::cUASTC_HDR_4x4;
  535. m_uastc_backend_output.m_etc1s = false;
  536. m_uastc_backend_output.m_srgb = false;
  537. m_uastc_backend_output.m_slice_desc = m_slice_descs;
  538. m_uastc_backend_output.m_slice_image_data.resize(m_slice_descs.size());
  539. m_uastc_backend_output.m_slice_image_crcs.resize(m_slice_descs.size());
  540. if (!m_params.m_perceptual)
  541. {
  542. m_params.m_uastc_hdr_4x4_options.m_r_err_scale = 1.0f;
  543. m_params.m_uastc_hdr_4x4_options.m_g_err_scale = 1.0f;
  544. }
  545. const float DEFAULT_BC6H_ERROR_WEIGHT = .65f;// .85f;
  546. const float LOWEST_BC6H_ERROR_WEIGHT = .1f;
  547. m_params.m_uastc_hdr_4x4_options.m_bc6h_err_weight = m_params.m_hdr_favor_astc ? LOWEST_BC6H_ERROR_WEIGHT : DEFAULT_BC6H_ERROR_WEIGHT;
  548. std::atomic<bool> any_failures;
  549. any_failures.store(false);
  550. astc_hdr_4x4_block_stats enc_stats;
  551. struct uastc_blk_desc
  552. {
  553. uint32_t m_solid_flag;
  554. uint32_t m_num_partitions;
  555. uint32_t m_cem_index;
  556. uint32_t m_weight_ise_range;
  557. uint32_t m_endpoint_ise_range;
  558. bool operator< (const uastc_blk_desc& desc) const
  559. {
  560. if (this == &desc)
  561. return false;
  562. #define COMP(XX) if (XX < desc.XX) return true; else if (XX != desc.XX) return false;
  563. COMP(m_solid_flag)
  564. COMP(m_num_partitions)
  565. COMP(m_cem_index)
  566. COMP(m_weight_ise_range)
  567. COMP(m_endpoint_ise_range)
  568. #undef COMP
  569. return false;
  570. }
  571. bool operator== (const uastc_blk_desc& desc) const
  572. {
  573. if (this == &desc)
  574. return true;
  575. if ((*this < desc) || (desc < *this))
  576. return false;
  577. return true;
  578. }
  579. bool operator!= (const uastc_blk_desc& desc) const
  580. {
  581. return !(*this == desc);
  582. }
  583. };
  584. struct uastc_blk_desc_stats
  585. {
  586. uastc_blk_desc_stats() : m_count(0) { }
  587. uint32_t m_count;
  588. #ifdef UASTC_HDR_DEBUG_SAVE_CATEGORIZED_BLOCKS
  589. basisu::vector<basist::astc_blk> m_blks;
  590. #endif
  591. };
  592. std::map<uastc_blk_desc, uastc_blk_desc_stats> unique_block_descs;
  593. std::mutex unique_block_desc_mutex;
  594. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  595. {
  596. gpu_image& tex = m_uastc_slice_textures[slice_index];
  597. basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  598. (void)slice_desc;
  599. const uint32_t num_blocks_x = tex.get_blocks_x();
  600. const uint32_t num_blocks_y = tex.get_blocks_y();
  601. const uint32_t total_blocks = tex.get_total_blocks();
  602. const imagef& source_image = m_slice_images_hdr[slice_index];
  603. std::atomic<uint32_t> total_blocks_processed;
  604. total_blocks_processed.store(0);
  605. const uint32_t N = 256;
  606. for (uint32_t block_index_iter = 0; block_index_iter < total_blocks; block_index_iter += N)
  607. {
  608. const uint32_t first_index = block_index_iter;
  609. const uint32_t last_index = minimum<uint32_t>(total_blocks, block_index_iter + N);
  610. m_params.m_pJob_pool->add_job([this, first_index, last_index, num_blocks_x, num_blocks_y, total_blocks, &source_image,
  611. &tex, &total_blocks_processed, &any_failures, &enc_stats, &unique_block_descs, &unique_block_desc_mutex]
  612. {
  613. BASISU_NOTE_UNUSED(num_blocks_y);
  614. basisu::vector<astc_hdr_4x4_pack_results> all_results;
  615. all_results.reserve(256);
  616. for (uint32_t block_index = first_index; block_index < last_index; block_index++)
  617. {
  618. const uint32_t block_x = block_index % num_blocks_x;
  619. const uint32_t block_y = block_index / num_blocks_x;
  620. //if ((block_x == 176) && (block_y == 128))
  621. // printf("!");
  622. vec4F block_pixels[16];
  623. source_image.extract_block_clamped(&block_pixels[0], block_x * 4, block_y * 4, 4, 4);
  624. basist::astc_blk& dest_block = *(basist::astc_blk*)tex.get_block_ptr(block_x, block_y);
  625. float rgb_pixels[16 * 3];
  626. basist::half_float rgb_pixels_half[16 * 3];
  627. for (uint32_t i = 0; i < 16; i++)
  628. {
  629. rgb_pixels[i * 3 + 0] = block_pixels[i][0];
  630. rgb_pixels_half[i * 3 + 0] = float_to_half_non_neg_no_nan_inf(block_pixels[i][0]);
  631. rgb_pixels[i * 3 + 1] = block_pixels[i][1];
  632. rgb_pixels_half[i * 3 + 1] = float_to_half_non_neg_no_nan_inf(block_pixels[i][1]);
  633. rgb_pixels[i * 3 + 2] = block_pixels[i][2];
  634. rgb_pixels_half[i * 3 + 2] = float_to_half_non_neg_no_nan_inf(block_pixels[i][2]);
  635. }
  636. bool status = astc_hdr_4x4_enc_block(&rgb_pixels[0], rgb_pixels_half, m_params.m_uastc_hdr_4x4_options, all_results);
  637. if (!status)
  638. {
  639. any_failures.store(true);
  640. continue;
  641. }
  642. double best_err = 1e+30f;
  643. int best_result_index = -1;
  644. const double bc6h_err_weight = m_params.m_uastc_hdr_4x4_options.m_bc6h_err_weight;
  645. const double astc_err_weight = (1.0f - bc6h_err_weight);
  646. for (uint32_t i = 0; i < all_results.size(); i++)
  647. {
  648. basist::half_float unpacked_bc6h_block[4 * 4 * 3];
  649. unpack_bc6h(&all_results[i].m_bc6h_block, unpacked_bc6h_block, false);
  650. all_results[i].m_bc6h_block_error = compute_block_error(16, rgb_pixels_half, unpacked_bc6h_block, m_params.m_uastc_hdr_4x4_options);
  651. double overall_err = (all_results[i].m_bc6h_block_error * bc6h_err_weight) + (all_results[i].m_best_block_error * astc_err_weight);
  652. if ((!i) || (overall_err < best_err))
  653. {
  654. best_err = overall_err;
  655. best_result_index = i;
  656. }
  657. }
  658. const astc_hdr_4x4_pack_results& best_results = all_results[best_result_index];
  659. astc_hdr_4x4_pack_results_to_block(dest_block, best_results);
  660. // Verify that this block is valid UASTC HDR and we can successfully transcode it to BC6H.
  661. // (Well, except in fastest mode.)
  662. if (m_params.m_uastc_hdr_4x4_options.m_level > 0)
  663. {
  664. basist::bc6h_block transcoded_bc6h_blk;
  665. bool transcode_results = astc_hdr_transcode_to_bc6h(dest_block, transcoded_bc6h_blk);
  666. assert(transcode_results);
  667. if ((!transcode_results) && (!any_failures))
  668. {
  669. error_printf("basis_compressor::encode_slices_to_uastc_4x4_hdr: UASTC HDR block transcode check failed!\n");
  670. any_failures.store(true);
  671. continue;
  672. }
  673. }
  674. if (m_params.m_debug)
  675. {
  676. // enc_stats has its own mutex
  677. enc_stats.update(best_results);
  678. uastc_blk_desc blk_desc;
  679. clear_obj(blk_desc);
  680. blk_desc.m_solid_flag = best_results.m_is_solid;
  681. if (!blk_desc.m_solid_flag)
  682. {
  683. blk_desc.m_num_partitions = best_results.m_best_blk.m_num_partitions;
  684. blk_desc.m_cem_index = best_results.m_best_blk.m_color_endpoint_modes[0];
  685. blk_desc.m_weight_ise_range = best_results.m_best_blk.m_weight_ise_range;
  686. blk_desc.m_endpoint_ise_range = best_results.m_best_blk.m_endpoint_ise_range;
  687. }
  688. {
  689. std::lock_guard<std::mutex> lck(unique_block_desc_mutex);
  690. auto res = unique_block_descs.insert(std::make_pair(blk_desc, uastc_blk_desc_stats()));
  691. (res.first)->second.m_count++;
  692. #ifdef UASTC_HDR_DEBUG_SAVE_CATEGORIZED_BLOCKS
  693. (res.first)->second.m_blks.push_back(dest_block);
  694. #endif
  695. }
  696. }
  697. total_blocks_processed++;
  698. uint32_t val = total_blocks_processed;
  699. if (((val & 1023) == 1023) && m_params.m_status_output)
  700. {
  701. debug_printf("basis_compressor::encode_slices_to_uastc_4x4_hdr: %3.1f%% done\n", static_cast<float>(val) * 100.0f / total_blocks);
  702. }
  703. }
  704. });
  705. } // block_index_iter
  706. m_params.m_pJob_pool->wait_for_all();
  707. if (any_failures)
  708. return cECFailedEncodeUASTC;
  709. m_uastc_backend_output.m_slice_image_data[slice_index].resize(tex.get_size_in_bytes());
  710. memcpy(&m_uastc_backend_output.m_slice_image_data[slice_index][0], tex.get_ptr(), tex.get_size_in_bytes());
  711. m_uastc_backend_output.m_slice_image_crcs[slice_index] = basist::crc16(tex.get_ptr(), tex.get_size_in_bytes(), 0);
  712. } // slice_index
  713. debug_printf("basis_compressor::encode_slices_to_uastc_4x4_hdr: Total time: %3.3f secs\n", tm.get_elapsed_secs());
  714. if (m_params.m_debug)
  715. {
  716. debug_printf("\n----- Total unique UASTC block descs: %u\n", (uint32_t)unique_block_descs.size());
  717. uint32_t c = 0;
  718. for (auto it = unique_block_descs.begin(); it != unique_block_descs.end(); ++it)
  719. {
  720. debug_printf("%u. Total uses: %u %3.2f%%, solid color: %u\n", c, it->second.m_count,
  721. ((float)it->second.m_count * 100.0f) / enc_stats.m_total_blocks, it->first.m_solid_flag);
  722. if (!it->first.m_solid_flag)
  723. {
  724. debug_printf(" Num partitions: %u\n", it->first.m_num_partitions);
  725. debug_printf(" CEM index: %u\n", it->first.m_cem_index);
  726. debug_printf(" Weight ISE range: %u (%u levels)\n", it->first.m_weight_ise_range, astc_helpers::get_ise_levels(it->first.m_weight_ise_range));
  727. debug_printf(" Endpoint ISE range: %u (%u levels)\n", it->first.m_endpoint_ise_range, astc_helpers::get_ise_levels(it->first.m_endpoint_ise_range));
  728. }
  729. #ifdef UASTC_HDR_DEBUG_SAVE_CATEGORIZED_BLOCKS
  730. debug_printf(" -- UASTC HDR block bytes:\n");
  731. for (uint32_t j = 0; j < minimum<uint32_t>(4, it->second.m_blks.size()); j++)
  732. {
  733. basist::astc_blk& blk = it->second.m_blks[j];
  734. debug_printf(" - UASTC HDR: { ");
  735. for (uint32_t k = 0; k < 16; k++)
  736. debug_printf("%u%s", ((const uint8_t*)&blk)[k], (k != 15) ? ", " : "");
  737. debug_printf(" }\n");
  738. basist::bc6h_block bc6h_blk;
  739. bool res = astc_hdr_transcode_to_bc6h(blk, bc6h_blk);
  740. assert(res);
  741. if (!res)
  742. {
  743. error_printf("astc_hdr_transcode_to_bc6h() failed!\n");
  744. return cECFailedEncodeUASTC;
  745. }
  746. debug_printf(" - BC6H: { ");
  747. for (uint32_t k = 0; k < 16; k++)
  748. debug_printf("%u%s", ((const uint8_t*)&bc6h_blk)[k], (k != 15) ? ", " : "");
  749. debug_printf(" }\n");
  750. }
  751. #endif
  752. c++;
  753. }
  754. printf("\n");
  755. enc_stats.print();
  756. }
  757. return cECSuccess;
  758. }
  759. basis_compressor::error_code basis_compressor::encode_slices_to_uastc_4x4_ldr()
  760. {
  761. debug_printf("basis_compressor::encode_slices_to_uastc_4x4_ldr\n");
  762. m_uastc_slice_textures.resize(m_slice_descs.size());
  763. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  764. m_uastc_slice_textures[slice_index].init(texture_format::cUASTC4x4, m_slice_descs[slice_index].m_orig_width, m_slice_descs[slice_index].m_orig_height);
  765. m_uastc_backend_output.m_tex_format = basist::basis_tex_format::cUASTC4x4;
  766. m_uastc_backend_output.m_etc1s = false;
  767. m_uastc_backend_output.m_slice_desc = m_slice_descs;
  768. m_uastc_backend_output.m_slice_image_data.resize(m_slice_descs.size());
  769. m_uastc_backend_output.m_slice_image_crcs.resize(m_slice_descs.size());
  770. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  771. {
  772. gpu_image& tex = m_uastc_slice_textures[slice_index];
  773. basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  774. (void)slice_desc;
  775. const uint32_t num_blocks_x = tex.get_blocks_x();
  776. const uint32_t num_blocks_y = tex.get_blocks_y();
  777. const uint32_t total_blocks = tex.get_total_blocks();
  778. const image& source_image = m_slice_images[slice_index];
  779. std::atomic<uint32_t> total_blocks_processed;
  780. total_blocks_processed.store(0);
  781. const uint32_t N = 256;
  782. for (uint32_t block_index_iter = 0; block_index_iter < total_blocks; block_index_iter += N)
  783. {
  784. const uint32_t first_index = block_index_iter;
  785. const uint32_t last_index = minimum<uint32_t>(total_blocks, block_index_iter + N);
  786. m_params.m_pJob_pool->add_job([this, first_index, last_index, num_blocks_x, num_blocks_y, total_blocks, &source_image, &tex, &total_blocks_processed]
  787. {
  788. BASISU_NOTE_UNUSED(num_blocks_y);
  789. uint32_t uastc_flags = m_params.m_pack_uastc_ldr_4x4_flags;
  790. if ((m_params.m_rdo_uastc_ldr_4x4) && (m_params.m_rdo_uastc_ldr_4x4_favor_simpler_modes_in_rdo_mode))
  791. uastc_flags |= cPackUASTCFavorSimplerModes;
  792. for (uint32_t block_index = first_index; block_index < last_index; block_index++)
  793. {
  794. const uint32_t block_x = block_index % num_blocks_x;
  795. const uint32_t block_y = block_index / num_blocks_x;
  796. color_rgba block_pixels[4][4];
  797. source_image.extract_block_clamped((color_rgba*)block_pixels, block_x * 4, block_y * 4, 4, 4);
  798. basist::uastc_block& dest_block = *(basist::uastc_block*)tex.get_block_ptr(block_x, block_y);
  799. encode_uastc(&block_pixels[0][0].r, dest_block, uastc_flags);
  800. total_blocks_processed++;
  801. uint32_t val = total_blocks_processed;
  802. if (((val & 16383) == 16383) && m_params.m_status_output)
  803. {
  804. debug_printf("basis_compressor::encode_slices_to_uastc_4x4_ldr: %3.1f%% done\n", static_cast<float>(val) * 100.0f / total_blocks);
  805. }
  806. }
  807. });
  808. } // block_index_iter
  809. m_params.m_pJob_pool->wait_for_all();
  810. if (m_params.m_rdo_uastc_ldr_4x4)
  811. {
  812. uastc_rdo_params rdo_params;
  813. rdo_params.m_lambda = m_params.m_rdo_uastc_ldr_4x4_quality_scalar;
  814. rdo_params.m_max_allowed_rms_increase_ratio = m_params.m_rdo_uastc_ldr_4x4_max_allowed_rms_increase_ratio;
  815. rdo_params.m_skip_block_rms_thresh = m_params.m_rdo_uastc_ldr_4x4_skip_block_rms_thresh;
  816. rdo_params.m_lz_dict_size = m_params.m_rdo_uastc_ldr_4x4_dict_size;
  817. rdo_params.m_smooth_block_max_error_scale = m_params.m_rdo_uastc_ldr_4x4_max_smooth_block_error_scale;
  818. rdo_params.m_max_smooth_block_std_dev = m_params.m_rdo_uastc_ldr_4x4_smooth_block_max_std_dev;
  819. bool status = uastc_rdo(tex.get_total_blocks(), (basist::uastc_block*)tex.get_ptr(),
  820. (const color_rgba *)m_source_blocks[slice_desc.m_first_block_index].m_pixels, rdo_params, m_params.m_pack_uastc_ldr_4x4_flags, m_params.m_rdo_uastc_ldr_4x4_multithreading ? m_params.m_pJob_pool : nullptr,
  821. (m_params.m_rdo_uastc_ldr_4x4_multithreading && m_params.m_pJob_pool) ? basisu::minimum<uint32_t>(4, (uint32_t)m_params.m_pJob_pool->get_total_threads()) : 0);
  822. if (!status)
  823. {
  824. return cECFailedUASTCRDOPostProcess;
  825. }
  826. }
  827. m_uastc_backend_output.m_slice_image_data[slice_index].resize(tex.get_size_in_bytes());
  828. memcpy(&m_uastc_backend_output.m_slice_image_data[slice_index][0], tex.get_ptr(), tex.get_size_in_bytes());
  829. m_uastc_backend_output.m_slice_image_crcs[slice_index] = basist::crc16(tex.get_ptr(), tex.get_size_in_bytes(), 0);
  830. } // slice_index
  831. return cECSuccess;
  832. }
  833. bool basis_compressor::generate_mipmaps(const imagef& img, basisu::vector<imagef>& mips, bool has_alpha)
  834. {
  835. debug_printf("basis_compressor::generate_mipmaps\n");
  836. interval_timer tm;
  837. tm.start();
  838. uint32_t total_levels = 1;
  839. uint32_t w = img.get_width(), h = img.get_height();
  840. while (maximum<uint32_t>(w, h) > (uint32_t)m_params.m_mip_smallest_dimension)
  841. {
  842. w = maximum(w >> 1U, 1U);
  843. h = maximum(h >> 1U, 1U);
  844. total_levels++;
  845. }
  846. for (uint32_t level = 1; level < total_levels; level++)
  847. {
  848. const uint32_t level_width = maximum<uint32_t>(1, img.get_width() >> level);
  849. const uint32_t level_height = maximum<uint32_t>(1, img.get_height() >> level);
  850. imagef& level_img = *enlarge_vector(mips, 1);
  851. level_img.resize(level_width, level_height);
  852. const imagef* pSource_image = &img;
  853. if (m_params.m_mip_fast)
  854. {
  855. if (level > 1)
  856. pSource_image = &mips[level - 1];
  857. }
  858. bool status = image_resample(*pSource_image, level_img,
  859. //m_params.m_mip_filter.c_str(),
  860. "box", // TODO: negative lobes in the filter are causing negative colors, try Mitchell
  861. m_params.m_mip_scale, m_params.m_mip_wrapping, 0, has_alpha ? 4 : 3);
  862. if (!status)
  863. {
  864. error_printf("basis_compressor::generate_mipmaps: image_resample() failed!\n");
  865. return false;
  866. }
  867. clean_hdr_image(level_img);
  868. }
  869. if (m_params.m_debug)
  870. debug_printf("Total mipmap generation time: %3.3f secs\n", tm.get_elapsed_secs());
  871. return true;
  872. }
  873. bool basis_compressor::generate_mipmaps(const image &img, basisu::vector<image> &mips, bool has_alpha)
  874. {
  875. debug_printf("basis_compressor::generate_mipmaps\n");
  876. interval_timer tm;
  877. tm.start();
  878. uint32_t total_levels = 1;
  879. uint32_t w = img.get_width(), h = img.get_height();
  880. while (maximum<uint32_t>(w, h) > (uint32_t)m_params.m_mip_smallest_dimension)
  881. {
  882. w = maximum(w >> 1U, 1U);
  883. h = maximum(h >> 1U, 1U);
  884. total_levels++;
  885. }
  886. #if BASISU_USE_STB_IMAGE_RESIZE_FOR_MIPMAP_GEN
  887. // Requires stb_image_resize
  888. stbir_filter filter = STBIR_FILTER_DEFAULT;
  889. if (m_params.m_mip_filter == "box")
  890. filter = STBIR_FILTER_BOX;
  891. else if (m_params.m_mip_filter == "triangle")
  892. filter = STBIR_FILTER_TRIANGLE;
  893. else if (m_params.m_mip_filter == "cubic")
  894. filter = STBIR_FILTER_CUBICBSPLINE;
  895. else if (m_params.m_mip_filter == "catmull")
  896. filter = STBIR_FILTER_CATMULLROM;
  897. else if (m_params.m_mip_filter == "mitchell")
  898. filter = STBIR_FILTER_MITCHELL;
  899. for (uint32_t level = 1; level < total_levels; level++)
  900. {
  901. const uint32_t level_width = maximum<uint32_t>(1, img.get_width() >> level);
  902. const uint32_t level_height = maximum<uint32_t>(1, img.get_height() >> level);
  903. image &level_img = *enlarge_vector(mips, 1);
  904. level_img.resize(level_width, level_height);
  905. int result = stbir_resize_uint8_generic(
  906. (const uint8_t *)img.get_ptr(), img.get_width(), img.get_height(), img.get_pitch() * sizeof(color_rgba),
  907. (uint8_t *)level_img.get_ptr(), level_img.get_width(), level_img.get_height(), level_img.get_pitch() * sizeof(color_rgba),
  908. has_alpha ? 4 : 3, has_alpha ? 3 : STBIR_ALPHA_CHANNEL_NONE, m_params.m_mip_premultiplied ? STBIR_FLAG_ALPHA_PREMULTIPLIED : 0,
  909. m_params.m_mip_wrapping ? STBIR_EDGE_WRAP : STBIR_EDGE_CLAMP, filter, m_params.m_mip_srgb ? STBIR_COLORSPACE_SRGB : STBIR_COLORSPACE_LINEAR,
  910. nullptr);
  911. if (result == 0)
  912. {
  913. error_printf("basis_compressor::generate_mipmaps: stbir_resize_uint8_generic() failed!\n");
  914. return false;
  915. }
  916. if (m_params.m_mip_renormalize)
  917. level_img.renormalize_normal_map();
  918. }
  919. #else
  920. for (uint32_t level = 1; level < total_levels; level++)
  921. {
  922. const uint32_t level_width = maximum<uint32_t>(1, img.get_width() >> level);
  923. const uint32_t level_height = maximum<uint32_t>(1, img.get_height() >> level);
  924. image& level_img = *enlarge_vector(mips, 1);
  925. level_img.resize(level_width, level_height);
  926. const image* pSource_image = &img;
  927. if (m_params.m_mip_fast)
  928. {
  929. if (level > 1)
  930. pSource_image = &mips[level - 1];
  931. }
  932. bool status = image_resample(*pSource_image, level_img, m_params.m_mip_srgb, m_params.m_mip_filter.c_str(), m_params.m_mip_scale, m_params.m_mip_wrapping, 0, has_alpha ? 4 : 3);
  933. if (!status)
  934. {
  935. error_printf("basis_compressor::generate_mipmaps: image_resample() failed!\n");
  936. return false;
  937. }
  938. if (m_params.m_mip_renormalize)
  939. level_img.renormalize_normal_map();
  940. }
  941. #endif
  942. if (m_params.m_debug)
  943. debug_printf("Total mipmap generation time: %3.3f secs\n", tm.get_elapsed_secs());
  944. return true;
  945. }
  946. void basis_compressor::clean_hdr_image(imagef& src_img)
  947. {
  948. const uint32_t width = src_img.get_width();
  949. const uint32_t height = src_img.get_height();
  950. float max_used_val = 0.0f;
  951. for (uint32_t y = 0; y < height; y++)
  952. {
  953. for (uint32_t x = 0; x < width; x++)
  954. {
  955. vec4F& c = src_img(x, y);
  956. for (uint32_t i = 0; i < 3; i++)
  957. max_used_val = maximum(max_used_val, c[i]);
  958. }
  959. }
  960. double hdr_image_scale = 1.0f;
  961. if (max_used_val > basist::ASTC_HDR_MAX_VAL)
  962. {
  963. hdr_image_scale = max_used_val / basist::ASTC_HDR_MAX_VAL;
  964. const double inv_hdr_image_scale = basist::ASTC_HDR_MAX_VAL / max_used_val;
  965. for (uint32_t y = 0; y < src_img.get_height(); y++)
  966. {
  967. for (uint32_t x = 0; x < src_img.get_width(); x++)
  968. {
  969. vec4F& c = src_img(x, y);
  970. for (uint32_t i = 0; i < 3; i++)
  971. c[i] = (float)minimum<double>(c[i] * inv_hdr_image_scale, basist::ASTC_HDR_MAX_VAL);
  972. }
  973. }
  974. printf("Warning: The input HDR image's maximum used float value was %f, which is too high to encode as ASTC HDR. The image's components have been linearly scaled so the maximum used value is %f, by multiplying by %f.\n",
  975. max_used_val, basist::ASTC_HDR_MAX_VAL, inv_hdr_image_scale);
  976. printf("The decoded ASTC HDR texture will have to be scaled up by %f.\n", hdr_image_scale);
  977. }
  978. // TODO: Determine a constant scale factor, apply if > MAX_HALF_FLOAT
  979. if (!src_img.clean_astc_hdr_pixels(basist::ASTC_HDR_MAX_VAL))
  980. printf("Warning: clean_astc_hdr_pixels() had to modify the input image to encode to ASTC HDR - see previous warning(s).\n");
  981. m_hdr_image_scale = (float)hdr_image_scale;
  982. float lowest_nonzero_val = 1e+30f;
  983. float lowest_val = 1e+30f;
  984. float highest_val = -1e+30f;
  985. for (uint32_t y = 0; y < src_img.get_height(); y++)
  986. {
  987. for (uint32_t x = 0; x < src_img.get_width(); x++)
  988. {
  989. const vec4F& c = src_img(x, y);
  990. for (uint32_t i = 0; i < 3; i++)
  991. {
  992. lowest_val = basisu::minimum(lowest_val, c[i]);
  993. if (c[i] != 0.0f)
  994. lowest_nonzero_val = basisu::minimum(lowest_nonzero_val, c[i]);
  995. highest_val = basisu::maximum(highest_val, c[i]);
  996. }
  997. }
  998. }
  999. debug_printf("Lowest image value: %e, lowest non-zero value: %e, highest value: %e, dynamic range: %e\n", lowest_val, lowest_nonzero_val, highest_val, highest_val / lowest_nonzero_val);
  1000. }
  1001. bool basis_compressor::read_dds_source_images()
  1002. {
  1003. debug_printf("basis_compressor::read_dds_source_images\n");
  1004. // Nothing to do if the caller doesn't want us reading source images.
  1005. if ((!m_params.m_read_source_images) || (!m_params.m_source_filenames.size()))
  1006. return true;
  1007. // Just bail of the caller has specified their own source images.
  1008. if (m_params.m_source_images.size() || m_params.m_source_images_hdr.size())
  1009. return true;
  1010. if (m_params.m_source_mipmap_images.size() || m_params.m_source_mipmap_images_hdr.size())
  1011. return true;
  1012. // See if any input filenames are .DDS
  1013. bool any_dds = false, all_dds = true;
  1014. for (uint32_t i = 0; i < m_params.m_source_filenames.size(); i++)
  1015. {
  1016. std::string ext(string_get_extension(m_params.m_source_filenames[i]));
  1017. if (strcasecmp(ext.c_str(), "dds") == 0)
  1018. any_dds = true;
  1019. else
  1020. all_dds = false;
  1021. }
  1022. // Bail if no .DDS files specified.
  1023. if (!any_dds)
  1024. return true;
  1025. // If any input is .DDS they all must be .DDS, for simplicity.
  1026. if (!all_dds)
  1027. {
  1028. error_printf("If any filename is DDS, all filenames must be DDS.\n");
  1029. return false;
  1030. }
  1031. // Can't jam in alpha channel images if any .DDS files specified.
  1032. if (m_params.m_source_alpha_filenames.size())
  1033. {
  1034. error_printf("Source alpha filenames are not supported in DDS mode.\n");
  1035. return false;
  1036. }
  1037. bool any_mipmaps = false;
  1038. // Read each .DDS texture file
  1039. for (uint32_t i = 0; i < m_params.m_source_filenames.size(); i++)
  1040. {
  1041. basisu::vector<image> ldr_mips;
  1042. basisu::vector<imagef> hdr_mips;
  1043. bool status = read_uncompressed_dds_file(m_params.m_source_filenames[i].c_str(), ldr_mips, hdr_mips);
  1044. if (!status)
  1045. return false;
  1046. assert(ldr_mips.size() || hdr_mips.size());
  1047. if (m_params.m_status_output)
  1048. {
  1049. printf("Read DDS file \"%s\", %s, %ux%u, %zu mipmap levels\n",
  1050. m_params.m_source_filenames[i].c_str(),
  1051. ldr_mips.size() ? "LDR" : "HDR",
  1052. ldr_mips.size() ? ldr_mips[0].get_width() : hdr_mips[0].get_width(),
  1053. ldr_mips.size() ? ldr_mips[0].get_height() : hdr_mips[0].get_height(),
  1054. ldr_mips.size() ? ldr_mips.size() : hdr_mips.size());
  1055. }
  1056. if (ldr_mips.size())
  1057. {
  1058. if (m_params.m_source_images_hdr.size())
  1059. {
  1060. error_printf("All DDS files must be of the same type (all LDR, or all HDR)\n");
  1061. return false;
  1062. }
  1063. m_params.m_source_images.push_back(ldr_mips[0]);
  1064. m_params.m_source_mipmap_images.resize(m_params.m_source_mipmap_images.size() + 1);
  1065. if (ldr_mips.size() > 1)
  1066. {
  1067. ldr_mips.erase_index(0U);
  1068. m_params.m_source_mipmap_images.back().swap(ldr_mips);
  1069. any_mipmaps = true;
  1070. }
  1071. }
  1072. else
  1073. {
  1074. if (m_params.m_source_images.size())
  1075. {
  1076. error_printf("All DDS files must be of the same type (all LDR, or all HDR)\n");
  1077. return false;
  1078. }
  1079. m_params.m_source_images_hdr.push_back(hdr_mips[0]);
  1080. m_params.m_source_mipmap_images_hdr.resize(m_params.m_source_mipmap_images_hdr.size() + 1);
  1081. if (hdr_mips.size() > 1)
  1082. {
  1083. hdr_mips.erase_index(0U);
  1084. m_params.m_source_mipmap_images_hdr.back().swap(hdr_mips);
  1085. any_mipmaps = true;
  1086. }
  1087. m_params.m_hdr = true;
  1088. m_params.m_uastc = true;
  1089. }
  1090. }
  1091. m_params.m_read_source_images = false;
  1092. m_params.m_source_filenames.clear();
  1093. m_params.m_source_alpha_filenames.clear();
  1094. if (!any_mipmaps)
  1095. {
  1096. m_params.m_source_mipmap_images.clear();
  1097. m_params.m_source_mipmap_images_hdr.clear();
  1098. }
  1099. if ((m_params.m_hdr) && (!m_params.m_source_images_hdr.size()))
  1100. {
  1101. error_printf("HDR mode enabled, but only LDR .DDS files were loaded. HDR mode requires half or float (HDR) .DDS inputs.\n");
  1102. return false;
  1103. }
  1104. return true;
  1105. }
  1106. bool basis_compressor::read_source_images()
  1107. {
  1108. debug_printf("basis_compressor::read_source_images\n");
  1109. const uint32_t total_source_files = m_params.m_read_source_images ? (uint32_t)m_params.m_source_filenames.size() :
  1110. (m_params.m_hdr ? (uint32_t)m_params.m_source_images_hdr.size() : (uint32_t)m_params.m_source_images.size());
  1111. if (!total_source_files)
  1112. {
  1113. debug_printf("basis_compressor::read_source_images: No source images to process\n");
  1114. return false;
  1115. }
  1116. m_stats.resize(0);
  1117. m_slice_descs.resize(0);
  1118. m_slice_images.resize(0);
  1119. m_slice_images_hdr.resize(0);
  1120. m_total_blocks = 0;
  1121. uint32_t total_macroblocks = 0;
  1122. m_any_source_image_has_alpha = false;
  1123. basisu::vector<image> source_images;
  1124. basisu::vector<imagef> source_images_hdr;
  1125. basisu::vector<std::string> source_filenames;
  1126. // TODO: Note HDR images don't support alpha here, currently.
  1127. // First load all source images, and determine if any have an alpha channel.
  1128. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  1129. {
  1130. const char* pSource_filename = "";
  1131. image file_image;
  1132. imagef file_image_hdr;
  1133. if (m_params.m_read_source_images)
  1134. {
  1135. pSource_filename = m_params.m_source_filenames[source_file_index].c_str();
  1136. // Load the source image
  1137. if (m_params.m_hdr)
  1138. {
  1139. float upconversion_nit_multiplier = m_params.m_ldr_hdr_upconversion_nit_multiplier;
  1140. if (upconversion_nit_multiplier == 0.0f)
  1141. {
  1142. // Note: We used to use a normalized nit multiplier of 1.0 for UASTC HDR 4x4. We're now writing upconverted output files in absolute luminance (100 nits).
  1143. upconversion_nit_multiplier = LDR_TO_HDR_NITS;
  1144. }
  1145. m_ldr_to_hdr_upconversion_nit_multiplier = upconversion_nit_multiplier;
  1146. if (!is_image_filename_hdr(pSource_filename))
  1147. m_upconverted_any_ldr_images = true;
  1148. if (!load_image_hdr(pSource_filename, file_image_hdr, m_params.m_ldr_hdr_upconversion_srgb_to_linear, upconversion_nit_multiplier, m_params.m_ldr_hdr_upconversion_black_bias))
  1149. {
  1150. error_printf("Failed reading source image: %s\n", pSource_filename);
  1151. return false;
  1152. }
  1153. // TODO: For now, just slam alpha to 1.0f. None of our HDR encoders support alpha yet.
  1154. for (uint32_t y = 0; y < file_image_hdr.get_height(); y++)
  1155. for (uint32_t x = 0; x < file_image_hdr.get_width(); x++)
  1156. file_image_hdr(x, y)[3] = 1.0f;
  1157. }
  1158. else
  1159. {
  1160. if (!load_image(pSource_filename, file_image))
  1161. {
  1162. error_printf("Failed reading source image: %s\n", pSource_filename);
  1163. return false;
  1164. }
  1165. }
  1166. const uint32_t width = m_params.m_hdr ? file_image_hdr.get_width() : file_image.get_width();
  1167. const uint32_t height = m_params.m_hdr ? file_image_hdr.get_height() : file_image.get_height();
  1168. if (m_params.m_status_output)
  1169. {
  1170. printf("Read source image \"%s\", %ux%u\n", pSource_filename, width, height);
  1171. }
  1172. if (m_params.m_hdr)
  1173. {
  1174. clean_hdr_image(file_image_hdr);
  1175. }
  1176. else
  1177. {
  1178. // Optionally load another image and put a grayscale version of it into the alpha channel.
  1179. if ((source_file_index < m_params.m_source_alpha_filenames.size()) && (m_params.m_source_alpha_filenames[source_file_index].size()))
  1180. {
  1181. const char* pSource_alpha_image = m_params.m_source_alpha_filenames[source_file_index].c_str();
  1182. image alpha_data;
  1183. if (!load_image(pSource_alpha_image, alpha_data))
  1184. {
  1185. error_printf("Failed reading source image: %s\n", pSource_alpha_image);
  1186. return false;
  1187. }
  1188. if (m_params.m_status_output)
  1189. printf("Read source alpha image \"%s\", %ux%u\n", pSource_alpha_image, alpha_data.get_width(), alpha_data.get_height());
  1190. alpha_data.crop(width, height);
  1191. for (uint32_t y = 0; y < height; y++)
  1192. for (uint32_t x = 0; x < width; x++)
  1193. file_image(x, y).a = (uint8_t)alpha_data(x, y).get_709_luma();
  1194. }
  1195. }
  1196. }
  1197. else
  1198. {
  1199. if (m_params.m_hdr)
  1200. {
  1201. file_image_hdr = m_params.m_source_images_hdr[source_file_index];
  1202. clean_hdr_image(file_image_hdr);
  1203. }
  1204. else
  1205. {
  1206. file_image = m_params.m_source_images[source_file_index];
  1207. }
  1208. }
  1209. if (!m_params.m_hdr)
  1210. {
  1211. if (m_params.m_renormalize)
  1212. file_image.renormalize_normal_map();
  1213. }
  1214. bool alpha_swizzled = false;
  1215. if (m_params.m_swizzle[0] != 0 ||
  1216. m_params.m_swizzle[1] != 1 ||
  1217. m_params.m_swizzle[2] != 2 ||
  1218. m_params.m_swizzle[3] != 3)
  1219. {
  1220. if (!m_params.m_hdr)
  1221. {
  1222. // Used for XY normal maps in RG - puts X in color, Y in alpha
  1223. for (uint32_t y = 0; y < file_image.get_height(); y++)
  1224. {
  1225. for (uint32_t x = 0; x < file_image.get_width(); x++)
  1226. {
  1227. const color_rgba& c = file_image(x, y);
  1228. file_image(x, y).set_noclamp_rgba(c[m_params.m_swizzle[0]], c[m_params.m_swizzle[1]], c[m_params.m_swizzle[2]], c[m_params.m_swizzle[3]]);
  1229. }
  1230. }
  1231. alpha_swizzled = (m_params.m_swizzle[3] != 3);
  1232. }
  1233. else
  1234. {
  1235. // Used for XY normal maps in RG - puts X in color, Y in alpha
  1236. for (uint32_t y = 0; y < file_image_hdr.get_height(); y++)
  1237. {
  1238. for (uint32_t x = 0; x < file_image_hdr.get_width(); x++)
  1239. {
  1240. const vec4F& c = file_image_hdr(x, y);
  1241. // For now, alpha is always 1.0f in UASTC HDR.
  1242. file_image_hdr(x, y).set(c[m_params.m_swizzle[0]], c[m_params.m_swizzle[1]], c[m_params.m_swizzle[2]], 1.0f); // c[m_params.m_swizzle[3]]);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. bool has_alpha = false;
  1248. if (!m_params.m_hdr)
  1249. {
  1250. if (m_params.m_force_alpha || alpha_swizzled)
  1251. has_alpha = true;
  1252. else if (!m_params.m_check_for_alpha)
  1253. file_image.set_alpha(255);
  1254. else if (file_image.has_alpha())
  1255. has_alpha = true;
  1256. if (has_alpha)
  1257. m_any_source_image_has_alpha = true;
  1258. }
  1259. {
  1260. const uint32_t width = m_params.m_hdr ? file_image_hdr.get_width() : file_image.get_width();
  1261. const uint32_t height = m_params.m_hdr ? file_image_hdr.get_height() : file_image.get_height();
  1262. debug_printf("Source image index %u filename %s %ux%u has alpha: %u\n", source_file_index, pSource_filename, width, height, has_alpha);
  1263. }
  1264. if (m_params.m_y_flip)
  1265. {
  1266. if (m_params.m_hdr)
  1267. file_image_hdr.flip_y();
  1268. else
  1269. file_image.flip_y();
  1270. }
  1271. #if DEBUG_CROP_TEXTURE_TO_64x64
  1272. if (m_params.m_hdr)
  1273. file_image_hdr.resize(64, 64);
  1274. else
  1275. file_image.resize(64, 64);
  1276. #endif
  1277. if ((m_params.m_resample_width > 0) && (m_params.m_resample_height > 0))
  1278. {
  1279. int new_width = basisu::minimum<int>(m_params.m_resample_width, BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1280. int new_height = basisu::minimum<int>(m_params.m_resample_height, BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1281. debug_printf("Resampling to %ix%i\n", new_width, new_height);
  1282. // TODO: A box filter - kaiser looks too sharp on video. Let the caller control this.
  1283. if (m_params.m_hdr)
  1284. {
  1285. imagef temp_img(new_width, new_height);
  1286. image_resample(file_image_hdr, temp_img, "box"); // "kaiser");
  1287. clean_hdr_image(temp_img);
  1288. temp_img.swap(file_image_hdr);
  1289. }
  1290. else
  1291. {
  1292. image temp_img(new_width, new_height);
  1293. image_resample(file_image, temp_img, m_params.m_perceptual, "box"); // "kaiser");
  1294. temp_img.swap(file_image);
  1295. }
  1296. }
  1297. else if (m_params.m_resample_factor > 0.0f)
  1298. {
  1299. // TODO: A box filter - kaiser looks too sharp on video. Let the caller control this.
  1300. if (m_params.m_hdr)
  1301. {
  1302. int new_width = basisu::minimum<int>(basisu::maximum(1, (int)ceilf(file_image_hdr.get_width() * m_params.m_resample_factor)), BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1303. int new_height = basisu::minimum<int>(basisu::maximum(1, (int)ceilf(file_image_hdr.get_height() * m_params.m_resample_factor)), BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1304. debug_printf("Resampling to %ix%i\n", new_width, new_height);
  1305. imagef temp_img(new_width, new_height);
  1306. image_resample(file_image_hdr, temp_img, "box"); // "kaiser");
  1307. clean_hdr_image(temp_img);
  1308. temp_img.swap(file_image_hdr);
  1309. }
  1310. else
  1311. {
  1312. int new_width = basisu::minimum<int>(basisu::maximum(1, (int)ceilf(file_image.get_width() * m_params.m_resample_factor)), BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1313. int new_height = basisu::minimum<int>(basisu::maximum(1, (int)ceilf(file_image.get_height() * m_params.m_resample_factor)), BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  1314. debug_printf("Resampling to %ix%i\n", new_width, new_height);
  1315. image temp_img(new_width, new_height);
  1316. image_resample(file_image, temp_img, m_params.m_perceptual, "box"); // "kaiser");
  1317. temp_img.swap(file_image);
  1318. }
  1319. }
  1320. const uint32_t width = m_params.m_hdr ? file_image_hdr.get_width() : file_image.get_width();
  1321. const uint32_t height = m_params.m_hdr ? file_image_hdr.get_height() : file_image.get_height();
  1322. if ((!width) || (!height))
  1323. {
  1324. error_printf("basis_compressor::read_source_images: Source image has a zero width and/or height!\n");
  1325. return false;
  1326. }
  1327. if ((width > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION) || (height > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION))
  1328. {
  1329. error_printf("basis_compressor::read_source_images: Source image \"%s\" is too large!\n", pSource_filename);
  1330. return false;
  1331. }
  1332. if (!m_params.m_hdr)
  1333. source_images.enlarge(1)->swap(file_image);
  1334. else
  1335. source_images_hdr.enlarge(1)->swap(file_image_hdr);
  1336. source_filenames.push_back(pSource_filename);
  1337. }
  1338. // Check if the caller has generated their own mipmaps.
  1339. if (m_params.m_hdr)
  1340. {
  1341. if (m_params.m_source_mipmap_images_hdr.size())
  1342. {
  1343. // Make sure they've passed us enough mipmap chains.
  1344. if ((m_params.m_source_images_hdr.size() != m_params.m_source_mipmap_images_hdr.size()) || (total_source_files != m_params.m_source_images_hdr.size()))
  1345. {
  1346. error_printf("basis_compressor::read_source_images(): m_params.m_source_mipmap_images_hdr.size() must equal m_params.m_source_images_hdr.size()!\n");
  1347. return false;
  1348. }
  1349. }
  1350. }
  1351. else
  1352. {
  1353. if (m_params.m_source_mipmap_images.size())
  1354. {
  1355. // Make sure they've passed us enough mipmap chains.
  1356. if ((m_params.m_source_images.size() != m_params.m_source_mipmap_images.size()) || (total_source_files != m_params.m_source_images.size()))
  1357. {
  1358. error_printf("basis_compressor::read_source_images(): m_params.m_source_mipmap_images.size() must equal m_params.m_source_images.size()!\n");
  1359. return false;
  1360. }
  1361. // Check if any of the user-supplied mipmap levels has alpha.
  1362. if (!m_any_source_image_has_alpha)
  1363. {
  1364. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  1365. {
  1366. for (uint32_t mip_index = 0; mip_index < m_params.m_source_mipmap_images[source_file_index].size(); mip_index++)
  1367. {
  1368. const image& mip_img = m_params.m_source_mipmap_images[source_file_index][mip_index];
  1369. // Be sure to take into account any swizzling which will be applied.
  1370. if (mip_img.has_alpha(m_params.m_swizzle[3]))
  1371. {
  1372. m_any_source_image_has_alpha = true;
  1373. break;
  1374. }
  1375. }
  1376. if (m_any_source_image_has_alpha)
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. }
  1382. debug_printf("Any source image has alpha: %u\n", m_any_source_image_has_alpha);
  1383. // Now, for each source image, create the slices corresponding to that image.
  1384. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  1385. {
  1386. const std::string &source_filename = source_filenames[source_file_index];
  1387. basisu::vector<image> slices;
  1388. basisu::vector<imagef> slices_hdr;
  1389. slices.reserve(32);
  1390. slices_hdr.reserve(32);
  1391. // The first (largest) mipmap level.
  1392. image *pFile_image = source_images.size() ? &source_images[source_file_index] : nullptr;
  1393. imagef *pFile_image_hdr = source_images_hdr.size() ? &source_images_hdr[source_file_index] : nullptr;
  1394. // Reserve a slot for mip0.
  1395. if (m_params.m_hdr)
  1396. slices_hdr.resize(1);
  1397. else
  1398. slices.resize(1);
  1399. if ((!m_params.m_hdr) && (m_params.m_source_mipmap_images.size()))
  1400. {
  1401. // User-provided mipmaps for each layer or image in the texture array.
  1402. for (uint32_t mip_index = 0; mip_index < m_params.m_source_mipmap_images[source_file_index].size(); mip_index++)
  1403. {
  1404. image& mip_img = m_params.m_source_mipmap_images[source_file_index][mip_index];
  1405. if ((m_params.m_swizzle[0] != 0) ||
  1406. (m_params.m_swizzle[1] != 1) ||
  1407. (m_params.m_swizzle[2] != 2) ||
  1408. (m_params.m_swizzle[3] != 3))
  1409. {
  1410. // Used for XY normal maps in RG - puts X in color, Y in alpha
  1411. for (uint32_t y = 0; y < mip_img.get_height(); y++)
  1412. {
  1413. for (uint32_t x = 0; x < mip_img.get_width(); x++)
  1414. {
  1415. const color_rgba& c = mip_img(x, y);
  1416. mip_img(x, y).set_noclamp_rgba(c[m_params.m_swizzle[0]], c[m_params.m_swizzle[1]], c[m_params.m_swizzle[2]], c[m_params.m_swizzle[3]]);
  1417. }
  1418. }
  1419. }
  1420. slices.push_back(mip_img);
  1421. }
  1422. }
  1423. else if ((m_params.m_hdr) && (m_params.m_source_mipmap_images_hdr.size()))
  1424. {
  1425. // User-provided mipmaps for each layer or image in the texture array.
  1426. for (uint32_t mip_index = 0; mip_index < m_params.m_source_mipmap_images_hdr[source_file_index].size(); mip_index++)
  1427. {
  1428. imagef& mip_img = m_params.m_source_mipmap_images_hdr[source_file_index][mip_index];
  1429. if ((m_params.m_swizzle[0] != 0) ||
  1430. (m_params.m_swizzle[1] != 1) ||
  1431. (m_params.m_swizzle[2] != 2) ||
  1432. (m_params.m_swizzle[3] != 3))
  1433. {
  1434. // Used for XY normal maps in RG - puts X in color, Y in alpha
  1435. for (uint32_t y = 0; y < mip_img.get_height(); y++)
  1436. {
  1437. for (uint32_t x = 0; x < mip_img.get_width(); x++)
  1438. {
  1439. const vec4F& c = mip_img(x, y);
  1440. // For now, HDR alpha is always 1.0f.
  1441. mip_img(x, y).set(c[m_params.m_swizzle[0]], c[m_params.m_swizzle[1]], c[m_params.m_swizzle[2]], 1.0f); // c[m_params.m_swizzle[3]]);
  1442. }
  1443. }
  1444. }
  1445. clean_hdr_image(mip_img);
  1446. slices_hdr.push_back(mip_img);
  1447. }
  1448. }
  1449. else if (m_params.m_mip_gen)
  1450. {
  1451. // Automatically generate mipmaps.
  1452. if (m_params.m_hdr)
  1453. {
  1454. if (!generate_mipmaps(*pFile_image_hdr, slices_hdr, m_any_source_image_has_alpha))
  1455. return false;
  1456. }
  1457. else
  1458. {
  1459. if (!generate_mipmaps(*pFile_image, slices, m_any_source_image_has_alpha))
  1460. return false;
  1461. }
  1462. }
  1463. // Swap in the largest mipmap level here to avoid copying it, because generate_mips() will change the array.
  1464. // NOTE: file_image is now blank.
  1465. if (m_params.m_hdr)
  1466. slices_hdr[0].swap(*pFile_image_hdr);
  1467. else
  1468. slices[0].swap(*pFile_image);
  1469. uint_vec mip_indices(m_params.m_hdr ? slices_hdr.size() : slices.size());
  1470. for (uint32_t i = 0; i < (m_params.m_hdr ? slices_hdr.size() : slices.size()); i++)
  1471. mip_indices[i] = i;
  1472. if ((!m_params.m_hdr) && (m_any_source_image_has_alpha) && (!m_params.m_uastc))
  1473. {
  1474. // For ETC1S, if source has alpha, then even mips will have RGB, and odd mips will have alpha in RGB.
  1475. basisu::vector<image> alpha_slices;
  1476. uint_vec new_mip_indices;
  1477. alpha_slices.reserve(slices.size() * 2);
  1478. for (uint32_t i = 0; i < slices.size(); i++)
  1479. {
  1480. image lvl_rgb(slices[i]);
  1481. image lvl_a(lvl_rgb);
  1482. for (uint32_t y = 0; y < lvl_a.get_height(); y++)
  1483. {
  1484. for (uint32_t x = 0; x < lvl_a.get_width(); x++)
  1485. {
  1486. uint8_t a = lvl_a(x, y).a;
  1487. lvl_a(x, y).set_noclamp_rgba(a, a, a, 255);
  1488. }
  1489. }
  1490. lvl_rgb.set_alpha(255);
  1491. alpha_slices.push_back(lvl_rgb);
  1492. new_mip_indices.push_back(i);
  1493. alpha_slices.push_back(lvl_a);
  1494. new_mip_indices.push_back(i);
  1495. }
  1496. slices.swap(alpha_slices);
  1497. mip_indices.swap(new_mip_indices);
  1498. }
  1499. if (m_params.m_hdr)
  1500. {
  1501. assert(slices_hdr.size() == mip_indices.size());
  1502. }
  1503. else
  1504. {
  1505. assert(slices.size() == mip_indices.size());
  1506. }
  1507. for (uint32_t slice_index = 0; slice_index < (m_params.m_hdr ? slices_hdr.size() : slices.size()); slice_index++)
  1508. {
  1509. image *pSlice_image = m_params.m_hdr ? nullptr : &slices[slice_index];
  1510. imagef *pSlice_image_hdr = m_params.m_hdr ? &slices_hdr[slice_index] : nullptr;
  1511. const uint32_t orig_width = m_params.m_hdr ? pSlice_image_hdr->get_width() : pSlice_image->get_width();
  1512. const uint32_t orig_height = m_params.m_hdr ? pSlice_image_hdr->get_height() : pSlice_image->get_height();
  1513. bool is_alpha_slice = false;
  1514. if ((!m_params.m_hdr) && (m_any_source_image_has_alpha))
  1515. {
  1516. if (m_params.m_uastc)
  1517. {
  1518. is_alpha_slice = pSlice_image->has_alpha();
  1519. }
  1520. else
  1521. {
  1522. is_alpha_slice = (slice_index & 1) != 0;
  1523. }
  1524. }
  1525. // Enlarge the source image to block boundaries, duplicating edge pixels if necessary to avoid introducing extra colors into blocks.
  1526. if (m_params.m_hdr)
  1527. {
  1528. // Don't pad in 6x6 mode, the lower level compressor handles it.
  1529. if (m_params.m_hdr_mode == hdr_modes::cUASTC_HDR_4X4)
  1530. {
  1531. pSlice_image_hdr->crop_dup_borders(pSlice_image_hdr->get_block_width(get_block_width()) * get_block_width(), pSlice_image_hdr->get_block_height(get_block_height()) * get_block_height());
  1532. }
  1533. }
  1534. else
  1535. {
  1536. pSlice_image->crop_dup_borders(pSlice_image->get_block_width(get_block_width()) * get_block_width(), pSlice_image->get_block_height(get_block_height()) * get_block_height());
  1537. }
  1538. if (m_params.m_debug_images)
  1539. {
  1540. if (m_params.m_hdr)
  1541. write_exr(string_format("basis_debug_source_image_%u_slice_%u.exr", source_file_index, slice_index).c_str(), *pSlice_image_hdr, 3, 0);
  1542. else
  1543. save_png(string_format("basis_debug_source_image_%u_slice_%u.png", source_file_index, slice_index).c_str(), *pSlice_image);
  1544. }
  1545. const size_t dest_image_index = (m_params.m_hdr ? m_slice_images_hdr.size() : m_slice_images.size());
  1546. enlarge_vector(m_stats, 1);
  1547. if (m_params.m_hdr)
  1548. enlarge_vector(m_slice_images_hdr, 1);
  1549. else
  1550. enlarge_vector(m_slice_images, 1);
  1551. enlarge_vector(m_slice_descs, 1);
  1552. m_stats[dest_image_index].m_filename = source_filename.c_str();
  1553. m_stats[dest_image_index].m_width = orig_width;
  1554. m_stats[dest_image_index].m_height = orig_height;
  1555. debug_printf("****** Slice %u: mip %u, alpha_slice: %u, filename: \"%s\", original: %ux%u actual: %ux%u\n",
  1556. m_slice_descs.size() - 1, mip_indices[slice_index], is_alpha_slice, source_filename.c_str(),
  1557. orig_width, orig_height,
  1558. m_params.m_hdr ? pSlice_image_hdr->get_width() : pSlice_image->get_width(),
  1559. m_params.m_hdr ? pSlice_image_hdr->get_height() : pSlice_image->get_height());
  1560. basisu_backend_slice_desc& slice_desc = m_slice_descs[dest_image_index];
  1561. slice_desc.m_first_block_index = m_total_blocks;
  1562. slice_desc.m_orig_width = orig_width;
  1563. slice_desc.m_orig_height = orig_height;
  1564. if (m_params.m_hdr)
  1565. {
  1566. slice_desc.m_width = pSlice_image_hdr->get_width();
  1567. slice_desc.m_height = pSlice_image_hdr->get_height();
  1568. slice_desc.m_num_blocks_x = pSlice_image_hdr->get_block_width(get_block_width());
  1569. slice_desc.m_num_blocks_y = pSlice_image_hdr->get_block_height(get_block_height());
  1570. }
  1571. else
  1572. {
  1573. slice_desc.m_width = pSlice_image->get_width();
  1574. slice_desc.m_height = pSlice_image->get_height();
  1575. slice_desc.m_num_blocks_x = pSlice_image->get_block_width(get_block_width());
  1576. slice_desc.m_num_blocks_y = pSlice_image->get_block_height(get_block_height());
  1577. }
  1578. slice_desc.m_num_macroblocks_x = (slice_desc.m_num_blocks_x + 1) >> 1;
  1579. slice_desc.m_num_macroblocks_y = (slice_desc.m_num_blocks_y + 1) >> 1;
  1580. slice_desc.m_source_file_index = source_file_index;
  1581. slice_desc.m_mip_index = mip_indices[slice_index];
  1582. slice_desc.m_alpha = is_alpha_slice;
  1583. slice_desc.m_iframe = false;
  1584. if (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames)
  1585. {
  1586. slice_desc.m_iframe = (source_file_index == 0);
  1587. }
  1588. m_total_blocks += slice_desc.m_num_blocks_x * slice_desc.m_num_blocks_y;
  1589. total_macroblocks += slice_desc.m_num_macroblocks_x * slice_desc.m_num_macroblocks_y;
  1590. // Finally, swap in the slice's image to avoid copying it.
  1591. // NOTE: slice_image is now blank.
  1592. if (m_params.m_hdr)
  1593. m_slice_images_hdr[dest_image_index].swap(*pSlice_image_hdr);
  1594. else
  1595. m_slice_images[dest_image_index].swap(*pSlice_image);
  1596. } // slice_index
  1597. } // source_file_index
  1598. debug_printf("Total blocks: %u, Total macroblocks: %u\n", m_total_blocks, total_macroblocks);
  1599. // Make sure we don't have too many slices
  1600. if (m_slice_descs.size() > BASISU_MAX_SLICES)
  1601. {
  1602. error_printf("Too many slices!\n");
  1603. return false;
  1604. }
  1605. // Basic sanity check on the slices
  1606. for (uint32_t i = 1; i < m_slice_descs.size(); i++)
  1607. {
  1608. const basisu_backend_slice_desc &prev_slice_desc = m_slice_descs[i - 1];
  1609. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  1610. // Make sure images are in order
  1611. int image_delta = (int)slice_desc.m_source_file_index - (int)prev_slice_desc.m_source_file_index;
  1612. if (image_delta > 1)
  1613. return false;
  1614. // Make sure mipmap levels are in order
  1615. if (!image_delta)
  1616. {
  1617. int level_delta = (int)slice_desc.m_mip_index - (int)prev_slice_desc.m_mip_index;
  1618. if (level_delta > 1)
  1619. return false;
  1620. }
  1621. }
  1622. if (m_params.m_status_output)
  1623. {
  1624. printf("Total slices: %u\n", (uint32_t)m_slice_descs.size());
  1625. }
  1626. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1627. {
  1628. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  1629. if (m_params.m_status_output)
  1630. {
  1631. printf("Slice: %u, alpha: %u, orig width/height: %ux%u, width/height: %ux%u, first_block: %u, image_index: %u, mip_level: %u, iframe: %u\n",
  1632. i, slice_desc.m_alpha, slice_desc.m_orig_width, slice_desc.m_orig_height,
  1633. slice_desc.m_width, slice_desc.m_height,
  1634. slice_desc.m_first_block_index, slice_desc.m_source_file_index, slice_desc.m_mip_index, slice_desc.m_iframe);
  1635. }
  1636. if (m_any_source_image_has_alpha)
  1637. {
  1638. // HDR doesn't support alpha yet
  1639. if (m_params.m_hdr)
  1640. return false;
  1641. if (!m_params.m_uastc)
  1642. {
  1643. // For ETC1S, alpha slices must be at odd slice indices.
  1644. if (slice_desc.m_alpha)
  1645. {
  1646. if ((i & 1) == 0)
  1647. return false;
  1648. const basisu_backend_slice_desc& prev_slice_desc = m_slice_descs[i - 1];
  1649. // Make sure previous slice has this image's color data
  1650. if (prev_slice_desc.m_source_file_index != slice_desc.m_source_file_index)
  1651. return false;
  1652. if (prev_slice_desc.m_alpha)
  1653. return false;
  1654. if (prev_slice_desc.m_mip_index != slice_desc.m_mip_index)
  1655. return false;
  1656. if (prev_slice_desc.m_num_blocks_x != slice_desc.m_num_blocks_x)
  1657. return false;
  1658. if (prev_slice_desc.m_num_blocks_y != slice_desc.m_num_blocks_y)
  1659. return false;
  1660. }
  1661. else if (i & 1)
  1662. return false;
  1663. }
  1664. }
  1665. else if (slice_desc.m_alpha)
  1666. {
  1667. return false;
  1668. }
  1669. if ((slice_desc.m_orig_width > slice_desc.m_width) || (slice_desc.m_orig_height > slice_desc.m_height))
  1670. return false;
  1671. if ((slice_desc.m_source_file_index == 0) && (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames))
  1672. {
  1673. if (!slice_desc.m_iframe)
  1674. return false;
  1675. }
  1676. }
  1677. return true;
  1678. }
  1679. // Do some basic validation for 2D arrays, cubemaps, video, and volumes.
  1680. bool basis_compressor::validate_texture_type_constraints()
  1681. {
  1682. debug_printf("basis_compressor::validate_texture_type_constraints\n");
  1683. // In 2D mode anything goes (each image may have a different resolution and # of mipmap levels).
  1684. if (m_params.m_tex_type == basist::cBASISTexType2D)
  1685. return true;
  1686. uint32_t total_basis_images = 0;
  1687. for (uint32_t slice_index = 0; slice_index < (m_params.m_hdr ? m_slice_images_hdr.size() : m_slice_images.size()); slice_index++)
  1688. {
  1689. const basisu_backend_slice_desc &slice_desc = m_slice_descs[slice_index];
  1690. total_basis_images = maximum<uint32_t>(total_basis_images, slice_desc.m_source_file_index + 1);
  1691. }
  1692. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  1693. {
  1694. // For cubemaps, validate that the total # of Basis images is a multiple of 6.
  1695. if ((total_basis_images % 6) != 0)
  1696. {
  1697. error_printf("basis_compressor::validate_texture_type_constraints: For cubemaps the total number of input images is not a multiple of 6!\n");
  1698. return false;
  1699. }
  1700. }
  1701. // Now validate that all the mip0's have the same dimensions, and that each image has the same # of mipmap levels.
  1702. uint_vec image_mipmap_levels(total_basis_images);
  1703. int width = -1, height = -1;
  1704. for (uint32_t slice_index = 0; slice_index < (m_params.m_hdr ? m_slice_images_hdr.size() : m_slice_images.size()); slice_index++)
  1705. {
  1706. const basisu_backend_slice_desc &slice_desc = m_slice_descs[slice_index];
  1707. image_mipmap_levels[slice_desc.m_source_file_index] = maximum(image_mipmap_levels[slice_desc.m_source_file_index], slice_desc.m_mip_index + 1);
  1708. if (slice_desc.m_mip_index != 0)
  1709. continue;
  1710. if (width < 0)
  1711. {
  1712. width = slice_desc.m_orig_width;
  1713. height = slice_desc.m_orig_height;
  1714. }
  1715. else if ((width != (int)slice_desc.m_orig_width) || (height != (int)slice_desc.m_orig_height))
  1716. {
  1717. error_printf("basis_compressor::validate_texture_type_constraints: The source image resolutions are not all equal!\n");
  1718. return false;
  1719. }
  1720. }
  1721. for (size_t i = 1; i < image_mipmap_levels.size(); i++)
  1722. {
  1723. if (image_mipmap_levels[0] != image_mipmap_levels[i])
  1724. {
  1725. error_printf("basis_compressor::validate_texture_type_constraints: Each image must have the same number of mipmap levels!\n");
  1726. return false;
  1727. }
  1728. }
  1729. return true;
  1730. }
  1731. bool basis_compressor::extract_source_blocks()
  1732. {
  1733. debug_printf("basis_compressor::extract_source_blocks\n");
  1734. // No need to extract blocks in 6x6 mode, but the 4x4 compressors want 4x4 blocks.
  1735. if ((m_fmt_mode == basist::basis_tex_format::cASTC_HDR_6x6) || (m_fmt_mode == basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE))
  1736. return true;
  1737. if (m_params.m_hdr)
  1738. m_source_blocks_hdr.resize(m_total_blocks);
  1739. else
  1740. m_source_blocks.resize(m_total_blocks);
  1741. for (uint32_t slice_index = 0; slice_index < (m_params.m_hdr ? m_slice_images_hdr.size() : m_slice_images.size()); slice_index++)
  1742. {
  1743. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1744. const uint32_t num_blocks_x = slice_desc.m_num_blocks_x;
  1745. const uint32_t num_blocks_y = slice_desc.m_num_blocks_y;
  1746. const image *pSource_image = m_params.m_hdr ? nullptr : &m_slice_images[slice_index];
  1747. const imagef *pSource_image_hdr = m_params.m_hdr ? &m_slice_images_hdr[slice_index] : nullptr;
  1748. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  1749. {
  1750. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  1751. {
  1752. if (m_params.m_hdr)
  1753. {
  1754. vec4F* pBlock = m_source_blocks_hdr[slice_desc.m_first_block_index + block_x + block_y * num_blocks_x].get_ptr();
  1755. pSource_image_hdr->extract_block_clamped(pBlock, block_x * 4, block_y * 4, 4, 4);
  1756. // Additional (technically optional) early sanity checking of the block texels.
  1757. for (uint32_t i = 0; i < 16; i++)
  1758. {
  1759. for (uint32_t c = 0; c < 3; c++)
  1760. {
  1761. float v = pBlock[i][c];
  1762. if (std::isnan(v) || std::isinf(v) || (v < 0.0f) || (v > basist::MAX_HALF_FLOAT))
  1763. {
  1764. error_printf("basis_compressor::extract_source_blocks: invalid float component\n");
  1765. return false;
  1766. }
  1767. }
  1768. }
  1769. }
  1770. else
  1771. {
  1772. pSource_image->extract_block_clamped(m_source_blocks[slice_desc.m_first_block_index + block_x + block_y * num_blocks_x].get_ptr(), block_x * 4, block_y * 4, 4, 4);
  1773. }
  1774. }
  1775. }
  1776. }
  1777. return true;
  1778. }
  1779. bool basis_compressor::process_frontend()
  1780. {
  1781. debug_printf("basis_compressor::process_frontend\n");
  1782. #if 0
  1783. // TODO
  1784. basis_etc1_pack_params pack_params;
  1785. pack_params.m_quality = cETCQualityMedium;
  1786. pack_params.m_perceptual = m_params.m_perceptual;
  1787. pack_params.m_use_color4 = false;
  1788. pack_etc1_block_context pack_context;
  1789. std::unordered_set<uint64_t> endpoint_hash;
  1790. std::unordered_set<uint32_t> selector_hash;
  1791. for (uint32_t i = 0; i < m_source_blocks.size(); i++)
  1792. {
  1793. etc_block blk;
  1794. pack_etc1_block(blk, m_source_blocks[i].get_ptr(), pack_params, pack_context);
  1795. const color_rgba c0(blk.get_block_color(0, false));
  1796. endpoint_hash.insert((c0.r | (c0.g << 5) | (c0.b << 10)) | (blk.get_inten_table(0) << 16));
  1797. const color_rgba c1(blk.get_block_color(1, false));
  1798. endpoint_hash.insert((c1.r | (c1.g << 5) | (c1.b << 10)) | (blk.get_inten_table(1) << 16));
  1799. selector_hash.insert(blk.get_raw_selector_bits());
  1800. }
  1801. const uint32_t total_unique_endpoints = (uint32_t)endpoint_hash.size();
  1802. const uint32_t total_unique_selectors = (uint32_t)selector_hash.size();
  1803. if (m_params.m_debug)
  1804. {
  1805. debug_printf("Unique endpoints: %u, unique selectors: %u\n", total_unique_endpoints, total_unique_selectors);
  1806. }
  1807. #endif
  1808. const double total_texels = m_total_blocks * 16.0f;
  1809. int endpoint_clusters = m_params.m_etc1s_max_endpoint_clusters;
  1810. int selector_clusters = m_params.m_etc1s_max_selector_clusters;
  1811. if (endpoint_clusters > basisu_frontend::cMaxEndpointClusters)
  1812. {
  1813. error_printf("Too many endpoint clusters! (%u but max is %u)\n", endpoint_clusters, basisu_frontend::cMaxEndpointClusters);
  1814. return false;
  1815. }
  1816. if (selector_clusters > basisu_frontend::cMaxSelectorClusters)
  1817. {
  1818. error_printf("Too many selector clusters! (%u but max is %u)\n", selector_clusters, basisu_frontend::cMaxSelectorClusters);
  1819. return false;
  1820. }
  1821. if (m_params.m_etc1s_quality_level != -1)
  1822. {
  1823. const float quality = saturate(m_params.m_etc1s_quality_level / 255.0f);
  1824. const float bits_per_endpoint_cluster = 14.0f;
  1825. const float max_desired_endpoint_cluster_bits_per_texel = 1.0f; // .15f
  1826. int max_endpoints = static_cast<int>((max_desired_endpoint_cluster_bits_per_texel * total_texels) / bits_per_endpoint_cluster);
  1827. const float mid = 128.0f / 255.0f;
  1828. float color_endpoint_quality = quality;
  1829. const float endpoint_split_point = 0.5f;
  1830. // In v1.2 and in previous versions, the endpoint codebook size at quality 128 was 3072. This wasn't quite large enough.
  1831. const int ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE = 4800;
  1832. const int MAX_ENDPOINT_CODEBOOK_SIZE = 8192;
  1833. if (color_endpoint_quality <= mid)
  1834. {
  1835. color_endpoint_quality = lerp(0.0f, endpoint_split_point, powf(color_endpoint_quality / mid, .65f));
  1836. max_endpoints = clamp<int>(max_endpoints, 256, ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE);
  1837. max_endpoints = minimum<uint32_t>(max_endpoints, m_total_blocks);
  1838. if (max_endpoints < 64)
  1839. max_endpoints = 64;
  1840. endpoint_clusters = clamp<uint32_t>((uint32_t)(.5f + lerp<float>(32, static_cast<float>(max_endpoints), color_endpoint_quality)), 32, basisu_frontend::cMaxEndpointClusters);
  1841. }
  1842. else
  1843. {
  1844. color_endpoint_quality = powf((color_endpoint_quality - mid) / (1.0f - mid), 1.6f);
  1845. max_endpoints = clamp<int>(max_endpoints, 256, MAX_ENDPOINT_CODEBOOK_SIZE);
  1846. max_endpoints = minimum<uint32_t>(max_endpoints, m_total_blocks);
  1847. if (max_endpoints < ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE)
  1848. max_endpoints = ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE;
  1849. endpoint_clusters = clamp<uint32_t>((uint32_t)(.5f + lerp<float>(ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE, static_cast<float>(max_endpoints), color_endpoint_quality)), 32, basisu_frontend::cMaxEndpointClusters);
  1850. }
  1851. float bits_per_selector_cluster = 14.0f;
  1852. const float max_desired_selector_cluster_bits_per_texel = 1.0f; // .15f
  1853. int max_selectors = static_cast<int>((max_desired_selector_cluster_bits_per_texel * total_texels) / bits_per_selector_cluster);
  1854. max_selectors = clamp<int>(max_selectors, 256, basisu_frontend::cMaxSelectorClusters);
  1855. max_selectors = minimum<uint32_t>(max_selectors, m_total_blocks);
  1856. float color_selector_quality = quality;
  1857. //color_selector_quality = powf(color_selector_quality, 1.65f);
  1858. color_selector_quality = powf(color_selector_quality, 2.62f);
  1859. if (max_selectors < 96)
  1860. max_selectors = 96;
  1861. selector_clusters = clamp<uint32_t>((uint32_t)(.5f + lerp<float>(96, static_cast<float>(max_selectors), color_selector_quality)), 8, basisu_frontend::cMaxSelectorClusters);
  1862. debug_printf("Max endpoints: %u, max selectors: %u\n", endpoint_clusters, selector_clusters);
  1863. if (m_params.m_etc1s_quality_level >= 223)
  1864. {
  1865. if (!m_params.m_selector_rdo_thresh.was_changed())
  1866. {
  1867. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  1868. m_params.m_endpoint_rdo_thresh *= .25f;
  1869. if (!m_params.m_selector_rdo_thresh.was_changed())
  1870. m_params.m_selector_rdo_thresh *= .25f;
  1871. }
  1872. }
  1873. else if (m_params.m_etc1s_quality_level >= 192)
  1874. {
  1875. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  1876. m_params.m_endpoint_rdo_thresh *= .5f;
  1877. if (!m_params.m_selector_rdo_thresh.was_changed())
  1878. m_params.m_selector_rdo_thresh *= .5f;
  1879. }
  1880. else if (m_params.m_etc1s_quality_level >= 160)
  1881. {
  1882. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  1883. m_params.m_endpoint_rdo_thresh *= .75f;
  1884. if (!m_params.m_selector_rdo_thresh.was_changed())
  1885. m_params.m_selector_rdo_thresh *= .75f;
  1886. }
  1887. else if (m_params.m_etc1s_quality_level >= 129)
  1888. {
  1889. float l = (quality - 129 / 255.0f) / ((160 - 129) / 255.0f);
  1890. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  1891. m_params.m_endpoint_rdo_thresh *= lerp<float>(1.0f, .75f, l);
  1892. if (!m_params.m_selector_rdo_thresh.was_changed())
  1893. m_params.m_selector_rdo_thresh *= lerp<float>(1.0f, .75f, l);
  1894. }
  1895. }
  1896. basisu_frontend::params p;
  1897. p.m_num_source_blocks = m_total_blocks;
  1898. p.m_pSource_blocks = &m_source_blocks[0];
  1899. p.m_max_endpoint_clusters = endpoint_clusters;
  1900. p.m_max_selector_clusters = selector_clusters;
  1901. p.m_perceptual = m_params.m_perceptual;
  1902. p.m_debug_stats = m_params.m_debug;
  1903. p.m_debug_images = m_params.m_debug_images;
  1904. p.m_compression_level = m_params.m_compression_level;
  1905. p.m_tex_type = m_params.m_tex_type;
  1906. p.m_multithreaded = m_params.m_multithreading;
  1907. p.m_disable_hierarchical_endpoint_codebooks = m_params.m_disable_hierarchical_endpoint_codebooks;
  1908. p.m_validate = m_params.m_validate_etc1s;
  1909. p.m_pJob_pool = m_params.m_pJob_pool;
  1910. p.m_pGlobal_codebooks = m_params.m_pGlobal_codebooks;
  1911. // Don't keep trying to use OpenCL if it ever fails.
  1912. p.m_pOpenCL_context = !m_opencl_failed ? m_pOpenCL_context : nullptr;
  1913. if (!m_frontend.init(p))
  1914. {
  1915. error_printf("basisu_frontend::init() failed!\n");
  1916. return false;
  1917. }
  1918. m_frontend.compress();
  1919. if (m_frontend.get_opencl_failed())
  1920. m_opencl_failed = true;
  1921. if (m_params.m_debug_images)
  1922. {
  1923. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1924. {
  1925. char filename[1024];
  1926. #ifdef _WIN32
  1927. sprintf_s(filename, sizeof(filename), "rdo_frontend_output_output_blocks_%u.png", i);
  1928. #else
  1929. snprintf(filename, sizeof(filename), "rdo_frontend_output_output_blocks_%u.png", i);
  1930. #endif
  1931. m_frontend.dump_debug_image(filename, m_slice_descs[i].m_first_block_index, m_slice_descs[i].m_num_blocks_x, m_slice_descs[i].m_num_blocks_y, true);
  1932. #ifdef _WIN32
  1933. sprintf_s(filename, sizeof(filename), "rdo_frontend_output_api_%u.png", i);
  1934. #else
  1935. snprintf(filename, sizeof(filename), "rdo_frontend_output_api_%u.png", i);
  1936. #endif
  1937. m_frontend.dump_debug_image(filename, m_slice_descs[i].m_first_block_index, m_slice_descs[i].m_num_blocks_x, m_slice_descs[i].m_num_blocks_y, false);
  1938. }
  1939. }
  1940. return true;
  1941. }
  1942. bool basis_compressor::extract_frontend_texture_data()
  1943. {
  1944. if (!m_params.m_compute_stats)
  1945. return true;
  1946. debug_printf("basis_compressor::extract_frontend_texture_data\n");
  1947. m_frontend_output_textures.resize(m_slice_descs.size());
  1948. m_best_etc1s_images.resize(m_slice_descs.size());
  1949. m_best_etc1s_images_unpacked.resize(m_slice_descs.size());
  1950. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1951. {
  1952. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  1953. const uint32_t num_blocks_x = slice_desc.m_num_blocks_x;
  1954. const uint32_t num_blocks_y = slice_desc.m_num_blocks_y;
  1955. const uint32_t width = num_blocks_x * 4;
  1956. const uint32_t height = num_blocks_y * 4;
  1957. m_frontend_output_textures[i].init(texture_format::cETC1, width, height);
  1958. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  1959. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  1960. memcpy(m_frontend_output_textures[i].get_block_ptr(block_x, block_y, 0), &m_frontend.get_output_block(slice_desc.m_first_block_index + block_x + block_y * num_blocks_x), sizeof(etc_block));
  1961. #if 0
  1962. if (m_params.m_debug_images)
  1963. {
  1964. char filename[1024];
  1965. sprintf_s(filename, sizeof(filename), "rdo_etc_frontend_%u_", i);
  1966. write_etc1_vis_images(m_frontend_output_textures[i], filename);
  1967. }
  1968. #endif
  1969. m_best_etc1s_images[i].init(texture_format::cETC1, width, height);
  1970. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  1971. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  1972. memcpy(m_best_etc1s_images[i].get_block_ptr(block_x, block_y, 0), &m_frontend.get_etc1s_block(slice_desc.m_first_block_index + block_x + block_y * num_blocks_x), sizeof(etc_block));
  1973. m_best_etc1s_images[i].unpack(m_best_etc1s_images_unpacked[i]);
  1974. }
  1975. return true;
  1976. }
  1977. bool basis_compressor::process_backend()
  1978. {
  1979. debug_printf("basis_compressor::process_backend\n");
  1980. basisu_backend_params backend_params;
  1981. backend_params.m_debug = m_params.m_debug;
  1982. backend_params.m_debug_images = m_params.m_debug_images;
  1983. backend_params.m_etc1s = true;
  1984. backend_params.m_compression_level = m_params.m_compression_level;
  1985. if (!m_params.m_no_endpoint_rdo)
  1986. backend_params.m_endpoint_rdo_quality_thresh = m_params.m_endpoint_rdo_thresh;
  1987. if (!m_params.m_no_selector_rdo)
  1988. backend_params.m_selector_rdo_quality_thresh = m_params.m_selector_rdo_thresh;
  1989. backend_params.m_used_global_codebooks = m_frontend.get_params().m_pGlobal_codebooks != nullptr;
  1990. backend_params.m_validate = m_params.m_validate_output_data;
  1991. m_backend.init(&m_frontend, backend_params, m_slice_descs);
  1992. uint32_t total_packed_bytes = m_backend.encode();
  1993. if (!total_packed_bytes)
  1994. {
  1995. error_printf("basis_compressor::encode() failed!\n");
  1996. return false;
  1997. }
  1998. debug_printf("Total packed bytes (estimated): %u\n", total_packed_bytes);
  1999. return true;
  2000. }
  2001. bool basis_compressor::create_basis_file_and_transcode()
  2002. {
  2003. debug_printf("basis_compressor::create_basis_file_and_transcode\n");
  2004. const basisu_backend_output& encoded_output = m_params.m_uastc ? m_uastc_backend_output : m_backend.get_output();
  2005. if (!m_basis_file.init(encoded_output, m_params.m_tex_type, m_params.m_userdata0, m_params.m_userdata1, m_params.m_y_flip, m_params.m_us_per_frame))
  2006. {
  2007. error_printf("basis_compressor::create_basis_file_and_transcode: basisu_backend:init() failed!\n");
  2008. return false;
  2009. }
  2010. const uint8_vec& comp_data = m_basis_file.get_compressed_data();
  2011. m_output_basis_file = comp_data;
  2012. uint32_t total_orig_pixels = 0;
  2013. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2014. {
  2015. const basisu_backend_slice_desc& slice_desc = m_slice_descs[i];
  2016. total_orig_pixels += slice_desc.m_orig_width * slice_desc.m_orig_height;
  2017. }
  2018. m_basis_file_size = (uint32_t)comp_data.size();
  2019. m_basis_bits_per_texel = total_orig_pixels ? (comp_data.size() * 8.0f) / total_orig_pixels : 0;
  2020. debug_printf("Total .basis output file size: %u, %3.3f bits/texel\n", comp_data.size(), comp_data.size() * 8.0f / total_orig_pixels);
  2021. // HDR 6x6 TODO
  2022. // HACK HACK
  2023. const bool is_hdr_6x6 = m_params.m_hdr && (m_params.m_hdr_mode != hdr_modes::cUASTC_HDR_4X4);
  2024. if (m_params.m_validate_output_data)
  2025. {
  2026. interval_timer tm;
  2027. tm.start();
  2028. basist::basisu_transcoder_init();
  2029. debug_printf("basist::basisu_transcoder_init: Took %f ms\n", tm.get_elapsed_ms());
  2030. // Verify the compressed data by transcoding it to ASTC (or ETC1)/BC7 and validating the CRC's.
  2031. basist::basisu_transcoder decoder;
  2032. if (!decoder.validate_file_checksums(&comp_data[0], (uint32_t)comp_data.size(), true))
  2033. {
  2034. error_printf("decoder.validate_file_checksums() failed!\n");
  2035. return false;
  2036. }
  2037. m_decoded_output_textures.resize(m_slice_descs.size());
  2038. if (m_params.m_hdr)
  2039. {
  2040. m_decoded_output_textures_bc6h_hdr_unpacked.resize(m_slice_descs.size());
  2041. m_decoded_output_textures_astc_hdr.resize(m_slice_descs.size());
  2042. m_decoded_output_textures_astc_hdr_unpacked.resize(m_slice_descs.size());
  2043. }
  2044. else
  2045. {
  2046. m_decoded_output_textures_unpacked.resize(m_slice_descs.size());
  2047. m_decoded_output_textures_bc7.resize(m_slice_descs.size());
  2048. m_decoded_output_textures_unpacked_bc7.resize(m_slice_descs.size());
  2049. }
  2050. tm.start();
  2051. if (m_params.m_pGlobal_codebooks)
  2052. {
  2053. decoder.set_global_codebooks(m_params.m_pGlobal_codebooks);
  2054. }
  2055. if (!decoder.start_transcoding(&comp_data[0], (uint32_t)comp_data.size()))
  2056. {
  2057. error_printf("decoder.start_transcoding() failed!\n");
  2058. return false;
  2059. }
  2060. double start_transcoding_time = tm.get_elapsed_secs();
  2061. debug_printf("basisu_compressor::start_transcoding() took %3.3fms\n", start_transcoding_time * 1000.0f);
  2062. double total_time_etc1s_or_astc = 0;
  2063. for (uint32_t slice_iter = 0; slice_iter < m_slice_descs.size(); slice_iter++)
  2064. {
  2065. // Select either BC6H, UASTC LDR 4x4, or ETC1
  2066. basisu::texture_format tex_format = m_params.m_hdr ? texture_format::cBC6HUnsigned : (m_params.m_uastc ? texture_format::cUASTC4x4 : texture_format::cETC1);
  2067. basist::block_format blk_format = m_params.m_hdr ? basist::block_format::cBC6H : (m_params.m_uastc ? basist::block_format::cUASTC_4x4 : basist::block_format::cETC1);
  2068. gpu_image decoded_texture;
  2069. decoded_texture.init(
  2070. tex_format,
  2071. m_slice_descs[slice_iter].m_width, m_slice_descs[slice_iter].m_height);
  2072. tm.start();
  2073. const uint32_t block_size_x = basisu::get_block_width(tex_format);
  2074. const uint32_t block_size_y = basisu::get_block_height(tex_format);
  2075. const uint32_t num_dst_blocks_x = (m_slice_descs[slice_iter].m_orig_width + block_size_x - 1) / block_size_x;
  2076. const uint32_t num_dst_blocks_y = (m_slice_descs[slice_iter].m_orig_height + block_size_y - 1) / block_size_y;
  2077. const uint32_t total_dst_blocks = num_dst_blocks_x * num_dst_blocks_y;
  2078. uint32_t bytes_per_block = m_params.m_uastc ? 16 : 8;
  2079. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), slice_iter,
  2080. reinterpret_cast<etc_block*>(decoded_texture.get_ptr()), total_dst_blocks, blk_format, bytes_per_block))
  2081. {
  2082. error_printf("Transcoding failed on slice %u!\n", slice_iter);
  2083. return false;
  2084. }
  2085. total_time_etc1s_or_astc += tm.get_elapsed_secs();
  2086. if (encoded_output.m_tex_format == basist::basis_tex_format::cETC1S)
  2087. {
  2088. uint32_t image_crc16 = basist::crc16(decoded_texture.get_ptr(), decoded_texture.get_size_in_bytes(), 0);
  2089. if (image_crc16 != encoded_output.m_slice_image_crcs[slice_iter])
  2090. {
  2091. error_printf("Decoded image data CRC check failed on slice %u!\n", slice_iter);
  2092. return false;
  2093. }
  2094. debug_printf("Decoded image data CRC check succeeded on slice %i\n", slice_iter);
  2095. }
  2096. m_decoded_output_textures[slice_iter] = decoded_texture;
  2097. }
  2098. double total_alt_transcode_time = 0;
  2099. tm.start();
  2100. if (m_params.m_hdr)
  2101. {
  2102. if (is_hdr_6x6)
  2103. {
  2104. assert(basist::basis_is_format_supported(basist::transcoder_texture_format::cTFASTC_HDR_6x6_RGBA, basist::basis_tex_format::cASTC_HDR_6x6));
  2105. assert(basist::basis_is_format_supported(basist::transcoder_texture_format::cTFASTC_HDR_6x6_RGBA, basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE));
  2106. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2107. {
  2108. gpu_image decoded_texture;
  2109. decoded_texture.init(texture_format::cASTC_HDR_6x6, m_slice_descs[i].m_width, m_slice_descs[i].m_height);
  2110. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), i,
  2111. reinterpret_cast<basist::astc_blk*>(decoded_texture.get_ptr()), m_slice_descs[i].m_num_blocks_x * m_slice_descs[i].m_num_blocks_y, basist::block_format::cASTC_HDR_6x6, 16))
  2112. {
  2113. error_printf("Transcoding failed to ASTC HDR on slice %u!\n", i);
  2114. return false;
  2115. }
  2116. m_decoded_output_textures_astc_hdr[i] = decoded_texture;
  2117. }
  2118. }
  2119. else
  2120. {
  2121. assert(basist::basis_is_format_supported(basist::transcoder_texture_format::cTFASTC_HDR_4x4_RGBA, basist::basis_tex_format::cUASTC_HDR_4x4));
  2122. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2123. {
  2124. gpu_image decoded_texture;
  2125. decoded_texture.init(texture_format::cASTC_HDR_4x4, m_slice_descs[i].m_width, m_slice_descs[i].m_height);
  2126. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), i,
  2127. reinterpret_cast<basist::astc_blk*>(decoded_texture.get_ptr()), m_slice_descs[i].m_num_blocks_x * m_slice_descs[i].m_num_blocks_y, basist::block_format::cASTC_HDR_4x4, 16))
  2128. {
  2129. error_printf("Transcoding failed to ASTC HDR on slice %u!\n", i);
  2130. return false;
  2131. }
  2132. m_decoded_output_textures_astc_hdr[i] = decoded_texture;
  2133. }
  2134. }
  2135. }
  2136. else
  2137. {
  2138. if (basist::basis_is_format_supported(basist::transcoder_texture_format::cTFBC7_RGBA, basist::basis_tex_format::cUASTC4x4) &&
  2139. basist::basis_is_format_supported(basist::transcoder_texture_format::cTFBC7_RGBA, basist::basis_tex_format::cETC1S))
  2140. {
  2141. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2142. {
  2143. gpu_image decoded_texture;
  2144. decoded_texture.init(texture_format::cBC7, m_slice_descs[i].m_width, m_slice_descs[i].m_height);
  2145. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), i,
  2146. reinterpret_cast<etc_block*>(decoded_texture.get_ptr()), m_slice_descs[i].m_num_blocks_x * m_slice_descs[i].m_num_blocks_y, basist::block_format::cBC7, 16))
  2147. {
  2148. error_printf("Transcoding failed to BC7 on slice %u!\n", i);
  2149. return false;
  2150. }
  2151. m_decoded_output_textures_bc7[i] = decoded_texture;
  2152. }
  2153. }
  2154. }
  2155. total_alt_transcode_time = tm.get_elapsed_secs();
  2156. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2157. {
  2158. if (m_params.m_hdr)
  2159. {
  2160. // BC6H
  2161. bool status = m_decoded_output_textures[i].unpack_hdr(m_decoded_output_textures_bc6h_hdr_unpacked[i]);
  2162. assert(status);
  2163. BASISU_NOTE_UNUSED(status);
  2164. // ASTC HDR
  2165. status = m_decoded_output_textures_astc_hdr[i].unpack_hdr(m_decoded_output_textures_astc_hdr_unpacked[i]);
  2166. assert(status);
  2167. }
  2168. else
  2169. {
  2170. bool status = m_decoded_output_textures[i].unpack(m_decoded_output_textures_unpacked[i]);
  2171. assert(status);
  2172. BASISU_NOTE_UNUSED(status);
  2173. if (m_decoded_output_textures_bc7[i].get_pixel_width())
  2174. {
  2175. status = m_decoded_output_textures_bc7[i].unpack(m_decoded_output_textures_unpacked_bc7[i]);
  2176. assert(status);
  2177. }
  2178. }
  2179. }
  2180. debug_printf("Transcoded to %s in %3.3fms, %f texels/sec\n",
  2181. m_params.m_hdr ? "BC6H" : (m_params.m_uastc ? "ASTC" : "ETC1"),
  2182. total_time_etc1s_or_astc * 1000.0f, total_orig_pixels / total_time_etc1s_or_astc);
  2183. if (total_alt_transcode_time != 0)
  2184. debug_printf("Alternate transcode in %3.3fms, %f texels/sec\n", total_alt_transcode_time * 1000.0f, total_orig_pixels / total_alt_transcode_time);
  2185. if (!is_hdr_6x6)
  2186. {
  2187. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2188. {
  2189. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2190. const uint32_t total_blocks = slice_desc.m_num_blocks_x * slice_desc.m_num_blocks_y;
  2191. BASISU_NOTE_UNUSED(total_blocks);
  2192. assert(m_decoded_output_textures[slice_index].get_total_blocks() == total_blocks);
  2193. }
  2194. }
  2195. } // if (m_params.m_validate_output_data)
  2196. return true;
  2197. }
  2198. bool basis_compressor::write_hdr_debug_images(const char* pBasename, const imagef& orig_hdr_img, uint32_t width, uint32_t height)
  2199. {
  2200. // Copy image to account for 4x4 block expansion
  2201. imagef hdr_img(orig_hdr_img);
  2202. hdr_img.resize(width, height);
  2203. image srgb_img(width, height);
  2204. const float inv_upconversion_scale = (m_ldr_to_hdr_upconversion_nit_multiplier > 0.0f) ? (1.0f / m_ldr_to_hdr_upconversion_nit_multiplier) : 1.0f;
  2205. for (uint32_t y = 0; y < height; y++)
  2206. {
  2207. for (uint32_t x = 0; x < width; x++)
  2208. {
  2209. vec4F p(hdr_img(x, y));
  2210. p[0] = clamp(p[0] * inv_upconversion_scale, 0.0f, 1.0f);
  2211. p[1] = clamp(p[1] * inv_upconversion_scale, 0.0f, 1.0f);
  2212. p[2] = clamp(p[2] * inv_upconversion_scale, 0.0f, 1.0f);
  2213. int rc = (int)std::round(linear_to_srgb(p[0]) * 255.0f);
  2214. int gc = (int)std::round(linear_to_srgb(p[1]) * 255.0f);
  2215. int bc = (int)std::round(linear_to_srgb(p[2]) * 255.0f);
  2216. srgb_img.set_clipped(x, y, color_rgba(rc, gc, bc, 255));
  2217. }
  2218. }
  2219. {
  2220. const std::string filename(string_format("%s_linear_clamped_to_srgb.png", pBasename));
  2221. save_png(filename.c_str(), srgb_img);
  2222. printf("Wrote .PNG file %s\n", filename.c_str());
  2223. }
  2224. {
  2225. const std::string filename(string_format("%s_compressive_tonemapped.png", pBasename));
  2226. image compressive_tonemapped_img;
  2227. bool status = tonemap_image_compressive(compressive_tonemapped_img, hdr_img);
  2228. if (!status)
  2229. {
  2230. error_printf("basis_compressor::write_hdr_debug_images: tonemap_image_compressive() failed (invalid half-float input)\n");
  2231. }
  2232. else
  2233. {
  2234. save_png(filename.c_str(), compressive_tonemapped_img);
  2235. printf("Wrote .PNG file %s\n", filename.c_str());
  2236. }
  2237. }
  2238. image tonemapped_img;
  2239. for (int e = -5; e <= 5; e++)
  2240. {
  2241. const float scale = powf(2.0f, (float)e);
  2242. tonemap_image_reinhard(tonemapped_img, hdr_img, scale);
  2243. std::string filename(string_format("%s_reinhard_tonemapped_scale_%f.png", pBasename, scale));
  2244. save_png(filename.c_str(), tonemapped_img, cImageSaveIgnoreAlpha);
  2245. printf("Wrote .PNG file %s\n", filename.c_str());
  2246. }
  2247. return true;
  2248. }
  2249. bool basis_compressor::write_output_files_and_compute_stats()
  2250. {
  2251. debug_printf("basis_compressor::write_output_files_and_compute_stats\n");
  2252. const uint8_vec& comp_data = m_params.m_create_ktx2_file ? m_output_ktx2_file : m_basis_file.get_compressed_data();
  2253. if (m_params.m_write_output_basis_or_ktx2_files)
  2254. {
  2255. const std::string& output_filename = m_params.m_out_filename;
  2256. if (!write_vec_to_file(output_filename.c_str(), comp_data))
  2257. {
  2258. error_printf("Failed writing output data to file \"%s\"\n", output_filename.c_str());
  2259. return false;
  2260. }
  2261. if (m_params.m_status_output)
  2262. {
  2263. printf("Wrote output .basis/.ktx2 file \"%s\"\n", output_filename.c_str());
  2264. }
  2265. }
  2266. size_t comp_size = 0;
  2267. if ((m_params.m_compute_stats) && (m_params.m_uastc) && (comp_data.size()))
  2268. {
  2269. void* pComp_data = tdefl_compress_mem_to_heap(&comp_data[0], comp_data.size(), &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
  2270. size_t decomp_size = 0;
  2271. void* pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, comp_size, &decomp_size, 0);
  2272. if ((decomp_size != comp_data.size()) || (memcmp(pDecomp_data, &comp_data[0], decomp_size) != 0))
  2273. {
  2274. printf("basis_compressor::create_basis_file_and_transcode:: miniz compression or decompression failed!\n");
  2275. return false;
  2276. }
  2277. mz_free(pComp_data);
  2278. mz_free(pDecomp_data);
  2279. uint32_t total_texels = 0;
  2280. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2281. total_texels += (m_slice_descs[i].m_orig_width * m_slice_descs[i].m_orig_height);
  2282. m_basis_bits_per_texel = ((float)comp_size * 8.0f) / total_texels;
  2283. fmt_debug_printf("Output file size: {}, {3.2} bits/texel, LZ compressed file size: {}, {3.2} bits/texel\n",
  2284. (uint64_t)comp_data.size(), ((float)comp_data.size() * 8.0f) / total_texels,
  2285. (uint64_t)comp_size, m_basis_bits_per_texel);
  2286. }
  2287. m_stats.resize(m_slice_descs.size());
  2288. if (m_params.m_validate_output_data)
  2289. {
  2290. if (m_params.m_hdr)
  2291. {
  2292. if (m_params.m_print_stats)
  2293. {
  2294. printf("ASTC/BC6H half float space error metrics (a piecewise linear approximation of log2 error):\n");
  2295. }
  2296. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2297. {
  2298. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2299. if (m_params.m_compute_stats)
  2300. {
  2301. image_stats& s = m_stats[slice_index];
  2302. if (m_params.m_print_stats)
  2303. {
  2304. printf("Slice: %u\n", slice_index);
  2305. }
  2306. image_metrics im;
  2307. if (m_params.m_print_stats)
  2308. {
  2309. printf("\nASTC channels:\n");
  2310. for (uint32_t i = 0; i < 3; i++)
  2311. {
  2312. im.calc_half(m_slice_images_hdr[slice_index], m_decoded_output_textures_astc_hdr_unpacked[slice_index], i, 1, true);
  2313. printf("%c: ", "RGB"[i]);
  2314. im.print_hp();
  2315. }
  2316. printf("BC6H channels:\n");
  2317. for (uint32_t i = 0; i < 3; i++)
  2318. {
  2319. im.calc_half(m_slice_images_hdr[slice_index], m_decoded_output_textures_bc6h_hdr_unpacked[slice_index], i, 1, true);
  2320. printf("%c: ", "RGB"[i]);
  2321. im.print_hp();
  2322. }
  2323. }
  2324. im.calc_half(m_slice_images_hdr[slice_index], m_decoded_output_textures_astc_hdr_unpacked[slice_index], 0, 3, true);
  2325. s.m_basis_rgb_avg_psnr = (float)im.m_psnr;
  2326. if (m_params.m_print_stats)
  2327. {
  2328. printf("\nASTC RGB: ");
  2329. im.print_hp();
  2330. #if 0
  2331. // Validation
  2332. im.calc_half2(m_slice_images_hdr[slice_index], m_decoded_output_textures_astc_hdr_unpacked[slice_index], 0, 3, true);
  2333. printf("\nASTC RGB (Alt): ");
  2334. im.print_hp();
  2335. #endif
  2336. }
  2337. im.calc_half(m_slice_images_hdr[slice_index], m_decoded_output_textures_bc6h_hdr_unpacked[slice_index], 0, 3, true);
  2338. s.m_basis_rgb_avg_bc6h_psnr = (float)im.m_psnr;
  2339. if (m_params.m_print_stats)
  2340. {
  2341. printf("BC6H RGB: ");
  2342. im.print_hp();
  2343. //printf("\n");
  2344. }
  2345. im.calc(m_slice_images_hdr[slice_index], m_decoded_output_textures_astc_hdr_unpacked[slice_index], 0, 3, true, true);
  2346. s.m_basis_rgb_avg_log2_psnr = (float)im.m_psnr;
  2347. if (m_params.m_print_stats)
  2348. {
  2349. printf("\nASTC Log2 RGB: ");
  2350. im.print_hp();
  2351. }
  2352. im.calc(m_slice_images_hdr[slice_index], m_decoded_output_textures_bc6h_hdr_unpacked[slice_index], 0, 3, true, true);
  2353. s.m_basis_rgb_avg_bc6h_log2_psnr = (float)im.m_psnr;
  2354. if (m_params.m_print_stats)
  2355. {
  2356. printf("BC6H Log2 RGB: ");
  2357. im.print_hp();
  2358. printf("\n");
  2359. }
  2360. }
  2361. if (m_params.m_debug_images)
  2362. {
  2363. std::string out_basename;
  2364. if (m_params.m_out_filename.size())
  2365. string_get_filename(m_params.m_out_filename.c_str(), out_basename);
  2366. else if (m_params.m_source_filenames.size())
  2367. string_get_filename(m_params.m_source_filenames[slice_desc.m_source_file_index].c_str(), out_basename);
  2368. string_remove_extension(out_basename);
  2369. out_basename = "basis_debug_" + out_basename + string_format("_slice_%u", slice_index);
  2370. // Write BC6H .DDS file.
  2371. {
  2372. gpu_image bc6h_tex(m_decoded_output_textures[slice_index]);
  2373. bc6h_tex.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2374. std::string filename(out_basename + "_bc6h.dds");
  2375. write_compressed_texture_file(filename.c_str(), bc6h_tex, true);
  2376. printf("Wrote .DDS file %s\n", filename.c_str());
  2377. }
  2378. // Write ASTC .KTX/.astc files. ("astcenc -dh input.astc output.exr" to decode the astc file.)
  2379. {
  2380. gpu_image astc_tex(m_decoded_output_textures_astc_hdr[slice_index]);
  2381. astc_tex.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2382. std::string filename1(out_basename + "_astc.astc");
  2383. uint32_t block_width = 4, block_height = 4;
  2384. if ((m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6) || (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE))
  2385. {
  2386. block_width = 6;
  2387. block_height = 6;
  2388. }
  2389. write_astc_file(filename1.c_str(), astc_tex.get_ptr(), block_width, block_height, slice_desc.m_orig_width, slice_desc.m_orig_height);
  2390. printf("Wrote .ASTC file %s\n", filename1.c_str());
  2391. std::string filename2(out_basename + "_astc.ktx");
  2392. write_compressed_texture_file(filename2.c_str(), astc_tex, true);
  2393. printf("Wrote .KTX file %s\n", filename2.c_str());
  2394. }
  2395. // Write unpacked ASTC image to .EXR
  2396. {
  2397. imagef astc_img(m_decoded_output_textures_astc_hdr_unpacked[slice_index]);
  2398. astc_img.resize(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2399. std::string filename(out_basename + "_unpacked_astc.exr");
  2400. write_exr(filename.c_str(), astc_img, 3, 0);
  2401. printf("Wrote .EXR file %s\n", filename.c_str());
  2402. }
  2403. // Write unpacked BC6H image to .EXR
  2404. {
  2405. imagef bc6h_img(m_decoded_output_textures_bc6h_hdr_unpacked[slice_index]);
  2406. bc6h_img.resize(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2407. std::string filename(out_basename + "_unpacked_bc6h.exr");
  2408. write_exr(filename.c_str(), bc6h_img, 3, 0);
  2409. printf("Wrote .EXR file %s\n", filename.c_str());
  2410. }
  2411. // Write tonemapped/srgb images
  2412. write_hdr_debug_images((out_basename + "_source").c_str(), m_slice_images_hdr[slice_index], slice_desc.m_orig_width, slice_desc.m_orig_height);
  2413. write_hdr_debug_images((out_basename + "_unpacked_astc").c_str(), m_decoded_output_textures_astc_hdr_unpacked[slice_index], slice_desc.m_orig_width, slice_desc.m_orig_height);
  2414. write_hdr_debug_images((out_basename + "_unpacked_bc6h").c_str(), m_decoded_output_textures_bc6h_hdr_unpacked[slice_index], slice_desc.m_orig_width, slice_desc.m_orig_height);
  2415. }
  2416. }
  2417. }
  2418. else
  2419. {
  2420. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2421. {
  2422. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2423. if (m_params.m_compute_stats)
  2424. {
  2425. if (m_params.m_print_stats)
  2426. printf("Slice: %u\n", slice_index);
  2427. image_stats& s = m_stats[slice_index];
  2428. image_metrics em;
  2429. // ---- .basis stats
  2430. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 3);
  2431. if (m_params.m_print_stats)
  2432. em.print(".basis RGB Avg: ");
  2433. s.m_basis_rgb_avg_psnr = (float)em.m_psnr;
  2434. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 4);
  2435. if (m_params.m_print_stats)
  2436. em.print(".basis RGBA Avg: ");
  2437. s.m_basis_rgba_avg_psnr = (float)em.m_psnr;
  2438. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 1);
  2439. if (m_params.m_print_stats)
  2440. em.print(".basis R Avg: ");
  2441. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 1, 1);
  2442. if (m_params.m_print_stats)
  2443. em.print(".basis G Avg: ");
  2444. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 2, 1);
  2445. if (m_params.m_print_stats)
  2446. em.print(".basis B Avg: ");
  2447. if (m_params.m_uastc)
  2448. {
  2449. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 3, 1);
  2450. if (m_params.m_print_stats)
  2451. em.print(".basis A Avg: ");
  2452. s.m_basis_a_avg_psnr = (float)em.m_psnr;
  2453. }
  2454. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0);
  2455. if (m_params.m_print_stats)
  2456. em.print(".basis 709 Luma: ");
  2457. s.m_basis_luma_709_psnr = static_cast<float>(em.m_psnr);
  2458. s.m_basis_luma_709_ssim = static_cast<float>(em.m_ssim);
  2459. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0, true, true);
  2460. if (m_params.m_print_stats)
  2461. em.print(".basis 601 Luma: ");
  2462. s.m_basis_luma_601_psnr = static_cast<float>(em.m_psnr);
  2463. if (m_slice_descs.size() == 1)
  2464. {
  2465. const uint32_t output_size = comp_size ? (uint32_t)comp_size : (uint32_t)comp_data.size();
  2466. if (m_params.m_print_stats)
  2467. {
  2468. debug_printf(".basis RGB PSNR per bit/texel*10000: %3.3f\n", 10000.0f * s.m_basis_rgb_avg_psnr / ((output_size * 8.0f) / (slice_desc.m_orig_width * slice_desc.m_orig_height)));
  2469. debug_printf(".basis Luma 709 PSNR per bit/texel*10000: %3.3f\n", 10000.0f * s.m_basis_luma_709_psnr / ((output_size * 8.0f) / (slice_desc.m_orig_width * slice_desc.m_orig_height)));
  2470. }
  2471. }
  2472. if (m_decoded_output_textures_unpacked_bc7[slice_index].get_width())
  2473. {
  2474. // ---- BC7 stats
  2475. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 3);
  2476. //if (m_params.m_print_stats)
  2477. // em.print("BC7 RGB Avg: ");
  2478. s.m_bc7_rgb_avg_psnr = (float)em.m_psnr;
  2479. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 4);
  2480. //if (m_params.m_print_stats)
  2481. // em.print("BC7 RGBA Avg: ");
  2482. s.m_bc7_rgba_avg_psnr = (float)em.m_psnr;
  2483. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 1);
  2484. //if (m_params.m_print_stats)
  2485. // em.print("BC7 R Avg: ");
  2486. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 1, 1);
  2487. //if (m_params.m_print_stats)
  2488. // em.print("BC7 G Avg: ");
  2489. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 2, 1);
  2490. //if (m_params.m_print_stats)
  2491. // em.print("BC7 B Avg: ");
  2492. if (m_params.m_uastc)
  2493. {
  2494. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 3, 1);
  2495. //if (m_params.m_print_stats)
  2496. // em.print("BC7 A Avg: ");
  2497. s.m_bc7_a_avg_psnr = (float)em.m_psnr;
  2498. }
  2499. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0);
  2500. //if (m_params.m_print_stats)
  2501. // em.print("BC7 709 Luma: ");
  2502. s.m_bc7_luma_709_psnr = static_cast<float>(em.m_psnr);
  2503. s.m_bc7_luma_709_ssim = static_cast<float>(em.m_ssim);
  2504. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0, true, true);
  2505. //if (m_params.m_print_stats)
  2506. // em.print("BC7 601 Luma: ");
  2507. s.m_bc7_luma_601_psnr = static_cast<float>(em.m_psnr);
  2508. }
  2509. if (!m_params.m_uastc)
  2510. {
  2511. // ---- Nearly best possible ETC1S stats
  2512. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 3);
  2513. //if (m_params.m_print_stats)
  2514. // em.print("Unquantized ETC1S RGB Avg: ");
  2515. s.m_best_etc1s_rgb_avg_psnr = static_cast<float>(em.m_psnr);
  2516. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0);
  2517. //if (m_params.m_print_stats)
  2518. // em.print("Unquantized ETC1S 709 Luma: ");
  2519. s.m_best_etc1s_luma_709_psnr = static_cast<float>(em.m_psnr);
  2520. s.m_best_etc1s_luma_709_ssim = static_cast<float>(em.m_ssim);
  2521. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0, true, true);
  2522. //if (m_params.m_print_stats)
  2523. // em.print("Unquantized ETC1S 601 Luma: ");
  2524. s.m_best_etc1s_luma_601_psnr = static_cast<float>(em.m_psnr);
  2525. }
  2526. }
  2527. std::string out_basename;
  2528. if (m_params.m_out_filename.size())
  2529. string_get_filename(m_params.m_out_filename.c_str(), out_basename);
  2530. else if (m_params.m_source_filenames.size())
  2531. string_get_filename(m_params.m_source_filenames[slice_desc.m_source_file_index].c_str(), out_basename);
  2532. string_remove_extension(out_basename);
  2533. out_basename = "basis_debug_" + out_basename + string_format("_slice_%u", slice_index);
  2534. if ((!m_params.m_uastc) && (m_frontend.get_params().m_debug_images))
  2535. {
  2536. // Write "best" ETC1S debug images
  2537. if (!m_params.m_uastc)
  2538. {
  2539. gpu_image best_etc1s_gpu_image(m_best_etc1s_images[slice_index]);
  2540. best_etc1s_gpu_image.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2541. write_compressed_texture_file((out_basename + "_best_etc1s.ktx").c_str(), best_etc1s_gpu_image, true);
  2542. image best_etc1s_unpacked;
  2543. best_etc1s_gpu_image.unpack(best_etc1s_unpacked);
  2544. save_png(out_basename + "_best_etc1s.png", best_etc1s_unpacked);
  2545. }
  2546. }
  2547. if (m_params.m_debug_images)
  2548. {
  2549. // Write decoded ETC1S/ASTC debug images
  2550. {
  2551. gpu_image decoded_etc1s_or_astc(m_decoded_output_textures[slice_index]);
  2552. decoded_etc1s_or_astc.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2553. write_compressed_texture_file((out_basename + "_transcoded_etc1s_or_astc.ktx").c_str(), decoded_etc1s_or_astc, true);
  2554. image temp(m_decoded_output_textures_unpacked[slice_index]);
  2555. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2556. save_png(out_basename + "_transcoded_etc1s_or_astc.png", temp);
  2557. }
  2558. // Write decoded BC7 debug images
  2559. if (m_decoded_output_textures_bc7[slice_index].get_pixel_width())
  2560. {
  2561. gpu_image decoded_bc7(m_decoded_output_textures_bc7[slice_index]);
  2562. decoded_bc7.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2563. write_compressed_texture_file((out_basename + "_transcoded_bc7.ktx").c_str(), decoded_bc7, true);
  2564. image temp(m_decoded_output_textures_unpacked_bc7[slice_index]);
  2565. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  2566. save_png(out_basename + "_transcoded_bc7.png", temp);
  2567. }
  2568. }
  2569. }
  2570. } // if (m_params.m_hdr)
  2571. } // if (m_params.m_validate_output_data)
  2572. return true;
  2573. }
  2574. // Make sure all the mip 0's have the same dimensions and number of mipmap levels, or we can't encode the KTX2 file.
  2575. bool basis_compressor::validate_ktx2_constraints()
  2576. {
  2577. uint32_t base_width = 0, base_height = 0;
  2578. uint32_t total_layers = 0;
  2579. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2580. {
  2581. if (m_slice_descs[i].m_mip_index == 0)
  2582. {
  2583. if (!base_width)
  2584. {
  2585. base_width = m_slice_descs[i].m_orig_width;
  2586. base_height = m_slice_descs[i].m_orig_height;
  2587. }
  2588. else
  2589. {
  2590. if ((m_slice_descs[i].m_orig_width != base_width) || (m_slice_descs[i].m_orig_height != base_height))
  2591. {
  2592. return false;
  2593. }
  2594. }
  2595. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  2596. }
  2597. }
  2598. basisu::vector<uint32_t> total_mips(total_layers);
  2599. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2600. total_mips[m_slice_descs[i].m_source_file_index] = maximum<uint32_t>(total_mips[m_slice_descs[i].m_source_file_index], m_slice_descs[i].m_mip_index + 1);
  2601. for (uint32_t i = 1; i < total_layers; i++)
  2602. {
  2603. if (total_mips[0] != total_mips[i])
  2604. {
  2605. return false;
  2606. }
  2607. }
  2608. return true;
  2609. }
  2610. // colorModel=KTX2_KDF_DF_MODEL_ETC1S (0xA3)
  2611. // LDR ETC1S texture data in a custom format, with global codebooks
  2612. static uint8_t g_ktx2_etc1s_nonalpha_dfd[44] = { 0x2C,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x28,0x0,0xA3,0x1,0x2,0x0,0x3,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3F,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFF,0xFF,0xFF,0xFF };
  2613. static uint8_t g_ktx2_etc1s_alpha_dfd[60] = { 0x3C,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x38,0x0,0xA3,0x1,0x2,0x0,0x3,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3F,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFF,0xFF,0xFF,0xFF,0x40,0x0,0x3F,0xF,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFF,0xFF,0xFF,0xFF };
  2614. // colorModel=KTX2_KDF_DF_MODEL_UASTC_LDR_4X4 (0xA6)
  2615. // LDR UASTC 4x4 texture data in a custom block format
  2616. static uint8_t g_ktx2_uastc_ldr_4x4_nonalpha_dfd[44] = { 0x2C,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x28,0x0,0xA6,0x1,0x2,0x0,0x3,0x3,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7F,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFF,0xFF,0xFF,0xFF };
  2617. static uint8_t g_ktx2_uastc_ldr_4x4_alpha_dfd[44] = { 0x2C,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x28,0x0,0xA6,0x1,0x2,0x0,0x3,0x3,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7F,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFF,0xFF,0xFF,0xFF };
  2618. // colorModel=KTX2_KDF_DF_MODEL_UASTC_HDR_4X4 (0xA7)
  2619. // Standard ASTC HDR 4x4 texture data but constrained for easy transcoding to BC6H, either highest quality or RDO optimized.
  2620. static uint8_t g_ktx2_uastc_hdr_4x4_nonalpha_dfd[44] =
  2621. {
  2622. 0x2C,0x0,0x0,0x0, // 0 totalSize
  2623. 0x0,0x0,0x0,0x0, // 1 descriptorType/vendorId
  2624. 0x2,0x0,0x28,0x0, // 2 descriptorBlockSize/versionNumber
  2625. 0xA7,0x1,0x1,0x0, // 3 flags, transferFunction, colorPrimaries, colorModel (KTX2_KDF_DF_MODEL_UASTC_HDR_4X4)
  2626. 0x3,0x3,0x0,0x0, // 4 texelBlockDimension0-texelBlockDimension3
  2627. 0x10,0x0,0x0,0x0, // 5 bytesPlane0-bytesPlane3
  2628. 0x0,0x0,0x0,0x0, // 6 bytesPlane4-bytesPlane7
  2629. 0x0,0x0,0x7F,0x80, // 7 bitLength/bitOffset/channelType and Qualifer flags (KHR_DF_SAMPLE_DATATYPE_FLOAT etc.)
  2630. 0x0,0x0,0x0,0x0, // 8 samplePosition0-samplePosition3
  2631. 0x0,0x0,0x0,0x0, // 9 sampleLower (0.0)
  2632. 0x00, 0x00, 0x80, 0x3F // 10 sampleHigher (1.0)
  2633. };
  2634. // colorModel=KTX2_KDF_DF_MODEL_ASTC (0xA2)
  2635. // Standard ASTC HDR 6x6 texture data, either highest quality or RDO optimized.
  2636. static uint8_t g_ktx2_astc_hdr_6x6_nonalpha_dfd[44] =
  2637. {
  2638. 0x2C,0x0,0x0,0x0, // 0 totalSize
  2639. 0x0,0x0,0x0,0x0, // 1 descriptorType/vendorId
  2640. 0x2,0x0,0x28,0x0, // 2 descriptorBlockSize/versionNumber
  2641. 0xA2,0x1,0x1,0x0, // 3 flags, transferFunction, colorPrimaries, colorModel (0xA2/162, standard ASTC, KTX2_KDF_DF_MODEL_ASTC)
  2642. 0x5,0x5,0x0,0x0, // 4 texelBlockDimension0-texelBlockDimension3
  2643. 0x10,0x0,0x0,0x0, // 5 bytesPlane0-bytesPlane3
  2644. 0x0,0x0,0x0,0x0, // 6 bytesPlane4-bytesPlane7
  2645. 0x0,0x0,0x7F,0x80, // 7 bitLength/bitOffset/channelType and Qualifer flags (KHR_DF_SAMPLE_DATATYPE_FLOAT etc.)
  2646. 0x0,0x0,0x0,0x0, // 8 samplePosition0-samplePosition3
  2647. 0x0,0x0,0x0,0x0, // 9 sampleLower (0.0)
  2648. 0x00, 0x00, 0x80, 0x3F // 10 sampleHigher (1.0)
  2649. };
  2650. // colorModel=KTX2_KDF_DF_MODEL_ASTC_HDR_6X6_INTERMEDIATE (0xA8)
  2651. // Our custom intermediate format that when decoded directly outputs ASTC HDR 6x6
  2652. static uint8_t g_ktx2_astc_hdr_6x6_intermediate_nonalpha_dfd[44] =
  2653. {
  2654. 0x2C,0x0,0x0,0x0, // 0 totalSize
  2655. 0x0,0x0,0x0,0x0, // 1 descriptorType/vendorId
  2656. 0x2,0x0,0x28,0x0, // 2 descriptorBlockSize/versionNumber
  2657. 0xA8,0x1,0x1,0x0, // 3 flags, transferFunction, colorPrimaries, colorModel (KTX2_KDF_DF_MODEL_ASTC_HDR_6X6_INTERMEDIATE)
  2658. 0x5,0x5,0x0,0x0, // 4 texelBlockDimension0-texelBlockDimension3
  2659. 0x10,0x0,0x0,0x0, // 5 bytesPlane0-bytesPlane3
  2660. 0x0,0x0,0x0,0x0, // 6 bytesPlane4-bytesPlane7
  2661. 0x0,0x0,0x7F,0x80, // 7 bitLength/bitOffset/channelType and Qualifer flags (KHR_DF_SAMPLE_DATATYPE_FLOAT etc.)
  2662. 0x0,0x0,0x0,0x0, // 8 samplePosition0-samplePosition3
  2663. 0x0,0x0,0x0,0x0, // 9 sampleLower (0.0)
  2664. 0x00, 0x00, 0x80, 0x3F // 10 sampleHigher (1.0)
  2665. };
  2666. bool basis_compressor::get_dfd(uint8_vec &dfd, const basist::ktx2_header &header)
  2667. {
  2668. const uint8_t* pDFD;
  2669. uint32_t dfd_len;
  2670. if (m_params.m_uastc)
  2671. {
  2672. if (m_params.m_hdr)
  2673. {
  2674. switch (m_params.m_hdr_mode)
  2675. {
  2676. case hdr_modes::cUASTC_HDR_4X4:
  2677. {
  2678. pDFD = g_ktx2_uastc_hdr_4x4_nonalpha_dfd;
  2679. dfd_len = sizeof(g_ktx2_uastc_hdr_4x4_nonalpha_dfd);
  2680. break;
  2681. }
  2682. case hdr_modes::cASTC_HDR_6X6:
  2683. {
  2684. pDFD = g_ktx2_astc_hdr_6x6_nonalpha_dfd;
  2685. dfd_len = sizeof(g_ktx2_astc_hdr_6x6_nonalpha_dfd);
  2686. break;
  2687. }
  2688. case hdr_modes::cASTC_HDR_6X6_INTERMEDIATE:
  2689. {
  2690. pDFD = g_ktx2_astc_hdr_6x6_intermediate_nonalpha_dfd;
  2691. dfd_len = sizeof(g_ktx2_astc_hdr_6x6_intermediate_nonalpha_dfd);
  2692. break;
  2693. }
  2694. default:
  2695. {
  2696. assert(0);
  2697. return false;
  2698. }
  2699. }
  2700. }
  2701. // Must be LDR UASTC 4x4
  2702. else if (m_any_source_image_has_alpha)
  2703. {
  2704. pDFD = g_ktx2_uastc_ldr_4x4_alpha_dfd;
  2705. dfd_len = sizeof(g_ktx2_uastc_ldr_4x4_alpha_dfd);
  2706. }
  2707. else
  2708. {
  2709. pDFD = g_ktx2_uastc_ldr_4x4_nonalpha_dfd;
  2710. dfd_len = sizeof(g_ktx2_uastc_ldr_4x4_nonalpha_dfd);
  2711. }
  2712. }
  2713. else
  2714. {
  2715. // Must be ETC1S.
  2716. assert(!m_params.m_hdr);
  2717. if (m_any_source_image_has_alpha)
  2718. {
  2719. pDFD = g_ktx2_etc1s_alpha_dfd;
  2720. dfd_len = sizeof(g_ktx2_etc1s_alpha_dfd);
  2721. }
  2722. else
  2723. {
  2724. pDFD = g_ktx2_etc1s_nonalpha_dfd;
  2725. dfd_len = sizeof(g_ktx2_etc1s_nonalpha_dfd);
  2726. }
  2727. }
  2728. assert(dfd_len >= 44);
  2729. dfd.resize(dfd_len);
  2730. memcpy(dfd.data(), pDFD, dfd_len);
  2731. uint32_t dfd_bits = basisu::read_le_dword(dfd.data() + 3 * sizeof(uint32_t));
  2732. // Color primaries
  2733. if ((m_params.m_hdr) && (m_params.m_astc_hdr_6x6_options.m_rec2020_bt2100_color_gamut))
  2734. {
  2735. dfd_bits &= ~(0xFF << 8);
  2736. dfd_bits |= (basist::KTX2_DF_PRIMARIES_BT2020 << 8);
  2737. }
  2738. // Transfer function
  2739. dfd_bits &= ~(0xFF << 16);
  2740. if (m_params.m_hdr)
  2741. {
  2742. // TODO: In HDR mode, always write linear for now.
  2743. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_LINEAR << 16);
  2744. }
  2745. else
  2746. {
  2747. if (m_params.m_ktx2_srgb_transfer_func)
  2748. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_SRGB << 16);
  2749. else
  2750. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_LINEAR << 16);
  2751. }
  2752. basisu::write_le_dword(dfd.data() + 3 * sizeof(uint32_t), dfd_bits);
  2753. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  2754. {
  2755. uint32_t plane_bits = basisu::read_le_dword(dfd.data() + 5 * sizeof(uint32_t));
  2756. plane_bits &= ~0xFF;
  2757. basisu::write_le_dword(dfd.data() + 5 * sizeof(uint32_t), plane_bits);
  2758. }
  2759. // Fix up the DFD channel(s)
  2760. uint32_t dfd_chan0 = basisu::read_le_dword(dfd.data() + 7 * sizeof(uint32_t));
  2761. if (m_params.m_uastc)
  2762. {
  2763. dfd_chan0 &= ~(0xF << 24);
  2764. // TODO: Allow the caller to override this
  2765. if (m_any_source_image_has_alpha)
  2766. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGBA << 24);
  2767. else
  2768. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGB << 24);
  2769. }
  2770. basisu::write_le_dword(dfd.data() + 7 * sizeof(uint32_t), dfd_chan0);
  2771. return true;
  2772. }
  2773. bool basis_compressor::create_ktx2_file()
  2774. {
  2775. //bool needs_global_data = false;
  2776. bool can_use_zstd = false;
  2777. switch (m_fmt_mode)
  2778. {
  2779. case basist::basis_tex_format::cETC1S:
  2780. {
  2781. //needs_global_data = true;
  2782. break;
  2783. }
  2784. case basist::basis_tex_format::cUASTC4x4:
  2785. {
  2786. can_use_zstd = true;
  2787. break;
  2788. }
  2789. case basist::basis_tex_format::cUASTC_HDR_4x4:
  2790. {
  2791. can_use_zstd = true;
  2792. break;
  2793. }
  2794. case basist::basis_tex_format::cASTC_HDR_6x6:
  2795. {
  2796. can_use_zstd = true;
  2797. break;
  2798. }
  2799. case basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE:
  2800. {
  2801. //needs_global_data = true;
  2802. break;
  2803. }
  2804. default:
  2805. assert(0);
  2806. //fmt_debug_printf("HERE 1\n");
  2807. return false;
  2808. }
  2809. if (can_use_zstd)
  2810. {
  2811. if ((m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_NONE) && (m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_ZSTANDARD))
  2812. {
  2813. //fmt_debug_printf("HERE 2\n");
  2814. return false;
  2815. }
  2816. }
  2817. const basisu_backend_output& backend_output = m_backend.get_output();
  2818. // Determine the width/height, number of array layers, mipmap levels, and the number of faces (1 for 2D, 6 for cubemap).
  2819. // This does not support 1D or 3D.
  2820. uint32_t base_width = 0, base_height = 0, total_layers = 0, total_levels = 0, total_faces = 1;
  2821. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  2822. {
  2823. if ((m_slice_descs[i].m_mip_index == 0) && (!base_width))
  2824. {
  2825. base_width = m_slice_descs[i].m_orig_width;
  2826. base_height = m_slice_descs[i].m_orig_height;
  2827. }
  2828. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  2829. if (!m_slice_descs[i].m_source_file_index)
  2830. total_levels = maximum<uint32_t>(total_levels, m_slice_descs[i].m_mip_index + 1);
  2831. }
  2832. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  2833. {
  2834. assert((total_layers % 6) == 0);
  2835. total_layers /= 6;
  2836. assert(total_layers >= 1);
  2837. total_faces = 6;
  2838. }
  2839. basist::ktx2_header header;
  2840. memset((void *)&header, 0, sizeof(header));
  2841. memcpy(header.m_identifier, basist::g_ktx2_file_identifier, sizeof(basist::g_ktx2_file_identifier));
  2842. header.m_pixel_width = base_width;
  2843. header.m_pixel_height = base_height;
  2844. header.m_face_count = total_faces;
  2845. if (m_params.m_hdr)
  2846. {
  2847. if (m_params.m_hdr_mode == hdr_modes::cUASTC_HDR_4X4)
  2848. header.m_vk_format = basist::KTX2_FORMAT_ASTC_4x4_SFLOAT_BLOCK;
  2849. else if (m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6)
  2850. header.m_vk_format = basist::KTX2_FORMAT_ASTC_6x6_SFLOAT_BLOCK;
  2851. else
  2852. {
  2853. assert(m_params.m_hdr_mode == hdr_modes::cASTC_HDR_6X6_INTERMEDIATE);
  2854. header.m_vk_format = basist::KTX2_VK_FORMAT_UNDEFINED;
  2855. }
  2856. }
  2857. else
  2858. {
  2859. // Either ETC1S or UASTC LDR 4x4.
  2860. assert((m_fmt_mode == basist::basis_tex_format::cETC1S) || (m_fmt_mode == basist::basis_tex_format::cUASTC4x4));
  2861. header.m_vk_format = basist::KTX2_VK_FORMAT_UNDEFINED;
  2862. }
  2863. header.m_type_size = 1;
  2864. header.m_level_count = total_levels;
  2865. header.m_layer_count = (total_layers > 1) ? total_layers : 0;
  2866. if (can_use_zstd)
  2867. {
  2868. switch (m_params.m_ktx2_uastc_supercompression)
  2869. {
  2870. case basist::KTX2_SS_NONE:
  2871. {
  2872. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  2873. break;
  2874. }
  2875. case basist::KTX2_SS_ZSTANDARD:
  2876. {
  2877. #if BASISD_SUPPORT_KTX2_ZSTD
  2878. header.m_supercompression_scheme = basist::KTX2_SS_ZSTANDARD;
  2879. #else
  2880. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  2881. #endif
  2882. break;
  2883. }
  2884. default:
  2885. assert(0);
  2886. //fmt_debug_printf("HERE 3\n");
  2887. return false;
  2888. }
  2889. }
  2890. basisu::vector<uint8_vec> level_data_bytes(total_levels);
  2891. basisu::vector<uint8_vec> compressed_level_data_bytes(total_levels);
  2892. size_t_vec slice_level_offsets(m_slice_descs.size());
  2893. // This will append the texture data in the correct order (for each level: layer, then face).
  2894. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2895. {
  2896. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2897. slice_level_offsets[slice_index] = level_data_bytes[slice_desc.m_mip_index].size();
  2898. if (m_fmt_mode == basist::basis_tex_format::cETC1S)
  2899. {
  2900. append_vector(level_data_bytes[slice_desc.m_mip_index], backend_output.m_slice_image_data[slice_index]);
  2901. }
  2902. else
  2903. {
  2904. append_vector(level_data_bytes[slice_desc.m_mip_index], m_uastc_backend_output.m_slice_image_data[slice_index]);
  2905. }
  2906. }
  2907. // Zstd Supercompression
  2908. if ((can_use_zstd) && (header.m_supercompression_scheme == basist::KTX2_SS_ZSTANDARD))
  2909. {
  2910. #if BASISD_SUPPORT_KTX2_ZSTD
  2911. for (uint32_t level_index = 0; level_index < total_levels; level_index++)
  2912. {
  2913. compressed_level_data_bytes[level_index].resize(ZSTD_compressBound(level_data_bytes[level_index].size()));
  2914. size_t result = ZSTD_compress(compressed_level_data_bytes[level_index].data(), compressed_level_data_bytes[level_index].size(),
  2915. level_data_bytes[level_index].data(), level_data_bytes[level_index].size(),
  2916. m_params.m_ktx2_zstd_supercompression_level);
  2917. if (ZSTD_isError(result))
  2918. {
  2919. //fmt_debug_printf("HERE 5\n");
  2920. return false;
  2921. }
  2922. compressed_level_data_bytes[level_index].resize(result);
  2923. }
  2924. #else
  2925. // Can't get here
  2926. assert(0);
  2927. //fmt_debug_printf("HERE 6\n");
  2928. return false;
  2929. #endif
  2930. }
  2931. else
  2932. {
  2933. // No supercompression
  2934. compressed_level_data_bytes = level_data_bytes;
  2935. }
  2936. uint8_vec ktx2_global_data;
  2937. // Create ETC1S global supercompressed data
  2938. if (m_fmt_mode == basist::basis_tex_format::cETC1S)
  2939. {
  2940. basist::ktx2_etc1s_global_data_header etc1s_global_data_header;
  2941. clear_obj(etc1s_global_data_header);
  2942. etc1s_global_data_header.m_endpoint_count = backend_output.m_num_endpoints;
  2943. etc1s_global_data_header.m_selector_count = backend_output.m_num_selectors;
  2944. etc1s_global_data_header.m_endpoints_byte_length = backend_output.m_endpoint_palette.size();
  2945. etc1s_global_data_header.m_selectors_byte_length = backend_output.m_selector_palette.size();
  2946. etc1s_global_data_header.m_tables_byte_length = backend_output.m_slice_image_tables.size();
  2947. basisu::vector<basist::ktx2_etc1s_image_desc> etc1s_image_descs(total_levels * total_layers * total_faces);
  2948. memset((void *)etc1s_image_descs.data(), 0, etc1s_image_descs.size_in_bytes());
  2949. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2950. {
  2951. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2952. const uint32_t level_index = slice_desc.m_mip_index;
  2953. uint32_t layer_index = slice_desc.m_source_file_index;
  2954. uint32_t face_index = 0;
  2955. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  2956. {
  2957. face_index = layer_index % 6;
  2958. layer_index /= 6;
  2959. }
  2960. const uint32_t etc1s_image_index = level_index * (total_layers * total_faces) + layer_index * total_faces + face_index;
  2961. if (slice_desc.m_alpha)
  2962. {
  2963. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  2964. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_offset = slice_level_offsets[slice_index];
  2965. }
  2966. else
  2967. {
  2968. if (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames)
  2969. etc1s_image_descs[etc1s_image_index].m_image_flags = !slice_desc.m_iframe ? basist::KTX2_IMAGE_IS_P_FRAME : 0;
  2970. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  2971. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_offset = slice_level_offsets[slice_index];
  2972. }
  2973. } // slice_index
  2974. append_vector(ktx2_global_data, (const uint8_t*)&etc1s_global_data_header, sizeof(etc1s_global_data_header));
  2975. append_vector(ktx2_global_data, (const uint8_t*)etc1s_image_descs.data(), etc1s_image_descs.size_in_bytes());
  2976. append_vector(ktx2_global_data, backend_output.m_endpoint_palette);
  2977. append_vector(ktx2_global_data, backend_output.m_selector_palette);
  2978. append_vector(ktx2_global_data, backend_output.m_slice_image_tables);
  2979. header.m_supercompression_scheme = basist::KTX2_SS_BASISLZ;
  2980. }
  2981. else if (m_fmt_mode == basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE)
  2982. {
  2983. basisu::vector<basist::ktx2_astc_hdr_6x6_intermediate_image_desc> image_descs(total_levels * total_layers * total_faces);
  2984. memset((void *)image_descs.data(), 0, image_descs.size_in_bytes());
  2985. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  2986. {
  2987. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  2988. const uint32_t level_index = slice_desc.m_mip_index;
  2989. uint32_t layer_index = slice_desc.m_source_file_index;
  2990. uint32_t face_index = 0;
  2991. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  2992. {
  2993. face_index = layer_index % 6;
  2994. layer_index /= 6;
  2995. }
  2996. const uint32_t output_image_index = level_index * (total_layers * total_faces) + layer_index * total_faces + face_index;
  2997. image_descs[output_image_index].m_rgb_slice_byte_length = m_uastc_backend_output.m_slice_image_data[slice_index].size();
  2998. image_descs[output_image_index].m_rgb_slice_byte_offset = slice_level_offsets[slice_index];
  2999. } // slice_index
  3000. append_vector(ktx2_global_data, (const uint8_t*)image_descs.data(), image_descs.size_in_bytes());
  3001. header.m_supercompression_scheme = basist::KTX2_SS_BASISLZ;
  3002. }
  3003. // Key values
  3004. basist::ktx2_transcoder::key_value_vec key_values(m_params.m_ktx2_key_values);
  3005. basist::ktx2_add_key_value(key_values, "KTXwriter", fmt_string("Basis Universal {}", BASISU_LIB_VERSION_STRING));
  3006. if (m_params.m_hdr)
  3007. {
  3008. if (m_upconverted_any_ldr_images)
  3009. basist::ktx2_add_key_value(key_values, "LDRUpconversionMultiplier", fmt_string("{}", m_ldr_to_hdr_upconversion_nit_multiplier));
  3010. if (m_params.m_ldr_hdr_upconversion_srgb_to_linear)
  3011. basist::ktx2_add_key_value(key_values, "LDRUpconversionSRGBToLinear", "1");
  3012. }
  3013. key_values.sort();
  3014. #if BASISU_DISABLE_KTX2_KEY_VALUES
  3015. // HACK HACK - Clear the key values array, which causes no key values to be written (triggering the ktx2check validator bug).
  3016. key_values.clear();
  3017. #endif
  3018. uint8_vec key_value_data;
  3019. // DFD
  3020. uint8_vec dfd;
  3021. if (!get_dfd(dfd, header))
  3022. {
  3023. //fmt_debug_printf("HERE 7\n");
  3024. return false;
  3025. }
  3026. const uint32_t kvd_file_offset = sizeof(header) + sizeof(basist::ktx2_level_index) * total_levels + (uint32_t)dfd.size();
  3027. for (uint32_t pass = 0; pass < 2; pass++)
  3028. {
  3029. for (uint32_t i = 0; i < key_values.size(); i++)
  3030. {
  3031. if (key_values[i].m_key.size() < 2)
  3032. {
  3033. //fmt_debug_printf("HERE 8\n");
  3034. return false;
  3035. }
  3036. if (key_values[i].m_key.back() != 0)
  3037. {
  3038. //fmt_debug_printf("HERE 9\n");
  3039. return false;
  3040. }
  3041. const uint64_t total_len = (uint64_t)key_values[i].m_key.size() + (uint64_t)key_values[i].m_value.size();
  3042. if (total_len >= UINT32_MAX)
  3043. {
  3044. //fmt_debug_printf("HERE 10\n");
  3045. return false;
  3046. }
  3047. packed_uint<4> le_len((uint32_t)total_len);
  3048. append_vector(key_value_data, (const uint8_t*)&le_len, sizeof(le_len));
  3049. append_vector(key_value_data, key_values[i].m_key);
  3050. append_vector(key_value_data, key_values[i].m_value);
  3051. const uint32_t ofs = key_value_data.size() & 3;
  3052. const uint32_t padding = (4 - ofs) & 3;
  3053. for (uint32_t p = 0; p < padding; p++)
  3054. key_value_data.push_back(0);
  3055. }
  3056. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  3057. break;
  3058. #if BASISU_DISABLE_KTX2_ALIGNMENT_WORKAROUND
  3059. break;
  3060. #endif
  3061. // Hack to ensure the KVD block ends on a 16 byte boundary, because we have no other official way of aligning the data.
  3062. uint32_t kvd_end_file_offset = kvd_file_offset + (uint32_t)key_value_data.size();
  3063. uint32_t bytes_needed_to_pad = (16 - (kvd_end_file_offset & 15)) & 15;
  3064. if (!bytes_needed_to_pad)
  3065. {
  3066. // We're good. No need to add a dummy key.
  3067. break;
  3068. }
  3069. assert(!pass);
  3070. if (pass)
  3071. {
  3072. //fmt_debug_printf("HERE 11\n");
  3073. return false;
  3074. }
  3075. if (bytes_needed_to_pad < 6)
  3076. bytes_needed_to_pad += 16;
  3077. // Just add the padding. It's likely not necessary anymore, but can't really hurt.
  3078. //printf("WARNING: Due to a KTX2 validator bug related to mipPadding, we must insert a dummy key into the KTX2 file of %u bytes\n", bytes_needed_to_pad);
  3079. // We're not good - need to add a dummy key large enough to force file alignment so the mip level array gets aligned.
  3080. // We can't just add some bytes before the mip level array because ktx2check will see that as extra data in the file that shouldn't be there in ktxValidator::validateDataSize().
  3081. key_values.enlarge(1);
  3082. for (uint32_t i = 0; i < (bytes_needed_to_pad - 4 - 1 - 1); i++)
  3083. key_values.back().m_key.push_back(127);
  3084. key_values.back().m_key.push_back(0);
  3085. key_values.back().m_value.push_back(0);
  3086. key_values.sort();
  3087. key_value_data.resize(0);
  3088. // Try again
  3089. }
  3090. basisu::vector<basist::ktx2_level_index> level_index_array(total_levels);
  3091. memset((void *)level_index_array.data(), 0, level_index_array.size_in_bytes());
  3092. m_output_ktx2_file.clear();
  3093. m_output_ktx2_file.reserve(m_output_basis_file.size());
  3094. // Dummy header
  3095. m_output_ktx2_file.resize(sizeof(header));
  3096. // Level index array
  3097. append_vector(m_output_ktx2_file, (const uint8_t*)level_index_array.data(), level_index_array.size_in_bytes());
  3098. // DFD
  3099. const uint8_t* pDFD = dfd.data();
  3100. uint32_t dfd_len = (uint32_t)dfd.size();
  3101. header.m_dfd_byte_offset = m_output_ktx2_file.size();
  3102. header.m_dfd_byte_length = dfd_len;
  3103. append_vector(m_output_ktx2_file, pDFD, dfd_len);
  3104. // Key value data
  3105. if (key_value_data.size())
  3106. {
  3107. assert(kvd_file_offset == m_output_ktx2_file.size());
  3108. header.m_kvd_byte_offset = m_output_ktx2_file.size();
  3109. header.m_kvd_byte_length = key_value_data.size();
  3110. append_vector(m_output_ktx2_file, key_value_data);
  3111. }
  3112. // Global Supercompressed Data
  3113. if (ktx2_global_data.size())
  3114. {
  3115. uint32_t ofs = m_output_ktx2_file.size() & 7;
  3116. uint32_t padding = (8 - ofs) & 7;
  3117. for (uint32_t i = 0; i < padding; i++)
  3118. m_output_ktx2_file.push_back(0);
  3119. header.m_sgd_byte_length = ktx2_global_data.size();
  3120. header.m_sgd_byte_offset = m_output_ktx2_file.size();
  3121. append_vector(m_output_ktx2_file, ktx2_global_data);
  3122. }
  3123. // mipPadding
  3124. if (header.m_supercompression_scheme == basist::KTX2_SS_NONE)
  3125. {
  3126. // We currently can't do this or the validator will incorrectly give an error.
  3127. uint32_t ofs = m_output_ktx2_file.size() & 15;
  3128. uint32_t padding = (16 - ofs) & 15;
  3129. // Make sure we're always aligned here (due to a validator bug).
  3130. if (padding)
  3131. {
  3132. printf("Warning: KTX2 mip level data is not 16-byte aligned. This may trigger a ktx2check validation bug. Writing %u bytes of mipPadding.\n", padding);
  3133. }
  3134. for (uint32_t i = 0; i < padding; i++)
  3135. m_output_ktx2_file.push_back(0);
  3136. }
  3137. // Level data - write the smallest mipmap first.
  3138. for (int level = total_levels - 1; level >= 0; level--)
  3139. {
  3140. level_index_array[level].m_byte_length = compressed_level_data_bytes[level].size();
  3141. //if (m_params.m_uastc)
  3142. if (can_use_zstd)
  3143. {
  3144. level_index_array[level].m_uncompressed_byte_length = level_data_bytes[level].size();
  3145. }
  3146. level_index_array[level].m_byte_offset = m_output_ktx2_file.size();
  3147. append_vector(m_output_ktx2_file, compressed_level_data_bytes[level]);
  3148. }
  3149. // Write final header
  3150. memcpy(m_output_ktx2_file.data(), &header, sizeof(header));
  3151. // Write final level index array
  3152. memcpy(m_output_ktx2_file.data() + sizeof(header), level_index_array.data(), level_index_array.size_in_bytes());
  3153. uint32_t total_orig_pixels = 0;
  3154. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  3155. {
  3156. const basisu_backend_slice_desc& slice_desc = m_slice_descs[i];
  3157. total_orig_pixels += slice_desc.m_orig_width * slice_desc.m_orig_height;
  3158. }
  3159. debug_printf("Total .ktx2 output file size: %u, %3.3f bits/texel\n", m_output_ktx2_file.size(), ((float)m_output_ktx2_file.size() * 8.0f) / total_orig_pixels);
  3160. return true;
  3161. }
  3162. bool basis_parallel_compress(
  3163. uint32_t total_threads,
  3164. const basisu::vector<basis_compressor_params>& params_vec,
  3165. basisu::vector< parallel_results >& results_vec)
  3166. {
  3167. assert(g_library_initialized);
  3168. if (!g_library_initialized)
  3169. {
  3170. error_printf("basis_parallel_compress: basisu_encoder_init() MUST be called before using any encoder functionality!\n");
  3171. return false;
  3172. }
  3173. assert(total_threads >= 1);
  3174. total_threads = basisu::maximum<uint32_t>(total_threads, 1);
  3175. job_pool jpool(total_threads);
  3176. results_vec.resize(0);
  3177. results_vec.resize(params_vec.size());
  3178. std::atomic<bool> result;
  3179. result.store(true);
  3180. std::atomic<bool> opencl_failed;
  3181. opencl_failed.store(false);
  3182. for (uint32_t pindex = 0; pindex < params_vec.size(); pindex++)
  3183. {
  3184. jpool.add_job([pindex, &params_vec, &results_vec, &result, &opencl_failed] {
  3185. basis_compressor_params params = params_vec[pindex];
  3186. parallel_results& results = results_vec[pindex];
  3187. interval_timer tm;
  3188. tm.start();
  3189. basis_compressor c;
  3190. // Dummy job pool
  3191. job_pool task_jpool(1);
  3192. params.m_pJob_pool = &task_jpool;
  3193. // TODO: Remove this flag entirely
  3194. params.m_multithreading = true;
  3195. // Stop using OpenCL if a failure ever occurs.
  3196. if (opencl_failed)
  3197. params.m_use_opencl = false;
  3198. bool status = c.init(params);
  3199. if (c.get_opencl_failed())
  3200. opencl_failed.store(true);
  3201. if (status)
  3202. {
  3203. basis_compressor::error_code ec = c.process();
  3204. if (c.get_opencl_failed())
  3205. opencl_failed.store(true);
  3206. results.m_error_code = ec;
  3207. if (ec == basis_compressor::cECSuccess)
  3208. {
  3209. results.m_basis_file = c.get_output_basis_file();
  3210. results.m_ktx2_file = c.get_output_ktx2_file();
  3211. results.m_stats = c.get_stats();
  3212. results.m_basis_bits_per_texel = c.get_basis_bits_per_texel();
  3213. results.m_any_source_image_has_alpha = c.get_any_source_image_has_alpha();
  3214. }
  3215. else
  3216. {
  3217. result = false;
  3218. }
  3219. }
  3220. else
  3221. {
  3222. results.m_error_code = basis_compressor::cECFailedInitializing;
  3223. result = false;
  3224. }
  3225. results.m_total_time = tm.get_elapsed_secs();
  3226. } );
  3227. } // pindex
  3228. jpool.wait_for_all();
  3229. if (opencl_failed)
  3230. error_printf("An OpenCL error occured sometime during compression. The compressor fell back to CPU processing after the failure.\n");
  3231. return result;
  3232. }
  3233. static void* basis_compress(
  3234. basist::basis_tex_format mode,
  3235. const basisu::vector<image> *pSource_images,
  3236. const basisu::vector<imagef> *pSource_images_hdr,
  3237. uint32_t flags_and_quality, float uastc_rdo_quality,
  3238. size_t* pSize,
  3239. image_stats* pStats)
  3240. {
  3241. assert((pSource_images != nullptr) || (pSource_images_hdr != nullptr));
  3242. assert(!((pSource_images != nullptr) && (pSource_images_hdr != nullptr)));
  3243. // Check input parameters
  3244. if (pSource_images)
  3245. {
  3246. if ((!pSource_images->size()) || (!pSize))
  3247. {
  3248. error_printf("basis_compress: Invalid parameter\n");
  3249. assert(0);
  3250. return nullptr;
  3251. }
  3252. }
  3253. else
  3254. {
  3255. if ((!pSource_images_hdr->size()) || (!pSize))
  3256. {
  3257. error_printf("basis_compress: Invalid parameter\n");
  3258. assert(0);
  3259. return nullptr;
  3260. }
  3261. }
  3262. *pSize = 0;
  3263. // Initialize a job pool
  3264. uint32_t num_threads = 1;
  3265. if (flags_and_quality & cFlagThreaded)
  3266. num_threads = basisu::maximum<uint32_t>(1, std::thread::hardware_concurrency());
  3267. job_pool jp(num_threads);
  3268. // Initialize the compressor parameter struct
  3269. basis_compressor_params comp_params;
  3270. comp_params.set_format_mode(mode);
  3271. comp_params.m_pJob_pool = &jp;
  3272. comp_params.m_y_flip = (flags_and_quality & cFlagYFlip) != 0;
  3273. comp_params.m_debug = (flags_and_quality & cFlagDebug) != 0;
  3274. comp_params.m_debug_images = (flags_and_quality & cFlagDebugImages) != 0;
  3275. // Copy the largest mipmap level
  3276. if (pSource_images)
  3277. {
  3278. comp_params.m_source_images.resize(1);
  3279. comp_params.m_source_images[0] = (*pSource_images)[0];
  3280. // Copy the smaller mipmap levels, if any
  3281. if (pSource_images->size() > 1)
  3282. {
  3283. comp_params.m_source_mipmap_images.resize(1);
  3284. comp_params.m_source_mipmap_images[0].resize(pSource_images->size() - 1);
  3285. for (uint32_t i = 1; i < pSource_images->size(); i++)
  3286. comp_params.m_source_mipmap_images[0][i - 1] = (*pSource_images)[i];
  3287. }
  3288. }
  3289. else
  3290. {
  3291. comp_params.m_source_images_hdr.resize(1);
  3292. comp_params.m_source_images_hdr[0] = (*pSource_images_hdr)[0];
  3293. // Copy the smaller mipmap levels, if any
  3294. if (pSource_images_hdr->size() > 1)
  3295. {
  3296. comp_params.m_source_mipmap_images_hdr.resize(1);
  3297. comp_params.m_source_mipmap_images_hdr[0].resize(pSource_images_hdr->size() - 1);
  3298. for (uint32_t i = 1; i < pSource_images->size(); i++)
  3299. comp_params.m_source_mipmap_images_hdr[0][i - 1] = (*pSource_images_hdr)[i];
  3300. }
  3301. }
  3302. comp_params.m_multithreading = (flags_and_quality & cFlagThreaded) != 0;
  3303. comp_params.m_use_opencl = (flags_and_quality & cFlagUseOpenCL) != 0;
  3304. comp_params.m_write_output_basis_or_ktx2_files = false;
  3305. comp_params.m_perceptual = (flags_and_quality & cFlagSRGB) != 0;
  3306. comp_params.m_mip_srgb = comp_params.m_perceptual;
  3307. comp_params.m_mip_gen = (flags_and_quality & (cFlagGenMipsWrap | cFlagGenMipsClamp)) != 0;
  3308. comp_params.m_mip_wrapping = (flags_and_quality & cFlagGenMipsWrap) != 0;
  3309. if (mode == basist::basis_tex_format::cUASTC4x4)
  3310. {
  3311. comp_params.m_pack_uastc_ldr_4x4_flags = flags_and_quality & cPackUASTCLevelMask;
  3312. comp_params.m_rdo_uastc_ldr_4x4 = (flags_and_quality & cFlagUASTCRDO) != 0;
  3313. comp_params.m_rdo_uastc_ldr_4x4_quality_scalar = uastc_rdo_quality;
  3314. }
  3315. else if (mode == basist::basis_tex_format::cETC1S)
  3316. {
  3317. comp_params.m_etc1s_quality_level = basisu::maximum<uint32_t>(1, flags_and_quality & 255);
  3318. }
  3319. comp_params.m_create_ktx2_file = (flags_and_quality & cFlagKTX2) != 0;
  3320. if (comp_params.m_create_ktx2_file)
  3321. {
  3322. // Set KTX2 specific parameters.
  3323. if ((flags_and_quality & cFlagKTX2UASTCSuperCompression) && (comp_params.m_uastc))
  3324. comp_params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD;
  3325. comp_params.m_ktx2_srgb_transfer_func = comp_params.m_perceptual;
  3326. }
  3327. comp_params.m_compute_stats = (pStats != nullptr);
  3328. comp_params.m_print_stats = (flags_and_quality & cFlagPrintStats) != 0;
  3329. comp_params.m_status_output = (flags_and_quality & cFlagPrintStatus) != 0;
  3330. if (mode == basist::basis_tex_format::cUASTC_HDR_4x4)
  3331. {
  3332. comp_params.m_uastc_hdr_4x4_options.set_quality_level(flags_and_quality & cPackUASTCLevelMask);
  3333. }
  3334. else if ((mode == basist::basis_tex_format::cASTC_HDR_6x6) || (mode == basist::basis_tex_format::cASTC_HDR_6x6_INTERMEDIATE))
  3335. {
  3336. comp_params.m_astc_hdr_6x6_options.set_user_level(flags_and_quality & cPackUASTCLevelMask);
  3337. comp_params.m_astc_hdr_6x6_options.m_lambda = uastc_rdo_quality;
  3338. comp_params.m_astc_hdr_6x6_options.m_rec2020_bt2100_color_gamut = (flags_and_quality & cFlagREC2020) != 0;
  3339. }
  3340. // Create the compressor, initialize it, and process the input
  3341. basis_compressor comp;
  3342. if (!comp.init(comp_params))
  3343. {
  3344. error_printf("basis_compress: basis_compressor::init() failed!\n");
  3345. return nullptr;
  3346. }
  3347. basis_compressor::error_code ec = comp.process();
  3348. if (ec != basis_compressor::cECSuccess)
  3349. {
  3350. error_printf("basis_compress: basis_compressor::process() failed with error code %u\n", (uint32_t)ec);
  3351. return nullptr;
  3352. }
  3353. if ((pStats) && (comp.get_opencl_failed()))
  3354. {
  3355. pStats->m_opencl_failed = true;
  3356. }
  3357. // Get the output file data and return it to the caller
  3358. void* pFile_data = nullptr;
  3359. const uint8_vec* pFile_data_vec = comp_params.m_create_ktx2_file ? &comp.get_output_ktx2_file() : &comp.get_output_basis_file();
  3360. pFile_data = malloc(pFile_data_vec->size());
  3361. if (!pFile_data)
  3362. {
  3363. error_printf("basis_compress: Out of memory\n");
  3364. return nullptr;
  3365. }
  3366. memcpy(pFile_data, pFile_data_vec->get_ptr(), pFile_data_vec->size());
  3367. *pSize = pFile_data_vec->size();
  3368. if ((pStats) && (comp.get_stats().size()))
  3369. {
  3370. *pStats = comp.get_stats()[0];
  3371. }
  3372. return pFile_data;
  3373. }
  3374. void* basis_compress(
  3375. basist::basis_tex_format mode,
  3376. const basisu::vector<image>& source_images,
  3377. uint32_t flags_and_quality, float uastc_rdo_quality,
  3378. size_t* pSize,
  3379. image_stats* pStats)
  3380. {
  3381. return basis_compress(mode, &source_images, nullptr, flags_and_quality, uastc_rdo_quality, pSize, pStats);
  3382. }
  3383. void* basis_compress(
  3384. basist::basis_tex_format mode,
  3385. const basisu::vector<imagef>& source_images_hdr,
  3386. uint32_t flags_and_quality, float lambda,
  3387. size_t* pSize,
  3388. image_stats* pStats)
  3389. {
  3390. return basis_compress(mode, nullptr, &source_images_hdr, flags_and_quality, lambda, pSize, pStats);
  3391. }
  3392. void* basis_compress(
  3393. basist::basis_tex_format mode,
  3394. const uint8_t* pImageRGBA, uint32_t width, uint32_t height, uint32_t pitch_in_pixels,
  3395. uint32_t flags_and_quality, float uastc_rdo_quality,
  3396. size_t* pSize,
  3397. image_stats* pStats)
  3398. {
  3399. if (!pitch_in_pixels)
  3400. pitch_in_pixels = width;
  3401. if ((!pImageRGBA) || (!width) || (!height) || (pitch_in_pixels < width) || (!pSize))
  3402. {
  3403. error_printf("basis_compress: Invalid parameter\n");
  3404. assert(0);
  3405. return nullptr;
  3406. }
  3407. *pSize = 0;
  3408. if ((width > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION) || (height > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION))
  3409. {
  3410. error_printf("basis_compress: Image too large\n");
  3411. return nullptr;
  3412. }
  3413. // Copy the source image
  3414. basisu::vector<image> source_image(1);
  3415. source_image[0].crop(width, height, width, g_black_color, false);
  3416. for (uint32_t y = 0; y < height; y++)
  3417. memcpy(source_image[0].get_ptr() + y * width, (const color_rgba*)pImageRGBA + y * pitch_in_pixels, width * sizeof(color_rgba));
  3418. return basis_compress(mode, source_image, flags_and_quality, uastc_rdo_quality, pSize, pStats);
  3419. }
  3420. void basis_free_data(void* p)
  3421. {
  3422. free(p);
  3423. }
  3424. bool basis_benchmark_etc1s_opencl(bool* pOpenCL_failed)
  3425. {
  3426. if (pOpenCL_failed)
  3427. *pOpenCL_failed = false;
  3428. if (!opencl_is_available())
  3429. {
  3430. error_printf("basis_benchmark_etc1s_opencl: OpenCL support must be enabled first!\n");
  3431. return false;
  3432. }
  3433. const uint32_t W = 1024, H = 1024;
  3434. basisu::vector<image> images;
  3435. image& img = images.enlarge(1)->resize(W, H);
  3436. const uint32_t NUM_RAND_LETTERS = 6000;// 40000;
  3437. rand r;
  3438. r.seed(200);
  3439. for (uint32_t i = 0; i < NUM_RAND_LETTERS; i++)
  3440. {
  3441. uint32_t x = r.irand(0, W - 1), y = r.irand(0, H - 1);
  3442. uint32_t sx = r.irand(1, 4), sy = r.irand(1, 4);
  3443. color_rgba c(r.byte(), r.byte(), r.byte(), 255);
  3444. img.debug_text(x, y, sx, sy, c, nullptr, false, "%c", static_cast<char>(r.irand(32, 127)));
  3445. }
  3446. //save_png("test.png", img);
  3447. image_stats stats;
  3448. uint32_t flags_and_quality = cFlagSRGB | cFlagThreaded | 255;
  3449. size_t comp_size = 0;
  3450. double best_cpu_time = 1e+9f, best_gpu_time = 1e+9f;
  3451. const uint32_t TIMES_TO_ENCODE = 2;
  3452. interval_timer tm;
  3453. for (uint32_t i = 0; i < TIMES_TO_ENCODE; i++)
  3454. {
  3455. tm.start();
  3456. void* pComp_data = basis_compress(
  3457. basist::basis_tex_format::cETC1S,
  3458. images,
  3459. flags_and_quality, 1.0f,
  3460. &comp_size,
  3461. &stats);
  3462. double cpu_time = tm.get_elapsed_secs();
  3463. if (!pComp_data)
  3464. {
  3465. error_printf("basis_benchmark_etc1s_opencl: basis_compress() failed (CPU)!\n");
  3466. return false;
  3467. }
  3468. best_cpu_time = minimum(best_cpu_time, cpu_time);
  3469. basis_free_data(pComp_data);
  3470. }
  3471. printf("Best CPU time: %3.3f\n", best_cpu_time);
  3472. for (uint32_t i = 0; i < TIMES_TO_ENCODE; i++)
  3473. {
  3474. tm.start();
  3475. void* pComp_data = basis_compress(
  3476. basist::basis_tex_format::cETC1S,
  3477. images,
  3478. flags_and_quality | cFlagUseOpenCL, 1.0f,
  3479. &comp_size,
  3480. &stats);
  3481. if (stats.m_opencl_failed)
  3482. {
  3483. error_printf("basis_benchmark_etc1s_opencl: OpenCL failed!\n");
  3484. basis_free_data(pComp_data);
  3485. if (pOpenCL_failed)
  3486. *pOpenCL_failed = true;
  3487. return false;
  3488. }
  3489. double gpu_time = tm.get_elapsed_secs();
  3490. if (!pComp_data)
  3491. {
  3492. error_printf("basis_benchmark_etc1s_opencl: basis_compress() failed (GPU)!\n");
  3493. return false;
  3494. }
  3495. best_gpu_time = minimum(best_gpu_time, gpu_time);
  3496. basis_free_data(pComp_data);
  3497. }
  3498. printf("Best GPU time: %3.3f\n", best_gpu_time);
  3499. return best_gpu_time < best_cpu_time;
  3500. }
  3501. } // namespace basisu