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