Coverage Report

Created: 2026-11-09 07:09

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