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