• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: Apache-2.0
2 // ----------------------------------------------------------------------------
3 // Copyright 2011-2024 Arm Limited
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
6 // use this file except in compliance with the License. You may obtain a copy
7 // of the License at:
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 // License for the specific language governing permissions and limitations
15 // under the License.
16 // ----------------------------------------------------------------------------
17 
18 /**
19  * @brief Functions and data declarations.
20  */
21 
22 #ifndef ASTCENC_INTERNAL_INCLUDED
23 #define ASTCENC_INTERNAL_INCLUDED
24 
25 #include <algorithm>
26 #include <cstddef>
27 #include <cstdint>
28 #if defined(ASTCENC_DIAGNOSTICS)
29 	#include <cstdio>
30 #endif
31 #include <cstdlib>
32 #include <limits>
33 #include <mutex>
34 
35 #ifdef ASTC_CUSTOMIZED_ENABLE
36 #include <unistd.h>
37 #include <string>
38 #include "hilog/log.h"
39 #define ASTCENC_LOG_DOMAIN 0x2102
40 #define ASTCENC_OHOS_LOG_TAG "astcenc"
41 
42 #ifdef MS_COMPILE_WITH_OHOS_NDK
43 #define ASTCENC_DEBUG(content, args...) \
44   { OH_LOG_Print(LOG_APP, LOG_DEBUG, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
45   "%s:%d " #content, __func__, __LINE__, ##args); }
46 #define ASTCENC_WARN(content, args...) \
47   { OH_LOG_Print(LOG_APP, LOG_WARN, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
48   "%s:%d " #content, __func__, __LINE__, ##args); }
49 #define ASTCENC_INFO(content, args...) \
50   { OH_LOG_Print(LOG_APP, LOG_INFO, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
51   "%s:%d " #content, __func__, __LINE__, ##args); }
52 #define ASTCENC_ERROR(content, args...) \
53   { OH_LOG_Print(LOG_APP, LOG_ERROR, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
54   "%s:%d " #content, __func__, __LINE__, ##args); }
55 #else
56 #define ASTCENC_DEBUG(content, args...) \
57   { HiLogPrint(LOG_APP, LOG_DEBUG, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
58   "%s:%d " #content, __func__, __LINE__, ##args); }
59 #define ASTCENC_WARN(content, args...) \
60   { HiLogPrint(LOG_APP, LOG_WARN, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
61   "%s:%d " #content, __func__, __LINE__, ##args); }
62 #define ASTCENC_INFO(content, args...) \
63   { HiLogPrint(LOG_APP, LOG_INFO, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
64   "%s:%d " #content, __func__, __LINE__, ##args); }
65 #define ASTCENC_ERROR(content, args...) \
66   { HiLogPrint(LOG_APP, LOG_ERROR, ASTCENC_LOG_DOMAIN, ASTCENC_OHOS_LOG_TAG, \
67   "%s:%d " #content, __func__, __LINE__, ##args); }
68 #endif
69 #if defined(_WIN32) && !defined(__CYGWIN__)
70 #define NOMINMAX
71 #include <windows.h>
72 #include <io.h>
73 #else
74 #include <dlfcn.h>
75 #endif
76 #endif
77 
78 #include "astcenc.h"
79 #include "astcenc_mathlib.h"
80 #include "astcenc_vecmathlib.h"
81 
82 /**
83  * @brief Make a promise to the compiler's optimizer.
84  *
85  * A promise is an expression that the optimizer is can assume is true for to help it generate
86  * faster code. Common use cases for this are to promise that a for loop will iterate more than
87  * once, or that the loop iteration count is a multiple of a vector length, which avoids pre-loop
88  * checks and can avoid loop tails if loops are unrolled by the auto-vectorizer.
89  */
90 #if defined(NDEBUG)
91 	#if !defined(__clang__) && defined(_MSC_VER)
92 		#define promise(cond) __assume(cond)
93 	#elif defined(__clang__)
94 		#if __has_builtin(__builtin_assume)
95 			#define promise(cond) __builtin_assume(cond)
96 		#elif __has_builtin(__builtin_unreachable)
97 			#define promise(cond) if (!(cond)) { __builtin_unreachable(); }
98 		#else
99 			#define promise(cond)
100 		#endif
101 	#else // Assume GCC
102 		#define promise(cond) if (!(cond)) { __builtin_unreachable(); }
103 	#endif
104 #else
105 	#define promise(cond) assert(cond)
106 #endif
107 
108 /* ============================================================================
109   Constants
110 ============================================================================ */
111 #if !defined(ASTCENC_BLOCK_MAX_TEXELS)
112 	#define ASTCENC_BLOCK_MAX_TEXELS 216 // A 3D 6x6x6 block
113 #endif
114 
115 /** @brief The maximum number of texels a block can support (6x6x6 block). */
116 static constexpr unsigned int BLOCK_MAX_TEXELS { ASTCENC_BLOCK_MAX_TEXELS };
117 
118 /** @brief The maximum number of components a block can support. */
119 static constexpr unsigned int BLOCK_MAX_COMPONENTS { 4 };
120 
121 /** @brief The maximum number of partitions a block can support. */
122 static constexpr unsigned int BLOCK_MAX_PARTITIONS { 4 };
123 
124 /** @brief The number of partitionings, per partition count, suported by the ASTC format. */
125 static constexpr unsigned int BLOCK_MAX_PARTITIONINGS { 1024 };
126 
127 /** @brief The maximum number of texels used during partition selection for texel clustering. */
128 static constexpr uint8_t BLOCK_MAX_KMEANS_TEXELS { 64 };
129 
130 /** @brief The maximum number of weights a block can support. */
131 static constexpr unsigned int BLOCK_MAX_WEIGHTS { 64 };
132 
133 /** @brief The maximum number of weights a block can support per plane in 2 plane mode. */
134 static constexpr unsigned int BLOCK_MAX_WEIGHTS_2PLANE { BLOCK_MAX_WEIGHTS / 2 };
135 
136 /** @brief The minimum number of weight bits a candidate encoding must encode. */
137 static constexpr unsigned int BLOCK_MIN_WEIGHT_BITS { 24 };
138 
139 /** @brief The maximum number of weight bits a candidate encoding can encode. */
140 static constexpr unsigned int BLOCK_MAX_WEIGHT_BITS { 96 };
141 
142 /** @brief The index indicating a bad (unused) block mode in the remap array. */
143 static constexpr uint16_t BLOCK_BAD_BLOCK_MODE { 0xFFFFu };
144 
145 /** @brief The index indicating a bad (unused) partitioning in the remap array. */
146 static constexpr uint16_t BLOCK_BAD_PARTITIONING { 0xFFFFu };
147 
148 /** @brief The number of partition index bits supported by the ASTC format . */
149 static constexpr unsigned int PARTITION_INDEX_BITS { 10 };
150 
151 /** @brief The offset of the plane 2 weights in shared weight arrays. */
152 static constexpr unsigned int WEIGHTS_PLANE2_OFFSET { BLOCK_MAX_WEIGHTS_2PLANE };
153 
154 /** @brief The sum of quantized weights for one texel. */
155 static constexpr float WEIGHTS_TEXEL_SUM { 16.0f };
156 
157 /** @brief The number of block modes supported by the ASTC format. */
158 static constexpr unsigned int WEIGHTS_MAX_BLOCK_MODES { 2048 };
159 
160 /** @brief The number of weight grid decimation modes supported by the ASTC format. */
161 static constexpr unsigned int WEIGHTS_MAX_DECIMATION_MODES { 87 };
162 
163 /** @brief The high default error used to initialize error trackers. */
164 static constexpr float ERROR_CALC_DEFAULT { 1e30f };
165 
166 /**
167  * @brief The minimum tuning setting threshold for the one partition fast path.
168  */
169 static constexpr float TUNE_MIN_SEARCH_MODE0 { 0.85f };
170 
171 /**
172  * @brief The maximum number of candidate encodings tested for each encoding mode.
173  *
174  * This can be dynamically reduced by the compression quality preset.
175  */
176 static constexpr unsigned int TUNE_MAX_TRIAL_CANDIDATES { 8 };
177 
178 /**
179  * @brief The maximum number of candidate partitionings tested for each encoding mode.
180  *
181  * This can be dynamically reduced by the compression quality preset.
182  */
183 static constexpr unsigned int TUNE_MAX_PARTITIONING_CANDIDATES { 8 };
184 
185 /**
186  * @brief The maximum quant level using full angular endpoint search method.
187  *
188  * The angular endpoint search is used to find the min/max weight that should
189  * be used for a given quantization level. It is effective but expensive, so
190  * we only use it where it has the most value - low quant levels with wide
191  * spacing. It is used below TUNE_MAX_ANGULAR_QUANT (inclusive). Above this we
192  * assume the min weight is 0.0f, and the max weight is 1.0f.
193  *
194  * Note the angular algorithm is vectorized, and using QUANT_12 exactly fills
195  * one 8-wide vector. Decreasing by one doesn't buy much performance, and
196  * increasing by one is disproportionately expensive.
197  */
198 static constexpr unsigned int TUNE_MAX_ANGULAR_QUANT { 7 }; /* QUANT_12 */
199 
200 static_assert((BLOCK_MAX_TEXELS % ASTCENC_SIMD_WIDTH) == 0,
201               "BLOCK_MAX_TEXELS must be multiple of ASTCENC_SIMD_WIDTH");
202 
203 static_assert(BLOCK_MAX_TEXELS <= 216,
204               "BLOCK_MAX_TEXELS must not be greater than 216");
205 
206 static_assert((BLOCK_MAX_WEIGHTS % ASTCENC_SIMD_WIDTH) == 0,
207               "BLOCK_MAX_WEIGHTS must be multiple of ASTCENC_SIMD_WIDTH");
208 
209 static_assert((WEIGHTS_MAX_BLOCK_MODES % ASTCENC_SIMD_WIDTH) == 0,
210               "WEIGHTS_MAX_BLOCK_MODES must be multiple of ASTCENC_SIMD_WIDTH");
211 
212 
213 /* ============================================================================
214   Commonly used data structures
215 ============================================================================ */
216 
217 /**
218  * @brief The ASTC endpoint formats.
219  *
220  * Note, the values here are used directly in the encoding in the format so do not rearrange.
221  */
222 enum endpoint_formats
223 {
224 	FMT_LUMINANCE = 0,
225 	FMT_LUMINANCE_DELTA = 1,
226 	FMT_HDR_LUMINANCE_LARGE_RANGE = 2,
227 	FMT_HDR_LUMINANCE_SMALL_RANGE = 3,
228 	FMT_LUMINANCE_ALPHA = 4,
229 	FMT_LUMINANCE_ALPHA_DELTA = 5,
230 	FMT_RGB_SCALE = 6,
231 	FMT_HDR_RGB_SCALE = 7,
232 	FMT_RGB = 8,
233 	FMT_RGB_DELTA = 9,
234 	FMT_RGB_SCALE_ALPHA = 10,
235 	FMT_HDR_RGB = 11,
236 	FMT_RGBA = 12,
237 	FMT_RGBA_DELTA = 13,
238 	FMT_HDR_RGB_LDR_ALPHA = 14,
239 	FMT_HDR_RGBA = 15
240 };
241 
242 /**
243  * @brief The ASTC quantization methods.
244  *
245  * Note, the values here are used directly in the encoding in the format so do not rearrange.
246  */
247 enum quant_method
248 {
249 	QUANT_2 = 0,
250 	QUANT_3 = 1,
251 	QUANT_4 = 2,
252 	QUANT_5 = 3,
253 	QUANT_6 = 4,
254 	QUANT_8 = 5,
255 	QUANT_10 = 6,
256 	QUANT_12 = 7,
257 	QUANT_16 = 8,
258 	QUANT_20 = 9,
259 	QUANT_24 = 10,
260 	QUANT_32 = 11,
261 	QUANT_40 = 12,
262 	QUANT_48 = 13,
263 	QUANT_64 = 14,
264 	QUANT_80 = 15,
265 	QUANT_96 = 16,
266 	QUANT_128 = 17,
267 	QUANT_160 = 18,
268 	QUANT_192 = 19,
269 	QUANT_256 = 20
270 };
271 
272 /**
273  * @brief The number of levels use by an ASTC quantization method.
274  *
275  * @param method   The quantization method
276  *
277  * @return   The number of levels used by @c method.
278  */
get_quant_level(quant_method method)279 static inline unsigned int get_quant_level(quant_method method)
280 {
281 	switch (method)
282 	{
283 	case QUANT_2:   return   2;
284 	case QUANT_3:   return   3;
285 	case QUANT_4:   return   4;
286 	case QUANT_5:   return   5;
287 	case QUANT_6:   return   6;
288 	case QUANT_8:   return   8;
289 	case QUANT_10:  return  10;
290 	case QUANT_12:  return  12;
291 	case QUANT_16:  return  16;
292 	case QUANT_20:  return  20;
293 	case QUANT_24:  return  24;
294 	case QUANT_32:  return  32;
295 	case QUANT_40:  return  40;
296 	case QUANT_48:  return  48;
297 	case QUANT_64:  return  64;
298 	case QUANT_80:  return  80;
299 	case QUANT_96:  return  96;
300 	case QUANT_128: return 128;
301 	case QUANT_160: return 160;
302 	case QUANT_192: return 192;
303 	case QUANT_256: return 256;
304 	}
305 
306 	// Unreachable - the enum is fully described
307 	return 0;
308 }
309 
310 /**
311  * @brief Computed metrics about a partition in a block.
312  */
313 struct partition_metrics
314 {
315 	/** @brief The error-weighted average color in the partition. */
316 	vfloat4 avg;
317 
318 	/** @brief The dominant error-weighted direction in the partition. */
319 	vfloat4 dir;
320 };
321 
322 /**
323  * @brief Computed lines for a a three component analysis.
324  */
325 struct partition_lines3
326 {
327 	/** @brief Line for uncorrelated chroma. */
328 	line3 uncor_line;
329 
330 	/** @brief Line for correlated chroma, passing though the origin. */
331 	line3 samec_line;
332 
333 	/** @brief Post-processed line for uncorrelated chroma. */
334 	processed_line3 uncor_pline;
335 
336 	/** @brief Post-processed line for correlated chroma, passing though the origin. */
337 	processed_line3 samec_pline;
338 
339 	/**
340 	 * @brief The length of the line for uncorrelated chroma.
341 	 *
342 	 * This is used for both the uncorrelated and same chroma lines - they are normally very similar
343 	 * and only used for the relative ranking of partitionings against one another.
344 	 */
345 	float line_length;
346 };
347 
348 /**
349  * @brief The partition information for a single partition.
350  *
351  * ASTC has a total of 1024 candidate partitions for each of 2/3/4 partition counts, although this
352  * 1024 includes seeds that generate duplicates of other seeds and seeds that generate completely
353  * empty partitions. These are both valid encodings, but astcenc will skip both during compression
354  * as they are not useful.
355  */
356 struct partition_info
357 {
358 	/** @brief The number of partitions in this partitioning. */
359 	uint16_t partition_count;
360 
361 	/** @brief The index (seed) of this partitioning. */
362 	uint16_t partition_index;
363 
364 	/**
365 	 * @brief The number of texels in each partition.
366 	 *
367 	 * Note that some seeds result in zero texels assigned to a partition. These are valid, but are
368 	 * skipped by this compressor as there is no point spending bits encoding an unused endpoints.
369 	 */
370 	uint8_t partition_texel_count[BLOCK_MAX_PARTITIONS];
371 
372 	/** @brief The partition of each texel in the block. */
373 	uint8_t partition_of_texel[BLOCK_MAX_TEXELS];
374 
375 	/** @brief The list of texels in each partition. */
376 	uint8_t texels_of_partition[BLOCK_MAX_PARTITIONS][BLOCK_MAX_TEXELS];
377 };
378 
379 /**
380  * @brief The weight grid information for a single decimation pattern.
381  *
382  * ASTC can store one weight per texel, but is also capable of storing lower resolution weight grids
383  * that are interpolated during decompression to assign a with to a texel. Storing fewer weights
384  * can free up a substantial amount of bits that we can then spend on more useful things, such as
385  * more accurate endpoints and weights, or additional partitions.
386  *
387  * This data structure is used to store information about a single weight grid decimation pattern,
388  * for a single block size.
389  */
390 struct decimation_info
391 {
392 	/** @brief The total number of texels in the block. */
393 	uint8_t texel_count;
394 
395 	/** @brief The maximum number of stored weights that contribute to each texel, between 1 and 4. */
396 	uint8_t max_texel_weight_count;
397 
398 	/** @brief The total number of weights stored. */
399 	uint8_t weight_count;
400 
401 	/** @brief The number of stored weights in the X dimension. */
402 	uint8_t weight_x;
403 
404 	/** @brief The number of stored weights in the Y dimension. */
405 	uint8_t weight_y;
406 
407 	/** @brief The number of stored weights in the Z dimension. */
408 	uint8_t weight_z;
409 
410 	/**
411 	 * @brief The number of weights that contribute to each texel.
412 	 * Value is between 1 and 4.
413 	 */
414 	uint8_t texel_weight_count[BLOCK_MAX_TEXELS];
415 
416 	/**
417 	 * @brief The weight index of the N weights that are interpolated for each texel.
418 	 * Stored transposed to improve vectorization.
419 	 */
420 	uint8_t texel_weights_tr[4][BLOCK_MAX_TEXELS];
421 
422 	/**
423 	 * @brief The bilinear contribution of the N weights that are interpolated for each texel.
424 	 * Value is between 0 and 16, stored transposed to improve vectorization.
425 	 */
426 	uint8_t texel_weight_contribs_int_tr[4][BLOCK_MAX_TEXELS];
427 
428 	/**
429 	 * @brief The bilinear contribution of the N weights that are interpolated for each texel.
430 	 * Value is between 0 and 1, stored transposed to improve vectorization.
431 	 */
432 	ASTCENC_ALIGNAS float texel_weight_contribs_float_tr[4][BLOCK_MAX_TEXELS];
433 
434 	/** @brief The number of texels that each stored weight contributes to. */
435 	uint8_t weight_texel_count[BLOCK_MAX_WEIGHTS];
436 
437 	/**
438 	 * @brief The list of texels that use a specific weight index.
439 	 * Stored transposed to improve vectorization.
440 	 */
441 	uint8_t weight_texels_tr[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];
442 
443 	/**
444 	 * @brief The bilinear contribution to the N texels that use each weight.
445 	 * Value is between 0 and 1, stored transposed to improve vectorization.
446 	 */
447 	ASTCENC_ALIGNAS float weights_texel_contribs_tr[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];
448 
449 	/**
450 	 * @brief The bilinear contribution to the Nth texel that uses each weight.
451 	 * Value is between 0 and 1, stored transposed to improve vectorization.
452 	 */
453 	float texel_contrib_for_weight[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];
454 };
455 
456 /**
457  * @brief Metadata for single block mode for a specific block size.
458  */
459 struct block_mode
460 {
461 	/** @brief The block mode index in the ASTC encoded form. */
462 	uint16_t mode_index;
463 
464 	/** @brief The decimation mode index in the compressor reindexed list. */
465 	uint8_t decimation_mode;
466 
467 	/** @brief The weight quantization used by this block mode. */
468 	uint8_t quant_mode;
469 
470 	/** @brief The weight quantization used by this block mode. */
471 	uint8_t weight_bits;
472 
473 	/** @brief Is a dual weight plane used by this block mode? */
474 	uint8_t is_dual_plane : 1;
475 
476 	/**
477 	 * @brief Get the weight quantization used by this block mode.
478 	 *
479 	 * @return The quantization level.
480 	 */
get_weight_quant_modeblock_mode481 	inline quant_method get_weight_quant_mode() const
482 	{
483 		return static_cast<quant_method>(this->quant_mode);
484 	}
485 };
486 
487 /**
488  * @brief Metadata for single decimation mode for a specific block size.
489  */
490 struct decimation_mode
491 {
492 	/** @brief The max weight precision for 1 plane, or -1 if not supported. */
493 	int8_t maxprec_1plane;
494 
495 	/** @brief The max weight precision for 2 planes, or -1 if not supported. */
496 	int8_t maxprec_2planes;
497 
498 	/**
499 	 * @brief Bitvector indicating weight quant modes used by active 1 plane block modes.
500 	 *
501 	 * Bit 0 = QUANT_2, Bit 1 = QUANT_3, etc.
502 	 */
503 	uint16_t refprec_1plane;
504 
505 	/**
506 	 * @brief Bitvector indicating weight quant methods used by active 2 plane block modes.
507 	 *
508 	 * Bit 0 = QUANT_2, Bit 1 = QUANT_3, etc.
509 	 */
510 	uint16_t refprec_2planes;
511 
512 	/**
513 	 * @brief Set a 1 plane weight quant as active.
514 	 *
515 	 * @param weight_quant   The quant method to set.
516 	 */
set_ref_1planedecimation_mode517 	void set_ref_1plane(quant_method weight_quant)
518 	{
519 		refprec_1plane |= (1 << weight_quant);
520 	}
521 
522 	/**
523 	 * @brief Test if this mode is active below a given 1 plane weight quant (inclusive).
524 	 *
525 	 * @param max_weight_quant   The max quant method to test.
526 	 */
is_ref_1planedecimation_mode527 	bool is_ref_1plane(quant_method max_weight_quant) const
528 	{
529 		uint16_t mask = static_cast<uint16_t>((1 << (max_weight_quant + 1)) - 1);
530 		return (refprec_1plane & mask) != 0;
531 	}
532 
533 	/**
534 	 * @brief Set a 2 plane weight quant as active.
535 	 *
536 	 * @param weight_quant   The quant method to set.
537 	 */
set_ref_2planedecimation_mode538 	void set_ref_2plane(quant_method weight_quant)
539 	{
540 		refprec_2planes |= static_cast<uint16_t>(1 << weight_quant);
541 	}
542 
543 	/**
544 	 * @brief Test if this mode is active below a given 2 plane weight quant (inclusive).
545 	 *
546 	 * @param max_weight_quant   The max quant method to test.
547 	 */
is_ref_2planedecimation_mode548 	bool is_ref_2plane(quant_method max_weight_quant) const
549 	{
550 		uint16_t mask = static_cast<uint16_t>((1 << (max_weight_quant + 1)) - 1);
551 		return (refprec_2planes & mask) != 0;
552 	}
553 };
554 
555 /**
556  * @brief Data tables for a single block size.
557  *
558  * The decimation tables store the information to apply weight grid dimension reductions. We only
559  * store the decimation modes that are actually needed by the current context; many of the possible
560  * modes will be unused (too many weights for the current block size or disabled by heuristics). The
561  * actual number of weights stored is @c decimation_mode_count, and the @c decimation_modes and
562  * @c decimation_tables arrays store the active modes contiguously at the start of the array. These
563  * entries are not stored in any particular order.
564  *
565  * The block mode tables store the unpacked block mode settings. Block modes are stored in the
566  * compressed block as an 11 bit field, but for any given block size and set of compressor
567  * heuristics, only a subset of the block modes will be used. The actual number of block modes
568  * stored is indicated in @c block_mode_count, and the @c block_modes array store the active modes
569  * contiguously at the start of the array. These entries are stored in incrementing "packed" value
570  * order, which doesn't mean much once unpacked. To allow decompressors to reference the packed data
571  * efficiently the @c block_mode_packed_index array stores the mapping between physical ID and the
572  * actual remapped array index.
573  */
574 struct block_size_descriptor
575 {
576 	/** @brief The block X dimension, in texels. */
577 	uint8_t xdim;
578 
579 	/** @brief The block Y dimension, in texels. */
580 	uint8_t ydim;
581 
582 	/** @brief The block Z dimension, in texels. */
583 	uint8_t zdim;
584 
585 	/** @brief The block total texel count. */
586 	uint8_t texel_count;
587 
588 	/**
589 	 * @brief The number of stored decimation modes which are "always" modes.
590 	 *
591 	 * Always modes are stored at the start of the decimation_modes list.
592 	 */
593 	unsigned int decimation_mode_count_always;
594 
595 	/** @brief The number of stored decimation modes for selected encodings. */
596 	unsigned int decimation_mode_count_selected;
597 
598 	/** @brief The number of stored decimation modes for any encoding. */
599 	unsigned int decimation_mode_count_all;
600 
601 	/**
602 	 * @brief The number of stored block modes which are "always" modes.
603 	 *
604 	 * Always modes are stored at the start of the block_modes list.
605 	 */
606 	unsigned int block_mode_count_1plane_always;
607 
608 	/** @brief The number of stored block modes for active 1 plane encodings. */
609 	unsigned int block_mode_count_1plane_selected;
610 
611 	/** @brief The number of stored block modes for active 1 and 2 plane encodings. */
612 	unsigned int block_mode_count_1plane_2plane_selected;
613 
614 	/** @brief The number of stored block modes for any encoding. */
615 	unsigned int block_mode_count_all;
616 
617 	/** @brief The number of selected partitionings for 1/2/3/4 partitionings. */
618 	unsigned int partitioning_count_selected[BLOCK_MAX_PARTITIONS];
619 
620 	/** @brief The number of partitionings for 1/2/3/4 partitionings. */
621 	unsigned int partitioning_count_all[BLOCK_MAX_PARTITIONS];
622 
623 	/** @brief The active decimation modes, stored in low indices. */
624 	decimation_mode decimation_modes[WEIGHTS_MAX_DECIMATION_MODES];
625 
626 	/** @brief The active decimation tables, stored in low indices. */
627 	ASTCENC_ALIGNAS decimation_info decimation_tables[WEIGHTS_MAX_DECIMATION_MODES];
628 
629 	/** @brief The packed block mode array index, or @c BLOCK_BAD_BLOCK_MODE if not active. */
630 	uint16_t block_mode_packed_index[WEIGHTS_MAX_BLOCK_MODES];
631 
632 	/** @brief The active block modes, stored in low indices. */
633 	block_mode block_modes[WEIGHTS_MAX_BLOCK_MODES];
634 
635 	/** @brief The active partition tables, stored in low indices per-count. */
636 	partition_info partitionings[(3 * BLOCK_MAX_PARTITIONINGS) + 1];
637 
638 	/**
639 	 * @brief The packed partition table array index, or @c BLOCK_BAD_PARTITIONING if not active.
640 	 *
641 	 * Indexed by partition_count - 2, containing 2, 3 and 4 partitions.
642 	 */
643 	uint16_t partitioning_packed_index[3][BLOCK_MAX_PARTITIONINGS];
644 
645 	/** @brief The active texels for k-means partition selection. */
646 	uint8_t kmeans_texels[BLOCK_MAX_KMEANS_TEXELS];
647 
648 	/**
649 	 * @brief The canonical 2-partition coverage pattern used during block partition search.
650 	 *
651 	 * Indexed by remapped index, not physical index.
652 	 */
653 	uint64_t coverage_bitmaps_2[BLOCK_MAX_PARTITIONINGS][2];
654 
655 	/**
656 	 * @brief The canonical 3-partition coverage pattern used during block partition search.
657 	 *
658 	 * Indexed by remapped index, not physical index.
659 	 */
660 	uint64_t coverage_bitmaps_3[BLOCK_MAX_PARTITIONINGS][3];
661 
662 	/**
663 	 * @brief The canonical 4-partition coverage pattern used during block partition search.
664 	 *
665 	 * Indexed by remapped index, not physical index.
666 	 */
667 	uint64_t coverage_bitmaps_4[BLOCK_MAX_PARTITIONINGS][4];
668 
669 	/**
670 	 * @brief Get the block mode structure for index @c block_mode.
671 	 *
672 	 * This function can only return block modes that are enabled by the current compressor config.
673 	 * Decompression from an arbitrary source should not use this without first checking that the
674 	 * packed block mode index is not @c BLOCK_BAD_BLOCK_MODE.
675 	 *
676 	 * @param block_mode   The packed block mode index.
677 	 *
678 	 * @return The block mode structure.
679 	 */
get_block_modeblock_size_descriptor680 	const block_mode& get_block_mode(unsigned int block_mode) const
681 	{
682 		unsigned int packed_index = this->block_mode_packed_index[block_mode];
683 		assert(packed_index != BLOCK_BAD_BLOCK_MODE && packed_index < this->block_mode_count_all);
684 		return this->block_modes[packed_index];
685 	}
686 
687 	/**
688 	 * @brief Get the decimation mode structure for index @c decimation_mode.
689 	 *
690 	 * This function can only return decimation modes that are enabled by the current compressor
691 	 * config. The mode array is stored packed, but this is only ever indexed by the packed index
692 	 * stored in the @c block_mode and never exists in an unpacked form.
693 	 *
694 	 * @param decimation_mode   The packed decimation mode index.
695 	 *
696 	 * @return The decimation mode structure.
697 	 */
get_decimation_modeblock_size_descriptor698 	const decimation_mode& get_decimation_mode(unsigned int decimation_mode) const
699 	{
700 		return this->decimation_modes[decimation_mode];
701 	}
702 
703 	/**
704 	 * @brief Get the decimation info structure for index @c decimation_mode.
705 	 *
706 	 * This function can only return decimation modes that are enabled by the current compressor
707 	 * config. The mode array is stored packed, but this is only ever indexed by the packed index
708 	 * stored in the @c block_mode and never exists in an unpacked form.
709 	 *
710 	 * @param decimation_mode   The packed decimation mode index.
711 	 *
712 	 * @return The decimation info structure.
713 	 */
get_decimation_infoblock_size_descriptor714 	const decimation_info& get_decimation_info(unsigned int decimation_mode) const
715 	{
716 		return this->decimation_tables[decimation_mode];
717 	}
718 
719 	/**
720 	 * @brief Get the partition info table for a given partition count.
721 	 *
722 	 * @param partition_count   The number of partitions we want the table for.
723 	 *
724 	 * @return The pointer to the table of 1024 entries (for 2/3/4 parts) or 1 entry (for 1 part).
725 	 */
get_partition_tableblock_size_descriptor726 	const partition_info* get_partition_table(unsigned int partition_count) const
727 	{
728 		if (partition_count == 1)
729 		{
730 			partition_count = 5;
731 		}
732 		unsigned int index = (partition_count - 2) * BLOCK_MAX_PARTITIONINGS;
733 		return this->partitionings + index;
734 	}
735 
736 	/**
737 	 * @brief Get the partition info structure for a given partition count and seed.
738 	 *
739 	 * @param partition_count   The number of partitions we want the info for.
740 	 * @param index             The partition seed (between 0 and 1023).
741 	 *
742 	 * @return The partition info structure.
743 	 */
get_partition_infoblock_size_descriptor744 	const partition_info& get_partition_info(unsigned int partition_count, unsigned int index) const
745 	{
746 		unsigned int packed_index = 0;
747 		if (partition_count >= 2)
748 		{
749 			packed_index = this->partitioning_packed_index[partition_count - 2][index];
750 		}
751 
752 		assert(packed_index != BLOCK_BAD_PARTITIONING && packed_index < this->partitioning_count_all[partition_count - 1]);
753 		auto& result = get_partition_table(partition_count)[packed_index];
754 		assert(index == result.partition_index);
755 		return result;
756 	}
757 
758 	/**
759 	 * @brief Get the partition info structure for a given partition count and seed.
760 	 *
761 	 * @param partition_count   The number of partitions we want the info for.
762 	 * @param packed_index      The raw array offset.
763 	 *
764 	 * @return The partition info structure.
765 	 */
get_raw_partition_infoblock_size_descriptor766 	const partition_info& get_raw_partition_info(unsigned int partition_count, unsigned int packed_index) const
767 	{
768 		assert(packed_index != BLOCK_BAD_PARTITIONING && packed_index < this->partitioning_count_all[partition_count - 1]);
769 		auto& result = get_partition_table(partition_count)[packed_index];
770 		return result;
771 	}
772 };
773 
774 /**
775  * @brief The image data for a single block.
776  *
777  * The @c data_[rgba] fields store the image data in an encoded SoA float form designed for easy
778  * vectorization. Input data is converted to float and stored as values between 0 and 65535. LDR
779  * data is stored as direct UNORM data, HDR data is stored as LNS data.
780  *
781  * The @c rgb_lns and @c alpha_lns fields that assigned a per-texel use of HDR are only used during
782  * decompression. The current compressor will always use HDR endpoint formats when in HDR mode.
783  */
784 struct image_block
785 {
786 	/** @brief The input (compress) or output (decompress) data for the red color component. */
787 	ASTCENC_ALIGNAS float data_r[BLOCK_MAX_TEXELS];
788 
789 	/** @brief The input (compress) or output (decompress) data for the green color component. */
790 	ASTCENC_ALIGNAS float data_g[BLOCK_MAX_TEXELS];
791 
792 	/** @brief The input (compress) or output (decompress) data for the blue color component. */
793 	ASTCENC_ALIGNAS float data_b[BLOCK_MAX_TEXELS];
794 
795 	/** @brief The input (compress) or output (decompress) data for the alpha color component. */
796 	ASTCENC_ALIGNAS float data_a[BLOCK_MAX_TEXELS];
797 
798 	mutable partition_metrics pms[BLOCK_MAX_PARTITIONS];
799 
800 	/** @brief The number of texels in the block. */
801 	uint8_t texel_count;
802 
803 	/** @brief The original data for texel 0 for constant color block encoding. */
804 	vfloat4 origin_texel;
805 
806 	/** @brief The min component value of all texels in the block. */
807 	vfloat4 data_min;
808 
809 	/** @brief The mean component value of all texels in the block. */
810 	vfloat4 data_mean;
811 
812 	/** @brief The max component value of all texels in the block. */
813 	vfloat4 data_max;
814 
815 	/** @brief The relative error significance of the color channels. */
816 	vfloat4 channel_weight;
817 
818 	/** @brief Is this grayscale block where R == G == B for all texels? */
819 	bool grayscale;
820 
821 	/** @brief Is the eventual decode using decode_unorm8 rounding? */
822 	bool decode_unorm8;
823 
824 	/** @brief Set to 1 if a texel is using HDR RGB endpoints (decompression only). */
825 	uint8_t rgb_lns[BLOCK_MAX_TEXELS];
826 
827 	/** @brief Set to 1 if a texel is using HDR alpha endpoints (decompression only). */
828 	uint8_t alpha_lns[BLOCK_MAX_TEXELS];
829 
830 	/** @brief The X position of this block in the input or output image. */
831 	unsigned int xpos;
832 
833 	/** @brief The Y position of this block in the input or output image. */
834 	unsigned int ypos;
835 
836 	/** @brief The Z position of this block in the input or output image. */
837 	unsigned int zpos;
838 
839 	/**
840 	 * @brief Get an RGBA texel value from the data.
841 	 *
842 	 * @param index   The texel index.
843 	 *
844 	 * @return The texel in RGBA component ordering.
845 	 */
texelimage_block846 	inline vfloat4 texel(unsigned int index) const
847 	{
848 		return vfloat4(data_r[index],
849 		               data_g[index],
850 		               data_b[index],
851 		               data_a[index]);
852 	}
853 
854 	/**
855 	 * @brief Get an RGB texel value from the data.
856 	 *
857 	 * @param index   The texel index.
858 	 *
859 	 * @return The texel in RGB0 component ordering.
860 	 */
texel3image_block861 	inline vfloat4 texel3(unsigned int index) const
862 	{
863 		return vfloat3(data_r[index],
864 		               data_g[index],
865 		               data_b[index]);
866 	}
867 
868 	/**
869 	 * @brief Get the default alpha value for endpoints that don't store it.
870 	 *
871 	 * The default depends on whether the alpha endpoint is LDR or HDR.
872 	 *
873 	 * @return The alpha value in the scaled range used by the compressor.
874 	 */
get_default_alphaimage_block875 	inline float get_default_alpha() const
876 	{
877 		return this->alpha_lns[0] ? static_cast<float>(0x7800) : static_cast<float>(0xFFFF);
878 	}
879 
880 	/**
881 	 * @brief Test if a single color channel is constant across the block.
882 	 *
883 	 * Constant color channels are easier to compress as interpolating between two identical colors
884 	 * always returns the same value, irrespective of the weight used. They therefore can be ignored
885 	 * for the purposes of weight selection and use of a second weight plane.
886 	 *
887 	 * @return @c true if the channel is constant across the block, @c false otherwise.
888 	 */
is_constant_channelimage_block889 	inline bool is_constant_channel(int channel) const
890 	{
891 		vmask4 lane_mask = vint4::lane_id() == vint4(channel);
892 		vmask4 color_mask = this->data_min == this->data_max;
893 		return any(lane_mask & color_mask);
894 	}
895 
896 	/**
897 	 * @brief Test if this block is a luminance block with constant 1.0 alpha.
898 	 *
899 	 * @return @c true if the block is a luminance block , @c false otherwise.
900 	 */
is_luminanceimage_block901 	inline bool is_luminance() const
902 	{
903 		float default_alpha = this->get_default_alpha();
904 		bool alpha1 = (this->data_min.lane<3>() == default_alpha) &&
905 		              (this->data_max.lane<3>() == default_alpha);
906 		return this->grayscale && alpha1;
907 	}
908 
909 	/**
910 	 * @brief Test if this block is a luminance block with variable alpha.
911 	 *
912 	 * @return @c true if the block is a luminance + alpha block , @c false otherwise.
913 	 */
is_luminancealphaimage_block914 	inline bool is_luminancealpha() const
915 	{
916 		float default_alpha = this->get_default_alpha();
917 		bool alpha1 = (this->data_min.lane<3>() == default_alpha) &&
918 		              (this->data_max.lane<3>() == default_alpha);
919 		return this->grayscale && !alpha1;
920 	}
921 };
922 
923 /**
924  * @brief Data structure storing the color endpoints for a block.
925  */
926 struct endpoints
927 {
928 	/** @brief The number of partition endpoints stored. */
929 	unsigned int partition_count;
930 
931 	/** @brief The colors for endpoint 0. */
932 	vfloat4 endpt0[BLOCK_MAX_PARTITIONS];
933 
934 	/** @brief The colors for endpoint 1. */
935 	vfloat4 endpt1[BLOCK_MAX_PARTITIONS];
936 };
937 
938 /**
939  * @brief Data structure storing the color endpoints and weights.
940  */
941 struct endpoints_and_weights
942 {
943 	/** @brief True if all active values in weight_error_scale are the same. */
944 	bool is_constant_weight_error_scale;
945 
946 	/** @brief The color endpoints. */
947 	endpoints ep;
948 
949 	/** @brief The ideal weight for each texel; may be undecimated or decimated. */
950 	ASTCENC_ALIGNAS float weights[BLOCK_MAX_TEXELS];
951 
952 	/** @brief The ideal weight error scaling for each texel; may be undecimated or decimated. */
953 	ASTCENC_ALIGNAS float weight_error_scale[BLOCK_MAX_TEXELS];
954 };
955 
956 /**
957  * @brief Utility storing estimated errors from choosing particular endpoint encodings.
958  */
959 struct encoding_choice_errors
960 {
961 	/** @brief Error of using LDR RGB-scale instead of complete endpoints. */
962 	float rgb_scale_error;
963 
964 	/** @brief Error of using HDR RGB-scale instead of complete endpoints. */
965 	float rgb_luma_error;
966 
967 	/** @brief Error of using luminance instead of RGB. */
968 	float luminance_error;
969 
970 	/** @brief Error of discarding alpha and using a constant 1.0 alpha. */
971 	float alpha_drop_error;
972 
973 	/** @brief Can we use delta offset encoding? */
974 	bool can_offset_encode;
975 
976 	/** @brief Can we use blue contraction encoding? */
977 	bool can_blue_contract;
978 };
979 
980 /**
981  * @brief Preallocated working buffers, allocated per thread during context creation.
982  */
983 struct ASTCENC_ALIGNAS compression_working_buffers
984 {
985 	/** @brief Ideal endpoints and weights for plane 1. */
986 	endpoints_and_weights ei1;
987 
988 	/** @brief Ideal endpoints and weights for plane 2. */
989 	endpoints_and_weights ei2;
990 
991 	/**
992 	 * @brief Decimated ideal weight values in the ~0-1 range.
993 	 *
994 	 * Note that values can be slightly below zero or higher than one due to
995 	 * endpoint extents being inside the ideal color representation.
996 	 *
997 	 * For two planes, second plane starts at @c WEIGHTS_PLANE2_OFFSET offsets.
998 	 */
999 	ASTCENC_ALIGNAS float dec_weights_ideal[WEIGHTS_MAX_DECIMATION_MODES * BLOCK_MAX_WEIGHTS];
1000 
1001 	/**
1002 	 * @brief Decimated quantized weight values in the unquantized 0-64 range.
1003 	 *
1004 	 * For two planes, second plane starts at @c WEIGHTS_PLANE2_OFFSET offsets.
1005 	 */
1006 	uint8_t dec_weights_uquant[WEIGHTS_MAX_BLOCK_MODES * BLOCK_MAX_WEIGHTS];
1007 
1008 	/** @brief Error of the best encoding combination for each block mode. */
1009 	ASTCENC_ALIGNAS float errors_of_best_combination[WEIGHTS_MAX_BLOCK_MODES];
1010 
1011 	/** @brief The best color quant for each block mode. */
1012 	uint8_t best_quant_levels[WEIGHTS_MAX_BLOCK_MODES];
1013 
1014 	/** @brief The best color quant for each block mode if modes are the same and we have spare bits. */
1015 	uint8_t best_quant_levels_mod[WEIGHTS_MAX_BLOCK_MODES];
1016 
1017 	/** @brief The best endpoint format for each partition. */
1018 	uint8_t best_ep_formats[WEIGHTS_MAX_BLOCK_MODES][BLOCK_MAX_PARTITIONS];
1019 
1020 	/** @brief The total bit storage needed for quantized weights for each block mode. */
1021 	int8_t qwt_bitcounts[WEIGHTS_MAX_BLOCK_MODES];
1022 
1023 	/** @brief The cumulative error for quantized weights for each block mode. */
1024 	float qwt_errors[WEIGHTS_MAX_BLOCK_MODES];
1025 
1026 	/** @brief The low weight value in plane 1 for each block mode. */
1027 	float weight_low_value1[WEIGHTS_MAX_BLOCK_MODES];
1028 
1029 	/** @brief The high weight value in plane 1 for each block mode. */
1030 	float weight_high_value1[WEIGHTS_MAX_BLOCK_MODES];
1031 
1032 	/** @brief The low weight value in plane 1 for each quant level and decimation mode. */
1033 	float weight_low_values1[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];
1034 
1035 	/** @brief The high weight value in plane 1 for each quant level and decimation mode. */
1036 	float weight_high_values1[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];
1037 
1038 	/** @brief The low weight value in plane 2 for each block mode. */
1039 	float weight_low_value2[WEIGHTS_MAX_BLOCK_MODES];
1040 
1041 	/** @brief The high weight value in plane 2 for each block mode. */
1042 	float weight_high_value2[WEIGHTS_MAX_BLOCK_MODES];
1043 
1044 	/** @brief The low weight value in plane 2 for each quant level and decimation mode. */
1045 	float weight_low_values2[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];
1046 
1047 	/** @brief The high weight value in plane 2 for each quant level and decimation mode. */
1048 	float weight_high_values2[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];
1049 };
1050 
1051 struct dt_init_working_buffers
1052 {
1053 	uint8_t weight_count_of_texel[BLOCK_MAX_TEXELS];
1054 	uint8_t grid_weights_of_texel[BLOCK_MAX_TEXELS][4];
1055 	uint8_t weights_of_texel[BLOCK_MAX_TEXELS][4];
1056 
1057 	uint8_t texel_count_of_weight[BLOCK_MAX_WEIGHTS];
1058 	uint8_t texels_of_weight[BLOCK_MAX_WEIGHTS][BLOCK_MAX_TEXELS];
1059 	uint8_t texel_weights_of_weight[BLOCK_MAX_WEIGHTS][BLOCK_MAX_TEXELS];
1060 };
1061 
1062 /**
1063  * @brief Weight quantization transfer table.
1064  *
1065  * ASTC can store texel weights at many quantization levels, so for performance we store essential
1066  * information about each level as a precomputed data structure. Unquantized weights are integers
1067  * or floats in the range [0, 64].
1068  *
1069  * This structure provides a table, used to estimate the closest quantized weight for a given
1070  * floating-point weight. For each quantized weight, the corresponding unquantized values. For each
1071  * quantized weight, a previous-value and a next-value.
1072 */
1073 struct quant_and_transfer_table
1074 {
1075 	/** @brief The unscrambled unquantized value. */
1076 	uint8_t quant_to_unquant[32];
1077 
1078 	/** @brief The scrambling order: scrambled_quant = map[unscrambled_quant]. */
1079 	uint8_t scramble_map[32];
1080 
1081 	/** @brief The unscrambling order: unscrambled_unquant = map[scrambled_quant]. */
1082 	uint8_t unscramble_and_unquant_map[32];
1083 
1084 	/**
1085 	 * @brief A table of previous-and-next weights, indexed by the current unquantized value.
1086 	 *  * bits 7:0 = previous-index, unquantized
1087 	 *  * bits 15:8 = next-index, unquantized
1088 	 */
1089 	uint16_t prev_next_values[65];
1090 };
1091 
1092 /** @brief The precomputed quant and transfer table. */
1093 extern const quant_and_transfer_table quant_and_xfer_tables[12];
1094 
1095 /** @brief The block is an error block, and will return error color or NaN. */
1096 static constexpr uint8_t SYM_BTYPE_ERROR { 0 };
1097 
1098 /** @brief The block is a constant color block using FP16 colors. */
1099 static constexpr uint8_t SYM_BTYPE_CONST_F16 { 1 };
1100 
1101 /** @brief The block is a constant color block using UNORM16 colors. */
1102 static constexpr uint8_t SYM_BTYPE_CONST_U16 { 2 };
1103 
1104 /** @brief The block is a normal non-constant color block. */
1105 static constexpr uint8_t SYM_BTYPE_NONCONST { 3 };
1106 
1107 /**
1108  * @brief A symbolic representation of a compressed block.
1109  *
1110  * The symbolic representation stores the unpacked content of a single
1111  * physical compressed block, in a form which is much easier to access for
1112  * the rest of the compressor code.
1113  */
1114 struct symbolic_compressed_block
1115 {
1116 	/** @brief The block type, one of the @c SYM_BTYPE_* constants. */
1117 	uint8_t block_type;
1118 
1119 	/** @brief The number of partitions; valid for @c NONCONST blocks. */
1120 	uint8_t partition_count;
1121 
1122 	/** @brief Non-zero if the color formats matched; valid for @c NONCONST blocks. */
1123 	uint8_t color_formats_matched;
1124 
1125 	/** @brief The plane 2 color component, or -1 if single plane; valid for @c NONCONST blocks. */
1126 	int8_t plane2_component;
1127 
1128 	/** @brief The block mode; valid for @c NONCONST blocks. */
1129 	uint16_t block_mode;
1130 
1131 	/** @brief The partition index; valid for @c NONCONST blocks if 2 or more partitions. */
1132 	uint16_t partition_index;
1133 
1134 	/** @brief The endpoint color formats for each partition; valid for @c NONCONST blocks. */
1135 	uint8_t color_formats[BLOCK_MAX_PARTITIONS];
1136 
1137 	/** @brief The endpoint color quant mode; valid for @c NONCONST blocks. */
1138 	quant_method quant_mode;
1139 
1140 	/** @brief The error of the current encoding; valid for @c NONCONST blocks. */
1141 	float errorval;
1142 
1143 	// We can't have both of these at the same time
1144 	union {
1145 		/** @brief The constant color; valid for @c CONST blocks. */
1146 		int constant_color[BLOCK_MAX_COMPONENTS];
1147 
1148 		/** @brief The quantized endpoint color pairs; valid for @c NONCONST blocks. */
1149 		uint8_t color_values[BLOCK_MAX_PARTITIONS][8];
1150 	};
1151 
1152 	/** @brief The quantized and decimated weights.
1153 	 *
1154 	 * Weights are stored in the 0-64 unpacked range allowing them to be used
1155 	 * directly in encoding passes without per-use unpacking. Packing happens
1156 	 * when converting to/from the physical bitstream encoding.
1157 	 *
1158 	 * If dual plane, the second plane starts at @c weights[WEIGHTS_PLANE2_OFFSET].
1159 	 */
1160 	uint8_t weights[BLOCK_MAX_WEIGHTS];
1161 
1162 	/**
1163 	 * @brief Get the weight quantization used by this block mode.
1164 	 *
1165 	 * @return The quantization level.
1166 	 */
get_color_quant_modesymbolic_compressed_block1167 	inline quant_method get_color_quant_mode() const
1168 	{
1169 		return this->quant_mode;
1170 	}
1171 	QualityProfile privateProfile;
1172 };
1173 
1174 /**
1175  * @brief Parameter structure for @c compute_pixel_region_variance().
1176  *
1177  * This function takes a structure to avoid spilling arguments to the stack on every function
1178  * invocation, as there are a lot of parameters.
1179  */
1180 struct pixel_region_args
1181 {
1182 	/** @brief The image to analyze. */
1183 	const astcenc_image* img;
1184 
1185 	/** @brief The component swizzle pattern. */
1186 	astcenc_swizzle swz;
1187 
1188 	/** @brief Should the algorithm bother with Z axis processing? */
1189 	bool have_z;
1190 
1191 	/** @brief The kernel radius for alpha processing. */
1192 	unsigned int alpha_kernel_radius;
1193 
1194 	/** @brief The X dimension of the working data to process. */
1195 	unsigned int size_x;
1196 
1197 	/** @brief The Y dimension of the working data to process. */
1198 	unsigned int size_y;
1199 
1200 	/** @brief The Z dimension of the working data to process. */
1201 	unsigned int size_z;
1202 
1203 	/** @brief The X position of first src and dst data in the data set. */
1204 	unsigned int offset_x;
1205 
1206 	/** @brief The Y position of first src and dst data in the data set. */
1207 	unsigned int offset_y;
1208 
1209 	/** @brief The Z position of first src and dst data in the data set. */
1210 	unsigned int offset_z;
1211 
1212 	/** @brief The working memory buffer. */
1213 	vfloat4 *work_memory;
1214 };
1215 
1216 /**
1217  * @brief Parameter structure for @c compute_averages_proc().
1218  */
1219 struct avg_args
1220 {
1221 	/** @brief The arguments for the nested variance computation. */
1222 	pixel_region_args arg;
1223 
1224 	/** @brief The image Stride dimensions. */
1225 	unsigned int img_size_stride;
1226 
1227 	/** @brief The image X dimensions. */
1228 	unsigned int img_size_x;
1229 
1230 	/** @brief The image Y dimensions. */
1231 	unsigned int img_size_y;
1232 
1233 	/** @brief The image Z dimensions. */
1234 	unsigned int img_size_z;
1235 
1236 	/** @brief The maximum working block dimensions in X and Y dimensions. */
1237 	unsigned int blk_size_xy;
1238 
1239 	/** @brief The maximum working block dimensions in Z dimensions. */
1240 	unsigned int blk_size_z;
1241 
1242 	/** @brief The working block memory size. */
1243 	unsigned int work_memory_size;
1244 };
1245 
1246 #if defined(ASTCENC_DIAGNOSTICS)
1247 /* See astcenc_diagnostic_trace header for details. */
1248 class TraceLog;
1249 #endif
1250 
1251 /**
1252  * @brief The astcenc compression context.
1253  */
1254 struct astcenc_contexti
1255 {
1256 	/** @brief The configuration this context was created with. */
1257 	astcenc_config config;
1258 
1259 	/** @brief The thread count supported by this context. */
1260 	unsigned int thread_count;
1261 
1262 	/** @brief The block size descriptor this context was created with. */
1263 	block_size_descriptor* bsd;
1264 
1265 	/*
1266 	 * Fields below here are not needed in a decompress-only build, but some remain as they are
1267 	 * small and it avoids littering the code with #ifdefs. The most significant contributors to
1268 	 * large structure size are omitted.
1269 	 */
1270 
1271 	/** @brief The input image alpha channel averages table, may be @c nullptr if not needed. */
1272 	float* input_alpha_averages;
1273 
1274 	/** @brief The scratch working buffers, one per thread (see @c thread_count). */
1275 	compression_working_buffers* working_buffers;
1276 
1277 #if !defined(ASTCENC_DECOMPRESS_ONLY)
1278 	/** @brief The pixel region and variance worker arguments. */
1279 	avg_args avg_preprocess_args;
1280 #endif
1281 
1282 #if defined(ASTCENC_DIAGNOSTICS)
1283 	/**
1284 	 * @brief The diagnostic trace logger.
1285 	 *
1286 	 * Note that this is a singleton, so can only be used in single threaded mode. It only exists
1287 	 * here so we have a reference to close the file at the end of the capture.
1288 	 */
1289 	TraceLog* trace_log;
1290 #endif
1291 };
1292 
1293 /* ============================================================================
1294   Functionality for managing block sizes and partition tables.
1295 ============================================================================ */
1296 
1297 /**
1298  * @brief Populate the block size descriptor for the target block size.
1299  *
1300  * This will also initialize the partition table metadata, which is stored as part of the BSD
1301  * structure.
1302  *
1303  * @param      x_texels                 The number of texels in the block X dimension.
1304  * @param      y_texels                 The number of texels in the block Y dimension.
1305  * @param      z_texels                 The number of texels in the block Z dimension.
1306  * @param      can_omit_modes           Can we discard modes and partitionings that astcenc won't use?
1307  * @param      partition_count_cutoff   The partition count cutoff to use, if we can omit partitionings.
1308  * @param      mode_cutoff              The block mode percentile cutoff [0-1].
1309  * @param[out] bsd                      The descriptor to initialize.
1310  */
1311 #ifdef ASTC_CUSTOMIZED_ENABLE
1312 bool init_block_size_descriptor(
1313 #else
1314 void init_block_size_descriptor(
1315 #endif
1316 	QualityProfile privateProfile,
1317 	unsigned int x_texels,
1318 	unsigned int y_texels,
1319 	unsigned int z_texels,
1320 	bool can_omit_modes,
1321 	unsigned int partition_count_cutoff,
1322 	float mode_cutoff,
1323 	block_size_descriptor& bsd);
1324 
1325 /**
1326  * @brief Populate the partition tables for the target block size.
1327  *
1328  * Note the @c bsd descriptor must be initialized by calling @c init_block_size_descriptor() before
1329  * calling this function.
1330  *
1331  * @param[out] bsd                      The block size information structure to populate.
1332  * @param      can_omit_partitionings   True if we can we drop partitionings that astcenc won't use.
1333  * @param      partition_count_cutoff   The partition count cutoff to use, if we can omit partitionings.
1334  */
1335 void init_partition_tables(
1336 	block_size_descriptor& bsd,
1337 	bool can_omit_partitionings,
1338 	unsigned int partition_count_cutoff);
1339 
1340 /**
1341  * @brief Get the percentile table for 2D block modes.
1342  *
1343  * This is an empirically determined prioritization of which block modes to use in the search in
1344  * terms of their centile (lower centiles = more useful).
1345  *
1346  * Returns a dynamically allocated array; caller must free with delete[].
1347  *
1348  * @param xdim The block x size.
1349  * @param ydim The block y size.
1350  *
1351  * @return The unpacked table.
1352  */
1353 const float* get_2d_percentile_table(
1354 	unsigned int xdim,
1355 	unsigned int ydim);
1356 
1357 /**
1358  * @brief Query if a 2D block size is legal.
1359  *
1360  * @return True if legal, false otherwise.
1361  */
1362 bool is_legal_2d_block_size(
1363 	unsigned int xdim,
1364 	unsigned int ydim);
1365 
1366 /**
1367  * @brief Query if a 3D block size is legal.
1368  *
1369  * @return True if legal, false otherwise.
1370  */
1371 bool is_legal_3d_block_size(
1372 	unsigned int xdim,
1373 	unsigned int ydim,
1374 	unsigned int zdim);
1375 
1376 /* ============================================================================
1377   Functionality for managing BISE quantization and unquantization.
1378 ============================================================================ */
1379 
1380 /**
1381  * @brief The precomputed table for quantizing color values.
1382  *
1383  * Converts unquant value in 0-255 range into quant value in 0-255 range.
1384  * No BISE scrambling is applied at this stage.
1385  *
1386  * The BISE encoding results in ties where available quant<256> values are
1387  * equidistant the available quant<BISE> values. This table stores two values
1388  * for each input - one for use with a negative residual, and one for use with
1389  * a positive residual.
1390  *
1391  * Indexed by [quant_mode - 4][data_value * 2 + residual].
1392  */
1393 extern const uint8_t color_unquant_to_uquant_tables[17][512];
1394 
1395 /**
1396  * @brief The precomputed table for packing quantized color values.
1397  *
1398  * Converts quant value in 0-255 range into packed quant value in 0-N range,
1399  * with BISE scrambling applied.
1400  *
1401  * Indexed by [quant_mode - 4][data_value].
1402  */
1403 extern const uint8_t color_uquant_to_scrambled_pquant_tables[17][256];
1404 
1405 /**
1406  * @brief The precomputed table for unpacking color values.
1407  *
1408  * Converts quant value in 0-N range into unpacked value in 0-255 range,
1409  * with BISE unscrambling applied.
1410  *
1411  * Indexed by [quant_mode - 4][data_value].
1412  */
1413 extern const uint8_t* color_scrambled_pquant_to_uquant_tables[17];
1414 
1415 /**
1416  * @brief The precomputed quant mode storage table.
1417  *
1418  * Indexing by [integer_count/2][bits] gives us the quantization level for a given integer count and
1419  * number of compressed storage bits. Returns -1 for cases where the requested integer count cannot
1420  * ever fit in the supplied storage size.
1421  */
1422 extern const int8_t quant_mode_table[10][128];
1423 
1424 /**
1425  * @brief Encode a packed string using BISE.
1426  *
1427  * Note that BISE can return strings that are not a whole number of bytes in length, and ASTC can
1428  * start storing strings in a block at arbitrary bit offsets in the encoded data.
1429  *
1430  * @param         quant_level       The BISE alphabet size.
1431  * @param         character_count   The number of characters in the string.
1432  * @param         input_data        The unpacked string, one byte per character.
1433  * @param[in,out] output_data       The output packed string.
1434  * @param         bit_offset        The starting offset in the output storage.
1435  */
1436 void encode_ise(
1437 	quant_method quant_level,
1438 	unsigned int character_count,
1439 	const uint8_t* input_data,
1440 	uint8_t* output_data,
1441 	unsigned int bit_offset);
1442 
1443 /**
1444  * @brief Decode a packed string using BISE.
1445  *
1446  * Note that BISE input strings are not a whole number of bytes in length, and ASTC can start
1447  * strings at arbitrary bit offsets in the encoded data.
1448  *
1449  * @param         quant_level       The BISE alphabet size.
1450  * @param         character_count   The number of characters in the string.
1451  * @param         input_data        The packed string.
1452  * @param[in,out] output_data       The output storage, one byte per character.
1453  * @param         bit_offset        The starting offset in the output storage.
1454  */
1455 void decode_ise(
1456 	quant_method quant_level,
1457 	unsigned int character_count,
1458 	const uint8_t* input_data,
1459 	uint8_t* output_data,
1460 	unsigned int bit_offset);
1461 
1462 /**
1463  * @brief Return the number of bits needed to encode an ISE sequence.
1464  *
1465  * This implementation assumes that the @c quant level is untrusted, given it may come from random
1466  * data being decompressed, so we return an arbitrary unencodable size if that is the case.
1467  *
1468  * @param character_count   The number of items in the sequence.
1469  * @param quant_level       The desired quantization level.
1470  *
1471  * @return The number of bits needed to encode the BISE string.
1472  */
1473 unsigned int get_ise_sequence_bitcount(
1474 	unsigned int character_count,
1475 	quant_method quant_level);
1476 
1477 /* ============================================================================
1478   Functionality for managing color partitioning.
1479 ============================================================================ */
1480 
1481 /**
1482  * @brief Compute averages and dominant directions for each partition in a 2 component texture.
1483  *
1484  * @param      pi           The partition info for the current trial.
1485  * @param      blk          The image block color data to be compressed.
1486  * @param      component1   The first component included in the analysis.
1487  * @param      component2   The second component included in the analysis.
1488  * @param[out] pm           The output partition metrics.
1489  *                          - Only pi.partition_count array entries actually get initialized.
1490  *                          - Direction vectors @c pm.dir are not normalized.
1491  */
1492 void compute_avgs_and_dirs_2_comp(
1493 	const partition_info& pi,
1494 	const image_block& blk,
1495 	unsigned int component1,
1496 	unsigned int component2,
1497 	partition_metrics pm[BLOCK_MAX_PARTITIONS]);
1498 
1499 /**
1500  * @brief Compute averages and dominant directions for each partition in a 3 component texture.
1501  *
1502  * @param      pi                  The partition info for the current trial.
1503  * @param      blk                 The image block color data to be compressed.
1504  * @param      omitted_component   The component excluded from the analysis.
1505  * @param[out] pm                  The output partition metrics.
1506  *                                 - Only pi.partition_count array entries actually get initialized.
1507  *                                 - Direction vectors @c pm.dir are not normalized.
1508  */
1509 void compute_avgs_and_dirs_3_comp(
1510 	const partition_info& pi,
1511 	const image_block& blk,
1512 	unsigned int omitted_component,
1513 	partition_metrics pm[BLOCK_MAX_PARTITIONS]);
1514 
1515 /**
1516  * @brief Compute averages and dominant directions for each partition in a 3 component texture.
1517  *
1518  * This is a specialization of @c compute_avgs_and_dirs_3_comp where the omitted component is
1519  * always alpha, a common case during partition search.
1520  *
1521  * @param      pi    The partition info for the current trial.
1522  * @param      blk   The image block color data to be compressed.
1523  * @param[out] pm    The output partition metrics.
1524  *                   - Only pi.partition_count array entries actually get initialized.
1525  *                   - Direction vectors @c pm.dir are not normalized.
1526  */
1527 void compute_avgs_and_dirs_3_comp_rgb(
1528 	const partition_info& pi,
1529 	const image_block& blk,
1530 	partition_metrics pm[BLOCK_MAX_PARTITIONS]);
1531 
1532 /**
1533  * @brief Compute averages and dominant directions for each partition in a 4 component texture.
1534  *
1535  * @param      pi    The partition info for the current trial.
1536  * @param      blk   The image block color data to be compressed.
1537  * @param[out] pm    The output partition metrics.
1538  *                   - Only pi.partition_count array entries actually get initialized.
1539  *                   - Direction vectors @c pm.dir are not normalized.
1540  */
1541 void compute_avgs_and_dirs_4_comp(
1542 	const partition_info& pi,
1543 	const image_block& blk,
1544 	partition_metrics pm[BLOCK_MAX_PARTITIONS]);
1545 
1546 /**
1547  * @brief Compute the RGB error for uncorrelated and same chroma projections.
1548  *
1549  * The output of compute averages and dirs is post processed to define two lines, both of which go
1550  * through the mean-color-value.  One line has a direction defined by the dominant direction; this
1551  * is used to assess the error from using an uncorrelated color representation. The other line goes
1552  * through (0,0,0) and is used to assess the error from using an RGBS color representation.
1553  *
1554  * This function computes the squared error when using these two representations.
1555  *
1556  * @param         pi            The partition info for the current trial.
1557  * @param         blk           The image block color data to be compressed.
1558  * @param[in,out] plines        Processed line inputs, and line length outputs.
1559  * @param[out]    uncor_error   The cumulative error for using the uncorrelated line.
1560  * @param[out]    samec_error   The cumulative error for using the same chroma line.
1561  */
1562 void compute_error_squared_rgb(
1563 	const partition_info& pi,
1564 	const image_block& blk,
1565 	partition_lines3 plines[BLOCK_MAX_PARTITIONS],
1566 	float& uncor_error,
1567 	float& samec_error);
1568 
1569 /**
1570  * @brief Compute the RGBA error for uncorrelated and same chroma projections.
1571  *
1572  * The output of compute averages and dirs is post processed to define two lines, both of which go
1573  * through the mean-color-value.  One line has a direction defined by the dominant direction; this
1574  * is used to assess the error from using an uncorrelated color representation. The other line goes
1575  * through (0,0,0,1) and is used to assess the error from using an RGBS color representation.
1576  *
1577  * This function computes the squared error when using these two representations.
1578  *
1579  * @param      pi              The partition info for the current trial.
1580  * @param      blk             The image block color data to be compressed.
1581  * @param      uncor_plines    Processed uncorrelated partition lines for each partition.
1582  * @param      samec_plines    Processed same chroma partition lines for each partition.
1583  * @param[out] line_lengths    The length of each components deviation from the line.
1584  * @param[out] uncor_error     The cumulative error for using the uncorrelated line.
1585  * @param[out] samec_error     The cumulative error for using the same chroma line.
1586  */
1587 void compute_error_squared_rgba(
1588 	const partition_info& pi,
1589 	const image_block& blk,
1590 	const processed_line4 uncor_plines[BLOCK_MAX_PARTITIONS],
1591 	const processed_line4 samec_plines[BLOCK_MAX_PARTITIONS],
1592 	float line_lengths[BLOCK_MAX_PARTITIONS],
1593 	float& uncor_error,
1594 	float& samec_error);
1595 
1596 /**
1597  * @brief Find the best set of partitions to trial for a given block.
1598  *
1599  * On return the @c best_partitions list will contain the two best partition
1600  * candidates; one assuming data has uncorrelated chroma and one assuming the
1601  * data has correlated chroma. The best candidate is returned first in the list.
1602  *
1603  * @param      bsd                      The block size information.
1604  * @param      blk                      The image block color data to compress.
1605  * @param      partition_count          The number of partitions in the block.
1606  * @param      partition_search_limit   The number of candidate partition encodings to trial.
1607  * @param[out] best_partitions          The best partition candidates.
1608  * @param      requested_candidates     The number of requested partitionings. May return fewer if
1609  *                                      candidates are not available.
1610  *
1611  * @return The actual number of candidates returned.
1612  */
1613 unsigned int find_best_partition_candidates(
1614 	const block_size_descriptor& bsd,
1615 	const image_block& blk,
1616 	unsigned int partition_count,
1617 	unsigned int partition_search_limit,
1618 	unsigned int best_partitions[TUNE_MAX_PARTITIONING_CANDIDATES],
1619 	unsigned int requested_candidates);
1620 
1621 /* ============================================================================
1622   Functionality for managing images and image related data.
1623 ============================================================================ */
1624 
1625 /**
1626  * @brief Get a vector mask indicating lanes decompressing into a UNORM8 value.
1627  *
1628  * @param decode_mode   The color profile for LDR_SRGB settings.
1629  * @param blk           The image block for output image bitness settings.
1630  *
1631  * @return The component mask vector.
1632  */
get_u8_component_mask(astcenc_profile decode_mode,const image_block & blk)1633 static inline vmask4 get_u8_component_mask(
1634 	astcenc_profile decode_mode,
1635 	const image_block& blk
1636 ) {
1637 	vmask4 u8_mask(false);
1638 	// Decode mode writing to a unorm8 output value
1639 	if (blk.decode_unorm8)
1640 	{
1641 		u8_mask = vmask4(true);
1642 	}
1643 	// SRGB writing to a unorm8 RGB value
1644 	else if (decode_mode == ASTCENC_PRF_LDR_SRGB)
1645 	{
1646 		u8_mask = vmask4(true, true, true, false);
1647 	}
1648 
1649 	return u8_mask;
1650 }
1651 
1652 /**
1653  * @brief Setup computation of regional averages in an image.
1654  *
1655  * This must be done by only a single thread per image, before any thread calls
1656  * @c compute_averages().
1657  *
1658  * Results are written back into @c img->input_alpha_averages.
1659  *
1660  * @param      img                   The input image data, also holds output data.
1661  * @param      alpha_kernel_radius   The kernel radius (in pixels) for alpha mods.
1662  * @param      swz                   Input data component swizzle.
1663  * @param[out] ag                    The average variance arguments to init.
1664  *
1665  * @return The number of tasks in the processing stage.
1666  */
1667 unsigned int init_compute_averages(
1668 	const astcenc_image& img,
1669 	unsigned int alpha_kernel_radius,
1670 	const astcenc_swizzle& swz,
1671 	avg_args& ag);
1672 
1673 /**
1674  * @brief Compute averages for a pixel region.
1675  *
1676  * The routine computes both in a single pass, using a summed-area table to decouple the running
1677  * time from the averaging/variance kernel size.
1678  *
1679  * @param[out] ctx   The compressor context storing the output data.
1680  * @param      arg   The input parameter structure.
1681  */
1682 void compute_pixel_region_variance(
1683 	astcenc_contexti& ctx,
1684 	const pixel_region_args& arg);
1685 /**
1686  * @brief Load a single image block from the input image.
1687  *
1688  * @param      decode_mode   The compression color profile.
1689  * @param      img           The input image data.
1690  * @param[out] blk           The image block to populate.
1691  * @param      bsd           The block size information.
1692  * @param      xpos          The block X coordinate in the input image.
1693  * @param      ypos          The block Y coordinate in the input image.
1694  * @param      zpos          The block Z coordinate in the input image.
1695  * @param      swz           The swizzle to apply on load.
1696  */
1697 void load_image_block(
1698 	astcenc_profile decode_mode,
1699 	const astcenc_image& img,
1700 	image_block& blk,
1701 	const block_size_descriptor& bsd,
1702 	unsigned int xpos,
1703 	unsigned int ypos,
1704 	unsigned int zpos,
1705 	const astcenc_swizzle& swz);
1706 
1707 /**
1708  * @brief Load a single image block from the input image.
1709  *
1710  * This specialized variant can be used only if the block is 2D LDR U8 data,
1711  * with no swizzle.
1712  *
1713  * @param      decode_mode   The compression color profile.
1714  * @param      img           The input image data.
1715  * @param[out] blk           The image block to populate.
1716  * @param      bsd           The block size information.
1717  * @param      xpos          The block X coordinate in the input image.
1718  * @param      ypos          The block Y coordinate in the input image.
1719  * @param      zpos          The block Z coordinate in the input image.
1720  * @param      swz           The swizzle to apply on load.
1721  */
1722 void load_image_block_fast_ldr(
1723 	astcenc_profile decode_mode,
1724 	const astcenc_image& img,
1725 	image_block& blk,
1726 	const block_size_descriptor& bsd,
1727 	unsigned int xpos,
1728 	unsigned int ypos,
1729 	unsigned int zpos,
1730 	const astcenc_swizzle& swz);
1731 
1732 /**
1733  * @brief Store a single image block to the output image.
1734  *
1735  * @param[out] img    The output image data.
1736  * @param      blk    The image block to export.
1737  * @param      bsd    The block size information.
1738  * @param      xpos   The block X coordinate in the input image.
1739  * @param      ypos   The block Y coordinate in the input image.
1740  * @param      zpos   The block Z coordinate in the input image.
1741  * @param      swz    The swizzle to apply on store.
1742  */
1743 void store_image_block(
1744 	astcenc_image& img,
1745 	const image_block& blk,
1746 	const block_size_descriptor& bsd,
1747 	unsigned int xpos,
1748 	unsigned int ypos,
1749 	unsigned int zpos,
1750 	const astcenc_swizzle& swz);
1751 
1752 /* ============================================================================
1753   Functionality for computing endpoint colors and weights for a block.
1754 ============================================================================ */
1755 
1756 /**
1757  * @brief Compute ideal endpoint colors and weights for 1 plane of weights.
1758  *
1759  * The ideal endpoints define a color line for the partition. For each texel the ideal weight
1760  * defines an exact position on the partition color line. We can then use these to assess the error
1761  * introduced by removing and quantizing the weight grid.
1762  *
1763  * @param      blk   The image block color data to compress.
1764  * @param      pi    The partition info for the current trial.
1765  * @param[out] ei    The endpoint and weight values.
1766  */
1767 void compute_ideal_colors_and_weights_1plane(
1768 	const image_block& blk,
1769 	const partition_info& pi,
1770 	endpoints_and_weights& ei);
1771 
1772 /**
1773  * @brief Compute ideal endpoint colors and weights for 2 planes of weights.
1774  *
1775  * The ideal endpoints define a color line for the partition. For each texel the ideal weight
1776  * defines an exact position on the partition color line. We can then use these to assess the error
1777  * introduced by removing and quantizing the weight grid.
1778  *
1779  * @param      bsd                The block size information.
1780  * @param      blk                The image block color data to compress.
1781  * @param      plane2_component   The component assigned to plane 2.
1782  * @param[out] ei1                The endpoint and weight values for plane 1.
1783  * @param[out] ei2                The endpoint and weight values for plane 2.
1784  */
1785 void compute_ideal_colors_and_weights_2planes(
1786 	const block_size_descriptor& bsd,
1787 	const image_block& blk,
1788 	unsigned int plane2_component,
1789 	endpoints_and_weights& ei1,
1790 	endpoints_and_weights& ei2);
1791 
1792 /**
1793  * @brief Compute the optimal unquantized weights for a decimation table.
1794  *
1795  * After computing ideal weights for the case for a complete weight grid, we we want to compute the
1796  * ideal weights for the case where weights exist only for some texels. We do this with a
1797  * steepest-descent grid solver which works as follows:
1798  *
1799  * First, for each actual weight, perform a weighted averaging of the texels affected by the weight.
1800  * Then, set step size to <some initial value> and attempt one step towards the original ideal
1801  * weight if it helps to reduce error.
1802  *
1803  * @param      ei                       The non-decimated endpoints and weights.
1804  * @param      di                       The selected weight decimation.
1805  * @param[out] dec_weight_ideal_value   The ideal values for the decimated weight set.
1806  */
1807 void compute_ideal_weights_for_decimation(
1808 	const endpoints_and_weights& ei,
1809 	const decimation_info& di,
1810 	float* dec_weight_ideal_value);
1811 
1812 /**
1813  * @brief Compute the optimal quantized weights for a decimation table.
1814  *
1815  * We test the two closest weight indices in the allowed quantization range and keep the weight that
1816  * is the closest match.
1817  *
1818  * @param      di                        The selected weight decimation.
1819  * @param      low_bound                 The lowest weight allowed.
1820  * @param      high_bound                The highest weight allowed.
1821  * @param      dec_weight_ideal_value    The ideal weight set.
1822  * @param[out] dec_weight_quant_uvalue   The output quantized weight as a float.
1823  * @param[out] dec_weight_uquant         The output quantized weight as encoded int.
1824  * @param      quant_level               The desired weight quant level.
1825  */
1826 void compute_quantized_weights_for_decimation(
1827 	const decimation_info& di,
1828 	float low_bound,
1829 	float high_bound,
1830 	const float* dec_weight_ideal_value,
1831 	float* dec_weight_quant_uvalue,
1832 	uint8_t* dec_weight_uquant,
1833 	quant_method quant_level);
1834 
1835 /**
1836  * @brief Compute the error of a decimated weight set for 1 plane.
1837  *
1838  * After computing ideal weights for the case with one weight per texel, we want to compute the
1839  * error for decimated weight grids where weights are stored at a lower resolution. This function
1840  * computes the error of the reduced grid, compared to the full grid.
1841  *
1842  * @param eai                       The ideal weights for the full grid.
1843  * @param di                        The selected weight decimation.
1844  * @param dec_weight_quant_uvalue   The quantized weights for the decimated grid.
1845  *
1846  * @return The accumulated error.
1847  */
1848 float compute_error_of_weight_set_1plane(
1849 	const endpoints_and_weights& eai,
1850 	const decimation_info& di,
1851 	const float* dec_weight_quant_uvalue);
1852 
1853 /**
1854  * @brief Compute the error of a decimated weight set for 2 planes.
1855  *
1856  * After computing ideal weights for the case with one weight per texel, we want to compute the
1857  * error for decimated weight grids where weights are stored at a lower resolution. This function
1858  * computes the error of the reduced grid, compared to the full grid.
1859  *
1860  * @param eai1                             The ideal weights for the full grid and plane 1.
1861  * @param eai2                             The ideal weights for the full grid and plane 2.
1862  * @param di                               The selected weight decimation.
1863  * @param dec_weight_quant_uvalue_plane1   The quantized weights for the decimated grid plane 1.
1864  * @param dec_weight_quant_uvalue_plane2   The quantized weights for the decimated grid plane 2.
1865  *
1866  * @return The accumulated error.
1867  */
1868 float compute_error_of_weight_set_2planes(
1869 	const endpoints_and_weights& eai1,
1870 	const endpoints_and_weights& eai2,
1871 	const decimation_info& di,
1872 	const float* dec_weight_quant_uvalue_plane1,
1873 	const float* dec_weight_quant_uvalue_plane2);
1874 
1875 /**
1876  * @brief Pack a single pair of color endpoints as effectively as possible.
1877  *
1878  * The user requests a base color endpoint mode in @c format, but the quantizer may choose a
1879  * delta-based representation. It will report back the format variant it actually used.
1880  *
1881  * @param      color0        The input unquantized color0 endpoint for absolute endpoint pairs.
1882  * @param      color1        The input unquantized color1 endpoint for absolute endpoint pairs.
1883  * @param      rgbs_color    The input unquantized RGBS variant endpoint for same chroma endpoints.
1884  * @param      rgbo_color    The input unquantized RGBS variant endpoint for HDR endpoints.
1885  * @param      format        The desired base format.
1886  * @param[out] output        The output storage for the quantized colors/
1887  * @param      quant_level   The quantization level requested.
1888  *
1889  * @return The actual endpoint mode used.
1890  */
1891 uint8_t pack_color_endpoints(
1892 	QualityProfile privateProfile,
1893 	vfloat4 color0,
1894 	vfloat4 color1,
1895 	vfloat4 rgbs_color,
1896 	vfloat4 rgbo_color,
1897 	int format,
1898 	uint8_t* output,
1899 	quant_method quant_level);
1900 
1901 /**
1902  * @brief Unpack a single pair of encoded endpoints.
1903  *
1904  * Endpoints must be unscrambled and converted into the 0-255 range before calling this functions.
1905  *
1906  * @param      decode_mode   The decode mode (LDR, HDR, etc).
1907  * @param      format        The color endpoint mode used.
1908  * @param      input         The raw array of encoded input integers. The length of this array
1909  *                           depends on @c format; it can be safely assumed to be large enough.
1910  * @param[out] rgb_hdr       Is the endpoint using HDR for the RGB channels?
1911  * @param[out] alpha_hdr     Is the endpoint using HDR for the A channel?
1912  * @param[out] output0       The output color for endpoint 0.
1913  * @param[out] output1       The output color for endpoint 1.
1914  */
1915 void unpack_color_endpoints(
1916 	astcenc_profile decode_mode,
1917 	int format,
1918 	const uint8_t* input,
1919 	bool& rgb_hdr,
1920 	bool& alpha_hdr,
1921 	vint4& output0,
1922 	vint4& output1);
1923 
1924 /**
1925  * @brief Unpack an LDR RGBA color that uses delta encoding.
1926  *
1927  * @param      input0    The packed endpoint 0 color.
1928  * @param      input1    The packed endpoint 1 color deltas.
1929  * @param[out] output0   The unpacked endpoint 0 color.
1930  * @param[out] output1   The unpacked endpoint 1 color.
1931  */
1932 void rgba_delta_unpack(
1933 	vint4 input0,
1934 	vint4 input1,
1935 	vint4& output0,
1936 	vint4& output1);
1937 
1938 /**
1939  * @brief Unpack an LDR RGBA color that uses direct encoding.
1940  *
1941  * @param      input0    The packed endpoint 0 color.
1942  * @param      input1    The packed endpoint 1 color.
1943  * @param[out] output0   The unpacked endpoint 0 color.
1944  * @param[out] output1   The unpacked endpoint 1 color.
1945  */
1946 void rgba_unpack(
1947 	vint4 input0,
1948 	vint4 input1,
1949 	vint4& output0,
1950 	vint4& output1);
1951 
1952 /**
1953  * @brief Unpack a set of quantized and decimated weights.
1954  *
1955  * TODO: Can we skip this for non-decimated weights now that the @c scb is
1956  * already storing unquantized weights?
1957  *
1958  * @param      bsd              The block size information.
1959  * @param      scb              The symbolic compressed encoding.
1960  * @param      di               The weight grid decimation table.
1961  * @param      is_dual_plane    @c true if this is a dual plane block, @c false otherwise.
1962  * @param[out] weights_plane1   The output array for storing the plane 1 weights.
1963  * @param[out] weights_plane2   The output array for storing the plane 2 weights.
1964  */
1965 void unpack_weights(
1966 	const block_size_descriptor& bsd,
1967 	const symbolic_compressed_block& scb,
1968 	const decimation_info& di,
1969 	bool is_dual_plane,
1970 	int weights_plane1[BLOCK_MAX_TEXELS],
1971 	int weights_plane2[BLOCK_MAX_TEXELS]);
1972 
1973 /**
1974  * @brief Identify, for each mode, which set of color endpoint produces the best result.
1975  *
1976  * Returns the best @c tune_candidate_limit best looking modes, along with the ideal color encoding
1977  * combination for each. The modified quantization level can be used when all formats are the same,
1978  * as this frees up two additional bits of storage.
1979  *
1980  * @param      pi                            The partition info for the current trial.
1981  * @param      blk                           The image block color data to compress.
1982  * @param      ep                            The ideal endpoints.
1983  * @param      qwt_bitcounts                 Bit counts for different quantization methods.
1984  * @param      qwt_errors                    Errors for different quantization methods.
1985  * @param      tune_candidate_limit          The max number of candidates to return, may be less.
1986  * @param      start_block_mode              The first block mode to inspect.
1987  * @param      end_block_mode                The last block mode to inspect.
1988  * @param[out] partition_format_specifiers   The best formats per partition.
1989  * @param[out] block_mode                    The best packed block mode indexes.
1990  * @param[out] quant_level                   The best color quant level.
1991  * @param[out] quant_level_mod               The best color quant level if endpoints are the same.
1992  * @param[out] tmpbuf                        Preallocated scratch buffers for the compressor.
1993  *
1994  * @return The actual number of candidate matches returned.
1995  */
1996 unsigned int compute_ideal_endpoint_formats(
1997 	QualityProfile privateProfile,
1998 	const partition_info& pi,
1999 	const image_block& blk,
2000 	const endpoints& ep,
2001 	const int8_t* qwt_bitcounts,
2002 	const float* qwt_errors,
2003 	unsigned int tune_candidate_limit,
2004 	unsigned int start_block_mode,
2005 	unsigned int end_block_mode,
2006 	uint8_t partition_format_specifiers[TUNE_MAX_TRIAL_CANDIDATES][BLOCK_MAX_PARTITIONS],
2007 	int block_mode[TUNE_MAX_TRIAL_CANDIDATES],
2008 	quant_method quant_level[TUNE_MAX_TRIAL_CANDIDATES],
2009 	quant_method quant_level_mod[TUNE_MAX_TRIAL_CANDIDATES],
2010 	compression_working_buffers& tmpbuf);
2011 
2012 /**
2013  * @brief For a given 1 plane weight set recompute the endpoint colors.
2014  *
2015  * As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must
2016  * recompute the ideal colors for a specific weight set.
2017  *
2018  * @param         blk                  The image block color data to compress.
2019  * @param         pi                   The partition info for the current trial.
2020  * @param         di                   The weight grid decimation table.
2021  * @param         dec_weights_uquant   The quantized weight set.
2022  * @param[in,out] ep                   The color endpoints (modifed in place).
2023  * @param[out]    rgbs_vectors         The RGB+scale vectors for LDR blocks.
2024  * @param[out]    rgbo_vectors         The RGB+offset vectors for HDR blocks.
2025  */
2026 void recompute_ideal_colors_1plane(
2027 	const image_block& blk,
2028 	const partition_info& pi,
2029 	const decimation_info& di,
2030 	const uint8_t* dec_weights_uquant,
2031 	endpoints& ep,
2032 	vfloat4 rgbs_vectors[BLOCK_MAX_PARTITIONS],
2033 	vfloat4 rgbo_vectors[BLOCK_MAX_PARTITIONS]);
2034 
2035 /**
2036  * @brief For a given 2 plane weight set recompute the endpoint colors.
2037  *
2038  * As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must
2039  * recompute the ideal colors for a specific weight set.
2040  *
2041  * @param         blk                         The image block color data to compress.
2042  * @param         bsd                         The block_size descriptor.
2043  * @param         di                          The weight grid decimation table.
2044  * @param         dec_weights_uquant_plane1   The quantized weight set for plane 1.
2045  * @param         dec_weights_uquant_plane2   The quantized weight set for plane 2.
2046  * @param[in,out] ep                          The color endpoints (modifed in place).
2047  * @param[out]    rgbs_vector                 The RGB+scale color for LDR blocks.
2048  * @param[out]    rgbo_vector                 The RGB+offset color for HDR blocks.
2049  * @param         plane2_component            The component assigned to plane 2.
2050  */
2051 void recompute_ideal_colors_2planes(
2052 	const image_block& blk,
2053 	const block_size_descriptor& bsd,
2054 	const decimation_info& di,
2055 	const uint8_t* dec_weights_uquant_plane1,
2056 	const uint8_t* dec_weights_uquant_plane2,
2057 	endpoints& ep,
2058 	vfloat4& rgbs_vector,
2059 	vfloat4& rgbo_vector,
2060 	int plane2_component);
2061 
2062 /**
2063  * @brief Expand the angular tables needed for the alternative to PCA that we use.
2064  */
2065 void prepare_angular_tables();
2066 
2067 /**
2068  * @brief Compute the angular endpoints for one plane for each block mode.
2069  *
2070  * @param      only_always              Only consider block modes that are always enabled.
2071  * @param      bsd                      The block size descriptor for the current trial.
2072  * @param      dec_weight_ideal_value   The ideal decimated unquantized weight values.
2073  * @param      max_weight_quant         The maximum block mode weight quantization allowed.
2074  * @param[out] tmpbuf                   Preallocated scratch buffers for the compressor.
2075  */
2076 void compute_angular_endpoints_1plane(
2077 	QualityProfile privateProfile,
2078 	bool only_always,
2079 	const block_size_descriptor& bsd,
2080 	const float* dec_weight_ideal_value,
2081 	unsigned int max_weight_quant,
2082 	compression_working_buffers& tmpbuf);
2083 
2084 /**
2085  * @brief Compute the angular endpoints for two planes for each block mode.
2086  *
2087  * @param      bsd                      The block size descriptor for the current trial.
2088  * @param      dec_weight_ideal_value   The ideal decimated unquantized weight values.
2089  * @param      max_weight_quant         The maximum block mode weight quantization allowed.
2090  * @param[out] tmpbuf                   Preallocated scratch buffers for the compressor.
2091  */
2092 void compute_angular_endpoints_2planes(
2093 	QualityProfile privateProfile,
2094 	const block_size_descriptor& bsd,
2095 	const float* dec_weight_ideal_value,
2096 	unsigned int max_weight_quant,
2097 	compression_working_buffers& tmpbuf);
2098 
2099 /* ============================================================================
2100   Functionality for high level compression and decompression access.
2101 ============================================================================ */
2102 
2103 /**
2104  * @brief Compress an image block into a physical block.
2105  *
2106  * @param      ctx      The compressor context and configuration.
2107  * @param      blk      The image block color data to compress.
2108  * @param[out] pcb      The physical compressed block output.
2109  * @param[out] tmpbuf   Preallocated scratch buffers for the compressor.
2110  */
2111 void compress_block(
2112 	const astcenc_contexti& ctx,
2113 	const image_block& blk,
2114 	uint8_t pcb[16],
2115 #if QUALITY_CONTROL
2116 	compression_working_buffers& tmpbuf,
2117 	bool calQualityEnable,
2118 	int32_t *mseBlock[RGBA_COM]
2119 #else
2120     compression_working_buffers& tmpbuf
2121 #endif
2122 	);
2123 
2124 /**
2125  * @brief Decompress a symbolic block in to an image block.
2126  *
2127  * @param      decode_mode   The decode mode (LDR, HDR, etc).
2128  * @param      bsd           The block size information.
2129  * @param      xpos          The X coordinate of the block in the overall image.
2130  * @param      ypos          The Y coordinate of the block in the overall image.
2131  * @param      zpos          The Z coordinate of the block in the overall image.
2132  * @param[out] blk           The decompressed image block color data.
2133  */
2134 void decompress_symbolic_block(
2135 	astcenc_profile decode_mode,
2136 	const block_size_descriptor& bsd,
2137 	int xpos,
2138 	int ypos,
2139 	int zpos,
2140 	const symbolic_compressed_block& scb,
2141 	image_block& blk);
2142 
2143 /**
2144  * @brief Compute the error between a symbolic block and the original input data.
2145  *
2146  * This function is specialized for 2 plane and 1 partition search.
2147  *
2148  * In RGBM mode this will reject blocks that attempt to encode a zero M value.
2149  *
2150  * @param config   The compressor config.
2151  * @param bsd      The block size information.
2152  * @param scb      The symbolic compressed encoding.
2153  * @param blk      The original image block color data.
2154  *
2155  * @return Returns the computed error, or a negative value if the encoding
2156  *         should be rejected for any reason.
2157  */
2158 float compute_symbolic_block_difference_2plane(
2159 	const astcenc_config& config,
2160 	const block_size_descriptor& bsd,
2161 	const symbolic_compressed_block& scb,
2162 	const image_block& blk);
2163 
2164 /**
2165  * @brief Compute the error between a symbolic block and the original input data.
2166  *
2167  * This function is specialized for 1 plane and N partition search.
2168  *
2169  * In RGBM mode this will reject blocks that attempt to encode a zero M value.
2170  *
2171  * @param config   The compressor config.
2172  * @param bsd      The block size information.
2173  * @param scb      The symbolic compressed encoding.
2174  * @param blk      The original image block color data.
2175  *
2176  * @return Returns the computed error, or a negative value if the encoding
2177  *         should be rejected for any reason.
2178  */
2179 float compute_symbolic_block_difference_1plane(
2180 	const astcenc_config& config,
2181 	const block_size_descriptor& bsd,
2182 	const symbolic_compressed_block& scb,
2183 	const image_block& blk);
2184 
2185 /**
2186  * @brief Compute the error between a symbolic block and the original input data.
2187  *
2188  * This function is specialized for 1 plane and 1 partition search.
2189  *
2190  * In RGBM mode this will reject blocks that attempt to encode a zero M value.
2191  *
2192  * @param config   The compressor config.
2193  * @param bsd      The block size information.
2194  * @param scb      The symbolic compressed encoding.
2195  * @param blk      The original image block color data.
2196  *
2197  * @return Returns the computed error, or a negative value if the encoding
2198  *         should be rejected for any reason.
2199  */
2200 float compute_symbolic_block_difference_1plane_1partition(
2201 	const astcenc_config& config,
2202 	const block_size_descriptor& bsd,
2203 	const symbolic_compressed_block& scb,
2204 	const image_block& blk);
2205 
2206 /**
2207  * @brief Convert a symbolic representation into a binary physical encoding.
2208  *
2209  * It is assumed that the symbolic encoding is valid and encodable, or
2210  * previously flagged as an error block if an error color it to be encoded.
2211  *
2212  * @param      bsd   The block size information.
2213  * @param      scb   The symbolic representation.
2214  * @param[out] pcb   The physical compressed block output.
2215  */
2216 void symbolic_to_physical(
2217 	const block_size_descriptor& bsd,
2218 	const symbolic_compressed_block& scb,
2219 	uint8_t pcb[16]);
2220 
2221 /**
2222  * @brief Convert a binary physical encoding into a symbolic representation.
2223  *
2224  * This function can cope with arbitrary input data; output blocks will be
2225  * flagged as an error block if the encoding is invalid.
2226  *
2227  * @param      bsd   The block size information.
2228  * @param      pcb   The physical compresesd block input.
2229  * @param[out] scb   The output symbolic representation.
2230  */
2231 void physical_to_symbolic(
2232 	const block_size_descriptor& bsd,
2233 	const uint8_t pcb[16],
2234 	symbolic_compressed_block& scb);
2235 
2236 /* ============================================================================
2237 Platform-specific functions.
2238 ============================================================================ */
2239 /**
2240  * @brief Allocate an aligned memory buffer.
2241  *
2242  * Allocated memory must be freed by aligned_free.
2243  *
2244  * @param size    The desired buffer size.
2245  * @param align   The desired buffer alignment; must be 2^N, may be increased
2246  *                by the implementation to a minimum allowable alignment.
2247  *
2248  * @return The memory buffer pointer or nullptr on allocation failure.
2249  */
2250 template<typename T>
aligned_malloc(size_t size,size_t align)2251 T* aligned_malloc(size_t size, size_t align)
2252 {
2253 	void* ptr;
2254 	int error = 0;
2255 
2256 	// Don't allow this to under-align a type
2257 	size_t min_align = astc::max(alignof(T), sizeof(void*));
2258 	size_t real_align = astc::max(min_align, align);
2259 
2260 #if defined(_WIN32)
2261 	ptr = _aligned_malloc(size, real_align);
2262 #else
2263 	error = posix_memalign(&ptr, real_align, size);
2264 #endif
2265 
2266 	if (error || (!ptr))
2267 	{
2268 		return nullptr;
2269 	}
2270 
2271 	return static_cast<T*>(ptr);
2272 }
2273 
2274 /**
2275  * @brief Free an aligned memory buffer.
2276  *
2277  * @param ptr   The buffer to free.
2278  */
2279 template<typename T>
aligned_free(T * ptr)2280 void aligned_free(T* ptr)
2281 {
2282 #if defined(_WIN32)
2283 	_aligned_free(ptr);
2284 #else
2285 	free(ptr);
2286 #endif
2287 }
2288 
2289 #ifdef ASTC_CUSTOMIZED_ENABLE
2290 #ifdef BUILD_HMOS_SDK
2291 #if defined(_WIN32) && !defined(__CYGWIN__)
2292 const LPCSTR g_astcCustomizedSo = "../../hms/toolchains/lib/libastcCustomizedEncode.dll";
2293 #elif defined(__APPLE__)
2294 const std::string g_astcCustomizedSo = "../../hms/toolchains/lib/libastcCustomizedEncode.dylib";
2295 #else
2296 const std::string g_astcCustomizedSo = "../../hms/toolchains/lib/libastcCustomizedEncode.so";
2297 #endif
2298 #else
2299 #ifdef SUT_PATH_X64
2300 const std::string g_astcCustomizedSo = "/system/lib64/module/hms/graphic/libastcCustomizedEncode.z.so";
2301 #else
2302 const std::string g_astcCustomizedSo = "/system/lib/module/hms/graphic/libastcCustomizedEncode.z.so";
2303 #endif
2304 #endif
2305 using IsCustomizedBlockMode = bool (*)(const int);
2306 using CustomizedMaxPartitions = int (*)();
2307 using CustomizedBlockMode = int (*)();
2308 
2309 class AstcCustomizedSoManager
2310 {
2311 public:
AstcCustomizedSoManager()2312 	AstcCustomizedSoManager()
2313 	{
2314 		astcCustomizedSoOpened_ = false;
2315 		astcCustomizedSoHandle_ = nullptr;
2316 		isCustomizedBlockModeFunc_ = nullptr;
2317 		customizedMaxPartitionsFunc_ = nullptr;
2318 		customizedBlockModeFunc_ = nullptr;
2319 	}
~AstcCustomizedSoManager()2320 	~AstcCustomizedSoManager()
2321 	{
2322 		if (!astcCustomizedSoOpened_ || astcCustomizedSoHandle_ == nullptr)
2323 		{
2324 			ASTCENC_DEBUG("astcenc customized so is not opened when dlclose!");
2325 			return;
2326 		}
2327 #if defined(_WIN32) && !defined(__CYGWIN__)
2328 		if (!FreeLibrary(astcCustomizedSoHandle_))
2329 		{
2330 			ASTCENC_ERROR("astc dll FreeLibrary failed: %{public}s", g_astcCustomizedSo);
2331 		}
2332 #else
2333 		if (dlclose(astcCustomizedSoHandle_) != 0)
2334 		{
2335 			ASTCENC_ERROR("astcenc so dlclose failed: %{public}s", g_astcCustomizedSo.c_str());
2336 		}
2337 #endif
2338 	}
2339 	IsCustomizedBlockMode isCustomizedBlockModeFunc_;
2340 	CustomizedMaxPartitions customizedMaxPartitionsFunc_;
2341 	CustomizedBlockMode customizedBlockModeFunc_;
LoadSutCustomizedSo()2342 	bool LoadSutCustomizedSo()
2343 	{
2344 		std::lock_guard<std::mutex> lock(astcCustomizedSoMutex_);
2345 		if (!astcCustomizedSoOpened_)
2346 		{
2347 #if defined(_WIN32) && !defined(__CYGWIN__)
2348 			if ((_access(g_astcCustomizedSo, 0) == -1))
2349 			{
2350 				ASTCENC_WARN("astc customized dll(%{public}s) is not found!", g_astcCustomizedSo);
2351 				return false;
2352 			}
2353 			astcCustomizedSoHandle_ = LoadLibrary(g_astcCustomizedSo);
2354 			if (astcCustomizedSoHandle_ == nullptr)
2355 			{
2356 				ASTCENC_ERROR("astc libAstcCustomizedEnc LoadLibrary failed!");
2357 				return false;
2358 			}
2359 			isCustomizedBlockModeFunc_ =
2360 				reinterpret_cast<IsCustomizedBlockMode>(GetProcAddress(astcCustomizedSoHandle_,
2361 				"IsCustomizedBlockMode"));
2362 			if (isCustomizedBlockModeFunc_ == nullptr)
2363 			{
2364 				ASTCENC_ERROR("astc isCustomizedBlockModeFunc_ GetProcAddress failed!");
2365 				if (!FreeLibrary(astcCustomizedSoHandle_))
2366 				{
2367 					ASTCENC_ERROR("astc isCustomizedBlockModeFunc_ FreeLibrary failed!");
2368 				}
2369 				return false;
2370 			}
2371 			customizedMaxPartitionsFunc_ =
2372 				reinterpret_cast<CustomizedMaxPartitions>(GetProcAddress(astcCustomizedSoHandle_,
2373 				"CustomizedMaxPartitions"));
2374 			if (customizedMaxPartitionsFunc_ == nullptr)
2375 			{
2376 				ASTCENC_ERROR("astc customizedMaxPartitionsFunc_ GetProcAddress failed!");
2377 				if (!FreeLibrary(astcCustomizedSoHandle_))
2378 				{
2379 					ASTCENC_ERROR("astc customizedMaxPartitionsFunc_ FreeLibrary failed!");
2380 				}
2381 				return false;
2382 			}
2383 			customizedBlockModeFunc_ =
2384 				reinterpret_cast<CustomizedBlockMode>(GetProcAddress(astcCustomizedSoHandle_,
2385 				"CustomizedBlockMode"));
2386 			if (customizedBlockModeFunc_ == nullptr)
2387 			{
2388 				ASTCENC_ERROR("astc customizedBlockModeFunc_ GetProcAddress failed!");
2389 				if (!FreeLibrary(astcCustomizedSoHandle_))
2390 				{
2391 					ASTCENC_ERROR("astc customizedBlockModeFunc_ FreeLibrary failed!");
2392 				}
2393 				return false;
2394 			}
2395 			ASTCENC_INFO("astcenc customized dll load success: %{public}s!", g_astcCustomizedSo);
2396 #else
2397 			if (access(g_astcCustomizedSo.c_str(), F_OK) == -1)
2398 			{
2399 				ASTCENC_WARN("astc customized so(%{public}s) is not found!", g_astcCustomizedSo.c_str());
2400 				return false;
2401 			}
2402 			astcCustomizedSoHandle_ = dlopen(g_astcCustomizedSo.c_str(), 1);
2403 			if (astcCustomizedSoHandle_ == nullptr)
2404 			{
2405 				ASTCENC_ERROR("astc libAstcCustomizedEnc dlopen failed!");
2406 				return false;
2407 			}
2408 			isCustomizedBlockModeFunc_ =
2409 				reinterpret_cast<IsCustomizedBlockMode>(dlsym(astcCustomizedSoHandle_,
2410 				"IsCustomizedBlockMode"));
2411 			if (isCustomizedBlockModeFunc_ == nullptr)
2412 			{
2413 				ASTCENC_ERROR("astc isCustomizedBlockModeFunc_ dlsym failed!");
2414 				dlclose(astcCustomizedSoHandle_);
2415 				astcCustomizedSoHandle_ = nullptr;
2416 				return false;
2417 			}
2418 			customizedMaxPartitionsFunc_ =
2419 				reinterpret_cast<CustomizedMaxPartitions>(dlsym(astcCustomizedSoHandle_,
2420 				"CustomizedMaxPartitions"));
2421 			if (customizedMaxPartitionsFunc_ == nullptr)
2422 			{
2423 				ASTCENC_ERROR("astc customizedMaxPartitionsFunc_ dlsym failed!");
2424 				dlclose(astcCustomizedSoHandle_);
2425 				astcCustomizedSoHandle_ = nullptr;
2426 				return false;
2427 			}
2428 			customizedBlockModeFunc_ =
2429 				reinterpret_cast<CustomizedBlockMode>(dlsym(astcCustomizedSoHandle_,
2430 				"CustomizedBlockMode"));
2431 			if (customizedBlockModeFunc_ == nullptr)
2432 			{
2433 				ASTCENC_ERROR("astc customizedBlockModeFunc_ dlsym failed!");
2434 				dlclose(astcCustomizedSoHandle_);
2435 				astcCustomizedSoHandle_ = nullptr;
2436 				return false;
2437 			}
2438 			ASTCENC_INFO("astcenc customized so dlopen success: %{public}s", g_astcCustomizedSo.c_str());
2439 #endif
2440 			astcCustomizedSoOpened_ = true;
2441 		}
2442 		return true;
2443 	}
2444 private:
2445 	bool astcCustomizedSoOpened_;
2446 #if defined(_WIN32) && !defined(__CYGWIN__)
2447 	HINSTANCE astcCustomizedSoHandle_;
2448 #else
2449 	void *astcCustomizedSoHandle_;
2450 #endif
2451     std::mutex astcCustomizedSoMutex_;
2452 };
2453 extern AstcCustomizedSoManager g_astcCustomizedSoManager;
2454 #endif
2455 
2456 #endif
2457