2
0

basisu_comp.cpp 128 KB

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