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