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