basisu_comp.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525
  1. // basisu_comp.cpp
  2. // Copyright (C) 2019-2021 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. // basisu_transcoder.cpp is where basisu_miniz lives now, we just need the declarations here.
  20. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  21. #include "basisu_miniz.h"
  22. #include "basisu_opencl.h"
  23. #if !BASISD_SUPPORT_KTX2
  24. #error BASISD_SUPPORT_KTX2 must be enabled (set to 1).
  25. #endif
  26. #if BASISD_SUPPORT_KTX2_ZSTD
  27. #include <zstd.h>
  28. #endif
  29. // Set to 1 to disable the mipPadding alignment workaround (which only seems to be needed when no key-values are written at all)
  30. #define BASISU_DISABLE_KTX2_ALIGNMENT_WORKAROUND (0)
  31. // Set to 1 to disable writing all KTX2 key values, triggering the validator bug.
  32. #define BASISU_DISABLE_KTX2_KEY_VALUES (0)
  33. using namespace buminiz;
  34. #define BASISU_USE_STB_IMAGE_RESIZE_FOR_MIPMAP_GEN 0
  35. #define DEBUG_CROP_TEXTURE_TO_64x64 (0)
  36. #define DEBUG_RESIZE_TEXTURE (0)
  37. #define DEBUG_EXTRACT_SINGLE_BLOCK (0)
  38. namespace basisu
  39. {
  40. basis_compressor::basis_compressor() :
  41. m_pOpenCL_context(nullptr),
  42. m_basis_file_size(0),
  43. m_basis_bits_per_texel(0.0f),
  44. m_total_blocks(0),
  45. m_any_source_image_has_alpha(false),
  46. m_opencl_failed(false)
  47. {
  48. debug_printf("basis_compressor::basis_compressor\n");
  49. assert(g_library_initialized);
  50. }
  51. basis_compressor::~basis_compressor()
  52. {
  53. if (m_pOpenCL_context)
  54. {
  55. opencl_destroy_context(m_pOpenCL_context);
  56. m_pOpenCL_context = nullptr;
  57. }
  58. }
  59. bool basis_compressor::init(const basis_compressor_params &params)
  60. {
  61. debug_printf("basis_compressor::init\n");
  62. if (!g_library_initialized)
  63. {
  64. error_printf("basis_compressor::init: basisu_encoder_init() MUST be called before using any encoder functionality!\n");
  65. return false;
  66. }
  67. if (!params.m_pJob_pool)
  68. {
  69. error_printf("basis_compressor::init: A non-null job_pool pointer must be specified\n");
  70. return false;
  71. }
  72. m_params = params;
  73. if (m_params.m_debug)
  74. {
  75. debug_printf("basis_compressor::init:\n");
  76. #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());
  77. #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());
  78. #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());
  79. #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());
  80. debug_printf("Source images: %u, source filenames: %u, source alpha filenames: %i, Source mipmap images: %u\n",
  81. m_params.m_source_images.size(), m_params.m_source_filenames.size(), m_params.m_source_alpha_filenames.size(), m_params.m_source_mipmap_images.size());
  82. if (m_params.m_source_mipmap_images.size())
  83. {
  84. debug_printf("m_source_mipmap_images array sizes:\n");
  85. for (uint32_t i = 0; i < m_params.m_source_mipmap_images.size(); i++)
  86. debug_printf("%u ", m_params.m_source_mipmap_images[i].size());
  87. debug_printf("\n");
  88. }
  89. PRINT_BOOL_VALUE(m_uastc);
  90. PRINT_BOOL_VALUE(m_use_opencl);
  91. PRINT_BOOL_VALUE(m_y_flip);
  92. PRINT_BOOL_VALUE(m_debug);
  93. PRINT_BOOL_VALUE(m_validate_etc1s);
  94. PRINT_BOOL_VALUE(m_debug_images);
  95. PRINT_INT_VALUE(m_compression_level);
  96. PRINT_BOOL_VALUE(m_perceptual);
  97. PRINT_BOOL_VALUE(m_no_endpoint_rdo);
  98. PRINT_BOOL_VALUE(m_no_selector_rdo);
  99. PRINT_BOOL_VALUE(m_read_source_images);
  100. PRINT_BOOL_VALUE(m_write_output_basis_files);
  101. PRINT_BOOL_VALUE(m_compute_stats);
  102. PRINT_BOOL_VALUE(m_check_for_alpha);
  103. PRINT_BOOL_VALUE(m_force_alpha);
  104. debug_printf("swizzle: %d,%d,%d,%d\n",
  105. m_params.m_swizzle[0],
  106. m_params.m_swizzle[1],
  107. m_params.m_swizzle[2],
  108. m_params.m_swizzle[3]);
  109. PRINT_BOOL_VALUE(m_renormalize);
  110. PRINT_BOOL_VALUE(m_multithreading);
  111. PRINT_BOOL_VALUE(m_disable_hierarchical_endpoint_codebooks);
  112. PRINT_FLOAT_VALUE(m_endpoint_rdo_thresh);
  113. PRINT_FLOAT_VALUE(m_selector_rdo_thresh);
  114. PRINT_BOOL_VALUE(m_mip_gen);
  115. PRINT_BOOL_VALUE(m_mip_renormalize);
  116. PRINT_BOOL_VALUE(m_mip_wrapping);
  117. PRINT_BOOL_VALUE(m_mip_fast);
  118. PRINT_BOOL_VALUE(m_mip_srgb);
  119. PRINT_FLOAT_VALUE(m_mip_premultiplied);
  120. PRINT_FLOAT_VALUE(m_mip_scale);
  121. PRINT_INT_VALUE(m_mip_smallest_dimension);
  122. debug_printf("m_mip_filter: %s\n", m_params.m_mip_filter.c_str());
  123. debug_printf("m_max_endpoint_clusters: %u\n", m_params.m_max_endpoint_clusters);
  124. debug_printf("m_max_selector_clusters: %u\n", m_params.m_max_selector_clusters);
  125. debug_printf("m_quality_level: %i\n", m_params.m_quality_level);
  126. debug_printf("m_tex_type: %u\n", m_params.m_tex_type);
  127. debug_printf("m_userdata0: 0x%X, m_userdata1: 0x%X\n", m_params.m_userdata0, m_params.m_userdata1);
  128. 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);
  129. debug_printf("m_pack_uastc_flags: 0x%X\n", m_params.m_pack_uastc_flags);
  130. PRINT_BOOL_VALUE(m_rdo_uastc);
  131. PRINT_FLOAT_VALUE(m_rdo_uastc_quality_scalar);
  132. PRINT_INT_VALUE(m_rdo_uastc_dict_size);
  133. PRINT_FLOAT_VALUE(m_rdo_uastc_max_allowed_rms_increase_ratio);
  134. PRINT_FLOAT_VALUE(m_rdo_uastc_skip_block_rms_thresh);
  135. PRINT_FLOAT_VALUE(m_rdo_uastc_max_smooth_block_error_scale);
  136. PRINT_FLOAT_VALUE(m_rdo_uastc_smooth_block_max_std_dev);
  137. PRINT_BOOL_VALUE(m_rdo_uastc_favor_simpler_modes_in_rdo_mode)
  138. PRINT_BOOL_VALUE(m_rdo_uastc_multithreading);
  139. PRINT_INT_VALUE(m_resample_width);
  140. PRINT_INT_VALUE(m_resample_height);
  141. PRINT_FLOAT_VALUE(m_resample_factor);
  142. debug_printf("Has global codebooks: %u\n", m_params.m_pGlobal_codebooks ? 1 : 0);
  143. if (m_params.m_pGlobal_codebooks)
  144. {
  145. 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());
  146. }
  147. PRINT_BOOL_VALUE(m_create_ktx2_file);
  148. debug_printf("KTX2 UASTC supercompression: %u\n", m_params.m_ktx2_uastc_supercompression);
  149. debug_printf("KTX2 Zstd supercompression level: %i\n", (int)m_params.m_ktx2_zstd_supercompression_level);
  150. debug_printf("KTX2 sRGB transfer func: %u\n", (int)m_params.m_ktx2_srgb_transfer_func);
  151. debug_printf("Total KTX2 key values: %u\n", m_params.m_ktx2_key_values.size());
  152. for (uint32_t i = 0; i < m_params.m_ktx2_key_values.size(); i++)
  153. {
  154. debug_printf("Key: \"%s\"\n", m_params.m_ktx2_key_values[i].m_key.data());
  155. debug_printf("Value size: %u\n", m_params.m_ktx2_key_values[i].m_value.size());
  156. }
  157. PRINT_BOOL_VALUE(m_validate_output_data);
  158. #undef PRINT_BOOL_VALUE
  159. #undef PRINT_INT_VALUE
  160. #undef PRINT_UINT_VALUE
  161. #undef PRINT_FLOAT_VALUE
  162. }
  163. if ((m_params.m_read_source_images) && (!m_params.m_source_filenames.size()))
  164. {
  165. assert(0);
  166. return false;
  167. }
  168. if ((m_params.m_compute_stats) && (!m_params.m_validate_output_data))
  169. {
  170. m_params.m_validate_output_data = true;
  171. debug_printf("Note: m_compute_stats is true, so forcing m_validate_output_data to true as well\n");
  172. }
  173. if ((m_params.m_use_opencl) && opencl_is_available() && !m_pOpenCL_context && !m_opencl_failed)
  174. {
  175. m_pOpenCL_context = opencl_create_context();
  176. if (!m_pOpenCL_context)
  177. m_opencl_failed = true;
  178. }
  179. return true;
  180. }
  181. basis_compressor::error_code basis_compressor::process()
  182. {
  183. debug_printf("basis_compressor::process\n");
  184. if (!read_source_images())
  185. return cECFailedReadingSourceImages;
  186. if (!validate_texture_type_constraints())
  187. return cECFailedValidating;
  188. if (m_params.m_create_ktx2_file)
  189. {
  190. if (!validate_ktx2_constraints())
  191. return cECFailedValidating;
  192. }
  193. if (!extract_source_blocks())
  194. return cECFailedFrontEnd;
  195. if (m_params.m_uastc)
  196. {
  197. error_code ec = encode_slices_to_uastc();
  198. if (ec != cECSuccess)
  199. return ec;
  200. }
  201. else
  202. {
  203. if (!process_frontend())
  204. return cECFailedFrontEnd;
  205. if (!extract_frontend_texture_data())
  206. return cECFailedFontendExtract;
  207. if (!process_backend())
  208. return cECFailedBackend;
  209. }
  210. if (!create_basis_file_and_transcode())
  211. return cECFailedCreateBasisFile;
  212. if (m_params.m_create_ktx2_file)
  213. {
  214. if (!create_ktx2_file())
  215. return cECFailedCreateKTX2File;
  216. }
  217. if (!write_output_files_and_compute_stats())
  218. return cECFailedWritingOutput;
  219. return cECSuccess;
  220. }
  221. basis_compressor::error_code basis_compressor::encode_slices_to_uastc()
  222. {
  223. debug_printf("basis_compressor::encode_slices_to_uastc\n");
  224. m_uastc_slice_textures.resize(m_slice_descs.size());
  225. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  226. 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);
  227. m_uastc_backend_output.m_tex_format = basist::basis_tex_format::cUASTC4x4;
  228. m_uastc_backend_output.m_etc1s = false;
  229. m_uastc_backend_output.m_slice_desc = m_slice_descs;
  230. m_uastc_backend_output.m_slice_image_data.resize(m_slice_descs.size());
  231. m_uastc_backend_output.m_slice_image_crcs.resize(m_slice_descs.size());
  232. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  233. {
  234. gpu_image& tex = m_uastc_slice_textures[slice_index];
  235. basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  236. (void)slice_desc;
  237. const uint32_t num_blocks_x = tex.get_blocks_x();
  238. const uint32_t num_blocks_y = tex.get_blocks_y();
  239. const uint32_t total_blocks = tex.get_total_blocks();
  240. const image& source_image = m_slice_images[slice_index];
  241. std::atomic<uint32_t> total_blocks_processed;
  242. total_blocks_processed = 0;
  243. const uint32_t N = 256;
  244. for (uint32_t block_index_iter = 0; block_index_iter < total_blocks; block_index_iter += N)
  245. {
  246. const uint32_t first_index = block_index_iter;
  247. const uint32_t last_index = minimum<uint32_t>(total_blocks, block_index_iter + N);
  248. // FIXME: This sucks, but we're having a stack size related problem with std::function with emscripten.
  249. #ifndef __EMSCRIPTEN__
  250. 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]
  251. {
  252. #endif
  253. BASISU_NOTE_UNUSED(num_blocks_y);
  254. uint32_t uastc_flags = m_params.m_pack_uastc_flags;
  255. if ((m_params.m_rdo_uastc) && (m_params.m_rdo_uastc_favor_simpler_modes_in_rdo_mode))
  256. uastc_flags |= cPackUASTCFavorSimplerModes;
  257. for (uint32_t block_index = first_index; block_index < last_index; block_index++)
  258. {
  259. const uint32_t block_x = block_index % num_blocks_x;
  260. const uint32_t block_y = block_index / num_blocks_x;
  261. color_rgba block_pixels[4][4];
  262. source_image.extract_block_clamped((color_rgba*)block_pixels, block_x * 4, block_y * 4, 4, 4);
  263. basist::uastc_block& dest_block = *(basist::uastc_block*)tex.get_block_ptr(block_x, block_y);
  264. encode_uastc(&block_pixels[0][0].r, dest_block, uastc_flags);
  265. total_blocks_processed++;
  266. uint32_t val = total_blocks_processed;
  267. if ((val & 16383) == 16383)
  268. {
  269. debug_printf("basis_compressor::encode_slices_to_uastc: %3.1f%% done\n", static_cast<float>(val) * 100.0f / total_blocks);
  270. }
  271. }
  272. #ifndef __EMSCRIPTEN__
  273. });
  274. #endif
  275. } // block_index_iter
  276. #ifndef __EMSCRIPTEN__
  277. m_params.m_pJob_pool->wait_for_all();
  278. #endif
  279. if (m_params.m_rdo_uastc)
  280. {
  281. uastc_rdo_params rdo_params;
  282. rdo_params.m_lambda = m_params.m_rdo_uastc_quality_scalar;
  283. rdo_params.m_max_allowed_rms_increase_ratio = m_params.m_rdo_uastc_max_allowed_rms_increase_ratio;
  284. rdo_params.m_skip_block_rms_thresh = m_params.m_rdo_uastc_skip_block_rms_thresh;
  285. rdo_params.m_lz_dict_size = m_params.m_rdo_uastc_dict_size;
  286. rdo_params.m_smooth_block_max_error_scale = m_params.m_rdo_uastc_max_smooth_block_error_scale;
  287. rdo_params.m_max_smooth_block_std_dev = m_params.m_rdo_uastc_smooth_block_max_std_dev;
  288. bool status = uastc_rdo(tex.get_total_blocks(), (basist::uastc_block*)tex.get_ptr(),
  289. (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,
  290. (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);
  291. if (!status)
  292. {
  293. return cECFailedUASTCRDOPostProcess;
  294. }
  295. }
  296. m_uastc_backend_output.m_slice_image_data[slice_index].resize(tex.get_size_in_bytes());
  297. memcpy(&m_uastc_backend_output.m_slice_image_data[slice_index][0], tex.get_ptr(), tex.get_size_in_bytes());
  298. m_uastc_backend_output.m_slice_image_crcs[slice_index] = basist::crc16(tex.get_ptr(), tex.get_size_in_bytes(), 0);
  299. } // slice_index
  300. return cECSuccess;
  301. }
  302. bool basis_compressor::generate_mipmaps(const image &img, basisu::vector<image> &mips, bool has_alpha)
  303. {
  304. debug_printf("basis_compressor::generate_mipmaps\n");
  305. interval_timer tm;
  306. tm.start();
  307. uint32_t total_levels = 1;
  308. uint32_t w = img.get_width(), h = img.get_height();
  309. while (maximum<uint32_t>(w, h) > (uint32_t)m_params.m_mip_smallest_dimension)
  310. {
  311. w = maximum(w >> 1U, 1U);
  312. h = maximum(h >> 1U, 1U);
  313. total_levels++;
  314. }
  315. #if BASISU_USE_STB_IMAGE_RESIZE_FOR_MIPMAP_GEN
  316. // Requires stb_image_resize
  317. stbir_filter filter = STBIR_FILTER_DEFAULT;
  318. if (m_params.m_mip_filter == "box")
  319. filter = STBIR_FILTER_BOX;
  320. else if (m_params.m_mip_filter == "triangle")
  321. filter = STBIR_FILTER_TRIANGLE;
  322. else if (m_params.m_mip_filter == "cubic")
  323. filter = STBIR_FILTER_CUBICBSPLINE;
  324. else if (m_params.m_mip_filter == "catmull")
  325. filter = STBIR_FILTER_CATMULLROM;
  326. else if (m_params.m_mip_filter == "mitchell")
  327. filter = STBIR_FILTER_MITCHELL;
  328. for (uint32_t level = 1; level < total_levels; level++)
  329. {
  330. const uint32_t level_width = maximum<uint32_t>(1, img.get_width() >> level);
  331. const uint32_t level_height = maximum<uint32_t>(1, img.get_height() >> level);
  332. image &level_img = *enlarge_vector(mips, 1);
  333. level_img.resize(level_width, level_height);
  334. int result = stbir_resize_uint8_generic(
  335. (const uint8_t *)img.get_ptr(), img.get_width(), img.get_height(), img.get_pitch() * sizeof(color_rgba),
  336. (uint8_t *)level_img.get_ptr(), level_img.get_width(), level_img.get_height(), level_img.get_pitch() * sizeof(color_rgba),
  337. has_alpha ? 4 : 3, has_alpha ? 3 : STBIR_ALPHA_CHANNEL_NONE, m_params.m_mip_premultiplied ? STBIR_FLAG_ALPHA_PREMULTIPLIED : 0,
  338. m_params.m_mip_wrapping ? STBIR_EDGE_WRAP : STBIR_EDGE_CLAMP, filter, m_params.m_mip_srgb ? STBIR_COLORSPACE_SRGB : STBIR_COLORSPACE_LINEAR,
  339. nullptr);
  340. if (result == 0)
  341. {
  342. error_printf("basis_compressor::generate_mipmaps: stbir_resize_uint8_generic() failed!\n");
  343. return false;
  344. }
  345. if (m_params.m_mip_renormalize)
  346. level_img.renormalize_normal_map();
  347. }
  348. #else
  349. for (uint32_t level = 1; level < total_levels; level++)
  350. {
  351. const uint32_t level_width = maximum<uint32_t>(1, img.get_width() >> level);
  352. const uint32_t level_height = maximum<uint32_t>(1, img.get_height() >> level);
  353. image& level_img = *enlarge_vector(mips, 1);
  354. level_img.resize(level_width, level_height);
  355. const image* pSource_image = &img;
  356. if (m_params.m_mip_fast)
  357. {
  358. if (level > 1)
  359. pSource_image = &mips[level - 1];
  360. }
  361. 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);
  362. if (!status)
  363. {
  364. error_printf("basis_compressor::generate_mipmaps: image_resample() failed!\n");
  365. return false;
  366. }
  367. if (m_params.m_mip_renormalize)
  368. level_img.renormalize_normal_map();
  369. }
  370. #endif
  371. if (m_params.m_debug)
  372. debug_printf("Total mipmap generation time: %3.3f secs\n", tm.get_elapsed_secs());
  373. return true;
  374. }
  375. bool basis_compressor::read_source_images()
  376. {
  377. debug_printf("basis_compressor::read_source_images\n");
  378. const uint32_t total_source_files = m_params.m_read_source_images ? (uint32_t)m_params.m_source_filenames.size() : (uint32_t)m_params.m_source_images.size();
  379. if (!total_source_files)
  380. return false;
  381. m_stats.resize(0);
  382. m_slice_descs.resize(0);
  383. m_slice_images.resize(0);
  384. m_total_blocks = 0;
  385. uint32_t total_macroblocks = 0;
  386. m_any_source_image_has_alpha = false;
  387. basisu::vector<image> source_images;
  388. basisu::vector<std::string> source_filenames;
  389. // First load all source images, and determine if any have an alpha channel.
  390. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  391. {
  392. const char *pSource_filename = "";
  393. image file_image;
  394. if (m_params.m_read_source_images)
  395. {
  396. pSource_filename = m_params.m_source_filenames[source_file_index].c_str();
  397. // Load the source image
  398. if (!load_image(pSource_filename, file_image))
  399. {
  400. error_printf("Failed reading source image: %s\n", pSource_filename);
  401. return false;
  402. }
  403. if (m_params.m_status_output)
  404. {
  405. printf("Read source image \"%s\", %ux%u\n", pSource_filename, file_image.get_width(), file_image.get_height());
  406. }
  407. // Optionally load another image and put a grayscale version of it into the alpha channel.
  408. if ((source_file_index < m_params.m_source_alpha_filenames.size()) && (m_params.m_source_alpha_filenames[source_file_index].size()))
  409. {
  410. const char *pSource_alpha_image = m_params.m_source_alpha_filenames[source_file_index].c_str();
  411. image alpha_data;
  412. if (!load_image(pSource_alpha_image, alpha_data))
  413. {
  414. error_printf("Failed reading source image: %s\n", pSource_alpha_image);
  415. return false;
  416. }
  417. printf("Read source alpha image \"%s\", %ux%u\n", pSource_alpha_image, alpha_data.get_width(), alpha_data.get_height());
  418. alpha_data.crop(file_image.get_width(), file_image.get_height());
  419. for (uint32_t y = 0; y < file_image.get_height(); y++)
  420. for (uint32_t x = 0; x < file_image.get_width(); x++)
  421. file_image(x, y).a = (uint8_t)alpha_data(x, y).get_709_luma();
  422. }
  423. }
  424. else
  425. {
  426. file_image = m_params.m_source_images[source_file_index];
  427. }
  428. if (m_params.m_renormalize)
  429. file_image.renormalize_normal_map();
  430. bool alpha_swizzled = false;
  431. if (m_params.m_swizzle[0] != 0 ||
  432. m_params.m_swizzle[1] != 1 ||
  433. m_params.m_swizzle[2] != 2 ||
  434. m_params.m_swizzle[3] != 3)
  435. {
  436. // Used for XY normal maps in RG - puts X in color, Y in alpha
  437. for (uint32_t y = 0; y < file_image.get_height(); y++)
  438. for (uint32_t x = 0; x < file_image.get_width(); x++)
  439. {
  440. const color_rgba &c = file_image(x, y);
  441. 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]]);
  442. }
  443. alpha_swizzled = m_params.m_swizzle[3] != 3;
  444. }
  445. bool has_alpha = false;
  446. if (m_params.m_force_alpha || alpha_swizzled)
  447. has_alpha = true;
  448. else if (!m_params.m_check_for_alpha)
  449. file_image.set_alpha(255);
  450. else if (file_image.has_alpha())
  451. has_alpha = true;
  452. if (has_alpha)
  453. m_any_source_image_has_alpha = true;
  454. debug_printf("Source image index %u filename %s %ux%u has alpha: %u\n", source_file_index, pSource_filename, file_image.get_width(), file_image.get_height(), has_alpha);
  455. if (m_params.m_y_flip)
  456. file_image.flip_y();
  457. #if DEBUG_EXTRACT_SINGLE_BLOCK
  458. image block_image(4, 4);
  459. const uint32_t block_x = 0;
  460. const uint32_t block_y = 0;
  461. block_image.blit(block_x * 4, block_y * 4, 4, 4, 0, 0, file_image, 0);
  462. file_image = block_image;
  463. #endif
  464. #if DEBUG_CROP_TEXTURE_TO_64x64
  465. file_image.resize(64, 64);
  466. #endif
  467. if (m_params.m_resample_width > 0 && m_params.m_resample_height > 0)
  468. {
  469. int new_width = basisu::minimum<int>(m_params.m_resample_width, BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  470. int new_height = basisu::minimum<int>(m_params.m_resample_height, BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION);
  471. debug_printf("Resampling to %ix%i\n", new_width, new_height);
  472. // TODO: A box filter - kaiser looks too sharp on video. Let the caller control this.
  473. image temp_img(new_width, new_height);
  474. image_resample(file_image, temp_img, m_params.m_perceptual, "box"); // "kaiser");
  475. temp_img.swap(file_image);
  476. }
  477. else if (m_params.m_resample_factor > 0.0f)
  478. {
  479. 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);
  480. 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);
  481. debug_printf("Resampling to %ix%i\n", new_width, new_height);
  482. // TODO: A box filter - kaiser looks too sharp on video. Let the caller control this.
  483. image temp_img(new_width, new_height);
  484. image_resample(file_image, temp_img, m_params.m_perceptual, "box"); // "kaiser");
  485. temp_img.swap(file_image);
  486. }
  487. if ((!file_image.get_width()) || (!file_image.get_height()))
  488. {
  489. error_printf("basis_compressor::read_source_images: Source image has a zero width and/or height!\n");
  490. return false;
  491. }
  492. if ((file_image.get_width() > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION) || (file_image.get_height() > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION))
  493. {
  494. error_printf("basis_compressor::read_source_images: Source image \"%s\" is too large!\n", pSource_filename);
  495. return false;
  496. }
  497. source_images.enlarge(1)->swap(file_image);
  498. source_filenames.push_back(pSource_filename);
  499. }
  500. // Check if the caller has generated their own mipmaps.
  501. if (m_params.m_source_mipmap_images.size())
  502. {
  503. // Make sure they've passed us enough mipmap chains.
  504. if ((m_params.m_source_images.size() != m_params.m_source_mipmap_images.size()) || (total_source_files != m_params.m_source_images.size()))
  505. {
  506. error_printf("basis_compressor::read_source_images(): m_params.m_source_mipmap_images.size() must equal m_params.m_source_images.size()!\n");
  507. return false;
  508. }
  509. // Check if any of the user-supplied mipmap levels has alpha.
  510. // We're assuming the user has already preswizzled their mipmap source images.
  511. if (!m_any_source_image_has_alpha)
  512. {
  513. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  514. {
  515. for (uint32_t mip_index = 0; mip_index < m_params.m_source_mipmap_images[source_file_index].size(); mip_index++)
  516. {
  517. const image& mip_img = m_params.m_source_mipmap_images[source_file_index][mip_index];
  518. if (mip_img.has_alpha())
  519. {
  520. m_any_source_image_has_alpha = true;
  521. break;
  522. }
  523. }
  524. if (m_any_source_image_has_alpha)
  525. break;
  526. }
  527. }
  528. }
  529. debug_printf("Any source image has alpha: %u\n", m_any_source_image_has_alpha);
  530. for (uint32_t source_file_index = 0; source_file_index < total_source_files; source_file_index++)
  531. {
  532. const std::string &source_filename = source_filenames[source_file_index];
  533. // Now, for each source image, create the slices corresponding to that image.
  534. basisu::vector<image> slices;
  535. slices.reserve(32);
  536. // The first (largest) mipmap level.
  537. image& file_image = source_images[source_file_index];
  538. // Reserve a slot for mip0.
  539. slices.resize(1);
  540. if (m_params.m_source_mipmap_images.size())
  541. {
  542. // User-provided mipmaps for each layer or image in the texture array.
  543. for (uint32_t mip_index = 0; mip_index < m_params.m_source_mipmap_images[source_file_index].size(); mip_index++)
  544. {
  545. image& mip_img = m_params.m_source_mipmap_images[source_file_index][mip_index];
  546. if (m_params.m_swizzle[0] != 0 ||
  547. m_params.m_swizzle[1] != 1 ||
  548. m_params.m_swizzle[2] != 2 ||
  549. m_params.m_swizzle[3] != 3)
  550. {
  551. // Used for XY normal maps in RG - puts X in color, Y in alpha
  552. for (uint32_t y = 0; y < mip_img.get_height(); y++)
  553. for (uint32_t x = 0; x < mip_img.get_width(); x++)
  554. {
  555. const color_rgba &c = mip_img(x, y);
  556. 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]]);
  557. }
  558. }
  559. slices.push_back(mip_img);
  560. }
  561. }
  562. else if (m_params.m_mip_gen)
  563. {
  564. // Automatically generate mipmaps.
  565. if (!generate_mipmaps(file_image, slices, m_any_source_image_has_alpha))
  566. return false;
  567. }
  568. // Swap in the largest mipmap level here to avoid copying it, because generate_mips() will change the array.
  569. // NOTE: file_image is now blank.
  570. slices[0].swap(file_image);
  571. uint_vec mip_indices(slices.size());
  572. for (uint32_t i = 0; i < slices.size(); i++)
  573. mip_indices[i] = i;
  574. if ((m_any_source_image_has_alpha) && (!m_params.m_uastc))
  575. {
  576. // For ETC1S, if source has alpha, then even mips will have RGB, and odd mips will have alpha in RGB.
  577. basisu::vector<image> alpha_slices;
  578. uint_vec new_mip_indices;
  579. alpha_slices.reserve(slices.size() * 2);
  580. for (uint32_t i = 0; i < slices.size(); i++)
  581. {
  582. image lvl_rgb(slices[i]);
  583. image lvl_a(lvl_rgb);
  584. for (uint32_t y = 0; y < lvl_a.get_height(); y++)
  585. {
  586. for (uint32_t x = 0; x < lvl_a.get_width(); x++)
  587. {
  588. uint8_t a = lvl_a(x, y).a;
  589. lvl_a(x, y).set_noclamp_rgba(a, a, a, 255);
  590. }
  591. }
  592. lvl_rgb.set_alpha(255);
  593. alpha_slices.push_back(lvl_rgb);
  594. new_mip_indices.push_back(i);
  595. alpha_slices.push_back(lvl_a);
  596. new_mip_indices.push_back(i);
  597. }
  598. slices.swap(alpha_slices);
  599. mip_indices.swap(new_mip_indices);
  600. }
  601. assert(slices.size() == mip_indices.size());
  602. for (uint32_t slice_index = 0; slice_index < slices.size(); slice_index++)
  603. {
  604. image& slice_image = slices[slice_index];
  605. const uint32_t orig_width = slice_image.get_width();
  606. const uint32_t orig_height = slice_image.get_height();
  607. bool is_alpha_slice = false;
  608. if (m_any_source_image_has_alpha)
  609. {
  610. if (m_params.m_uastc)
  611. {
  612. is_alpha_slice = slice_image.has_alpha();
  613. }
  614. else
  615. {
  616. is_alpha_slice = (slice_index & 1) != 0;
  617. }
  618. }
  619. // Enlarge the source image to 4x4 block boundaries, duplicating edge pixels if necessary to avoid introducing extra colors into blocks.
  620. slice_image.crop_dup_borders(slice_image.get_block_width(4) * 4, slice_image.get_block_height(4) * 4);
  621. if (m_params.m_debug_images)
  622. {
  623. save_png(string_format("basis_debug_source_image_%u_slice_%u.png", source_file_index, slice_index).c_str(), slice_image);
  624. }
  625. const uint32_t dest_image_index = m_slice_images.size();
  626. enlarge_vector(m_stats, 1);
  627. enlarge_vector(m_slice_images, 1);
  628. enlarge_vector(m_slice_descs, 1);
  629. m_stats[dest_image_index].m_filename = source_filename.c_str();
  630. m_stats[dest_image_index].m_width = orig_width;
  631. m_stats[dest_image_index].m_height = orig_height;
  632. debug_printf("****** Slice %u: mip %u, alpha_slice: %u, filename: \"%s\", original: %ux%u actual: %ux%u\n", m_slice_descs.size() - 1, mip_indices[slice_index], is_alpha_slice, source_filename.c_str(), orig_width, orig_height, slice_image.get_width(), slice_image.get_height());
  633. basisu_backend_slice_desc &slice_desc = m_slice_descs[dest_image_index];
  634. slice_desc.m_first_block_index = m_total_blocks;
  635. slice_desc.m_orig_width = orig_width;
  636. slice_desc.m_orig_height = orig_height;
  637. slice_desc.m_width = slice_image.get_width();
  638. slice_desc.m_height = slice_image.get_height();
  639. slice_desc.m_num_blocks_x = slice_image.get_block_width(4);
  640. slice_desc.m_num_blocks_y = slice_image.get_block_height(4);
  641. slice_desc.m_num_macroblocks_x = (slice_desc.m_num_blocks_x + 1) >> 1;
  642. slice_desc.m_num_macroblocks_y = (slice_desc.m_num_blocks_y + 1) >> 1;
  643. slice_desc.m_source_file_index = source_file_index;
  644. slice_desc.m_mip_index = mip_indices[slice_index];
  645. slice_desc.m_alpha = is_alpha_slice;
  646. slice_desc.m_iframe = false;
  647. if (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames)
  648. {
  649. slice_desc.m_iframe = (source_file_index == 0);
  650. }
  651. m_total_blocks += slice_desc.m_num_blocks_x * slice_desc.m_num_blocks_y;
  652. total_macroblocks += slice_desc.m_num_macroblocks_x * slice_desc.m_num_macroblocks_y;
  653. // Finally, swap in the slice's image to avoid copying it.
  654. // NOTE: slice_image is now blank.
  655. m_slice_images[dest_image_index].swap(slice_image);
  656. } // slice_index
  657. } // source_file_index
  658. debug_printf("Total blocks: %u, Total macroblocks: %u\n", m_total_blocks, total_macroblocks);
  659. // Make sure we don't have too many slices
  660. if (m_slice_descs.size() > BASISU_MAX_SLICES)
  661. {
  662. error_printf("Too many slices!\n");
  663. return false;
  664. }
  665. // Basic sanity check on the slices
  666. for (uint32_t i = 1; i < m_slice_descs.size(); i++)
  667. {
  668. const basisu_backend_slice_desc &prev_slice_desc = m_slice_descs[i - 1];
  669. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  670. // Make sure images are in order
  671. int image_delta = (int)slice_desc.m_source_file_index - (int)prev_slice_desc.m_source_file_index;
  672. if (image_delta > 1)
  673. return false;
  674. // Make sure mipmap levels are in order
  675. if (!image_delta)
  676. {
  677. int level_delta = (int)slice_desc.m_mip_index - (int)prev_slice_desc.m_mip_index;
  678. if (level_delta > 1)
  679. return false;
  680. }
  681. }
  682. if (m_params.m_status_output)
  683. {
  684. printf("Total basis file slices: %u\n", (uint32_t)m_slice_descs.size());
  685. }
  686. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  687. {
  688. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  689. if (m_params.m_status_output)
  690. {
  691. 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",
  692. i, slice_desc.m_alpha, slice_desc.m_orig_width, slice_desc.m_orig_height, slice_desc.m_width, slice_desc.m_height, slice_desc.m_first_block_index, slice_desc.m_source_file_index, slice_desc.m_mip_index, slice_desc.m_iframe);
  693. }
  694. if (m_any_source_image_has_alpha)
  695. {
  696. if (!m_params.m_uastc)
  697. {
  698. // For ETC1S, alpha slices must be at odd slice indices.
  699. if (slice_desc.m_alpha)
  700. {
  701. if ((i & 1) == 0)
  702. return false;
  703. const basisu_backend_slice_desc& prev_slice_desc = m_slice_descs[i - 1];
  704. // Make sure previous slice has this image's color data
  705. if (prev_slice_desc.m_source_file_index != slice_desc.m_source_file_index)
  706. return false;
  707. if (prev_slice_desc.m_alpha)
  708. return false;
  709. if (prev_slice_desc.m_mip_index != slice_desc.m_mip_index)
  710. return false;
  711. if (prev_slice_desc.m_num_blocks_x != slice_desc.m_num_blocks_x)
  712. return false;
  713. if (prev_slice_desc.m_num_blocks_y != slice_desc.m_num_blocks_y)
  714. return false;
  715. }
  716. else if (i & 1)
  717. return false;
  718. }
  719. }
  720. else if (slice_desc.m_alpha)
  721. {
  722. return false;
  723. }
  724. if ((slice_desc.m_orig_width > slice_desc.m_width) || (slice_desc.m_orig_height > slice_desc.m_height))
  725. return false;
  726. if ((slice_desc.m_source_file_index == 0) && (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames))
  727. {
  728. if (!slice_desc.m_iframe)
  729. return false;
  730. }
  731. }
  732. return true;
  733. }
  734. // Do some basic validation for 2D arrays, cubemaps, video, and volumes.
  735. bool basis_compressor::validate_texture_type_constraints()
  736. {
  737. debug_printf("basis_compressor::validate_texture_type_constraints\n");
  738. // In 2D mode anything goes (each image may have a different resolution and # of mipmap levels).
  739. if (m_params.m_tex_type == basist::cBASISTexType2D)
  740. return true;
  741. uint32_t total_basis_images = 0;
  742. for (uint32_t slice_index = 0; slice_index < m_slice_images.size(); slice_index++)
  743. {
  744. const basisu_backend_slice_desc &slice_desc = m_slice_descs[slice_index];
  745. total_basis_images = maximum<uint32_t>(total_basis_images, slice_desc.m_source_file_index + 1);
  746. }
  747. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  748. {
  749. // For cubemaps, validate that the total # of Basis images is a multiple of 6.
  750. if ((total_basis_images % 6) != 0)
  751. {
  752. error_printf("basis_compressor::validate_texture_type_constraints: For cubemaps the total number of input images is not a multiple of 6!\n");
  753. return false;
  754. }
  755. }
  756. // Now validate that all the mip0's have the same dimensions, and that each image has the same # of mipmap levels.
  757. uint_vec image_mipmap_levels(total_basis_images);
  758. int width = -1, height = -1;
  759. for (uint32_t slice_index = 0; slice_index < m_slice_images.size(); slice_index++)
  760. {
  761. const basisu_backend_slice_desc &slice_desc = m_slice_descs[slice_index];
  762. 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);
  763. if (slice_desc.m_mip_index != 0)
  764. continue;
  765. if (width < 0)
  766. {
  767. width = slice_desc.m_orig_width;
  768. height = slice_desc.m_orig_height;
  769. }
  770. else if ((width != (int)slice_desc.m_orig_width) || (height != (int)slice_desc.m_orig_height))
  771. {
  772. error_printf("basis_compressor::validate_texture_type_constraints: The source image resolutions are not all equal!\n");
  773. return false;
  774. }
  775. }
  776. for (size_t i = 1; i < image_mipmap_levels.size(); i++)
  777. {
  778. if (image_mipmap_levels[0] != image_mipmap_levels[i])
  779. {
  780. error_printf("basis_compressor::validate_texture_type_constraints: Each image must have the same number of mipmap levels!\n");
  781. return false;
  782. }
  783. }
  784. return true;
  785. }
  786. bool basis_compressor::extract_source_blocks()
  787. {
  788. debug_printf("basis_compressor::extract_source_blocks\n");
  789. m_source_blocks.resize(m_total_blocks);
  790. for (uint32_t slice_index = 0; slice_index < m_slice_images.size(); slice_index++)
  791. {
  792. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  793. const uint32_t num_blocks_x = slice_desc.m_num_blocks_x;
  794. const uint32_t num_blocks_y = slice_desc.m_num_blocks_y;
  795. const image& source_image = m_slice_images[slice_index];
  796. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  797. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  798. source_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);
  799. }
  800. return true;
  801. }
  802. bool basis_compressor::process_frontend()
  803. {
  804. debug_printf("basis_compressor::process_frontend\n");
  805. #if 0
  806. // TODO
  807. basis_etc1_pack_params pack_params;
  808. pack_params.m_quality = cETCQualityMedium;
  809. pack_params.m_perceptual = m_params.m_perceptual;
  810. pack_params.m_use_color4 = false;
  811. pack_etc1_block_context pack_context;
  812. std::unordered_set<uint64_t> endpoint_hash;
  813. std::unordered_set<uint32_t> selector_hash;
  814. for (uint32_t i = 0; i < m_source_blocks.size(); i++)
  815. {
  816. etc_block blk;
  817. pack_etc1_block(blk, m_source_blocks[i].get_ptr(), pack_params, pack_context);
  818. const color_rgba c0(blk.get_block_color(0, false));
  819. endpoint_hash.insert((c0.r | (c0.g << 5) | (c0.b << 10)) | (blk.get_inten_table(0) << 16));
  820. const color_rgba c1(blk.get_block_color(1, false));
  821. endpoint_hash.insert((c1.r | (c1.g << 5) | (c1.b << 10)) | (blk.get_inten_table(1) << 16));
  822. selector_hash.insert(blk.get_raw_selector_bits());
  823. }
  824. const uint32_t total_unique_endpoints = (uint32_t)endpoint_hash.size();
  825. const uint32_t total_unique_selectors = (uint32_t)selector_hash.size();
  826. if (m_params.m_debug)
  827. {
  828. debug_printf("Unique endpoints: %u, unique selectors: %u\n", total_unique_endpoints, total_unique_selectors);
  829. }
  830. #endif
  831. const double total_texels = m_total_blocks * 16.0f;
  832. int endpoint_clusters = m_params.m_max_endpoint_clusters;
  833. int selector_clusters = m_params.m_max_selector_clusters;
  834. if (endpoint_clusters > basisu_frontend::cMaxEndpointClusters)
  835. {
  836. error_printf("Too many endpoint clusters! (%u but max is %u)\n", endpoint_clusters, basisu_frontend::cMaxEndpointClusters);
  837. return false;
  838. }
  839. if (selector_clusters > basisu_frontend::cMaxSelectorClusters)
  840. {
  841. error_printf("Too many selector clusters! (%u but max is %u)\n", selector_clusters, basisu_frontend::cMaxSelectorClusters);
  842. return false;
  843. }
  844. if (m_params.m_quality_level != -1)
  845. {
  846. const float quality = saturate(m_params.m_quality_level / 255.0f);
  847. const float bits_per_endpoint_cluster = 14.0f;
  848. const float max_desired_endpoint_cluster_bits_per_texel = 1.0f; // .15f
  849. int max_endpoints = static_cast<int>((max_desired_endpoint_cluster_bits_per_texel * total_texels) / bits_per_endpoint_cluster);
  850. const float mid = 128.0f / 255.0f;
  851. float color_endpoint_quality = quality;
  852. const float endpoint_split_point = 0.5f;
  853. // In v1.2 and in previous versions, the endpoint codebook size at quality 128 was 3072. This wasn't quite large enough.
  854. const int ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE = 4800;
  855. const int MAX_ENDPOINT_CODEBOOK_SIZE = 8192;
  856. if (color_endpoint_quality <= mid)
  857. {
  858. color_endpoint_quality = lerp(0.0f, endpoint_split_point, powf(color_endpoint_quality / mid, .65f));
  859. max_endpoints = clamp<int>(max_endpoints, 256, ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE);
  860. max_endpoints = minimum<uint32_t>(max_endpoints, m_total_blocks);
  861. if (max_endpoints < 64)
  862. max_endpoints = 64;
  863. endpoint_clusters = clamp<uint32_t>((uint32_t)(.5f + lerp<float>(32, static_cast<float>(max_endpoints), color_endpoint_quality)), 32, basisu_frontend::cMaxEndpointClusters);
  864. }
  865. else
  866. {
  867. color_endpoint_quality = powf((color_endpoint_quality - mid) / (1.0f - mid), 1.6f);
  868. max_endpoints = clamp<int>(max_endpoints, 256, MAX_ENDPOINT_CODEBOOK_SIZE);
  869. max_endpoints = minimum<uint32_t>(max_endpoints, m_total_blocks);
  870. if (max_endpoints < ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE)
  871. max_endpoints = ENDPOINT_CODEBOOK_MID_QUALITY_CODEBOOK_SIZE;
  872. 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);
  873. }
  874. float bits_per_selector_cluster = 14.0f;
  875. const float max_desired_selector_cluster_bits_per_texel = 1.0f; // .15f
  876. int max_selectors = static_cast<int>((max_desired_selector_cluster_bits_per_texel * total_texels) / bits_per_selector_cluster);
  877. max_selectors = clamp<int>(max_selectors, 256, basisu_frontend::cMaxSelectorClusters);
  878. max_selectors = minimum<uint32_t>(max_selectors, m_total_blocks);
  879. float color_selector_quality = quality;
  880. //color_selector_quality = powf(color_selector_quality, 1.65f);
  881. color_selector_quality = powf(color_selector_quality, 2.62f);
  882. if (max_selectors < 96)
  883. max_selectors = 96;
  884. selector_clusters = clamp<uint32_t>((uint32_t)(.5f + lerp<float>(96, static_cast<float>(max_selectors), color_selector_quality)), 8, basisu_frontend::cMaxSelectorClusters);
  885. debug_printf("Max endpoints: %u, max selectors: %u\n", endpoint_clusters, selector_clusters);
  886. if (m_params.m_quality_level >= 223)
  887. {
  888. if (!m_params.m_selector_rdo_thresh.was_changed())
  889. {
  890. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  891. m_params.m_endpoint_rdo_thresh *= .25f;
  892. if (!m_params.m_selector_rdo_thresh.was_changed())
  893. m_params.m_selector_rdo_thresh *= .25f;
  894. }
  895. }
  896. else if (m_params.m_quality_level >= 192)
  897. {
  898. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  899. m_params.m_endpoint_rdo_thresh *= .5f;
  900. if (!m_params.m_selector_rdo_thresh.was_changed())
  901. m_params.m_selector_rdo_thresh *= .5f;
  902. }
  903. else if (m_params.m_quality_level >= 160)
  904. {
  905. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  906. m_params.m_endpoint_rdo_thresh *= .75f;
  907. if (!m_params.m_selector_rdo_thresh.was_changed())
  908. m_params.m_selector_rdo_thresh *= .75f;
  909. }
  910. else if (m_params.m_quality_level >= 129)
  911. {
  912. float l = (quality - 129 / 255.0f) / ((160 - 129) / 255.0f);
  913. if (!m_params.m_endpoint_rdo_thresh.was_changed())
  914. m_params.m_endpoint_rdo_thresh *= lerp<float>(1.0f, .75f, l);
  915. if (!m_params.m_selector_rdo_thresh.was_changed())
  916. m_params.m_selector_rdo_thresh *= lerp<float>(1.0f, .75f, l);
  917. }
  918. }
  919. basisu_frontend::params p;
  920. p.m_num_source_blocks = m_total_blocks;
  921. p.m_pSource_blocks = &m_source_blocks[0];
  922. p.m_max_endpoint_clusters = endpoint_clusters;
  923. p.m_max_selector_clusters = selector_clusters;
  924. p.m_perceptual = m_params.m_perceptual;
  925. p.m_debug_stats = m_params.m_debug;
  926. p.m_debug_images = m_params.m_debug_images;
  927. p.m_compression_level = m_params.m_compression_level;
  928. p.m_tex_type = m_params.m_tex_type;
  929. p.m_multithreaded = m_params.m_multithreading;
  930. p.m_disable_hierarchical_endpoint_codebooks = m_params.m_disable_hierarchical_endpoint_codebooks;
  931. p.m_validate = m_params.m_validate_etc1s;
  932. p.m_pJob_pool = m_params.m_pJob_pool;
  933. p.m_pGlobal_codebooks = m_params.m_pGlobal_codebooks;
  934. // Don't keep trying to use OpenCL if it ever fails.
  935. p.m_pOpenCL_context = !m_opencl_failed ? m_pOpenCL_context : nullptr;
  936. if (!m_frontend.init(p))
  937. {
  938. error_printf("basisu_frontend::init() failed!\n");
  939. return false;
  940. }
  941. m_frontend.compress();
  942. if (m_frontend.get_opencl_failed())
  943. m_opencl_failed = true;
  944. if (m_params.m_debug_images)
  945. {
  946. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  947. {
  948. char filename[1024];
  949. #ifdef _WIN32
  950. sprintf_s(filename, sizeof(filename), "rdo_frontend_output_output_blocks_%u.png", i);
  951. #else
  952. snprintf(filename, sizeof(filename), "rdo_frontend_output_output_blocks_%u.png", i);
  953. #endif
  954. 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);
  955. #ifdef _WIN32
  956. sprintf_s(filename, sizeof(filename), "rdo_frontend_output_api_%u.png", i);
  957. #else
  958. snprintf(filename, sizeof(filename), "rdo_frontend_output_api_%u.png", i);
  959. #endif
  960. 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);
  961. }
  962. }
  963. return true;
  964. }
  965. bool basis_compressor::extract_frontend_texture_data()
  966. {
  967. if (!m_params.m_compute_stats)
  968. return true;
  969. debug_printf("basis_compressor::extract_frontend_texture_data\n");
  970. m_frontend_output_textures.resize(m_slice_descs.size());
  971. m_best_etc1s_images.resize(m_slice_descs.size());
  972. m_best_etc1s_images_unpacked.resize(m_slice_descs.size());
  973. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  974. {
  975. const basisu_backend_slice_desc &slice_desc = m_slice_descs[i];
  976. const uint32_t num_blocks_x = slice_desc.m_num_blocks_x;
  977. const uint32_t num_blocks_y = slice_desc.m_num_blocks_y;
  978. const uint32_t width = num_blocks_x * 4;
  979. const uint32_t height = num_blocks_y * 4;
  980. m_frontend_output_textures[i].init(texture_format::cETC1, width, height);
  981. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  982. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  983. 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));
  984. #if 0
  985. if (m_params.m_debug_images)
  986. {
  987. char filename[1024];
  988. sprintf_s(filename, sizeof(filename), "rdo_etc_frontend_%u_", i);
  989. write_etc1_vis_images(m_frontend_output_textures[i], filename);
  990. }
  991. #endif
  992. m_best_etc1s_images[i].init(texture_format::cETC1, width, height);
  993. for (uint32_t block_y = 0; block_y < num_blocks_y; block_y++)
  994. for (uint32_t block_x = 0; block_x < num_blocks_x; block_x++)
  995. 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));
  996. m_best_etc1s_images[i].unpack(m_best_etc1s_images_unpacked[i]);
  997. }
  998. return true;
  999. }
  1000. bool basis_compressor::process_backend()
  1001. {
  1002. debug_printf("basis_compressor::process_backend\n");
  1003. basisu_backend_params backend_params;
  1004. backend_params.m_debug = m_params.m_debug;
  1005. backend_params.m_debug_images = m_params.m_debug_images;
  1006. backend_params.m_etc1s = true;
  1007. backend_params.m_compression_level = m_params.m_compression_level;
  1008. if (!m_params.m_no_endpoint_rdo)
  1009. backend_params.m_endpoint_rdo_quality_thresh = m_params.m_endpoint_rdo_thresh;
  1010. if (!m_params.m_no_selector_rdo)
  1011. backend_params.m_selector_rdo_quality_thresh = m_params.m_selector_rdo_thresh;
  1012. backend_params.m_used_global_codebooks = m_frontend.get_params().m_pGlobal_codebooks != nullptr;
  1013. backend_params.m_validate = m_params.m_validate_output_data;
  1014. m_backend.init(&m_frontend, backend_params, m_slice_descs);
  1015. uint32_t total_packed_bytes = m_backend.encode();
  1016. if (!total_packed_bytes)
  1017. {
  1018. error_printf("basis_compressor::encode() failed!\n");
  1019. return false;
  1020. }
  1021. debug_printf("Total packed bytes (estimated): %u\n", total_packed_bytes);
  1022. return true;
  1023. }
  1024. bool basis_compressor::create_basis_file_and_transcode()
  1025. {
  1026. debug_printf("basis_compressor::create_basis_file_and_transcode\n");
  1027. const basisu_backend_output& encoded_output = m_params.m_uastc ? m_uastc_backend_output : m_backend.get_output();
  1028. 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))
  1029. {
  1030. error_printf("basis_compressor::create_basis_file_and_transcode: basisu_backend:init() failed!\n");
  1031. return false;
  1032. }
  1033. const uint8_vec &comp_data = m_basis_file.get_compressed_data();
  1034. m_output_basis_file = comp_data;
  1035. uint32_t total_orig_pixels = 0, total_texels = 0, total_orig_texels = 0;
  1036. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1037. {
  1038. const basisu_backend_slice_desc& slice_desc = m_slice_descs[i];
  1039. total_orig_pixels += slice_desc.m_orig_width * slice_desc.m_orig_height;
  1040. total_texels += slice_desc.m_width * slice_desc.m_height;
  1041. }
  1042. m_basis_file_size = (uint32_t)comp_data.size();
  1043. m_basis_bits_per_texel = total_orig_texels ? (comp_data.size() * 8.0f) / total_orig_texels : 0;
  1044. debug_printf("Total .basis output file size: %u, %3.3f bits/texel\n", comp_data.size(), comp_data.size() * 8.0f / total_orig_pixels);
  1045. if (m_params.m_validate_output_data)
  1046. {
  1047. interval_timer tm;
  1048. tm.start();
  1049. basist::basisu_transcoder_init();
  1050. debug_printf("basist::basisu_transcoder_init: Took %f ms\n", tm.get_elapsed_ms());
  1051. // Verify the compressed data by transcoding it to ASTC (or ETC1)/BC7 and validating the CRC's.
  1052. basist::basisu_transcoder decoder;
  1053. if (!decoder.validate_file_checksums(&comp_data[0], (uint32_t)comp_data.size(), true))
  1054. {
  1055. error_printf("decoder.validate_file_checksums() failed!\n");
  1056. return false;
  1057. }
  1058. m_decoded_output_textures.resize(m_slice_descs.size());
  1059. m_decoded_output_textures_unpacked.resize(m_slice_descs.size());
  1060. m_decoded_output_textures_bc7.resize(m_slice_descs.size());
  1061. m_decoded_output_textures_unpacked_bc7.resize(m_slice_descs.size());
  1062. tm.start();
  1063. if (m_params.m_pGlobal_codebooks)
  1064. {
  1065. decoder.set_global_codebooks(m_params.m_pGlobal_codebooks);
  1066. }
  1067. if (!decoder.start_transcoding(&comp_data[0], (uint32_t)comp_data.size()))
  1068. {
  1069. error_printf("decoder.start_transcoding() failed!\n");
  1070. return false;
  1071. }
  1072. double start_transcoding_time = tm.get_elapsed_secs();
  1073. debug_printf("basisu_compressor::start_transcoding() took %3.3fms\n", start_transcoding_time * 1000.0f);
  1074. double total_time_etc1s_or_astc = 0;
  1075. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1076. {
  1077. gpu_image decoded_texture;
  1078. decoded_texture.init(m_params.m_uastc ? texture_format::cUASTC4x4 : texture_format::cETC1, m_slice_descs[i].m_width, m_slice_descs[i].m_height);
  1079. tm.start();
  1080. basist::block_format format = m_params.m_uastc ? basist::block_format::cUASTC_4x4 : basist::block_format::cETC1;
  1081. uint32_t bytes_per_block = m_params.m_uastc ? 16 : 8;
  1082. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), i,
  1083. 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))
  1084. {
  1085. error_printf("Transcoding failed on slice %u!\n", i);
  1086. return false;
  1087. }
  1088. total_time_etc1s_or_astc += tm.get_elapsed_secs();
  1089. if (encoded_output.m_tex_format == basist::basis_tex_format::cETC1S)
  1090. {
  1091. uint32_t image_crc16 = basist::crc16(decoded_texture.get_ptr(), decoded_texture.get_size_in_bytes(), 0);
  1092. if (image_crc16 != encoded_output.m_slice_image_crcs[i])
  1093. {
  1094. error_printf("Decoded image data CRC check failed on slice %u!\n", i);
  1095. return false;
  1096. }
  1097. debug_printf("Decoded image data CRC check succeeded on slice %i\n", i);
  1098. }
  1099. m_decoded_output_textures[i] = decoded_texture;
  1100. }
  1101. double total_time_bc7 = 0;
  1102. if (basist::basis_is_format_supported(basist::transcoder_texture_format::cTFBC7_RGBA, basist::basis_tex_format::cUASTC4x4) &&
  1103. basist::basis_is_format_supported(basist::transcoder_texture_format::cTFBC7_RGBA, basist::basis_tex_format::cETC1S))
  1104. {
  1105. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1106. {
  1107. gpu_image decoded_texture;
  1108. decoded_texture.init(texture_format::cBC7, m_slice_descs[i].m_width, m_slice_descs[i].m_height);
  1109. tm.start();
  1110. if (!decoder.transcode_slice(&comp_data[0], (uint32_t)comp_data.size(), i,
  1111. 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))
  1112. {
  1113. error_printf("Transcoding failed to BC7 on slice %u!\n", i);
  1114. return false;
  1115. }
  1116. total_time_bc7 += tm.get_elapsed_secs();
  1117. m_decoded_output_textures_bc7[i] = decoded_texture;
  1118. }
  1119. }
  1120. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1121. {
  1122. m_decoded_output_textures[i].unpack(m_decoded_output_textures_unpacked[i]);
  1123. if (m_decoded_output_textures_bc7[i].get_pixel_width())
  1124. m_decoded_output_textures_bc7[i].unpack(m_decoded_output_textures_unpacked_bc7[i]);
  1125. }
  1126. debug_printf("Transcoded to %s in %3.3fms, %f texels/sec\n", m_params.m_uastc ? "ASTC" : "ETC1", total_time_etc1s_or_astc * 1000.0f, total_orig_pixels / total_time_etc1s_or_astc);
  1127. if (total_time_bc7 != 0)
  1128. debug_printf("Transcoded to BC7 in %3.3fms, %f texels/sec\n", total_time_bc7 * 1000.0f, total_orig_pixels / total_time_bc7);
  1129. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1130. {
  1131. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1132. const uint32_t total_blocks = slice_desc.m_num_blocks_x * slice_desc.m_num_blocks_y;
  1133. BASISU_NOTE_UNUSED(total_blocks);
  1134. assert(m_decoded_output_textures[slice_index].get_total_blocks() == total_blocks);
  1135. }
  1136. } // if (m_params.m_validate_output_data)
  1137. return true;
  1138. }
  1139. bool basis_compressor::write_output_files_and_compute_stats()
  1140. {
  1141. debug_printf("basis_compressor::write_output_files_and_compute_stats\n");
  1142. const uint8_vec& comp_data = m_params.m_create_ktx2_file ? m_output_ktx2_file : m_basis_file.get_compressed_data();
  1143. if (m_params.m_write_output_basis_files)
  1144. {
  1145. const std::string& output_filename = m_params.m_out_filename;
  1146. if (!write_vec_to_file(output_filename.c_str(), comp_data))
  1147. {
  1148. error_printf("Failed writing output data to file \"%s\"\n", output_filename.c_str());
  1149. return false;
  1150. }
  1151. if (m_params.m_status_output)
  1152. {
  1153. printf("Wrote output .basis/.ktx2 file \"%s\"\n", output_filename.c_str());
  1154. }
  1155. }
  1156. size_t comp_size = 0;
  1157. if ((m_params.m_compute_stats) && (m_params.m_uastc) && (comp_data.size()))
  1158. {
  1159. void* pComp_data = tdefl_compress_mem_to_heap(&comp_data[0], comp_data.size(), &comp_size, TDEFL_MAX_PROBES_MASK);// TDEFL_DEFAULT_MAX_PROBES);
  1160. size_t decomp_size = 0;
  1161. void* pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, comp_size, &decomp_size, 0);
  1162. if ((decomp_size != comp_data.size()) || (memcmp(pDecomp_data, &comp_data[0], decomp_size) != 0))
  1163. {
  1164. printf("basis_compressor::create_basis_file_and_transcode:: miniz compression or decompression failed!\n");
  1165. return false;
  1166. }
  1167. mz_free(pComp_data);
  1168. mz_free(pDecomp_data);
  1169. uint32_t total_texels = 0;
  1170. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1171. total_texels += (m_slice_descs[i].m_num_blocks_x * m_slice_descs[i].m_num_blocks_y) * 16;
  1172. m_basis_bits_per_texel = comp_size * 8.0f / total_texels;
  1173. debug_printf(".basis file size: %u, LZ compressed file size: %u, %3.2f bits/texel\n",
  1174. (uint32_t)comp_data.size(),
  1175. (uint32_t)comp_size,
  1176. m_basis_bits_per_texel);
  1177. }
  1178. m_stats.resize(m_slice_descs.size());
  1179. if (m_params.m_validate_output_data)
  1180. {
  1181. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1182. {
  1183. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1184. if (m_params.m_compute_stats)
  1185. {
  1186. if (m_params.m_print_stats)
  1187. printf("Slice: %u\n", slice_index);
  1188. image_stats& s = m_stats[slice_index];
  1189. // TODO: We used to output SSIM (during heavy encoder development), but this slowed down compression too much. We'll be adding it back.
  1190. image_metrics em;
  1191. // ---- .basis stats
  1192. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 3);
  1193. if (m_params.m_print_stats)
  1194. em.print(".basis RGB Avg: ");
  1195. s.m_basis_rgb_avg_psnr = em.m_psnr;
  1196. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 4);
  1197. if (m_params.m_print_stats)
  1198. em.print(".basis RGBA Avg: ");
  1199. s.m_basis_rgba_avg_psnr = em.m_psnr;
  1200. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 1);
  1201. if (m_params.m_print_stats)
  1202. em.print(".basis R Avg: ");
  1203. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 1, 1);
  1204. if (m_params.m_print_stats)
  1205. em.print(".basis G Avg: ");
  1206. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 2, 1);
  1207. if (m_params.m_print_stats)
  1208. em.print(".basis B Avg: ");
  1209. if (m_params.m_uastc)
  1210. {
  1211. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 3, 1);
  1212. if (m_params.m_print_stats)
  1213. em.print(".basis A Avg: ");
  1214. s.m_basis_a_avg_psnr = em.m_psnr;
  1215. }
  1216. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0);
  1217. if (m_params.m_print_stats)
  1218. em.print(".basis 709 Luma: ");
  1219. s.m_basis_luma_709_psnr = static_cast<float>(em.m_psnr);
  1220. s.m_basis_luma_709_ssim = static_cast<float>(em.m_ssim);
  1221. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0, true, true);
  1222. if (m_params.m_print_stats)
  1223. em.print(".basis 601 Luma: ");
  1224. s.m_basis_luma_601_psnr = static_cast<float>(em.m_psnr);
  1225. if (m_slice_descs.size() == 1)
  1226. {
  1227. const uint32_t output_size = comp_size ? (uint32_t)comp_size : (uint32_t)comp_data.size();
  1228. if (m_params.m_print_stats)
  1229. {
  1230. 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)));
  1231. 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)));
  1232. }
  1233. }
  1234. if (m_decoded_output_textures_unpacked_bc7[slice_index].get_width())
  1235. {
  1236. // ---- BC7 stats
  1237. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 3);
  1238. if (m_params.m_print_stats)
  1239. em.print("BC7 RGB Avg: ");
  1240. s.m_bc7_rgb_avg_psnr = em.m_psnr;
  1241. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 4);
  1242. if (m_params.m_print_stats)
  1243. em.print("BC7 RGBA Avg: ");
  1244. s.m_bc7_rgba_avg_psnr = em.m_psnr;
  1245. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 1);
  1246. if (m_params.m_print_stats)
  1247. em.print("BC7 R Avg: ");
  1248. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 1, 1);
  1249. if (m_params.m_print_stats)
  1250. em.print("BC7 G Avg: ");
  1251. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 2, 1);
  1252. if (m_params.m_print_stats)
  1253. em.print("BC7 B Avg: ");
  1254. if (m_params.m_uastc)
  1255. {
  1256. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 3, 1);
  1257. if (m_params.m_print_stats)
  1258. em.print("BC7 A Avg: ");
  1259. s.m_bc7_a_avg_psnr = em.m_psnr;
  1260. }
  1261. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0);
  1262. if (m_params.m_print_stats)
  1263. em.print("BC7 709 Luma: ");
  1264. s.m_bc7_luma_709_psnr = static_cast<float>(em.m_psnr);
  1265. s.m_bc7_luma_709_ssim = static_cast<float>(em.m_ssim);
  1266. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0, true, true);
  1267. if (m_params.m_print_stats)
  1268. em.print("BC7 601 Luma: ");
  1269. s.m_bc7_luma_601_psnr = static_cast<float>(em.m_psnr);
  1270. }
  1271. if (!m_params.m_uastc)
  1272. {
  1273. // ---- Nearly best possible ETC1S stats
  1274. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 3);
  1275. if (m_params.m_print_stats)
  1276. em.print("Unquantized ETC1S RGB Avg: ");
  1277. s.m_best_etc1s_rgb_avg_psnr = static_cast<float>(em.m_psnr);
  1278. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0);
  1279. if (m_params.m_print_stats)
  1280. em.print("Unquantized ETC1S 709 Luma: ");
  1281. s.m_best_etc1s_luma_709_psnr = static_cast<float>(em.m_psnr);
  1282. s.m_best_etc1s_luma_709_ssim = static_cast<float>(em.m_ssim);
  1283. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0, true, true);
  1284. if (m_params.m_print_stats)
  1285. em.print("Unquantized ETC1S 601 Luma: ");
  1286. s.m_best_etc1s_luma_601_psnr = static_cast<float>(em.m_psnr);
  1287. }
  1288. }
  1289. std::string out_basename;
  1290. if (m_params.m_out_filename.size())
  1291. string_get_filename(m_params.m_out_filename.c_str(), out_basename);
  1292. else if (m_params.m_source_filenames.size())
  1293. string_get_filename(m_params.m_source_filenames[slice_desc.m_source_file_index].c_str(), out_basename);
  1294. string_remove_extension(out_basename);
  1295. out_basename = "basis_debug_" + out_basename + string_format("_slice_%u", slice_index);
  1296. if ((!m_params.m_uastc) && (m_frontend.get_params().m_debug_images))
  1297. {
  1298. // Write "best" ETC1S debug images
  1299. if (!m_params.m_uastc)
  1300. {
  1301. gpu_image best_etc1s_gpu_image(m_best_etc1s_images[slice_index]);
  1302. best_etc1s_gpu_image.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1303. write_compressed_texture_file((out_basename + "_best_etc1s.ktx").c_str(), best_etc1s_gpu_image);
  1304. image best_etc1s_unpacked;
  1305. best_etc1s_gpu_image.unpack(best_etc1s_unpacked);
  1306. save_png(out_basename + "_best_etc1s.png", best_etc1s_unpacked);
  1307. }
  1308. }
  1309. if (m_params.m_debug_images)
  1310. {
  1311. // Write decoded ETC1S/ASTC debug images
  1312. {
  1313. gpu_image decoded_etc1s_or_astc(m_decoded_output_textures[slice_index]);
  1314. decoded_etc1s_or_astc.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1315. write_compressed_texture_file((out_basename + "_transcoded_etc1s_or_astc.ktx").c_str(), decoded_etc1s_or_astc);
  1316. image temp(m_decoded_output_textures_unpacked[slice_index]);
  1317. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1318. save_png(out_basename + "_transcoded_etc1s_or_astc.png", temp);
  1319. }
  1320. // Write decoded BC7 debug images
  1321. if (m_decoded_output_textures_bc7[slice_index].get_pixel_width())
  1322. {
  1323. gpu_image decoded_bc7(m_decoded_output_textures_bc7[slice_index]);
  1324. decoded_bc7.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1325. write_compressed_texture_file((out_basename + "_transcoded_bc7.ktx").c_str(), decoded_bc7);
  1326. image temp(m_decoded_output_textures_unpacked_bc7[slice_index]);
  1327. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1328. save_png(out_basename + "_transcoded_bc7.png", temp);
  1329. }
  1330. }
  1331. }
  1332. } // if (m_params.m_validate_output_data)
  1333. return true;
  1334. }
  1335. // Make sure all the mip 0's have the same dimensions and number of mipmap levels, or we can't encode the KTX2 file.
  1336. bool basis_compressor::validate_ktx2_constraints()
  1337. {
  1338. uint32_t base_width = 0, base_height = 0;
  1339. uint32_t total_layers = 0;
  1340. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1341. {
  1342. if (m_slice_descs[i].m_mip_index == 0)
  1343. {
  1344. if (!base_width)
  1345. {
  1346. base_width = m_slice_descs[i].m_orig_width;
  1347. base_height = m_slice_descs[i].m_orig_height;
  1348. }
  1349. else
  1350. {
  1351. if ((m_slice_descs[i].m_orig_width != base_width) || (m_slice_descs[i].m_orig_height != base_height))
  1352. {
  1353. return false;
  1354. }
  1355. }
  1356. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  1357. }
  1358. }
  1359. basisu::vector<uint32_t> total_mips(total_layers);
  1360. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1361. 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);
  1362. for (uint32_t i = 1; i < total_layers; i++)
  1363. {
  1364. if (total_mips[0] != total_mips[i])
  1365. {
  1366. return false;
  1367. }
  1368. }
  1369. return true;
  1370. }
  1371. 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 };
  1372. 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 };
  1373. 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 };
  1374. 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 };
  1375. void basis_compressor::get_dfd(uint8_vec &dfd, const basist::ktx2_header &header)
  1376. {
  1377. const uint8_t* pDFD;
  1378. uint32_t dfd_len;
  1379. if (m_params.m_uastc)
  1380. {
  1381. if (m_any_source_image_has_alpha)
  1382. {
  1383. pDFD = g_ktx2_uastc_alpha_dfd;
  1384. dfd_len = sizeof(g_ktx2_uastc_alpha_dfd);
  1385. }
  1386. else
  1387. {
  1388. pDFD = g_ktx2_uastc_nonalpha_dfd;
  1389. dfd_len = sizeof(g_ktx2_uastc_nonalpha_dfd);
  1390. }
  1391. }
  1392. else
  1393. {
  1394. if (m_any_source_image_has_alpha)
  1395. {
  1396. pDFD = g_ktx2_etc1s_alpha_dfd;
  1397. dfd_len = sizeof(g_ktx2_etc1s_alpha_dfd);
  1398. }
  1399. else
  1400. {
  1401. pDFD = g_ktx2_etc1s_nonalpha_dfd;
  1402. dfd_len = sizeof(g_ktx2_etc1s_nonalpha_dfd);
  1403. }
  1404. }
  1405. assert(dfd_len >= 44);
  1406. dfd.resize(dfd_len);
  1407. memcpy(dfd.data(), pDFD, dfd_len);
  1408. uint32_t dfd_bits = basisu::read_le_dword(dfd.data() + 3 * sizeof(uint32_t));
  1409. dfd_bits &= ~(0xFF << 16);
  1410. if (m_params.m_ktx2_srgb_transfer_func)
  1411. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_SRGB << 16);
  1412. else
  1413. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_LINEAR << 16);
  1414. basisu::write_le_dword(dfd.data() + 3 * sizeof(uint32_t), dfd_bits);
  1415. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  1416. {
  1417. uint32_t plane_bits = basisu::read_le_dword(dfd.data() + 5 * sizeof(uint32_t));
  1418. plane_bits &= ~0xFF;
  1419. basisu::write_le_dword(dfd.data() + 5 * sizeof(uint32_t), plane_bits);
  1420. }
  1421. // Fix up the DFD channel(s)
  1422. uint32_t dfd_chan0 = basisu::read_le_dword(dfd.data() + 7 * sizeof(uint32_t));
  1423. if (m_params.m_uastc)
  1424. {
  1425. dfd_chan0 &= ~(0xF << 24);
  1426. // TODO: Allow the caller to override this
  1427. if (m_any_source_image_has_alpha)
  1428. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGBA << 24);
  1429. else
  1430. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGB << 24);
  1431. }
  1432. basisu::write_le_dword(dfd.data() + 7 * sizeof(uint32_t), dfd_chan0);
  1433. }
  1434. bool basis_compressor::create_ktx2_file()
  1435. {
  1436. if (m_params.m_uastc)
  1437. {
  1438. if ((m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_NONE) && (m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_ZSTANDARD))
  1439. return false;
  1440. }
  1441. const basisu_backend_output& backend_output = m_backend.get_output();
  1442. // Determine the width/height, number of array layers, mipmap levels, and the number of faces (1 for 2D, 6 for cubemap).
  1443. // This does not support 1D or 3D.
  1444. uint32_t base_width = 0, base_height = 0, total_layers = 0, total_levels = 0, total_faces = 1;
  1445. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1446. {
  1447. if ((m_slice_descs[i].m_mip_index == 0) && (!base_width))
  1448. {
  1449. base_width = m_slice_descs[i].m_orig_width;
  1450. base_height = m_slice_descs[i].m_orig_height;
  1451. }
  1452. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  1453. if (!m_slice_descs[i].m_source_file_index)
  1454. total_levels = maximum<uint32_t>(total_levels, m_slice_descs[i].m_mip_index + 1);
  1455. }
  1456. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  1457. {
  1458. assert((total_layers % 6) == 0);
  1459. total_layers /= 6;
  1460. assert(total_layers >= 1);
  1461. total_faces = 6;
  1462. }
  1463. basist::ktx2_header header;
  1464. memset(&header, 0, sizeof(header));
  1465. memcpy(header.m_identifier, basist::g_ktx2_file_identifier, sizeof(basist::g_ktx2_file_identifier));
  1466. header.m_pixel_width = base_width;
  1467. header.m_pixel_height = base_height;
  1468. header.m_face_count = total_faces;
  1469. header.m_vk_format = basist::KTX2_VK_FORMAT_UNDEFINED;
  1470. header.m_type_size = 1;
  1471. header.m_level_count = total_levels;
  1472. header.m_layer_count = (total_layers > 1) ? total_layers : 0;
  1473. if (m_params.m_uastc)
  1474. {
  1475. switch (m_params.m_ktx2_uastc_supercompression)
  1476. {
  1477. case basist::KTX2_SS_NONE:
  1478. {
  1479. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  1480. break;
  1481. }
  1482. case basist::KTX2_SS_ZSTANDARD:
  1483. {
  1484. #if BASISD_SUPPORT_KTX2_ZSTD
  1485. header.m_supercompression_scheme = basist::KTX2_SS_ZSTANDARD;
  1486. #else
  1487. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  1488. #endif
  1489. break;
  1490. }
  1491. default: assert(0); return false;
  1492. }
  1493. }
  1494. basisu::vector<uint8_vec> level_data_bytes(total_levels);
  1495. basisu::vector<uint8_vec> compressed_level_data_bytes(total_levels);
  1496. uint_vec slice_level_offsets(m_slice_descs.size());
  1497. // This will append the texture data in the correct order (for each level: layer, then face).
  1498. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1499. {
  1500. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1501. slice_level_offsets[slice_index] = level_data_bytes[slice_desc.m_mip_index].size();
  1502. if (m_params.m_uastc)
  1503. append_vector(level_data_bytes[slice_desc.m_mip_index], m_uastc_backend_output.m_slice_image_data[slice_index]);
  1504. else
  1505. append_vector(level_data_bytes[slice_desc.m_mip_index], backend_output.m_slice_image_data[slice_index]);
  1506. }
  1507. // UASTC supercompression
  1508. if ((m_params.m_uastc) && (header.m_supercompression_scheme == basist::KTX2_SS_ZSTANDARD))
  1509. {
  1510. #if BASISD_SUPPORT_KTX2_ZSTD
  1511. for (uint32_t level_index = 0; level_index < total_levels; level_index++)
  1512. {
  1513. compressed_level_data_bytes[level_index].resize(ZSTD_compressBound(level_data_bytes[level_index].size()));
  1514. size_t result = ZSTD_compress(compressed_level_data_bytes[level_index].data(), compressed_level_data_bytes[level_index].size(),
  1515. level_data_bytes[level_index].data(), level_data_bytes[level_index].size(),
  1516. m_params.m_ktx2_zstd_supercompression_level);
  1517. if (ZSTD_isError(result))
  1518. return false;
  1519. compressed_level_data_bytes[level_index].resize(result);
  1520. }
  1521. #else
  1522. // Can't get here
  1523. assert(0);
  1524. return false;
  1525. #endif
  1526. }
  1527. else
  1528. {
  1529. // No supercompression
  1530. compressed_level_data_bytes = level_data_bytes;
  1531. }
  1532. uint8_vec etc1s_global_data;
  1533. // Create ETC1S global supercompressed data
  1534. if (!m_params.m_uastc)
  1535. {
  1536. basist::ktx2_etc1s_global_data_header etc1s_global_data_header;
  1537. clear_obj(etc1s_global_data_header);
  1538. etc1s_global_data_header.m_endpoint_count = backend_output.m_num_endpoints;
  1539. etc1s_global_data_header.m_selector_count = backend_output.m_num_selectors;
  1540. etc1s_global_data_header.m_endpoints_byte_length = backend_output.m_endpoint_palette.size();
  1541. etc1s_global_data_header.m_selectors_byte_length = backend_output.m_selector_palette.size();
  1542. etc1s_global_data_header.m_tables_byte_length = backend_output.m_slice_image_tables.size();
  1543. basisu::vector<basist::ktx2_etc1s_image_desc> etc1s_image_descs(total_levels * total_layers * total_faces);
  1544. memset(etc1s_image_descs.data(), 0, etc1s_image_descs.size_in_bytes());
  1545. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1546. {
  1547. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1548. const uint32_t level_index = slice_desc.m_mip_index;
  1549. uint32_t layer_index = slice_desc.m_source_file_index;
  1550. uint32_t face_index = 0;
  1551. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  1552. {
  1553. face_index = layer_index % 6;
  1554. layer_index /= 6;
  1555. }
  1556. const uint32_t etc1s_image_index = level_index * (total_layers * total_faces) + layer_index * total_faces + face_index;
  1557. if (slice_desc.m_alpha)
  1558. {
  1559. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  1560. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_offset = slice_level_offsets[slice_index];
  1561. }
  1562. else
  1563. {
  1564. if (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames)
  1565. etc1s_image_descs[etc1s_image_index].m_image_flags = !slice_desc.m_iframe ? basist::KTX2_IMAGE_IS_P_FRAME : 0;
  1566. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  1567. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_offset = slice_level_offsets[slice_index];
  1568. }
  1569. } // slice_index
  1570. append_vector(etc1s_global_data, (const uint8_t*)&etc1s_global_data_header, sizeof(etc1s_global_data_header));
  1571. append_vector(etc1s_global_data, (const uint8_t*)etc1s_image_descs.data(), etc1s_image_descs.size_in_bytes());
  1572. append_vector(etc1s_global_data, backend_output.m_endpoint_palette);
  1573. append_vector(etc1s_global_data, backend_output.m_selector_palette);
  1574. append_vector(etc1s_global_data, backend_output.m_slice_image_tables);
  1575. header.m_supercompression_scheme = basist::KTX2_SS_BASISLZ;
  1576. }
  1577. // Key values
  1578. basist::ktx2_transcoder::key_value_vec key_values(m_params.m_ktx2_key_values);
  1579. key_values.enlarge(1);
  1580. const char* pKTXwriter = "KTXwriter";
  1581. key_values.back().m_key.resize(strlen(pKTXwriter) + 1);
  1582. memcpy(key_values.back().m_key.data(), pKTXwriter, strlen(pKTXwriter) + 1);
  1583. char writer_id[128];
  1584. #ifdef _MSC_VER
  1585. sprintf_s(writer_id, sizeof(writer_id), "Basis Universal %s", BASISU_LIB_VERSION_STRING);
  1586. #else
  1587. snprintf(writer_id, sizeof(writer_id), "Basis Universal %s", BASISU_LIB_VERSION_STRING);
  1588. #endif
  1589. key_values.back().m_value.resize(strlen(writer_id) + 1);
  1590. memcpy(key_values.back().m_value.data(), writer_id, strlen(writer_id) + 1);
  1591. key_values.sort();
  1592. #if BASISU_DISABLE_KTX2_KEY_VALUES
  1593. // HACK HACK - Clear the key values array, which causes no key values to be written (triggering the ktx2check validator bug).
  1594. key_values.clear();
  1595. #endif
  1596. uint8_vec key_value_data;
  1597. // DFD
  1598. uint8_vec dfd;
  1599. get_dfd(dfd, header);
  1600. const uint32_t kvd_file_offset = sizeof(header) + sizeof(basist::ktx2_level_index) * total_levels + dfd.size();
  1601. for (uint32_t pass = 0; pass < 2; pass++)
  1602. {
  1603. for (uint32_t i = 0; i < key_values.size(); i++)
  1604. {
  1605. if (key_values[i].m_key.size() < 2)
  1606. return false;
  1607. if (key_values[i].m_key.back() != 0)
  1608. return false;
  1609. const uint64_t total_len = (uint64_t)key_values[i].m_key.size() + (uint64_t)key_values[i].m_value.size();
  1610. if (total_len >= UINT32_MAX)
  1611. return false;
  1612. packed_uint<4> le_len((uint32_t)total_len);
  1613. append_vector(key_value_data, (const uint8_t*)&le_len, sizeof(le_len));
  1614. append_vector(key_value_data, key_values[i].m_key);
  1615. append_vector(key_value_data, key_values[i].m_value);
  1616. const uint32_t ofs = key_value_data.size() & 3;
  1617. const uint32_t padding = (4 - ofs) & 3;
  1618. for (uint32_t p = 0; p < padding; p++)
  1619. key_value_data.push_back(0);
  1620. }
  1621. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  1622. break;
  1623. #if BASISU_DISABLE_KTX2_ALIGNMENT_WORKAROUND
  1624. break;
  1625. #endif
  1626. // Hack to ensure the KVD block ends on a 16 byte boundary, because we have no other official way of aligning the data.
  1627. uint32_t kvd_end_file_offset = kvd_file_offset + key_value_data.size();
  1628. uint32_t bytes_needed_to_pad = (16 - (kvd_end_file_offset & 15)) & 15;
  1629. if (!bytes_needed_to_pad)
  1630. {
  1631. // We're good. No need to add a dummy key.
  1632. break;
  1633. }
  1634. assert(!pass);
  1635. if (pass)
  1636. return false;
  1637. if (bytes_needed_to_pad < 6)
  1638. bytes_needed_to_pad += 16;
  1639. 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);
  1640. // We're not good - need to add a dummy key large enough to force file alignment so the mip level array gets aligned.
  1641. // 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().
  1642. key_values.enlarge(1);
  1643. for (uint32_t i = 0; i < (bytes_needed_to_pad - 4 - 1 - 1); i++)
  1644. key_values.back().m_key.push_back(127);
  1645. key_values.back().m_key.push_back(0);
  1646. key_values.back().m_value.push_back(0);
  1647. key_values.sort();
  1648. key_value_data.resize(0);
  1649. // Try again
  1650. }
  1651. basisu::vector<basist::ktx2_level_index> level_index_array(total_levels);
  1652. memset(level_index_array.data(), 0, level_index_array.size_in_bytes());
  1653. m_output_ktx2_file.clear();
  1654. m_output_ktx2_file.reserve(m_output_basis_file.size());
  1655. // Dummy header
  1656. m_output_ktx2_file.resize(sizeof(header));
  1657. // Level index array
  1658. append_vector(m_output_ktx2_file, (const uint8_t*)level_index_array.data(), level_index_array.size_in_bytes());
  1659. // DFD
  1660. const uint8_t* pDFD = dfd.data();
  1661. uint32_t dfd_len = dfd.size();
  1662. header.m_dfd_byte_offset = m_output_ktx2_file.size();
  1663. header.m_dfd_byte_length = dfd_len;
  1664. append_vector(m_output_ktx2_file, pDFD, dfd_len);
  1665. // Key value data
  1666. if (key_value_data.size())
  1667. {
  1668. assert(kvd_file_offset == m_output_ktx2_file.size());
  1669. header.m_kvd_byte_offset = m_output_ktx2_file.size();
  1670. header.m_kvd_byte_length = key_value_data.size();
  1671. append_vector(m_output_ktx2_file, key_value_data);
  1672. }
  1673. // Global Supercompressed Data
  1674. if (etc1s_global_data.size())
  1675. {
  1676. uint32_t ofs = m_output_ktx2_file.size() & 7;
  1677. uint32_t padding = (8 - ofs) & 7;
  1678. for (uint32_t i = 0; i < padding; i++)
  1679. m_output_ktx2_file.push_back(0);
  1680. header.m_sgd_byte_length = etc1s_global_data.size();
  1681. header.m_sgd_byte_offset = m_output_ktx2_file.size();
  1682. append_vector(m_output_ktx2_file, etc1s_global_data);
  1683. }
  1684. // mipPadding
  1685. if (header.m_supercompression_scheme == basist::KTX2_SS_NONE)
  1686. {
  1687. // We currently can't do this or the validator will incorrectly give an error.
  1688. uint32_t ofs = m_output_ktx2_file.size() & 15;
  1689. uint32_t padding = (16 - ofs) & 15;
  1690. // Make sure we're always aligned here (due to a validator bug).
  1691. if (padding)
  1692. {
  1693. 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);
  1694. }
  1695. for (uint32_t i = 0; i < padding; i++)
  1696. m_output_ktx2_file.push_back(0);
  1697. }
  1698. // Level data - write the smallest mipmap first.
  1699. for (int level = total_levels - 1; level >= 0; level--)
  1700. {
  1701. level_index_array[level].m_byte_length = compressed_level_data_bytes[level].size();
  1702. if (m_params.m_uastc)
  1703. level_index_array[level].m_uncompressed_byte_length = level_data_bytes[level].size();
  1704. level_index_array[level].m_byte_offset = m_output_ktx2_file.size();
  1705. append_vector(m_output_ktx2_file, compressed_level_data_bytes[level]);
  1706. }
  1707. // Write final header
  1708. memcpy(m_output_ktx2_file.data(), &header, sizeof(header));
  1709. // Write final level index array
  1710. memcpy(m_output_ktx2_file.data() + sizeof(header), level_index_array.data(), level_index_array.size_in_bytes());
  1711. debug_printf("Total .ktx2 output file size: %u\n", m_output_ktx2_file.size());
  1712. return true;
  1713. }
  1714. bool basis_parallel_compress(
  1715. uint32_t total_threads,
  1716. const basisu::vector<basis_compressor_params>& params_vec,
  1717. basisu::vector< parallel_results >& results_vec)
  1718. {
  1719. assert(g_library_initialized);
  1720. if (!g_library_initialized)
  1721. {
  1722. error_printf("basis_parallel_compress: basisu_encoder_init() MUST be called before using any encoder functionality!\n");
  1723. return false;
  1724. }
  1725. assert(total_threads >= 1);
  1726. total_threads = basisu::maximum<uint32_t>(total_threads, 1);
  1727. job_pool jpool(total_threads);
  1728. results_vec.resize(0);
  1729. results_vec.resize(params_vec.size());
  1730. std::atomic<bool> result;
  1731. result = true;
  1732. std::atomic<bool> opencl_failed;
  1733. opencl_failed = false;
  1734. for (uint32_t pindex = 0; pindex < params_vec.size(); pindex++)
  1735. {
  1736. jpool.add_job([pindex, &params_vec, &results_vec, &result, &opencl_failed] {
  1737. basis_compressor_params params = params_vec[pindex];
  1738. parallel_results& results = results_vec[pindex];
  1739. interval_timer tm;
  1740. tm.start();
  1741. basis_compressor c;
  1742. // Dummy job pool
  1743. job_pool task_jpool(1);
  1744. params.m_pJob_pool = &task_jpool;
  1745. // TODO: Remove this flag entirely
  1746. params.m_multithreading = true;
  1747. // Stop using OpenCL if a failure ever occurs.
  1748. if (opencl_failed)
  1749. params.m_use_opencl = false;
  1750. bool status = c.init(params);
  1751. if (c.get_opencl_failed())
  1752. opencl_failed = true;
  1753. if (status)
  1754. {
  1755. basis_compressor::error_code ec = c.process();
  1756. if (c.get_opencl_failed())
  1757. opencl_failed = true;
  1758. results.m_error_code = ec;
  1759. if (ec == basis_compressor::cECSuccess)
  1760. {
  1761. results.m_basis_file = c.get_output_basis_file();
  1762. results.m_ktx2_file = c.get_output_ktx2_file();
  1763. results.m_stats = c.get_stats();
  1764. results.m_basis_bits_per_texel = c.get_basis_bits_per_texel();
  1765. results.m_any_source_image_has_alpha = c.get_any_source_image_has_alpha();
  1766. }
  1767. else
  1768. {
  1769. result = false;
  1770. }
  1771. }
  1772. else
  1773. {
  1774. results.m_error_code = basis_compressor::cECFailedInitializing;
  1775. result = false;
  1776. }
  1777. results.m_total_time = tm.get_elapsed_secs();
  1778. } );
  1779. } // pindex
  1780. jpool.wait_for_all();
  1781. if (opencl_failed)
  1782. error_printf("An OpenCL error occured sometime during compression. The compressor fell back to CPU processing after the failure.\n");
  1783. return result;
  1784. }
  1785. void* basis_compress(
  1786. const basisu::vector<image>& source_images,
  1787. uint32_t flags_and_quality, float uastc_rdo_quality,
  1788. size_t* pSize,
  1789. image_stats* pStats)
  1790. {
  1791. // Check input parameters
  1792. if ((!source_images.size()) || (!pSize))
  1793. {
  1794. error_printf("basis_compress: Invalid parameter\n");
  1795. assert(0);
  1796. return nullptr;
  1797. }
  1798. *pSize = 0;
  1799. // Initialize a job pool
  1800. uint32_t num_threads = 1;
  1801. if (flags_and_quality & cFlagThreaded)
  1802. num_threads = basisu::maximum<uint32_t>(1, std::thread::hardware_concurrency());
  1803. job_pool jp(num_threads);
  1804. // Initialize the compressor parameter struct
  1805. basis_compressor_params comp_params;
  1806. comp_params.m_pJob_pool = &jp;
  1807. comp_params.m_y_flip = (flags_and_quality & cFlagYFlip) != 0;
  1808. comp_params.m_debug = (flags_and_quality & cFlagDebug) != 0;
  1809. // Copy the largest mipmap level
  1810. comp_params.m_source_images.resize(1);
  1811. comp_params.m_source_images[0] = source_images[0];
  1812. // Copy the smaller mipmap levels, if any
  1813. if (source_images.size() > 1)
  1814. {
  1815. comp_params.m_source_mipmap_images.resize(1);
  1816. comp_params.m_source_mipmap_images[0].resize(source_images.size() - 1);
  1817. for (uint32_t i = 1; i < source_images.size(); i++)
  1818. comp_params.m_source_mipmap_images[0][i - 1] = source_images[i];
  1819. }
  1820. comp_params.m_multithreading = (flags_and_quality & cFlagThreaded) != 0;
  1821. comp_params.m_use_opencl = (flags_and_quality & cFlagUseOpenCL) != 0;
  1822. comp_params.m_write_output_basis_files = false;
  1823. comp_params.m_perceptual = (flags_and_quality & cFlagSRGB) != 0;
  1824. comp_params.m_mip_srgb = comp_params.m_perceptual;
  1825. comp_params.m_mip_gen = (flags_and_quality & (cFlagGenMipsWrap | cFlagGenMipsClamp)) != 0;
  1826. comp_params.m_mip_wrapping = (flags_and_quality & cFlagGenMipsWrap) != 0;
  1827. comp_params.m_uastc = (flags_and_quality & cFlagUASTC) != 0;
  1828. if (comp_params.m_uastc)
  1829. {
  1830. comp_params.m_pack_uastc_flags = flags_and_quality & cPackUASTCLevelMask;
  1831. comp_params.m_rdo_uastc = (flags_and_quality & cFlagUASTCRDO) != 0;
  1832. comp_params.m_rdo_uastc_quality_scalar = uastc_rdo_quality;
  1833. }
  1834. else
  1835. comp_params.m_quality_level = basisu::maximum<uint32_t>(1, flags_and_quality & 255);
  1836. comp_params.m_create_ktx2_file = (flags_and_quality & cFlagKTX2) != 0;
  1837. if (comp_params.m_create_ktx2_file)
  1838. {
  1839. // Set KTX2 specific parameters.
  1840. if ((flags_and_quality & cFlagKTX2UASTCSuperCompression) && (comp_params.m_uastc))
  1841. comp_params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD;
  1842. comp_params.m_ktx2_srgb_transfer_func = comp_params.m_perceptual;
  1843. }
  1844. comp_params.m_compute_stats = (pStats != nullptr);
  1845. comp_params.m_print_stats = (flags_and_quality & cFlagPrintStats) != 0;
  1846. comp_params.m_status_output = (flags_and_quality & cFlagPrintStatus) != 0;
  1847. // Create the compressor, initialize it, and process the input
  1848. basis_compressor comp;
  1849. if (!comp.init(comp_params))
  1850. {
  1851. error_printf("basis_compress: basis_compressor::init() failed!\n");
  1852. return nullptr;
  1853. }
  1854. basis_compressor::error_code ec = comp.process();
  1855. if (ec != basis_compressor::cECSuccess)
  1856. {
  1857. error_printf("basis_compress: basis_compressor::process() failed with error code %u\n", (uint32_t)ec);
  1858. return nullptr;
  1859. }
  1860. if ((pStats) && (comp.get_opencl_failed()))
  1861. {
  1862. pStats->m_opencl_failed = true;
  1863. }
  1864. // Get the output file data and return it to the caller
  1865. void* pFile_data = nullptr;
  1866. const uint8_vec* pFile_data_vec = comp_params.m_create_ktx2_file ? &comp.get_output_ktx2_file() : &comp.get_output_basis_file();
  1867. pFile_data = malloc(pFile_data_vec->size());
  1868. if (!pFile_data)
  1869. {
  1870. error_printf("basis_compress: Out of memory\n");
  1871. return nullptr;
  1872. }
  1873. memcpy(pFile_data, pFile_data_vec->get_ptr(), pFile_data_vec->size());
  1874. *pSize = pFile_data_vec->size();
  1875. if ((pStats) && (comp.get_stats().size()))
  1876. {
  1877. *pStats = comp.get_stats()[0];
  1878. }
  1879. return pFile_data;
  1880. }
  1881. void* basis_compress(
  1882. const uint8_t* pImageRGBA, uint32_t width, uint32_t height, uint32_t pitch_in_pixels,
  1883. uint32_t flags_and_quality, float uastc_rdo_quality,
  1884. size_t* pSize,
  1885. image_stats* pStats)
  1886. {
  1887. if (!pitch_in_pixels)
  1888. pitch_in_pixels = width;
  1889. if ((!pImageRGBA) || (!width) || (!height) || (pitch_in_pixels < width) || (!pSize))
  1890. {
  1891. error_printf("basis_compress: Invalid parameter\n");
  1892. assert(0);
  1893. return nullptr;
  1894. }
  1895. *pSize = 0;
  1896. if ((width > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION) || (height > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION))
  1897. {
  1898. error_printf("basis_compress: Image too large\n");
  1899. return nullptr;
  1900. }
  1901. // Copy the source image
  1902. basisu::vector<image> source_image(1);
  1903. source_image[0].crop(width, height, width, g_black_color, false);
  1904. for (uint32_t y = 0; y < height; y++)
  1905. memcpy(source_image[0].get_ptr() + y * width, (const color_rgba*)pImageRGBA + y * pitch_in_pixels, width * sizeof(color_rgba));
  1906. return basis_compress(source_image, flags_and_quality, uastc_rdo_quality, pSize, pStats);
  1907. }
  1908. void basis_free_data(void* p)
  1909. {
  1910. free(p);
  1911. }
  1912. bool basis_benchmark_etc1s_opencl(bool* pOpenCL_failed)
  1913. {
  1914. if (pOpenCL_failed)
  1915. *pOpenCL_failed = false;
  1916. if (!opencl_is_available())
  1917. {
  1918. error_printf("basis_benchmark_etc1s_opencl: OpenCL support must be enabled first!\n");
  1919. return false;
  1920. }
  1921. const uint32_t W = 1024, H = 1024;
  1922. basisu::vector<image> images;
  1923. image& img = images.enlarge(1)->resize(W, H);
  1924. const uint32_t NUM_RAND_LETTERS = 6000;// 40000;
  1925. rand r;
  1926. r.seed(200);
  1927. for (uint32_t i = 0; i < NUM_RAND_LETTERS; i++)
  1928. {
  1929. uint32_t x = r.irand(0, W - 1), y = r.irand(0, H - 1);
  1930. uint32_t sx = r.irand(1, 4), sy = r.irand(1, 4);
  1931. color_rgba c(r.byte(), r.byte(), r.byte(), 255);
  1932. img.debug_text(x, y, sx, sy, c, nullptr, false, "%c", static_cast<char>(r.irand(32, 127)));
  1933. }
  1934. //save_png("test.png", img);
  1935. image_stats stats;
  1936. uint32_t flags_and_quality = cFlagSRGB | cFlagThreaded | 255;
  1937. size_t comp_size = 0;
  1938. double best_cpu_time = 1e+9f, best_gpu_time = 1e+9f;
  1939. const uint32_t TIMES_TO_ENCODE = 2;
  1940. interval_timer tm;
  1941. for (uint32_t i = 0; i < TIMES_TO_ENCODE; i++)
  1942. {
  1943. tm.start();
  1944. void* pComp_data = basis_compress(
  1945. images,
  1946. flags_and_quality, 1.0f,
  1947. &comp_size,
  1948. &stats);
  1949. double cpu_time = tm.get_elapsed_secs();
  1950. if (!pComp_data)
  1951. {
  1952. error_printf("basis_benchmark_etc1s_opencl: basis_compress() failed (CPU)!\n");
  1953. return false;
  1954. }
  1955. best_cpu_time = minimum(best_cpu_time, cpu_time);
  1956. basis_free_data(pComp_data);
  1957. }
  1958. printf("Best CPU time: %3.3f\n", best_cpu_time);
  1959. for (uint32_t i = 0; i < TIMES_TO_ENCODE; i++)
  1960. {
  1961. tm.start();
  1962. void* pComp_data = basis_compress(
  1963. images,
  1964. flags_and_quality | cFlagUseOpenCL, 1.0f,
  1965. &comp_size,
  1966. &stats);
  1967. if (stats.m_opencl_failed)
  1968. {
  1969. error_printf("basis_benchmark_etc1s_opencl: OpenCL failed!\n");
  1970. basis_free_data(pComp_data);
  1971. if (pOpenCL_failed)
  1972. *pOpenCL_failed = true;
  1973. return false;
  1974. }
  1975. double gpu_time = tm.get_elapsed_secs();
  1976. if (!pComp_data)
  1977. {
  1978. error_printf("basis_benchmark_etc1s_opencl: basis_compress() failed (GPU)!\n");
  1979. return false;
  1980. }
  1981. best_gpu_time = minimum(best_gpu_time, gpu_time);
  1982. basis_free_data(pComp_data);
  1983. }
  1984. printf("Best GPU time: %3.3f\n", best_gpu_time);
  1985. return best_gpu_time < best_cpu_time;
  1986. }
  1987. } // namespace basisu