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