basisu_comp.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391
  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/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. printf("Slice: %u\n", slice_index);
  1187. image_stats& s = m_stats[slice_index];
  1188. // TODO: We used to output SSIM (during heavy encoder development), but this slowed down compression too much. We'll be adding it back.
  1189. image_metrics em;
  1190. // ---- .basis stats
  1191. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 3);
  1192. em.print(".basis RGB Avg: ");
  1193. s.m_basis_rgb_avg_psnr = em.m_psnr;
  1194. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 4);
  1195. em.print(".basis RGBA Avg: ");
  1196. s.m_basis_rgba_avg_psnr = em.m_psnr;
  1197. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 1);
  1198. em.print(".basis R Avg: ");
  1199. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 1, 1);
  1200. em.print(".basis G Avg: ");
  1201. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 2, 1);
  1202. em.print(".basis B Avg: ");
  1203. if (m_params.m_uastc)
  1204. {
  1205. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 3, 1);
  1206. em.print(".basis A Avg: ");
  1207. s.m_basis_a_avg_psnr = em.m_psnr;
  1208. }
  1209. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0);
  1210. em.print(".basis 709 Luma: ");
  1211. s.m_basis_luma_709_psnr = static_cast<float>(em.m_psnr);
  1212. s.m_basis_luma_709_ssim = static_cast<float>(em.m_ssim);
  1213. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked[slice_index], 0, 0, true, true);
  1214. em.print(".basis 601 Luma: ");
  1215. s.m_basis_luma_601_psnr = static_cast<float>(em.m_psnr);
  1216. if (m_slice_descs.size() == 1)
  1217. {
  1218. const uint32_t output_size = comp_size ? (uint32_t)comp_size : (uint32_t)comp_data.size();
  1219. 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)));
  1220. 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)));
  1221. }
  1222. if (m_decoded_output_textures_unpacked_bc7[slice_index].get_width())
  1223. {
  1224. // ---- BC7 stats
  1225. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 3);
  1226. em.print("BC7 RGB Avg: ");
  1227. s.m_bc7_rgb_avg_psnr = em.m_psnr;
  1228. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 4);
  1229. em.print("BC7 RGBA Avg: ");
  1230. s.m_bc7_rgba_avg_psnr = em.m_psnr;
  1231. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 1);
  1232. em.print("BC7 R Avg: ");
  1233. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 1, 1);
  1234. em.print("BC7 G Avg: ");
  1235. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 2, 1);
  1236. em.print("BC7 B Avg: ");
  1237. if (m_params.m_uastc)
  1238. {
  1239. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 3, 1);
  1240. em.print("BC7 A Avg: ");
  1241. s.m_bc7_a_avg_psnr = em.m_psnr;
  1242. }
  1243. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0);
  1244. em.print("BC7 709 Luma: ");
  1245. s.m_bc7_luma_709_psnr = static_cast<float>(em.m_psnr);
  1246. s.m_bc7_luma_709_ssim = static_cast<float>(em.m_ssim);
  1247. em.calc(m_slice_images[slice_index], m_decoded_output_textures_unpacked_bc7[slice_index], 0, 0, true, true);
  1248. em.print("BC7 601 Luma: ");
  1249. s.m_bc7_luma_601_psnr = static_cast<float>(em.m_psnr);
  1250. }
  1251. if (!m_params.m_uastc)
  1252. {
  1253. // ---- Nearly best possible ETC1S stats
  1254. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 3);
  1255. em.print("Unquantized ETC1S RGB Avg: ");
  1256. s.m_best_etc1s_rgb_avg_psnr = static_cast<float>(em.m_psnr);
  1257. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0);
  1258. em.print("Unquantized ETC1S 709 Luma: ");
  1259. s.m_best_etc1s_luma_709_psnr = static_cast<float>(em.m_psnr);
  1260. s.m_best_etc1s_luma_709_ssim = static_cast<float>(em.m_ssim);
  1261. em.calc(m_slice_images[slice_index], m_best_etc1s_images_unpacked[slice_index], 0, 0, true, true);
  1262. em.print("Unquantized ETC1S 601 Luma: ");
  1263. s.m_best_etc1s_luma_601_psnr = static_cast<float>(em.m_psnr);
  1264. }
  1265. }
  1266. std::string out_basename;
  1267. if (m_params.m_out_filename.size())
  1268. string_get_filename(m_params.m_out_filename.c_str(), out_basename);
  1269. else if (m_params.m_source_filenames.size())
  1270. string_get_filename(m_params.m_source_filenames[slice_desc.m_source_file_index].c_str(), out_basename);
  1271. string_remove_extension(out_basename);
  1272. out_basename = "basis_debug_" + out_basename + string_format("_slice_%u", slice_index);
  1273. if ((!m_params.m_uastc) && (m_frontend.get_params().m_debug_images))
  1274. {
  1275. // Write "best" ETC1S debug images
  1276. if (!m_params.m_uastc)
  1277. {
  1278. gpu_image best_etc1s_gpu_image(m_best_etc1s_images[slice_index]);
  1279. best_etc1s_gpu_image.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1280. write_compressed_texture_file((out_basename + "_best_etc1s.ktx").c_str(), best_etc1s_gpu_image);
  1281. image best_etc1s_unpacked;
  1282. best_etc1s_gpu_image.unpack(best_etc1s_unpacked);
  1283. save_png(out_basename + "_best_etc1s.png", best_etc1s_unpacked);
  1284. }
  1285. }
  1286. if (m_params.m_debug_images)
  1287. {
  1288. // Write decoded ETC1S/ASTC debug images
  1289. {
  1290. gpu_image decoded_etc1s_or_astc(m_decoded_output_textures[slice_index]);
  1291. decoded_etc1s_or_astc.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1292. write_compressed_texture_file((out_basename + "_transcoded_etc1s_or_astc.ktx").c_str(), decoded_etc1s_or_astc);
  1293. image temp(m_decoded_output_textures_unpacked[slice_index]);
  1294. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1295. save_png(out_basename + "_transcoded_etc1s_or_astc.png", temp);
  1296. }
  1297. // Write decoded BC7 debug images
  1298. if (m_decoded_output_textures_bc7[slice_index].get_pixel_width())
  1299. {
  1300. gpu_image decoded_bc7(m_decoded_output_textures_bc7[slice_index]);
  1301. decoded_bc7.override_dimensions(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1302. write_compressed_texture_file((out_basename + "_transcoded_bc7.ktx").c_str(), decoded_bc7);
  1303. image temp(m_decoded_output_textures_unpacked_bc7[slice_index]);
  1304. temp.crop(slice_desc.m_orig_width, slice_desc.m_orig_height);
  1305. save_png(out_basename + "_transcoded_bc7.png", temp);
  1306. }
  1307. }
  1308. }
  1309. } // if (m_params.m_validate_output_data)
  1310. return true;
  1311. }
  1312. // Make sure all the mip 0's have the same dimensions and number of mipmap levels, or we can't encode the KTX2 file.
  1313. bool basis_compressor::validate_ktx2_constraints()
  1314. {
  1315. uint32_t base_width = 0, base_height = 0;
  1316. uint32_t total_layers = 0;
  1317. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1318. {
  1319. if (m_slice_descs[i].m_mip_index == 0)
  1320. {
  1321. if (!base_width)
  1322. {
  1323. base_width = m_slice_descs[i].m_orig_width;
  1324. base_height = m_slice_descs[i].m_orig_height;
  1325. }
  1326. else
  1327. {
  1328. if ((m_slice_descs[i].m_orig_width != base_width) || (m_slice_descs[i].m_orig_height != base_height))
  1329. {
  1330. return false;
  1331. }
  1332. }
  1333. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  1334. }
  1335. }
  1336. basisu::vector<uint32_t> total_mips(total_layers);
  1337. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1338. 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);
  1339. for (uint32_t i = 1; i < total_layers; i++)
  1340. {
  1341. if (total_mips[0] != total_mips[i])
  1342. {
  1343. return false;
  1344. }
  1345. }
  1346. return true;
  1347. }
  1348. 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 };
  1349. 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 };
  1350. 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 };
  1351. 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 };
  1352. void basis_compressor::get_dfd(uint8_vec &dfd, const basist::ktx2_header &header)
  1353. {
  1354. const uint8_t* pDFD;
  1355. uint32_t dfd_len;
  1356. if (m_params.m_uastc)
  1357. {
  1358. if (m_any_source_image_has_alpha)
  1359. {
  1360. pDFD = g_ktx2_uastc_alpha_dfd;
  1361. dfd_len = sizeof(g_ktx2_uastc_alpha_dfd);
  1362. }
  1363. else
  1364. {
  1365. pDFD = g_ktx2_uastc_nonalpha_dfd;
  1366. dfd_len = sizeof(g_ktx2_uastc_nonalpha_dfd);
  1367. }
  1368. }
  1369. else
  1370. {
  1371. if (m_any_source_image_has_alpha)
  1372. {
  1373. pDFD = g_ktx2_etc1s_alpha_dfd;
  1374. dfd_len = sizeof(g_ktx2_etc1s_alpha_dfd);
  1375. }
  1376. else
  1377. {
  1378. pDFD = g_ktx2_etc1s_nonalpha_dfd;
  1379. dfd_len = sizeof(g_ktx2_etc1s_nonalpha_dfd);
  1380. }
  1381. }
  1382. assert(dfd_len >= 44);
  1383. dfd.resize(dfd_len);
  1384. memcpy(dfd.data(), pDFD, dfd_len);
  1385. uint32_t dfd_bits = basisu::read_le_dword(dfd.data() + 3 * sizeof(uint32_t));
  1386. dfd_bits &= ~(0xFF << 16);
  1387. if (m_params.m_ktx2_srgb_transfer_func)
  1388. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_SRGB << 16);
  1389. else
  1390. dfd_bits |= (basist::KTX2_KHR_DF_TRANSFER_LINEAR << 16);
  1391. basisu::write_le_dword(dfd.data() + 3 * sizeof(uint32_t), dfd_bits);
  1392. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  1393. {
  1394. uint32_t plane_bits = basisu::read_le_dword(dfd.data() + 5 * sizeof(uint32_t));
  1395. plane_bits &= ~0xFF;
  1396. basisu::write_le_dword(dfd.data() + 5 * sizeof(uint32_t), plane_bits);
  1397. }
  1398. // Fix up the DFD channel(s)
  1399. uint32_t dfd_chan0 = basisu::read_le_dword(dfd.data() + 7 * sizeof(uint32_t));
  1400. if (m_params.m_uastc)
  1401. {
  1402. dfd_chan0 &= ~(0xF << 24);
  1403. // TODO: Allow the caller to override this
  1404. if (m_any_source_image_has_alpha)
  1405. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGBA << 24);
  1406. else
  1407. dfd_chan0 |= (basist::KTX2_DF_CHANNEL_UASTC_RGB << 24);
  1408. }
  1409. basisu::write_le_dword(dfd.data() + 7 * sizeof(uint32_t), dfd_chan0);
  1410. }
  1411. bool basis_compressor::create_ktx2_file()
  1412. {
  1413. if (m_params.m_uastc)
  1414. {
  1415. if ((m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_NONE) && (m_params.m_ktx2_uastc_supercompression != basist::KTX2_SS_ZSTANDARD))
  1416. return false;
  1417. }
  1418. const basisu_backend_output& backend_output = m_backend.get_output();
  1419. // Determine the width/height, number of array layers, mipmap levels, and the number of faces (1 for 2D, 6 for cubemap).
  1420. // This does not support 1D or 3D.
  1421. uint32_t base_width = 0, base_height = 0, total_layers = 0, total_levels = 0, total_faces = 1;
  1422. for (uint32_t i = 0; i < m_slice_descs.size(); i++)
  1423. {
  1424. if ((m_slice_descs[i].m_mip_index == 0) && (!base_width))
  1425. {
  1426. base_width = m_slice_descs[i].m_orig_width;
  1427. base_height = m_slice_descs[i].m_orig_height;
  1428. }
  1429. total_layers = maximum<uint32_t>(total_layers, m_slice_descs[i].m_source_file_index + 1);
  1430. if (!m_slice_descs[i].m_source_file_index)
  1431. total_levels = maximum<uint32_t>(total_levels, m_slice_descs[i].m_mip_index + 1);
  1432. }
  1433. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  1434. {
  1435. assert((total_layers % 6) == 0);
  1436. total_layers /= 6;
  1437. assert(total_layers >= 1);
  1438. total_faces = 6;
  1439. }
  1440. basist::ktx2_header header;
  1441. memset(&header, 0, sizeof(header));
  1442. memcpy(header.m_identifier, basist::g_ktx2_file_identifier, sizeof(basist::g_ktx2_file_identifier));
  1443. header.m_pixel_width = base_width;
  1444. header.m_pixel_height = base_height;
  1445. header.m_face_count = total_faces;
  1446. header.m_vk_format = basist::KTX2_VK_FORMAT_UNDEFINED;
  1447. header.m_type_size = 1;
  1448. header.m_level_count = total_levels;
  1449. header.m_layer_count = (total_layers > 1) ? total_layers : 0;
  1450. if (m_params.m_uastc)
  1451. {
  1452. switch (m_params.m_ktx2_uastc_supercompression)
  1453. {
  1454. case basist::KTX2_SS_NONE:
  1455. {
  1456. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  1457. break;
  1458. }
  1459. case basist::KTX2_SS_ZSTANDARD:
  1460. {
  1461. #if BASISD_SUPPORT_KTX2_ZSTD
  1462. header.m_supercompression_scheme = basist::KTX2_SS_ZSTANDARD;
  1463. #else
  1464. header.m_supercompression_scheme = basist::KTX2_SS_NONE;
  1465. #endif
  1466. break;
  1467. }
  1468. default: assert(0); return false;
  1469. }
  1470. }
  1471. basisu::vector<uint8_vec> level_data_bytes(total_levels);
  1472. basisu::vector<uint8_vec> compressed_level_data_bytes(total_levels);
  1473. uint_vec slice_level_offsets(m_slice_descs.size());
  1474. // This will append the texture data in the correct order (for each level: layer, then face).
  1475. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1476. {
  1477. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1478. slice_level_offsets[slice_index] = level_data_bytes[slice_desc.m_mip_index].size();
  1479. if (m_params.m_uastc)
  1480. append_vector(level_data_bytes[slice_desc.m_mip_index], m_uastc_backend_output.m_slice_image_data[slice_index]);
  1481. else
  1482. append_vector(level_data_bytes[slice_desc.m_mip_index], backend_output.m_slice_image_data[slice_index]);
  1483. }
  1484. // UASTC supercompression
  1485. if ((m_params.m_uastc) && (header.m_supercompression_scheme == basist::KTX2_SS_ZSTANDARD))
  1486. {
  1487. #if BASISD_SUPPORT_KTX2_ZSTD
  1488. for (uint32_t level_index = 0; level_index < total_levels; level_index++)
  1489. {
  1490. compressed_level_data_bytes[level_index].resize(ZSTD_compressBound(level_data_bytes[level_index].size()));
  1491. size_t result = ZSTD_compress(compressed_level_data_bytes[level_index].data(), compressed_level_data_bytes[level_index].size(),
  1492. level_data_bytes[level_index].data(), level_data_bytes[level_index].size(),
  1493. m_params.m_ktx2_zstd_supercompression_level);
  1494. if (ZSTD_isError(result))
  1495. return false;
  1496. compressed_level_data_bytes[level_index].resize(result);
  1497. }
  1498. #else
  1499. // Can't get here
  1500. assert(0);
  1501. return false;
  1502. #endif
  1503. }
  1504. else
  1505. {
  1506. // No supercompression
  1507. compressed_level_data_bytes = level_data_bytes;
  1508. }
  1509. uint8_vec etc1s_global_data;
  1510. // Create ETC1S global supercompressed data
  1511. if (!m_params.m_uastc)
  1512. {
  1513. basist::ktx2_etc1s_global_data_header etc1s_global_data_header;
  1514. clear_obj(etc1s_global_data_header);
  1515. etc1s_global_data_header.m_endpoint_count = backend_output.m_num_endpoints;
  1516. etc1s_global_data_header.m_selector_count = backend_output.m_num_selectors;
  1517. etc1s_global_data_header.m_endpoints_byte_length = backend_output.m_endpoint_palette.size();
  1518. etc1s_global_data_header.m_selectors_byte_length = backend_output.m_selector_palette.size();
  1519. etc1s_global_data_header.m_tables_byte_length = backend_output.m_slice_image_tables.size();
  1520. basisu::vector<basist::ktx2_etc1s_image_desc> etc1s_image_descs(total_levels * total_layers * total_faces);
  1521. memset(etc1s_image_descs.data(), 0, etc1s_image_descs.size_in_bytes());
  1522. for (uint32_t slice_index = 0; slice_index < m_slice_descs.size(); slice_index++)
  1523. {
  1524. const basisu_backend_slice_desc& slice_desc = m_slice_descs[slice_index];
  1525. const uint32_t level_index = slice_desc.m_mip_index;
  1526. uint32_t layer_index = slice_desc.m_source_file_index;
  1527. uint32_t face_index = 0;
  1528. if (m_params.m_tex_type == basist::cBASISTexTypeCubemapArray)
  1529. {
  1530. face_index = layer_index % 6;
  1531. layer_index /= 6;
  1532. }
  1533. const uint32_t etc1s_image_index = level_index * (total_layers * total_faces) + layer_index * total_faces + face_index;
  1534. if (slice_desc.m_alpha)
  1535. {
  1536. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  1537. etc1s_image_descs[etc1s_image_index].m_alpha_slice_byte_offset = slice_level_offsets[slice_index];
  1538. }
  1539. else
  1540. {
  1541. if (m_params.m_tex_type == basist::cBASISTexTypeVideoFrames)
  1542. etc1s_image_descs[etc1s_image_index].m_image_flags = !slice_desc.m_iframe ? basist::KTX2_IMAGE_IS_P_FRAME : 0;
  1543. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_length = backend_output.m_slice_image_data[slice_index].size();
  1544. etc1s_image_descs[etc1s_image_index].m_rgb_slice_byte_offset = slice_level_offsets[slice_index];
  1545. }
  1546. } // slice_index
  1547. append_vector(etc1s_global_data, (const uint8_t*)&etc1s_global_data_header, sizeof(etc1s_global_data_header));
  1548. append_vector(etc1s_global_data, (const uint8_t*)etc1s_image_descs.data(), etc1s_image_descs.size_in_bytes());
  1549. append_vector(etc1s_global_data, backend_output.m_endpoint_palette);
  1550. append_vector(etc1s_global_data, backend_output.m_selector_palette);
  1551. append_vector(etc1s_global_data, backend_output.m_slice_image_tables);
  1552. header.m_supercompression_scheme = basist::KTX2_SS_BASISLZ;
  1553. }
  1554. // Key values
  1555. basist::ktx2_transcoder::key_value_vec key_values(m_params.m_ktx2_key_values);
  1556. key_values.enlarge(1);
  1557. const char* pKTXwriter = "KTXwriter";
  1558. key_values.back().m_key.resize(strlen(pKTXwriter) + 1);
  1559. memcpy(key_values.back().m_key.data(), pKTXwriter, strlen(pKTXwriter) + 1);
  1560. char writer_id[128];
  1561. #ifdef _MSC_VER
  1562. sprintf_s(writer_id, sizeof(writer_id), "Basis Universal %s", BASISU_LIB_VERSION_STRING);
  1563. #else
  1564. snprintf(writer_id, sizeof(writer_id), "Basis Universal %s", BASISU_LIB_VERSION_STRING);
  1565. #endif
  1566. key_values.back().m_value.resize(strlen(writer_id) + 1);
  1567. memcpy(key_values.back().m_value.data(), writer_id, strlen(writer_id) + 1);
  1568. key_values.sort();
  1569. #if BASISU_DISABLE_KTX2_KEY_VALUES
  1570. // HACK HACK - Clear the key values array, which causes no key values to be written (triggering the ktx2check validator bug).
  1571. key_values.clear();
  1572. #endif
  1573. uint8_vec key_value_data;
  1574. // DFD
  1575. uint8_vec dfd;
  1576. get_dfd(dfd, header);
  1577. const uint32_t kvd_file_offset = sizeof(header) + sizeof(basist::ktx2_level_index) * total_levels + dfd.size();
  1578. for (uint32_t pass = 0; pass < 2; pass++)
  1579. {
  1580. for (uint32_t i = 0; i < key_values.size(); i++)
  1581. {
  1582. if (key_values[i].m_key.size() < 2)
  1583. return false;
  1584. if (key_values[i].m_key.back() != 0)
  1585. return false;
  1586. const uint64_t total_len = (uint64_t)key_values[i].m_key.size() + (uint64_t)key_values[i].m_value.size();
  1587. if (total_len >= UINT32_MAX)
  1588. return false;
  1589. packed_uint<4> le_len((uint32_t)total_len);
  1590. append_vector(key_value_data, (const uint8_t*)&le_len, sizeof(le_len));
  1591. append_vector(key_value_data, key_values[i].m_key);
  1592. append_vector(key_value_data, key_values[i].m_value);
  1593. const uint32_t ofs = key_value_data.size() & 3;
  1594. const uint32_t padding = (4 - ofs) & 3;
  1595. for (uint32_t p = 0; p < padding; p++)
  1596. key_value_data.push_back(0);
  1597. }
  1598. if (header.m_supercompression_scheme != basist::KTX2_SS_NONE)
  1599. break;
  1600. #if BASISU_DISABLE_KTX2_ALIGNMENT_WORKAROUND
  1601. break;
  1602. #endif
  1603. // Hack to ensure the KVD block ends on a 16 byte boundary, because we have no other official way of aligning the data.
  1604. uint32_t kvd_end_file_offset = kvd_file_offset + key_value_data.size();
  1605. uint32_t bytes_needed_to_pad = (16 - (kvd_end_file_offset & 15)) & 15;
  1606. if (!bytes_needed_to_pad)
  1607. {
  1608. // We're good. No need to add a dummy key.
  1609. break;
  1610. }
  1611. assert(!pass);
  1612. if (pass)
  1613. return false;
  1614. if (bytes_needed_to_pad < 6)
  1615. bytes_needed_to_pad += 16;
  1616. 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);
  1617. // We're not good - need to add a dummy key large enough to force file alignment so the mip level array gets aligned.
  1618. // 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().
  1619. key_values.enlarge(1);
  1620. for (uint32_t i = 0; i < (bytes_needed_to_pad - 4 - 1 - 1); i++)
  1621. key_values.back().m_key.push_back(127);
  1622. key_values.back().m_key.push_back(0);
  1623. key_values.back().m_value.push_back(0);
  1624. key_values.sort();
  1625. key_value_data.resize(0);
  1626. // Try again
  1627. }
  1628. basisu::vector<basist::ktx2_level_index> level_index_array(total_levels);
  1629. memset(level_index_array.data(), 0, level_index_array.size_in_bytes());
  1630. m_output_ktx2_file.clear();
  1631. m_output_ktx2_file.reserve(m_output_basis_file.size());
  1632. // Dummy header
  1633. m_output_ktx2_file.resize(sizeof(header));
  1634. // Level index array
  1635. append_vector(m_output_ktx2_file, (const uint8_t*)level_index_array.data(), level_index_array.size_in_bytes());
  1636. // DFD
  1637. const uint8_t* pDFD = dfd.data();
  1638. uint32_t dfd_len = dfd.size();
  1639. header.m_dfd_byte_offset = m_output_ktx2_file.size();
  1640. header.m_dfd_byte_length = dfd_len;
  1641. append_vector(m_output_ktx2_file, pDFD, dfd_len);
  1642. // Key value data
  1643. if (key_value_data.size())
  1644. {
  1645. assert(kvd_file_offset == m_output_ktx2_file.size());
  1646. header.m_kvd_byte_offset = m_output_ktx2_file.size();
  1647. header.m_kvd_byte_length = key_value_data.size();
  1648. append_vector(m_output_ktx2_file, key_value_data);
  1649. }
  1650. // Global Supercompressed Data
  1651. if (etc1s_global_data.size())
  1652. {
  1653. uint32_t ofs = m_output_ktx2_file.size() & 7;
  1654. uint32_t padding = (8 - ofs) & 7;
  1655. for (uint32_t i = 0; i < padding; i++)
  1656. m_output_ktx2_file.push_back(0);
  1657. header.m_sgd_byte_length = etc1s_global_data.size();
  1658. header.m_sgd_byte_offset = m_output_ktx2_file.size();
  1659. append_vector(m_output_ktx2_file, etc1s_global_data);
  1660. }
  1661. // mipPadding
  1662. if (header.m_supercompression_scheme == basist::KTX2_SS_NONE)
  1663. {
  1664. // We currently can't do this or the validator will incorrectly give an error.
  1665. uint32_t ofs = m_output_ktx2_file.size() & 15;
  1666. uint32_t padding = (16 - ofs) & 15;
  1667. // Make sure we're always aligned here (due to a validator bug).
  1668. if (padding)
  1669. {
  1670. 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);
  1671. }
  1672. for (uint32_t i = 0; i < padding; i++)
  1673. m_output_ktx2_file.push_back(0);
  1674. }
  1675. // Level data - write the smallest mipmap first.
  1676. for (int level = total_levels - 1; level >= 0; level--)
  1677. {
  1678. level_index_array[level].m_byte_length = compressed_level_data_bytes[level].size();
  1679. if (m_params.m_uastc)
  1680. level_index_array[level].m_uncompressed_byte_length = level_data_bytes[level].size();
  1681. level_index_array[level].m_byte_offset = m_output_ktx2_file.size();
  1682. append_vector(m_output_ktx2_file, compressed_level_data_bytes[level]);
  1683. }
  1684. // Write final header
  1685. memcpy(m_output_ktx2_file.data(), &header, sizeof(header));
  1686. // Write final level index array
  1687. memcpy(m_output_ktx2_file.data() + sizeof(header), level_index_array.data(), level_index_array.size_in_bytes());
  1688. debug_printf("Total .ktx2 output file size: %u\n", m_output_ktx2_file.size());
  1689. return true;
  1690. }
  1691. bool basis_parallel_compress(
  1692. uint32_t total_threads,
  1693. const basisu::vector<basis_compressor_params>& params_vec,
  1694. basisu::vector< parallel_results >& results_vec)
  1695. {
  1696. assert(g_library_initialized);
  1697. if (!g_library_initialized)
  1698. {
  1699. error_printf("basis_parallel_compress: basisu_encoder_init() MUST be called before using any encoder functionality!\n");
  1700. return false;
  1701. }
  1702. assert(total_threads >= 1);
  1703. total_threads = basisu::maximum<uint32_t>(total_threads, 1);
  1704. job_pool jpool(total_threads);
  1705. results_vec.resize(0);
  1706. results_vec.resize(params_vec.size());
  1707. std::atomic<bool> result;
  1708. result = true;
  1709. std::atomic<bool> opencl_failed;
  1710. opencl_failed = false;
  1711. for (uint32_t pindex = 0; pindex < params_vec.size(); pindex++)
  1712. {
  1713. jpool.add_job([pindex, &params_vec, &results_vec, &result, &opencl_failed] {
  1714. basis_compressor_params params = params_vec[pindex];
  1715. parallel_results& results = results_vec[pindex];
  1716. interval_timer tm;
  1717. tm.start();
  1718. basis_compressor c;
  1719. // Dummy job pool
  1720. job_pool task_jpool(1);
  1721. params.m_pJob_pool = &task_jpool;
  1722. // TODO: Remove this flag entirely
  1723. params.m_multithreading = true;
  1724. // Stop using OpenCL if a failure ever occurs.
  1725. if (opencl_failed)
  1726. params.m_use_opencl = false;
  1727. bool status = c.init(params);
  1728. if (c.get_opencl_failed())
  1729. opencl_failed = true;
  1730. if (status)
  1731. {
  1732. basis_compressor::error_code ec = c.process();
  1733. if (c.get_opencl_failed())
  1734. opencl_failed = true;
  1735. results.m_error_code = ec;
  1736. if (ec == basis_compressor::cECSuccess)
  1737. {
  1738. results.m_basis_file = c.get_output_basis_file();
  1739. results.m_ktx2_file = c.get_output_ktx2_file();
  1740. results.m_stats = c.get_stats();
  1741. results.m_basis_bits_per_texel = c.get_basis_bits_per_texel();
  1742. results.m_any_source_image_has_alpha = c.get_any_source_image_has_alpha();
  1743. }
  1744. else
  1745. {
  1746. result = false;
  1747. }
  1748. }
  1749. else
  1750. {
  1751. results.m_error_code = basis_compressor::cECFailedInitializing;
  1752. result = false;
  1753. }
  1754. results.m_total_time = tm.get_elapsed_secs();
  1755. } );
  1756. } // pindex
  1757. jpool.wait_for_all();
  1758. if (opencl_failed)
  1759. error_printf("An OpenCL error occured sometime during compression. The compressor fell back to CPU processing after the failure.\n");
  1760. return result;
  1761. }
  1762. void* basis_compress(
  1763. const basisu::vector<image>& source_images,
  1764. uint32_t flags_and_quality, float uastc_rdo_quality,
  1765. size_t* pSize,
  1766. image_stats* pStats)
  1767. {
  1768. // Check input parameters
  1769. if ((!source_images.size()) || (!pSize))
  1770. {
  1771. error_printf("basis_compress: Invalid parameter\n");
  1772. assert(0);
  1773. return nullptr;
  1774. }
  1775. *pSize = 0;
  1776. // Initialize a job pool
  1777. uint32_t num_threads = 1;
  1778. if (flags_and_quality & cFlagThreaded)
  1779. num_threads = basisu::maximum<uint32_t>(1, std::thread::hardware_concurrency());
  1780. job_pool jp(num_threads);
  1781. // Initialize the compressor parameter struct
  1782. basis_compressor_params comp_params;
  1783. comp_params.m_pJob_pool = &jp;
  1784. comp_params.m_y_flip = (flags_and_quality & cFlagYFlip) != 0;
  1785. comp_params.m_debug = (flags_and_quality & cFlagDebug) != 0;
  1786. // Copy the largest mipmap level
  1787. comp_params.m_source_images.resize(1);
  1788. comp_params.m_source_images[0] = source_images[0];
  1789. // Copy the smaller mipmap levels, if any
  1790. if (source_images.size() > 1)
  1791. {
  1792. comp_params.m_source_mipmap_images.resize(1);
  1793. comp_params.m_source_mipmap_images[0].resize(source_images.size() - 1);
  1794. for (uint32_t i = 1; i < source_images.size(); i++)
  1795. comp_params.m_source_mipmap_images[0][i - 1] = source_images[i];
  1796. }
  1797. comp_params.m_multithreading = (flags_and_quality & cFlagThreaded) != 0;
  1798. comp_params.m_use_opencl = (flags_and_quality & cFlagUseOpenCL) != 0;
  1799. comp_params.m_write_output_basis_files = false;
  1800. comp_params.m_perceptual = (flags_and_quality & cFlagSRGB) != 0;
  1801. comp_params.m_mip_srgb = comp_params.m_perceptual;
  1802. comp_params.m_mip_gen = (flags_and_quality & (cFlagGenMipsWrap | cFlagGenMipsClamp)) != 0;
  1803. comp_params.m_mip_wrapping = (flags_and_quality & cFlagGenMipsWrap) != 0;
  1804. comp_params.m_uastc = (flags_and_quality & cFlagUASTC) != 0;
  1805. if (comp_params.m_uastc)
  1806. {
  1807. comp_params.m_pack_uastc_flags = flags_and_quality & cPackUASTCLevelMask;
  1808. comp_params.m_rdo_uastc = (flags_and_quality & cFlagUASTCRDO) != 0;
  1809. comp_params.m_rdo_uastc_quality_scalar = uastc_rdo_quality;
  1810. }
  1811. else
  1812. comp_params.m_quality_level = basisu::maximum<uint32_t>(1, flags_and_quality & 255);
  1813. comp_params.m_create_ktx2_file = (flags_and_quality & cFlagKTX2) != 0;
  1814. if (comp_params.m_create_ktx2_file)
  1815. {
  1816. // Set KTX2 specific parameters.
  1817. if ((flags_and_quality & cFlagKTX2UASTCSuperCompression) && (comp_params.m_uastc))
  1818. comp_params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD;
  1819. comp_params.m_ktx2_srgb_transfer_func = comp_params.m_perceptual;
  1820. }
  1821. comp_params.m_compute_stats = (pStats != nullptr);
  1822. // Create the compressor, initialize it, and process the input
  1823. basis_compressor comp;
  1824. if (!comp.init(comp_params))
  1825. {
  1826. error_printf("basis_compress: basis_compressor::init() failed!\n");
  1827. return nullptr;
  1828. }
  1829. basis_compressor::error_code ec = comp.process();
  1830. if (ec != basis_compressor::cECSuccess)
  1831. {
  1832. error_printf("basis_compress: basis_compressor::process() failed with error code %u\n", (uint32_t)ec);
  1833. return nullptr;
  1834. }
  1835. // Get the output file data and return it to the caller
  1836. void* pFile_data = nullptr;
  1837. const uint8_vec* pFile_data_vec = comp_params.m_create_ktx2_file ? &comp.get_output_ktx2_file() : &comp.get_output_basis_file();
  1838. pFile_data = malloc(pFile_data_vec->size());
  1839. if (!pFile_data)
  1840. {
  1841. error_printf("basis_compress: Out of memory\n");
  1842. return nullptr;
  1843. }
  1844. memcpy(pFile_data, pFile_data_vec->get_ptr(), pFile_data_vec->size());
  1845. *pSize = pFile_data_vec->size();
  1846. if ((pStats) && (comp.get_stats().size()))
  1847. {
  1848. *pStats = comp.get_stats()[0];
  1849. }
  1850. return pFile_data;
  1851. }
  1852. void* basis_compress(
  1853. const uint8_t* pImageRGBA, uint32_t width, uint32_t height, uint32_t pitch_in_pixels,
  1854. uint32_t flags_and_quality, float uastc_rdo_quality,
  1855. size_t* pSize,
  1856. image_stats* pStats)
  1857. {
  1858. if (!pitch_in_pixels)
  1859. pitch_in_pixels = width;
  1860. if ((!pImageRGBA) || (!width) || (!height) || (pitch_in_pixels < width) || (!pSize))
  1861. {
  1862. error_printf("basis_compress: Invalid parameter\n");
  1863. assert(0);
  1864. return nullptr;
  1865. }
  1866. *pSize = 0;
  1867. if ((width > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION) || (height > BASISU_MAX_SUPPORTED_TEXTURE_DIMENSION))
  1868. {
  1869. error_printf("basis_compress: Image too large\n");
  1870. return nullptr;
  1871. }
  1872. // Copy the source image
  1873. basisu::vector<image> source_image(1);
  1874. source_image[0].crop(width, height, width, g_black_color, false);
  1875. for (uint32_t y = 0; y < height; y++)
  1876. memcpy(source_image[0].get_ptr() + y * width, (const color_rgba*)pImageRGBA + y * pitch_in_pixels, width * sizeof(color_rgba));
  1877. return basis_compress(source_image, flags_and_quality, uastc_rdo_quality, pSize, pStats);
  1878. }
  1879. void basis_free_data(void* p)
  1880. {
  1881. free(p);
  1882. }
  1883. } // namespace basisu