Path: blob/master/thirdparty/astcenc/astcenc_internal.h
9905 views
// SPDX-License-Identifier: Apache-2.01// ----------------------------------------------------------------------------2// Copyright 2011-2024 Arm Limited3//4// Licensed under the Apache License, Version 2.0 (the "License"); you may not5// use this file except in compliance with the License. You may obtain a copy6// of the License at:7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13// License for the specific language governing permissions and limitations14// under the License.15// ----------------------------------------------------------------------------1617/**18* @brief Functions and data declarations.19*/2021#ifndef ASTCENC_INTERNAL_INCLUDED22#define ASTCENC_INTERNAL_INCLUDED2324#include <algorithm>25#include <cstddef>26#include <cstdint>27#if defined(ASTCENC_DIAGNOSTICS)28#include <cstdio>29#endif30#include <cstdlib>31#include <limits>3233#include "astcenc.h"34#include "astcenc_mathlib.h"35#include "astcenc_vecmathlib.h"3637/**38* @brief Make a promise to the compiler's optimizer.39*40* A promise is an expression that the optimizer is can assume is true for to help it generate41* faster code. Common use cases for this are to promise that a for loop will iterate more than42* once, or that the loop iteration count is a multiple of a vector length, which avoids pre-loop43* checks and can avoid loop tails if loops are unrolled by the auto-vectorizer.44*/45#if defined(NDEBUG)46#if !defined(__clang__) && defined(_MSC_VER)47#define promise(cond) __assume(cond)48#elif defined(__clang__)49#if __has_builtin(__builtin_assume)50#define promise(cond) __builtin_assume(cond)51#elif __has_builtin(__builtin_unreachable)52#define promise(cond) if (!(cond)) { __builtin_unreachable(); }53#else54#define promise(cond)55#endif56#else // Assume GCC57#define promise(cond) if (!(cond)) { __builtin_unreachable(); }58#endif59#else60#define promise(cond) assert(cond)61#endif6263/* ============================================================================64Constants65============================================================================ */66#if !defined(ASTCENC_BLOCK_MAX_TEXELS)67#define ASTCENC_BLOCK_MAX_TEXELS 216 // A 3D 6x6x6 block68#endif6970/** @brief The maximum number of texels a block can support (6x6x6 block). */71static constexpr unsigned int BLOCK_MAX_TEXELS { ASTCENC_BLOCK_MAX_TEXELS };7273/** @brief The maximum number of components a block can support. */74static constexpr unsigned int BLOCK_MAX_COMPONENTS { 4 };7576/** @brief The maximum number of partitions a block can support. */77static constexpr unsigned int BLOCK_MAX_PARTITIONS { 4 };7879/** @brief The number of partitionings, per partition count, suported by the ASTC format. */80static constexpr unsigned int BLOCK_MAX_PARTITIONINGS { 1024 };8182/** @brief The maximum number of texels used during partition selection for texel clustering. */83static constexpr uint8_t BLOCK_MAX_KMEANS_TEXELS { 64 };8485/** @brief The maximum number of weights a block can support. */86static constexpr unsigned int BLOCK_MAX_WEIGHTS { 64 };8788/** @brief The maximum number of weights a block can support per plane in 2 plane mode. */89static constexpr unsigned int BLOCK_MAX_WEIGHTS_2PLANE { BLOCK_MAX_WEIGHTS / 2 };9091/** @brief The minimum number of weight bits a candidate encoding must encode. */92static constexpr unsigned int BLOCK_MIN_WEIGHT_BITS { 24 };9394/** @brief The maximum number of weight bits a candidate encoding can encode. */95static constexpr unsigned int BLOCK_MAX_WEIGHT_BITS { 96 };9697/** @brief The index indicating a bad (unused) block mode in the remap array. */98static constexpr uint16_t BLOCK_BAD_BLOCK_MODE { 0xFFFFu };99100/** @brief The index indicating a bad (unused) partitioning in the remap array. */101static constexpr uint16_t BLOCK_BAD_PARTITIONING { 0xFFFFu };102103/** @brief The number of partition index bits supported by the ASTC format . */104static constexpr unsigned int PARTITION_INDEX_BITS { 10 };105106/** @brief The offset of the plane 2 weights in shared weight arrays. */107static constexpr unsigned int WEIGHTS_PLANE2_OFFSET { BLOCK_MAX_WEIGHTS_2PLANE };108109/** @brief The sum of quantized weights for one texel. */110static constexpr float WEIGHTS_TEXEL_SUM { 16.0f };111112/** @brief The number of block modes supported by the ASTC format. */113static constexpr unsigned int WEIGHTS_MAX_BLOCK_MODES { 2048 };114115/** @brief The number of weight grid decimation modes supported by the ASTC format. */116static constexpr unsigned int WEIGHTS_MAX_DECIMATION_MODES { 87 };117118/** @brief The high default error used to initialize error trackers. */119static constexpr float ERROR_CALC_DEFAULT { 1e30f };120121/**122* @brief The minimum tuning setting threshold for the one partition fast path.123*/124static constexpr float TUNE_MIN_SEARCH_MODE0 { 0.85f };125126/**127* @brief The maximum number of candidate encodings tested for each encoding mode.128*129* This can be dynamically reduced by the compression quality preset.130*/131static constexpr unsigned int TUNE_MAX_TRIAL_CANDIDATES { 8 };132133/**134* @brief The maximum number of candidate partitionings tested for each encoding mode.135*136* This can be dynamically reduced by the compression quality preset.137*/138static constexpr unsigned int TUNE_MAX_PARTITIONING_CANDIDATES { 8 };139140/**141* @brief The maximum quant level using full angular endpoint search method.142*143* The angular endpoint search is used to find the min/max weight that should144* be used for a given quantization level. It is effective but expensive, so145* we only use it where it has the most value - low quant levels with wide146* spacing. It is used below TUNE_MAX_ANGULAR_QUANT (inclusive). Above this we147* assume the min weight is 0.0f, and the max weight is 1.0f.148*149* Note the angular algorithm is vectorized, and using QUANT_12 exactly fills150* one 8-wide vector. Decreasing by one doesn't buy much performance, and151* increasing by one is disproportionately expensive.152*/153static constexpr unsigned int TUNE_MAX_ANGULAR_QUANT { 7 }; /* QUANT_12 */154155static_assert((BLOCK_MAX_TEXELS % ASTCENC_SIMD_WIDTH) == 0,156"BLOCK_MAX_TEXELS must be multiple of ASTCENC_SIMD_WIDTH");157158static_assert(BLOCK_MAX_TEXELS <= 216,159"BLOCK_MAX_TEXELS must not be greater than 216");160161static_assert((BLOCK_MAX_WEIGHTS % ASTCENC_SIMD_WIDTH) == 0,162"BLOCK_MAX_WEIGHTS must be multiple of ASTCENC_SIMD_WIDTH");163164static_assert((WEIGHTS_MAX_BLOCK_MODES % ASTCENC_SIMD_WIDTH) == 0,165"WEIGHTS_MAX_BLOCK_MODES must be multiple of ASTCENC_SIMD_WIDTH");166167168/* ============================================================================169Commonly used data structures170============================================================================ */171172/**173* @brief The ASTC endpoint formats.174*175* Note, the values here are used directly in the encoding in the format so do not rearrange.176*/177enum endpoint_formats178{179FMT_LUMINANCE = 0,180FMT_LUMINANCE_DELTA = 1,181FMT_HDR_LUMINANCE_LARGE_RANGE = 2,182FMT_HDR_LUMINANCE_SMALL_RANGE = 3,183FMT_LUMINANCE_ALPHA = 4,184FMT_LUMINANCE_ALPHA_DELTA = 5,185FMT_RGB_SCALE = 6,186FMT_HDR_RGB_SCALE = 7,187FMT_RGB = 8,188FMT_RGB_DELTA = 9,189FMT_RGB_SCALE_ALPHA = 10,190FMT_HDR_RGB = 11,191FMT_RGBA = 12,192FMT_RGBA_DELTA = 13,193FMT_HDR_RGB_LDR_ALPHA = 14,194FMT_HDR_RGBA = 15195};196197/**198* @brief The ASTC quantization methods.199*200* Note, the values here are used directly in the encoding in the format so do not rearrange.201*/202enum quant_method203{204QUANT_2 = 0,205QUANT_3 = 1,206QUANT_4 = 2,207QUANT_5 = 3,208QUANT_6 = 4,209QUANT_8 = 5,210QUANT_10 = 6,211QUANT_12 = 7,212QUANT_16 = 8,213QUANT_20 = 9,214QUANT_24 = 10,215QUANT_32 = 11,216QUANT_40 = 12,217QUANT_48 = 13,218QUANT_64 = 14,219QUANT_80 = 15,220QUANT_96 = 16,221QUANT_128 = 17,222QUANT_160 = 18,223QUANT_192 = 19,224QUANT_256 = 20225};226227/**228* @brief The number of levels use by an ASTC quantization method.229*230* @param method The quantization method231*232* @return The number of levels used by @c method.233*/234static inline unsigned int get_quant_level(quant_method method)235{236switch (method)237{238case QUANT_2: return 2;239case QUANT_3: return 3;240case QUANT_4: return 4;241case QUANT_5: return 5;242case QUANT_6: return 6;243case QUANT_8: return 8;244case QUANT_10: return 10;245case QUANT_12: return 12;246case QUANT_16: return 16;247case QUANT_20: return 20;248case QUANT_24: return 24;249case QUANT_32: return 32;250case QUANT_40: return 40;251case QUANT_48: return 48;252case QUANT_64: return 64;253case QUANT_80: return 80;254case QUANT_96: return 96;255case QUANT_128: return 128;256case QUANT_160: return 160;257case QUANT_192: return 192;258case QUANT_256: return 256;259}260261// Unreachable - the enum is fully described262return 0;263}264265/**266* @brief Computed metrics about a partition in a block.267*/268struct partition_metrics269{270/** @brief The error-weighted average color in the partition. */271vfloat4 avg;272273/** @brief The dominant error-weighted direction in the partition. */274vfloat4 dir;275};276277/**278* @brief Computed lines for a a three component analysis.279*/280struct partition_lines3281{282/** @brief Line for uncorrelated chroma. */283line3 uncor_line;284285/** @brief Line for correlated chroma, passing though the origin. */286line3 samec_line;287288/** @brief Post-processed line for uncorrelated chroma. */289processed_line3 uncor_pline;290291/** @brief Post-processed line for correlated chroma, passing though the origin. */292processed_line3 samec_pline;293294/**295* @brief The length of the line for uncorrelated chroma.296*297* This is used for both the uncorrelated and same chroma lines - they are normally very similar298* and only used for the relative ranking of partitionings against one another.299*/300float line_length;301};302303/**304* @brief The partition information for a single partition.305*306* ASTC has a total of 1024 candidate partitions for each of 2/3/4 partition counts, although this307* 1024 includes seeds that generate duplicates of other seeds and seeds that generate completely308* empty partitions. These are both valid encodings, but astcenc will skip both during compression309* as they are not useful.310*/311struct partition_info312{313/** @brief The number of partitions in this partitioning. */314uint16_t partition_count;315316/** @brief The index (seed) of this partitioning. */317uint16_t partition_index;318319/**320* @brief The number of texels in each partition.321*322* Note that some seeds result in zero texels assigned to a partition. These are valid, but are323* skipped by this compressor as there is no point spending bits encoding an unused endpoints.324*/325uint8_t partition_texel_count[BLOCK_MAX_PARTITIONS];326327/** @brief The partition of each texel in the block. */328ASTCENC_ALIGNAS uint8_t partition_of_texel[BLOCK_MAX_TEXELS];329330/** @brief The list of texels in each partition. */331ASTCENC_ALIGNAS uint8_t texels_of_partition[BLOCK_MAX_PARTITIONS][BLOCK_MAX_TEXELS];332};333334/**335* @brief The weight grid information for a single decimation pattern.336*337* ASTC can store one weight per texel, but is also capable of storing lower resolution weight grids338* that are interpolated during decompression to assign a with to a texel. Storing fewer weights339* can free up a substantial amount of bits that we can then spend on more useful things, such as340* more accurate endpoints and weights, or additional partitions.341*342* This data structure is used to store information about a single weight grid decimation pattern,343* for a single block size.344*/345struct decimation_info346{347/** @brief The total number of texels in the block. */348uint8_t texel_count;349350/** @brief The maximum number of stored weights that contribute to each texel, between 1 and 4. */351uint8_t max_texel_weight_count;352353/** @brief The total number of weights stored. */354uint8_t weight_count;355356/** @brief The number of stored weights in the X dimension. */357uint8_t weight_x;358359/** @brief The number of stored weights in the Y dimension. */360uint8_t weight_y;361362/** @brief The number of stored weights in the Z dimension. */363uint8_t weight_z;364365/**366* @brief The number of weights that contribute to each texel.367* Value is between 1 and 4.368*/369ASTCENC_ALIGNAS uint8_t texel_weight_count[BLOCK_MAX_TEXELS];370371/**372* @brief The weight index of the N weights that are interpolated for each texel.373* Stored transposed to improve vectorization.374*/375ASTCENC_ALIGNAS uint8_t texel_weights_tr[4][BLOCK_MAX_TEXELS];376377/**378* @brief The bilinear contribution of the N weights that are interpolated for each texel.379* Value is between 0 and 16, stored transposed to improve vectorization.380*/381ASTCENC_ALIGNAS uint8_t texel_weight_contribs_int_tr[4][BLOCK_MAX_TEXELS];382383/**384* @brief The bilinear contribution of the N weights that are interpolated for each texel.385* Value is between 0 and 1, stored transposed to improve vectorization.386*/387ASTCENC_ALIGNAS float texel_weight_contribs_float_tr[4][BLOCK_MAX_TEXELS];388389/** @brief The number of texels that each stored weight contributes to. */390ASTCENC_ALIGNAS uint8_t weight_texel_count[BLOCK_MAX_WEIGHTS];391392/**393* @brief The list of texels that use a specific weight index.394* Stored transposed to improve vectorization.395*/396ASTCENC_ALIGNAS uint8_t weight_texels_tr[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];397398/**399* @brief The bilinear contribution to the N texels that use each weight.400* Value is between 0 and 1, stored transposed to improve vectorization.401*/402ASTCENC_ALIGNAS float weights_texel_contribs_tr[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];403404/**405* @brief The bilinear contribution to the Nth texel that uses each weight.406* Value is between 0 and 1, stored transposed to improve vectorization.407*/408float texel_contrib_for_weight[BLOCK_MAX_TEXELS][BLOCK_MAX_WEIGHTS];409};410411/**412* @brief Metadata for single block mode for a specific block size.413*/414struct block_mode415{416/** @brief The block mode index in the ASTC encoded form. */417uint16_t mode_index;418419/** @brief The decimation mode index in the compressor reindexed list. */420uint8_t decimation_mode;421422/** @brief The weight quantization used by this block mode. */423uint8_t quant_mode;424425/** @brief The weight quantization used by this block mode. */426uint8_t weight_bits;427428/** @brief Is a dual weight plane used by this block mode? */429uint8_t is_dual_plane : 1;430431/**432* @brief Get the weight quantization used by this block mode.433*434* @return The quantization level.435*/436inline quant_method get_weight_quant_mode() const437{438return static_cast<quant_method>(this->quant_mode);439}440};441442/**443* @brief Metadata for single decimation mode for a specific block size.444*/445struct decimation_mode446{447/** @brief The max weight precision for 1 plane, or -1 if not supported. */448int8_t maxprec_1plane;449450/** @brief The max weight precision for 2 planes, or -1 if not supported. */451int8_t maxprec_2planes;452453/**454* @brief Bitvector indicating weight quant modes used by active 1 plane block modes.455*456* Bit 0 = QUANT_2, Bit 1 = QUANT_3, etc.457*/458uint16_t refprec_1plane;459460/**461* @brief Bitvector indicating weight quant methods used by active 2 plane block modes.462*463* Bit 0 = QUANT_2, Bit 1 = QUANT_3, etc.464*/465uint16_t refprec_2planes;466467/**468* @brief Set a 1 plane weight quant as active.469*470* @param weight_quant The quant method to set.471*/472void set_ref_1plane(quant_method weight_quant)473{474refprec_1plane |= (1 << weight_quant);475}476477/**478* @brief Test if this mode is active below a given 1 plane weight quant (inclusive).479*480* @param max_weight_quant The max quant method to test.481*/482bool is_ref_1plane(quant_method max_weight_quant) const483{484uint16_t mask = static_cast<uint16_t>((1 << (max_weight_quant + 1)) - 1);485return (refprec_1plane & mask) != 0;486}487488/**489* @brief Set a 2 plane weight quant as active.490*491* @param weight_quant The quant method to set.492*/493void set_ref_2plane(quant_method weight_quant)494{495refprec_2planes |= static_cast<uint16_t>(1 << weight_quant);496}497498/**499* @brief Test if this mode is active below a given 2 plane weight quant (inclusive).500*501* @param max_weight_quant The max quant method to test.502*/503bool is_ref_2plane(quant_method max_weight_quant) const504{505uint16_t mask = static_cast<uint16_t>((1 << (max_weight_quant + 1)) - 1);506return (refprec_2planes & mask) != 0;507}508};509510/**511* @brief Data tables for a single block size.512*513* The decimation tables store the information to apply weight grid dimension reductions. We only514* store the decimation modes that are actually needed by the current context; many of the possible515* modes will be unused (too many weights for the current block size or disabled by heuristics). The516* actual number of weights stored is @c decimation_mode_count, and the @c decimation_modes and517* @c decimation_tables arrays store the active modes contiguously at the start of the array. These518* entries are not stored in any particular order.519*520* The block mode tables store the unpacked block mode settings. Block modes are stored in the521* compressed block as an 11 bit field, but for any given block size and set of compressor522* heuristics, only a subset of the block modes will be used. The actual number of block modes523* stored is indicated in @c block_mode_count, and the @c block_modes array store the active modes524* contiguously at the start of the array. These entries are stored in incrementing "packed" value525* order, which doesn't mean much once unpacked. To allow decompressors to reference the packed data526* efficiently the @c block_mode_packed_index array stores the mapping between physical ID and the527* actual remapped array index.528*/529struct block_size_descriptor530{531/** @brief The block X dimension, in texels. */532uint8_t xdim;533534/** @brief The block Y dimension, in texels. */535uint8_t ydim;536537/** @brief The block Z dimension, in texels. */538uint8_t zdim;539540/** @brief The block total texel count. */541uint8_t texel_count;542543/**544* @brief The number of stored decimation modes which are "always" modes.545*546* Always modes are stored at the start of the decimation_modes list.547*/548unsigned int decimation_mode_count_always;549550/** @brief The number of stored decimation modes for selected encodings. */551unsigned int decimation_mode_count_selected;552553/** @brief The number of stored decimation modes for any encoding. */554unsigned int decimation_mode_count_all;555556/**557* @brief The number of stored block modes which are "always" modes.558*559* Always modes are stored at the start of the block_modes list.560*/561unsigned int block_mode_count_1plane_always;562563/** @brief The number of stored block modes for active 1 plane encodings. */564unsigned int block_mode_count_1plane_selected;565566/** @brief The number of stored block modes for active 1 and 2 plane encodings. */567unsigned int block_mode_count_1plane_2plane_selected;568569/** @brief The number of stored block modes for any encoding. */570unsigned int block_mode_count_all;571572/** @brief The number of selected partitionings for 1/2/3/4 partitionings. */573unsigned int partitioning_count_selected[BLOCK_MAX_PARTITIONS];574575/** @brief The number of partitionings for 1/2/3/4 partitionings. */576unsigned int partitioning_count_all[BLOCK_MAX_PARTITIONS];577578/** @brief The active decimation modes, stored in low indices. */579decimation_mode decimation_modes[WEIGHTS_MAX_DECIMATION_MODES];580581/** @brief The active decimation tables, stored in low indices. */582ASTCENC_ALIGNAS decimation_info decimation_tables[WEIGHTS_MAX_DECIMATION_MODES];583584/** @brief The packed block mode array index, or @c BLOCK_BAD_BLOCK_MODE if not active. */585uint16_t block_mode_packed_index[WEIGHTS_MAX_BLOCK_MODES];586587/** @brief The active block modes, stored in low indices. */588block_mode block_modes[WEIGHTS_MAX_BLOCK_MODES];589590/** @brief The active partition tables, stored in low indices per-count. */591partition_info partitionings[(3 * BLOCK_MAX_PARTITIONINGS) + 1];592593/**594* @brief The packed partition table array index, or @c BLOCK_BAD_PARTITIONING if not active.595*596* Indexed by partition_count - 2, containing 2, 3 and 4 partitions.597*/598uint16_t partitioning_packed_index[3][BLOCK_MAX_PARTITIONINGS];599600/** @brief The active texels for k-means partition selection. */601uint8_t kmeans_texels[BLOCK_MAX_KMEANS_TEXELS];602603/**604* @brief The canonical 2-partition coverage pattern used during block partition search.605*606* Indexed by remapped index, not physical index.607*/608uint64_t coverage_bitmaps_2[BLOCK_MAX_PARTITIONINGS][2];609610/**611* @brief The canonical 3-partition coverage pattern used during block partition search.612*613* Indexed by remapped index, not physical index.614*/615uint64_t coverage_bitmaps_3[BLOCK_MAX_PARTITIONINGS][3];616617/**618* @brief The canonical 4-partition coverage pattern used during block partition search.619*620* Indexed by remapped index, not physical index.621*/622uint64_t coverage_bitmaps_4[BLOCK_MAX_PARTITIONINGS][4];623624/**625* @brief Get the block mode structure for index @c block_mode.626*627* This function can only return block modes that are enabled by the current compressor config.628* Decompression from an arbitrary source should not use this without first checking that the629* packed block mode index is not @c BLOCK_BAD_BLOCK_MODE.630*631* @param block_mode The packed block mode index.632*633* @return The block mode structure.634*/635const block_mode& get_block_mode(unsigned int block_mode) const636{637unsigned int packed_index = this->block_mode_packed_index[block_mode];638assert(packed_index != BLOCK_BAD_BLOCK_MODE && packed_index < this->block_mode_count_all);639return this->block_modes[packed_index];640}641642/**643* @brief Get the decimation mode structure for index @c decimation_mode.644*645* This function can only return decimation modes that are enabled by the current compressor646* config. The mode array is stored packed, but this is only ever indexed by the packed index647* stored in the @c block_mode and never exists in an unpacked form.648*649* @param decimation_mode The packed decimation mode index.650*651* @return The decimation mode structure.652*/653const decimation_mode& get_decimation_mode(unsigned int decimation_mode) const654{655return this->decimation_modes[decimation_mode];656}657658/**659* @brief Get the decimation info structure for index @c decimation_mode.660*661* This function can only return decimation modes that are enabled by the current compressor662* config. The mode array is stored packed, but this is only ever indexed by the packed index663* stored in the @c block_mode and never exists in an unpacked form.664*665* @param decimation_mode The packed decimation mode index.666*667* @return The decimation info structure.668*/669const decimation_info& get_decimation_info(unsigned int decimation_mode) const670{671return this->decimation_tables[decimation_mode];672}673674/**675* @brief Get the partition info table for a given partition count.676*677* @param partition_count The number of partitions we want the table for.678*679* @return The pointer to the table of 1024 entries (for 2/3/4 parts) or 1 entry (for 1 part).680*/681const partition_info* get_partition_table(unsigned int partition_count) const682{683if (partition_count == 1)684{685partition_count = 5;686}687unsigned int index = (partition_count - 2) * BLOCK_MAX_PARTITIONINGS;688return this->partitionings + index;689}690691/**692* @brief Get the partition info structure for a given partition count and seed.693*694* @param partition_count The number of partitions we want the info for.695* @param index The partition seed (between 0 and 1023).696*697* @return The partition info structure.698*/699const partition_info& get_partition_info(unsigned int partition_count, unsigned int index) const700{701unsigned int packed_index = 0;702if (partition_count >= 2)703{704packed_index = this->partitioning_packed_index[partition_count - 2][index];705}706707assert(packed_index != BLOCK_BAD_PARTITIONING && packed_index < this->partitioning_count_all[partition_count - 1]);708auto& result = get_partition_table(partition_count)[packed_index];709assert(index == result.partition_index);710return result;711}712713/**714* @brief Get the partition info structure for a given partition count and seed.715*716* @param partition_count The number of partitions we want the info for.717* @param packed_index The raw array offset.718*719* @return The partition info structure.720*/721const partition_info& get_raw_partition_info(unsigned int partition_count, unsigned int packed_index) const722{723assert(packed_index != BLOCK_BAD_PARTITIONING && packed_index < this->partitioning_count_all[partition_count - 1]);724auto& result = get_partition_table(partition_count)[packed_index];725return result;726}727};728729/**730* @brief The image data for a single block.731*732* The @c data_[rgba] fields store the image data in an encoded SoA float form designed for easy733* vectorization. Input data is converted to float and stored as values between 0 and 65535. LDR734* data is stored as direct UNORM data, HDR data is stored as LNS data. They are allocated SIMD735* elements over-size to allow vectorized stores of unaligned and partial SIMD lanes (e.g. in a736* 6x6x6 block the final row write will read elements 210-217 (vec8) or 214-217 (vec4), which is737* two elements above the last real data element). The overspill values are never written to memory,738* and would be benign, but the padding avoids hitting undefined behavior.739*740* The @c rgb_lns and @c alpha_lns fields that assigned a per-texel use of HDR are only used during741* decompression. The current compressor will always use HDR endpoint formats when in HDR mode.742*/743struct image_block744{745/** @brief The input (compress) or output (decompress) data for the red color component. */746ASTCENC_ALIGNAS float data_r[BLOCK_MAX_TEXELS + ASTCENC_SIMD_WIDTH - 1];747748/** @brief The input (compress) or output (decompress) data for the green color component. */749ASTCENC_ALIGNAS float data_g[BLOCK_MAX_TEXELS + ASTCENC_SIMD_WIDTH - 1];750751/** @brief The input (compress) or output (decompress) data for the blue color component. */752ASTCENC_ALIGNAS float data_b[BLOCK_MAX_TEXELS + ASTCENC_SIMD_WIDTH - 1];753754/** @brief The input (compress) or output (decompress) data for the alpha color component. */755ASTCENC_ALIGNAS float data_a[BLOCK_MAX_TEXELS + ASTCENC_SIMD_WIDTH - 1];756757/** @brief The number of texels in the block. */758uint8_t texel_count;759760/** @brief The original data for texel 0 for constant color block encoding. */761vfloat4 origin_texel;762763/** @brief The min component value of all texels in the block. */764vfloat4 data_min;765766/** @brief The mean component value of all texels in the block. */767vfloat4 data_mean;768769/** @brief The max component value of all texels in the block. */770vfloat4 data_max;771772/** @brief The relative error significance of the color channels. */773vfloat4 channel_weight;774775/** @brief Is this grayscale block where R == G == B for all texels? */776bool grayscale;777778/** @brief Is the eventual decode using decode_unorm8 rounding? */779bool decode_unorm8;780781/** @brief Set to 1 if a texel is using HDR RGB endpoints (decompression only). */782uint8_t rgb_lns[BLOCK_MAX_TEXELS];783784/** @brief Set to 1 if a texel is using HDR alpha endpoints (decompression only). */785uint8_t alpha_lns[BLOCK_MAX_TEXELS];786787/** @brief The X position of this block in the input or output image. */788unsigned int xpos;789790/** @brief The Y position of this block in the input or output image. */791unsigned int ypos;792793/** @brief The Z position of this block in the input or output image. */794unsigned int zpos;795796/**797* @brief Get an RGBA texel value from the data.798*799* @param index The texel index.800*801* @return The texel in RGBA component ordering.802*/803inline vfloat4 texel(unsigned int index) const804{805return vfloat4(data_r[index],806data_g[index],807data_b[index],808data_a[index]);809}810811/**812* @brief Get an RGB texel value from the data.813*814* @param index The texel index.815*816* @return The texel in RGB0 component ordering.817*/818inline vfloat4 texel3(unsigned int index) const819{820return vfloat3(data_r[index],821data_g[index],822data_b[index]);823}824825/**826* @brief Get the default alpha value for endpoints that don't store it.827*828* The default depends on whether the alpha endpoint is LDR or HDR.829*830* @return The alpha value in the scaled range used by the compressor.831*/832inline float get_default_alpha() const833{834return this->alpha_lns[0] ? static_cast<float>(0x7800) : static_cast<float>(0xFFFF);835}836837/**838* @brief Test if a single color channel is constant across the block.839*840* Constant color channels are easier to compress as interpolating between two identical colors841* always returns the same value, irrespective of the weight used. They therefore can be ignored842* for the purposes of weight selection and use of a second weight plane.843*844* @return @c true if the channel is constant across the block, @c false otherwise.845*/846inline bool is_constant_channel(int channel) const847{848vmask4 lane_mask = vint4::lane_id() == vint4(channel);849vmask4 color_mask = this->data_min == this->data_max;850return any(lane_mask & color_mask);851}852853/**854* @brief Test if this block is a luminance block with constant 1.0 alpha.855*856* @return @c true if the block is a luminance block , @c false otherwise.857*/858inline bool is_luminance() const859{860float default_alpha = this->get_default_alpha();861bool alpha1 = (this->data_min.lane<3>() == default_alpha) &&862(this->data_max.lane<3>() == default_alpha);863return this->grayscale && alpha1;864}865866/**867* @brief Test if this block is a luminance block with variable alpha.868*869* @return @c true if the block is a luminance + alpha block , @c false otherwise.870*/871inline bool is_luminancealpha() const872{873float default_alpha = this->get_default_alpha();874bool alpha1 = (this->data_min.lane<3>() == default_alpha) &&875(this->data_max.lane<3>() == default_alpha);876return this->grayscale && !alpha1;877}878};879880/**881* @brief Data structure storing the color endpoints for a block.882*/883struct endpoints884{885/** @brief The number of partition endpoints stored. */886unsigned int partition_count;887888/** @brief The colors for endpoint 0. */889vfloat4 endpt0[BLOCK_MAX_PARTITIONS];890891/** @brief The colors for endpoint 1. */892vfloat4 endpt1[BLOCK_MAX_PARTITIONS];893};894895/**896* @brief Data structure storing the color endpoints and weights.897*/898struct endpoints_and_weights899{900/** @brief True if all active values in weight_error_scale are the same. */901bool is_constant_weight_error_scale;902903/** @brief The color endpoints. */904endpoints ep;905906/** @brief The ideal weight for each texel; may be undecimated or decimated. */907ASTCENC_ALIGNAS float weights[BLOCK_MAX_TEXELS];908909/** @brief The ideal weight error scaling for each texel; may be undecimated or decimated. */910ASTCENC_ALIGNAS float weight_error_scale[BLOCK_MAX_TEXELS];911};912913/**914* @brief Utility storing estimated errors from choosing particular endpoint encodings.915*/916struct encoding_choice_errors917{918/** @brief Error of using LDR RGB-scale instead of complete endpoints. */919float rgb_scale_error;920921/** @brief Error of using HDR RGB-scale instead of complete endpoints. */922float rgb_luma_error;923924/** @brief Error of using luminance instead of RGB. */925float luminance_error;926927/** @brief Error of discarding alpha and using a constant 1.0 alpha. */928float alpha_drop_error;929930/** @brief Can we use delta offset encoding? */931bool can_offset_encode;932933/** @brief Can we use blue contraction encoding? */934bool can_blue_contract;935};936937/**938* @brief Preallocated working buffers, allocated per thread during context creation.939*/940struct ASTCENC_ALIGNAS compression_working_buffers941{942/** @brief Ideal endpoints and weights for plane 1. */943endpoints_and_weights ei1;944945/** @brief Ideal endpoints and weights for plane 2. */946endpoints_and_weights ei2;947948/**949* @brief Decimated ideal weight values in the ~0-1 range.950*951* Note that values can be slightly below zero or higher than one due to952* endpoint extents being inside the ideal color representation.953*954* For two planes, second plane starts at @c WEIGHTS_PLANE2_OFFSET offsets.955*/956ASTCENC_ALIGNAS float dec_weights_ideal[WEIGHTS_MAX_DECIMATION_MODES * BLOCK_MAX_WEIGHTS];957958/**959* @brief Decimated quantized weight values in the unquantized 0-64 range.960*961* For two planes, second plane starts at @c WEIGHTS_PLANE2_OFFSET offsets.962*/963ASTCENC_ALIGNAS uint8_t dec_weights_uquant[WEIGHTS_MAX_BLOCK_MODES * BLOCK_MAX_WEIGHTS];964965/** @brief Error of the best encoding combination for each block mode. */966ASTCENC_ALIGNAS float errors_of_best_combination[WEIGHTS_MAX_BLOCK_MODES];967968/** @brief The best color quant for each block mode. */969uint8_t best_quant_levels[WEIGHTS_MAX_BLOCK_MODES];970971/** @brief The best color quant for each block mode if modes are the same and we have spare bits. */972uint8_t best_quant_levels_mod[WEIGHTS_MAX_BLOCK_MODES];973974/** @brief The best endpoint format for each partition. */975uint8_t best_ep_formats[WEIGHTS_MAX_BLOCK_MODES][BLOCK_MAX_PARTITIONS];976977/** @brief The total bit storage needed for quantized weights for each block mode. */978int8_t qwt_bitcounts[WEIGHTS_MAX_BLOCK_MODES];979980/** @brief The cumulative error for quantized weights for each block mode. */981float qwt_errors[WEIGHTS_MAX_BLOCK_MODES];982983/** @brief The low weight value in plane 1 for each block mode. */984float weight_low_value1[WEIGHTS_MAX_BLOCK_MODES];985986/** @brief The high weight value in plane 1 for each block mode. */987float weight_high_value1[WEIGHTS_MAX_BLOCK_MODES];988989/** @brief The low weight value in plane 1 for each quant level and decimation mode. */990float weight_low_values1[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];991992/** @brief The high weight value in plane 1 for each quant level and decimation mode. */993float weight_high_values1[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];994995/** @brief The low weight value in plane 2 for each block mode. */996float weight_low_value2[WEIGHTS_MAX_BLOCK_MODES];997998/** @brief The high weight value in plane 2 for each block mode. */999float weight_high_value2[WEIGHTS_MAX_BLOCK_MODES];10001001/** @brief The low weight value in plane 2 for each quant level and decimation mode. */1002float weight_low_values2[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];10031004/** @brief The high weight value in plane 2 for each quant level and decimation mode. */1005float weight_high_values2[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1];1006};10071008struct dt_init_working_buffers1009{1010uint8_t weight_count_of_texel[BLOCK_MAX_TEXELS];1011uint8_t grid_weights_of_texel[BLOCK_MAX_TEXELS][4];1012uint8_t weights_of_texel[BLOCK_MAX_TEXELS][4];10131014uint8_t texel_count_of_weight[BLOCK_MAX_WEIGHTS];1015uint8_t texels_of_weight[BLOCK_MAX_WEIGHTS][BLOCK_MAX_TEXELS];1016uint8_t texel_weights_of_weight[BLOCK_MAX_WEIGHTS][BLOCK_MAX_TEXELS];1017};10181019/**1020* @brief Weight quantization transfer table.1021*1022* ASTC can store texel weights at many quantization levels, so for performance we store essential1023* information about each level as a precomputed data structure. Unquantized weights are integers1024* or floats in the range [0, 64].1025*1026* This structure provides a table, used to estimate the closest quantized weight for a given1027* floating-point weight. For each quantized weight, the corresponding unquantized values. For each1028* quantized weight, a previous-value and a next-value.1029*/1030struct quant_and_transfer_table1031{1032/** @brief The unscrambled unquantized value. */1033uint8_t quant_to_unquant[32];10341035/** @brief The scrambling order: scrambled_quant = map[unscrambled_quant]. */1036uint8_t scramble_map[32];10371038/** @brief The unscrambling order: unscrambled_unquant = map[scrambled_quant]. */1039uint8_t unscramble_and_unquant_map[32];10401041/**1042* @brief A table of previous-and-next weights, indexed by the current unquantized value.1043* * bits 7:0 = previous-index, unquantized1044* * bits 15:8 = next-index, unquantized1045*/1046uint16_t prev_next_values[65];1047};10481049/** @brief The precomputed quant and transfer table. */1050extern const quant_and_transfer_table quant_and_xfer_tables[12];10511052/** @brief The block is an error block, and will return error color or NaN. */1053static constexpr uint8_t SYM_BTYPE_ERROR { 0 };10541055/** @brief The block is a constant color block using FP16 colors. */1056static constexpr uint8_t SYM_BTYPE_CONST_F16 { 1 };10571058/** @brief The block is a constant color block using UNORM16 colors. */1059static constexpr uint8_t SYM_BTYPE_CONST_U16 { 2 };10601061/** @brief The block is a normal non-constant color block. */1062static constexpr uint8_t SYM_BTYPE_NONCONST { 3 };10631064/**1065* @brief A symbolic representation of a compressed block.1066*1067* The symbolic representation stores the unpacked content of a single1068* physical compressed block, in a form which is much easier to access for1069* the rest of the compressor code.1070*/1071struct symbolic_compressed_block1072{1073/** @brief The block type, one of the @c SYM_BTYPE_* constants. */1074uint8_t block_type;10751076/** @brief The number of partitions; valid for @c NONCONST blocks. */1077uint8_t partition_count;10781079/** @brief Non-zero if the color formats matched; valid for @c NONCONST blocks. */1080uint8_t color_formats_matched;10811082/** @brief The plane 2 color component, or -1 if single plane; valid for @c NONCONST blocks. */1083int8_t plane2_component;10841085/** @brief The block mode; valid for @c NONCONST blocks. */1086uint16_t block_mode;10871088/** @brief The partition index; valid for @c NONCONST blocks if 2 or more partitions. */1089uint16_t partition_index;10901091/** @brief The endpoint color formats for each partition; valid for @c NONCONST blocks. */1092uint8_t color_formats[BLOCK_MAX_PARTITIONS];10931094/** @brief The endpoint color quant mode; valid for @c NONCONST blocks. */1095quant_method quant_mode;10961097/** @brief The error of the current encoding; valid for @c NONCONST blocks. */1098float errorval;10991100// We can't have both of these at the same time1101union {1102/** @brief The constant color; valid for @c CONST blocks. */1103int constant_color[BLOCK_MAX_COMPONENTS];11041105/** @brief The quantized endpoint color pairs; valid for @c NONCONST blocks. */1106uint8_t color_values[BLOCK_MAX_PARTITIONS][8];1107};11081109/** @brief The quantized and decimated weights.1110*1111* Weights are stored in the 0-64 unpacked range allowing them to be used1112* directly in encoding passes without per-use unpacking. Packing happens1113* when converting to/from the physical bitstream encoding.1114*1115* If dual plane, the second plane starts at @c weights[WEIGHTS_PLANE2_OFFSET].1116*/1117ASTCENC_ALIGNAS uint8_t weights[BLOCK_MAX_WEIGHTS];11181119/**1120* @brief Get the weight quantization used by this block mode.1121*1122* @return The quantization level.1123*/1124inline quant_method get_color_quant_mode() const1125{1126return this->quant_mode;1127}1128};11291130/**1131* @brief Parameter structure for @c compute_pixel_region_variance().1132*1133* This function takes a structure to avoid spilling arguments to the stack on every function1134* invocation, as there are a lot of parameters.1135*/1136struct pixel_region_args1137{1138/** @brief The image to analyze. */1139const astcenc_image* img;11401141/** @brief The component swizzle pattern. */1142astcenc_swizzle swz;11431144/** @brief Should the algorithm bother with Z axis processing? */1145bool have_z;11461147/** @brief The kernel radius for alpha processing. */1148unsigned int alpha_kernel_radius;11491150/** @brief The X dimension of the working data to process. */1151unsigned int size_x;11521153/** @brief The Y dimension of the working data to process. */1154unsigned int size_y;11551156/** @brief The Z dimension of the working data to process. */1157unsigned int size_z;11581159/** @brief The X position of first src and dst data in the data set. */1160unsigned int offset_x;11611162/** @brief The Y position of first src and dst data in the data set. */1163unsigned int offset_y;11641165/** @brief The Z position of first src and dst data in the data set. */1166unsigned int offset_z;11671168/** @brief The working memory buffer. */1169vfloat4 *work_memory;1170};11711172/**1173* @brief Parameter structure for @c compute_averages_proc().1174*/1175struct avg_args1176{1177/** @brief The arguments for the nested variance computation. */1178pixel_region_args arg;11791180/** @brief The image X dimensions. */1181unsigned int img_size_x;11821183/** @brief The image Y dimensions. */1184unsigned int img_size_y;11851186/** @brief The image Z dimensions. */1187unsigned int img_size_z;11881189/** @brief The maximum working block dimensions in X and Y dimensions. */1190unsigned int blk_size_xy;11911192/** @brief The maximum working block dimensions in Z dimensions. */1193unsigned int blk_size_z;11941195/** @brief The working block memory size. */1196unsigned int work_memory_size;1197};11981199#if defined(ASTCENC_DIAGNOSTICS)1200/* See astcenc_diagnostic_trace header for details. */1201class TraceLog;1202#endif12031204/**1205* @brief The astcenc compression context.1206*/1207struct astcenc_contexti1208{1209/** @brief The configuration this context was created with. */1210astcenc_config config;12111212/** @brief The thread count supported by this context. */1213unsigned int thread_count;12141215/** @brief The block size descriptor this context was created with. */1216block_size_descriptor* bsd;12171218/*1219* Fields below here are not needed in a decompress-only build, but some remain as they are1220* small and it avoids littering the code with #ifdefs. The most significant contributors to1221* large structure size are omitted.1222*/12231224/** @brief The input image alpha channel averages table, may be @c nullptr if not needed. */1225float* input_alpha_averages;12261227/** @brief The scratch working buffers, one per thread (see @c thread_count). */1228compression_working_buffers* working_buffers;12291230#if !defined(ASTCENC_DECOMPRESS_ONLY)1231/** @brief The pixel region and variance worker arguments. */1232avg_args avg_preprocess_args;1233#endif12341235#if defined(ASTCENC_DIAGNOSTICS)1236/**1237* @brief The diagnostic trace logger.1238*1239* Note that this is a singleton, so can only be used in single threaded mode. It only exists1240* here so we have a reference to close the file at the end of the capture.1241*/1242TraceLog* trace_log;1243#endif1244};12451246/* ============================================================================1247Functionality for managing block sizes and partition tables.1248============================================================================ */12491250/**1251* @brief Populate the block size descriptor for the target block size.1252*1253* This will also initialize the partition table metadata, which is stored as part of the BSD1254* structure.1255*1256* @param x_texels The number of texels in the block X dimension.1257* @param y_texels The number of texels in the block Y dimension.1258* @param z_texels The number of texels in the block Z dimension.1259* @param can_omit_modes Can we discard modes and partitionings that astcenc won't use?1260* @param partition_count_cutoff The partition count cutoff to use, if we can omit partitionings.1261* @param mode_cutoff The block mode percentile cutoff [0-1].1262* @param[out] bsd The descriptor to initialize.1263*/1264void init_block_size_descriptor(1265unsigned int x_texels,1266unsigned int y_texels,1267unsigned int z_texels,1268bool can_omit_modes,1269unsigned int partition_count_cutoff,1270float mode_cutoff,1271block_size_descriptor& bsd);12721273/**1274* @brief Populate the partition tables for the target block size.1275*1276* Note the @c bsd descriptor must be initialized by calling @c init_block_size_descriptor() before1277* calling this function.1278*1279* @param[out] bsd The block size information structure to populate.1280* @param can_omit_partitionings True if we can we drop partitionings that astcenc won't use.1281* @param partition_count_cutoff The partition count cutoff to use, if we can omit partitionings.1282*/1283void init_partition_tables(1284block_size_descriptor& bsd,1285bool can_omit_partitionings,1286unsigned int partition_count_cutoff);12871288/**1289* @brief Get the percentile table for 2D block modes.1290*1291* This is an empirically determined prioritization of which block modes to use in the search in1292* terms of their centile (lower centiles = more useful).1293*1294* Returns a dynamically allocated array; caller must free with delete[].1295*1296* @param xdim The block x size.1297* @param ydim The block y size.1298*1299* @return The unpacked table.1300*/1301const float* get_2d_percentile_table(1302unsigned int xdim,1303unsigned int ydim);13041305/**1306* @brief Query if a 2D block size is legal.1307*1308* @return True if legal, false otherwise.1309*/1310bool is_legal_2d_block_size(1311unsigned int xdim,1312unsigned int ydim);13131314/**1315* @brief Query if a 3D block size is legal.1316*1317* @return True if legal, false otherwise.1318*/1319bool is_legal_3d_block_size(1320unsigned int xdim,1321unsigned int ydim,1322unsigned int zdim);13231324/* ============================================================================1325Functionality for managing BISE quantization and unquantization.1326============================================================================ */13271328/**1329* @brief The precomputed table for quantizing color values.1330*1331* Converts unquant value in 0-255 range into quant value in 0-255 range.1332* No BISE scrambling is applied at this stage.1333*1334* The BISE encoding results in ties where available quant<256> values are1335* equidistant the available quant<BISE> values. This table stores two values1336* for each input - one for use with a negative residual, and one for use with1337* a positive residual.1338*1339* Indexed by [quant_mode - 4][data_value * 2 + residual].1340*/1341extern const uint8_t color_unquant_to_uquant_tables[17][512];13421343/**1344* @brief The precomputed table for packing quantized color values.1345*1346* Converts quant value in 0-255 range into packed quant value in 0-N range,1347* with BISE scrambling applied.1348*1349* Indexed by [quant_mode - 4][data_value].1350*/1351extern const uint8_t color_uquant_to_scrambled_pquant_tables[17][256];13521353/**1354* @brief The precomputed table for unpacking color values.1355*1356* Converts quant value in 0-N range into unpacked value in 0-255 range,1357* with BISE unscrambling applied.1358*1359* Indexed by [quant_mode - 4][data_value].1360*/1361extern const uint8_t* color_scrambled_pquant_to_uquant_tables[17];13621363/**1364* @brief The precomputed quant mode storage table.1365*1366* Indexing by [integer_count/2][bits] gives us the quantization level for a given integer count and1367* number of compressed storage bits. Returns -1 for cases where the requested integer count cannot1368* ever fit in the supplied storage size.1369*/1370extern const int8_t quant_mode_table[10][128];13711372/**1373* @brief Encode a packed string using BISE.1374*1375* Note that BISE can return strings that are not a whole number of bytes in length, and ASTC can1376* start storing strings in a block at arbitrary bit offsets in the encoded data.1377*1378* @param quant_level The BISE alphabet size.1379* @param character_count The number of characters in the string.1380* @param input_data The unpacked string, one byte per character.1381* @param[in,out] output_data The output packed string.1382* @param bit_offset The starting offset in the output storage.1383*/1384void encode_ise(1385quant_method quant_level,1386unsigned int character_count,1387const uint8_t* input_data,1388uint8_t* output_data,1389unsigned int bit_offset);13901391/**1392* @brief Decode a packed string using BISE.1393*1394* Note that BISE input strings are not a whole number of bytes in length, and ASTC can start1395* strings at arbitrary bit offsets in the encoded data.1396*1397* @param quant_level The BISE alphabet size.1398* @param character_count The number of characters in the string.1399* @param input_data The packed string.1400* @param[in,out] output_data The output storage, one byte per character.1401* @param bit_offset The starting offset in the output storage.1402*/1403void decode_ise(1404quant_method quant_level,1405unsigned int character_count,1406const uint8_t* input_data,1407uint8_t* output_data,1408unsigned int bit_offset);14091410/**1411* @brief Return the number of bits needed to encode an ISE sequence.1412*1413* This implementation assumes that the @c quant level is untrusted, given it may come from random1414* data being decompressed, so we return an arbitrary unencodable size if that is the case.1415*1416* @param character_count The number of items in the sequence.1417* @param quant_level The desired quantization level.1418*1419* @return The number of bits needed to encode the BISE string.1420*/1421unsigned int get_ise_sequence_bitcount(1422unsigned int character_count,1423quant_method quant_level);14241425/* ============================================================================1426Functionality for managing color partitioning.1427============================================================================ */14281429/**1430* @brief Compute averages and dominant directions for each partition in a 2 component texture.1431*1432* @param pi The partition info for the current trial.1433* @param blk The image block color data to be compressed.1434* @param component1 The first component included in the analysis.1435* @param component2 The second component included in the analysis.1436* @param[out] pm The output partition metrics.1437* - Only pi.partition_count array entries actually get initialized.1438* - Direction vectors @c pm.dir are not normalized.1439*/1440void compute_avgs_and_dirs_2_comp(1441const partition_info& pi,1442const image_block& blk,1443unsigned int component1,1444unsigned int component2,1445partition_metrics pm[BLOCK_MAX_PARTITIONS]);14461447/**1448* @brief Compute averages and dominant directions for each partition in a 3 component texture.1449*1450* @param pi The partition info for the current trial.1451* @param blk The image block color data to be compressed.1452* @param omitted_component The component excluded from the analysis.1453* @param[out] pm The output partition metrics.1454* - Only pi.partition_count array entries actually get initialized.1455* - Direction vectors @c pm.dir are not normalized.1456*/1457void compute_avgs_and_dirs_3_comp(1458const partition_info& pi,1459const image_block& blk,1460unsigned int omitted_component,1461partition_metrics pm[BLOCK_MAX_PARTITIONS]);14621463/**1464* @brief Compute averages and dominant directions for each partition in a 3 component texture.1465*1466* This is a specialization of @c compute_avgs_and_dirs_3_comp where the omitted component is1467* always alpha, a common case during partition search.1468*1469* @param pi The partition info for the current trial.1470* @param blk The image block color data to be compressed.1471* @param[out] pm The output partition metrics.1472* - Only pi.partition_count array entries actually get initialized.1473* - Direction vectors @c pm.dir are not normalized.1474*/1475void compute_avgs_and_dirs_3_comp_rgb(1476const partition_info& pi,1477const image_block& blk,1478partition_metrics pm[BLOCK_MAX_PARTITIONS]);14791480/**1481* @brief Compute averages and dominant directions for each partition in a 4 component texture.1482*1483* @param pi The partition info for the current trial.1484* @param blk The image block color data to be compressed.1485* @param[out] pm The output partition metrics.1486* - Only pi.partition_count array entries actually get initialized.1487* - Direction vectors @c pm.dir are not normalized.1488*/1489void compute_avgs_and_dirs_4_comp(1490const partition_info& pi,1491const image_block& blk,1492partition_metrics pm[BLOCK_MAX_PARTITIONS]);14931494/**1495* @brief Compute the RGB error for uncorrelated and same chroma projections.1496*1497* The output of compute averages and dirs is post processed to define two lines, both of which go1498* through the mean-color-value. One line has a direction defined by the dominant direction; this1499* is used to assess the error from using an uncorrelated color representation. The other line goes1500* through (0,0,0) and is used to assess the error from using an RGBS color representation.1501*1502* This function computes the squared error when using these two representations.1503*1504* @param pi The partition info for the current trial.1505* @param blk The image block color data to be compressed.1506* @param[in,out] plines Processed line inputs, and line length outputs.1507* @param[out] uncor_error The cumulative error for using the uncorrelated line.1508* @param[out] samec_error The cumulative error for using the same chroma line.1509*/1510void compute_error_squared_rgb(1511const partition_info& pi,1512const image_block& blk,1513partition_lines3 plines[BLOCK_MAX_PARTITIONS],1514float& uncor_error,1515float& samec_error);15161517/**1518* @brief Compute the RGBA error for uncorrelated and same chroma projections.1519*1520* The output of compute averages and dirs is post processed to define two lines, both of which go1521* through the mean-color-value. One line has a direction defined by the dominant direction; this1522* is used to assess the error from using an uncorrelated color representation. The other line goes1523* through (0,0,0,1) and is used to assess the error from using an RGBS color representation.1524*1525* This function computes the squared error when using these two representations.1526*1527* @param pi The partition info for the current trial.1528* @param blk The image block color data to be compressed.1529* @param uncor_plines Processed uncorrelated partition lines for each partition.1530* @param samec_plines Processed same chroma partition lines for each partition.1531* @param[out] line_lengths The length of each components deviation from the line.1532* @param[out] uncor_error The cumulative error for using the uncorrelated line.1533* @param[out] samec_error The cumulative error for using the same chroma line.1534*/1535void compute_error_squared_rgba(1536const partition_info& pi,1537const image_block& blk,1538const processed_line4 uncor_plines[BLOCK_MAX_PARTITIONS],1539const processed_line4 samec_plines[BLOCK_MAX_PARTITIONS],1540float line_lengths[BLOCK_MAX_PARTITIONS],1541float& uncor_error,1542float& samec_error);15431544/**1545* @brief Find the best set of partitions to trial for a given block.1546*1547* On return the @c best_partitions list will contain the two best partition1548* candidates; one assuming data has uncorrelated chroma and one assuming the1549* data has correlated chroma. The best candidate is returned first in the list.1550*1551* @param bsd The block size information.1552* @param blk The image block color data to compress.1553* @param partition_count The number of partitions in the block.1554* @param partition_search_limit The number of candidate partition encodings to trial.1555* @param[out] best_partitions The best partition candidates.1556* @param requested_candidates The number of requested partitionings. May return fewer if1557* candidates are not available.1558*1559* @return The actual number of candidates returned.1560*/1561unsigned int find_best_partition_candidates(1562const block_size_descriptor& bsd,1563const image_block& blk,1564unsigned int partition_count,1565unsigned int partition_search_limit,1566unsigned int best_partitions[TUNE_MAX_PARTITIONING_CANDIDATES],1567unsigned int requested_candidates);15681569/* ============================================================================1570Functionality for managing images and image related data.1571============================================================================ */15721573/**1574* @brief Get a vector mask indicating lanes decompressing into a UNORM8 value.1575*1576* @param decode_mode The color profile for LDR_SRGB settings.1577* @param blk The image block for output image bitness settings.1578*1579* @return The component mask vector.1580*/1581static inline vmask4 get_u8_component_mask(1582astcenc_profile decode_mode,1583const image_block& blk1584) {1585// Decode mode or sRGB forces writing to unorm8 output value1586if (blk.decode_unorm8 || decode_mode == ASTCENC_PRF_LDR_SRGB)1587{1588return vmask4(true);1589}15901591return vmask4(false);1592}15931594/**1595* @brief Setup computation of regional averages in an image.1596*1597* This must be done by only a single thread per image, before any thread calls1598* @c compute_averages().1599*1600* Results are written back into @c img->input_alpha_averages.1601*1602* @param img The input image data, also holds output data.1603* @param alpha_kernel_radius The kernel radius (in pixels) for alpha mods.1604* @param swz Input data component swizzle.1605* @param[out] ag The average variance arguments to init.1606*1607* @return The number of tasks in the processing stage.1608*/1609unsigned int init_compute_averages(1610const astcenc_image& img,1611unsigned int alpha_kernel_radius,1612const astcenc_swizzle& swz,1613avg_args& ag);16141615/**1616* @brief Compute averages for a pixel region.1617*1618* The routine computes both in a single pass, using a summed-area table to decouple the running1619* time from the averaging/variance kernel size.1620*1621* @param[out] ctx The compressor context storing the output data.1622* @param arg The input parameter structure.1623*/1624void compute_pixel_region_variance(1625astcenc_contexti& ctx,1626const pixel_region_args& arg);1627/**1628* @brief Load a single image block from the input image.1629*1630* @param decode_mode The compression color profile.1631* @param img The input image data.1632* @param[out] blk The image block to populate.1633* @param bsd The block size information.1634* @param xpos The block X coordinate in the input image.1635* @param ypos The block Y coordinate in the input image.1636* @param zpos The block Z coordinate in the input image.1637* @param swz The swizzle to apply on load.1638*/1639void load_image_block(1640astcenc_profile decode_mode,1641const astcenc_image& img,1642image_block& blk,1643const block_size_descriptor& bsd,1644unsigned int xpos,1645unsigned int ypos,1646unsigned int zpos,1647const astcenc_swizzle& swz);16481649/**1650* @brief Load a single image block from the input image.1651*1652* This specialized variant can be used only if the block is 2D LDR U8 data,1653* with no swizzle.1654*1655* @param decode_mode The compression color profile.1656* @param img The input image data.1657* @param[out] blk The image block to populate.1658* @param bsd The block size information.1659* @param xpos The block X coordinate in the input image.1660* @param ypos The block Y coordinate in the input image.1661* @param zpos The block Z coordinate in the input image.1662* @param swz The swizzle to apply on load.1663*/1664void load_image_block_fast_ldr(1665astcenc_profile decode_mode,1666const astcenc_image& img,1667image_block& blk,1668const block_size_descriptor& bsd,1669unsigned int xpos,1670unsigned int ypos,1671unsigned int zpos,1672const astcenc_swizzle& swz);16731674/**1675* @brief Store a single image block to the output image.1676*1677* @param[out] img The output image data.1678* @param blk The image block to export.1679* @param bsd The block size information.1680* @param xpos The block X coordinate in the input image.1681* @param ypos The block Y coordinate in the input image.1682* @param zpos The block Z coordinate in the input image.1683* @param swz The swizzle to apply on store.1684*/1685void store_image_block(1686astcenc_image& img,1687const image_block& blk,1688const block_size_descriptor& bsd,1689unsigned int xpos,1690unsigned int ypos,1691unsigned int zpos,1692const astcenc_swizzle& swz);16931694/* ============================================================================1695Functionality for computing endpoint colors and weights for a block.1696============================================================================ */16971698/**1699* @brief Compute ideal endpoint colors and weights for 1 plane of weights.1700*1701* The ideal endpoints define a color line for the partition. For each texel the ideal weight1702* defines an exact position on the partition color line. We can then use these to assess the error1703* introduced by removing and quantizing the weight grid.1704*1705* @param blk The image block color data to compress.1706* @param pi The partition info for the current trial.1707* @param[out] ei The endpoint and weight values.1708*/1709void compute_ideal_colors_and_weights_1plane(1710const image_block& blk,1711const partition_info& pi,1712endpoints_and_weights& ei);17131714/**1715* @brief Compute ideal endpoint colors and weights for 2 planes of weights.1716*1717* The ideal endpoints define a color line for the partition. For each texel the ideal weight1718* defines an exact position on the partition color line. We can then use these to assess the error1719* introduced by removing and quantizing the weight grid.1720*1721* @param bsd The block size information.1722* @param blk The image block color data to compress.1723* @param plane2_component The component assigned to plane 2.1724* @param[out] ei1 The endpoint and weight values for plane 1.1725* @param[out] ei2 The endpoint and weight values for plane 2.1726*/1727void compute_ideal_colors_and_weights_2planes(1728const block_size_descriptor& bsd,1729const image_block& blk,1730unsigned int plane2_component,1731endpoints_and_weights& ei1,1732endpoints_and_weights& ei2);17331734/**1735* @brief Compute the optimal unquantized weights for a decimation table.1736*1737* After computing ideal weights for the case for a complete weight grid, we we want to compute the1738* ideal weights for the case where weights exist only for some texels. We do this with a1739* steepest-descent grid solver which works as follows:1740*1741* First, for each actual weight, perform a weighted averaging of the texels affected by the weight.1742* Then, set step size to <some initial value> and attempt one step towards the original ideal1743* weight if it helps to reduce error.1744*1745* @param ei The non-decimated endpoints and weights.1746* @param di The selected weight decimation.1747* @param[out] dec_weight_ideal_value The ideal values for the decimated weight set.1748*/1749void compute_ideal_weights_for_decimation(1750const endpoints_and_weights& ei,1751const decimation_info& di,1752float* dec_weight_ideal_value);17531754/**1755* @brief Compute the optimal quantized weights for a decimation table.1756*1757* We test the two closest weight indices in the allowed quantization range and keep the weight that1758* is the closest match.1759*1760* @param di The selected weight decimation.1761* @param low_bound The lowest weight allowed.1762* @param high_bound The highest weight allowed.1763* @param dec_weight_ideal_value The ideal weight set.1764* @param[out] dec_weight_quant_uvalue The output quantized weight as a float.1765* @param[out] dec_weight_uquant The output quantized weight as encoded int.1766* @param quant_level The desired weight quant level.1767*/1768void compute_quantized_weights_for_decimation(1769const decimation_info& di,1770float low_bound,1771float high_bound,1772const float* dec_weight_ideal_value,1773float* dec_weight_quant_uvalue,1774uint8_t* dec_weight_uquant,1775quant_method quant_level);17761777/**1778* @brief Compute the error of a decimated weight set for 1 plane.1779*1780* After computing ideal weights for the case with one weight per texel, we want to compute the1781* error for decimated weight grids where weights are stored at a lower resolution. This function1782* computes the error of the reduced grid, compared to the full grid.1783*1784* @param eai The ideal weights for the full grid.1785* @param di The selected weight decimation.1786* @param dec_weight_quant_uvalue The quantized weights for the decimated grid.1787*1788* @return The accumulated error.1789*/1790float compute_error_of_weight_set_1plane(1791const endpoints_and_weights& eai,1792const decimation_info& di,1793const float* dec_weight_quant_uvalue);17941795/**1796* @brief Compute the error of a decimated weight set for 2 planes.1797*1798* After computing ideal weights for the case with one weight per texel, we want to compute the1799* error for decimated weight grids where weights are stored at a lower resolution. This function1800* computes the error of the reduced grid, compared to the full grid.1801*1802* @param eai1 The ideal weights for the full grid and plane 1.1803* @param eai2 The ideal weights for the full grid and plane 2.1804* @param di The selected weight decimation.1805* @param dec_weight_quant_uvalue_plane1 The quantized weights for the decimated grid plane 1.1806* @param dec_weight_quant_uvalue_plane2 The quantized weights for the decimated grid plane 2.1807*1808* @return The accumulated error.1809*/1810float compute_error_of_weight_set_2planes(1811const endpoints_and_weights& eai1,1812const endpoints_and_weights& eai2,1813const decimation_info& di,1814const float* dec_weight_quant_uvalue_plane1,1815const float* dec_weight_quant_uvalue_plane2);18161817/**1818* @brief Pack a single pair of color endpoints as effectively as possible.1819*1820* The user requests a base color endpoint mode in @c format, but the quantizer may choose a1821* delta-based representation. It will report back the format variant it actually used.1822*1823* @param color0 The input unquantized color0 endpoint for absolute endpoint pairs.1824* @param color1 The input unquantized color1 endpoint for absolute endpoint pairs.1825* @param rgbs_color The input unquantized RGBS variant endpoint for same chroma endpoints.1826* @param rgbo_color The input unquantized RGBS variant endpoint for HDR endpoints.1827* @param format The desired base format.1828* @param[out] output The output storage for the quantized colors/1829* @param quant_level The quantization level requested.1830*1831* @return The actual endpoint mode used.1832*/1833uint8_t pack_color_endpoints(1834vfloat4 color0,1835vfloat4 color1,1836vfloat4 rgbs_color,1837vfloat4 rgbo_color,1838int format,1839uint8_t* output,1840quant_method quant_level);18411842/**1843* @brief Unpack a single pair of encoded endpoints.1844*1845* Endpoints must be unscrambled and converted into the 0-255 range before calling this functions.1846*1847* @param decode_mode The decode mode (LDR, HDR, etc).1848* @param format The color endpoint mode used.1849* @param input The raw array of encoded input integers. The length of this array1850* depends on @c format; it can be safely assumed to be large enough.1851* @param[out] rgb_hdr Is the endpoint using HDR for the RGB channels?1852* @param[out] alpha_hdr Is the endpoint using HDR for the A channel?1853* @param[out] output0 The output color for endpoint 0.1854* @param[out] output1 The output color for endpoint 1.1855*/1856void unpack_color_endpoints(1857astcenc_profile decode_mode,1858int format,1859const uint8_t* input,1860bool& rgb_hdr,1861bool& alpha_hdr,1862vint4& output0,1863vint4& output1);18641865/**1866* @brief Unpack an LDR RGBA color that uses delta encoding.1867*1868* @param input0 The packed endpoint 0 color.1869* @param input1 The packed endpoint 1 color deltas.1870* @param[out] output0 The unpacked endpoint 0 color.1871* @param[out] output1 The unpacked endpoint 1 color.1872*/1873void rgba_delta_unpack(1874vint4 input0,1875vint4 input1,1876vint4& output0,1877vint4& output1);18781879/**1880* @brief Unpack an LDR RGBA color that uses direct encoding.1881*1882* @param input0 The packed endpoint 0 color.1883* @param input1 The packed endpoint 1 color.1884* @param[out] output0 The unpacked endpoint 0 color.1885* @param[out] output1 The unpacked endpoint 1 color.1886*/1887void rgba_unpack(1888vint4 input0,1889vint4 input1,1890vint4& output0,1891vint4& output1);18921893/**1894* @brief Unpack a set of quantized and decimated weights.1895*1896* TODO: Can we skip this for non-decimated weights now that the @c scb is1897* already storing unquantized weights?1898*1899* @param bsd The block size information.1900* @param scb The symbolic compressed encoding.1901* @param di The weight grid decimation table.1902* @param is_dual_plane @c true if this is a dual plane block, @c false otherwise.1903* @param[out] weights_plane1 The output array for storing the plane 1 weights.1904* @param[out] weights_plane2 The output array for storing the plane 2 weights.1905*/1906void unpack_weights(1907const block_size_descriptor& bsd,1908const symbolic_compressed_block& scb,1909const decimation_info& di,1910bool is_dual_plane,1911int weights_plane1[BLOCK_MAX_TEXELS],1912int weights_plane2[BLOCK_MAX_TEXELS]);19131914/**1915* @brief Identify, for each mode, which set of color endpoint produces the best result.1916*1917* Returns the best @c tune_candidate_limit best looking modes, along with the ideal color encoding1918* combination for each. The modified quantization level can be used when all formats are the same,1919* as this frees up two additional bits of storage.1920*1921* @param pi The partition info for the current trial.1922* @param blk The image block color data to compress.1923* @param ep The ideal endpoints.1924* @param qwt_bitcounts Bit counts for different quantization methods.1925* @param qwt_errors Errors for different quantization methods.1926* @param tune_candidate_limit The max number of candidates to return, may be less.1927* @param start_block_mode The first block mode to inspect.1928* @param end_block_mode The last block mode to inspect.1929* @param[out] partition_format_specifiers The best formats per partition.1930* @param[out] block_mode The best packed block mode indexes.1931* @param[out] quant_level The best color quant level.1932* @param[out] quant_level_mod The best color quant level if endpoints are the same.1933* @param[out] tmpbuf Preallocated scratch buffers for the compressor.1934*1935* @return The actual number of candidate matches returned.1936*/1937unsigned int compute_ideal_endpoint_formats(1938const partition_info& pi,1939const image_block& blk,1940const endpoints& ep,1941const int8_t* qwt_bitcounts,1942const float* qwt_errors,1943unsigned int tune_candidate_limit,1944unsigned int start_block_mode,1945unsigned int end_block_mode,1946uint8_t partition_format_specifiers[TUNE_MAX_TRIAL_CANDIDATES][BLOCK_MAX_PARTITIONS],1947int block_mode[TUNE_MAX_TRIAL_CANDIDATES],1948quant_method quant_level[TUNE_MAX_TRIAL_CANDIDATES],1949quant_method quant_level_mod[TUNE_MAX_TRIAL_CANDIDATES],1950compression_working_buffers& tmpbuf);19511952/**1953* @brief For a given 1 plane weight set recompute the endpoint colors.1954*1955* As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must1956* recompute the ideal colors for a specific weight set.1957*1958* @param blk The image block color data to compress.1959* @param pi The partition info for the current trial.1960* @param di The weight grid decimation table.1961* @param dec_weights_uquant The quantized weight set.1962* @param[in,out] ep The color endpoints (modifed in place).1963* @param[out] rgbs_vectors The RGB+scale vectors for LDR blocks.1964* @param[out] rgbo_vectors The RGB+offset vectors for HDR blocks.1965*/1966void recompute_ideal_colors_1plane(1967const image_block& blk,1968const partition_info& pi,1969const decimation_info& di,1970const uint8_t* dec_weights_uquant,1971endpoints& ep,1972vfloat4 rgbs_vectors[BLOCK_MAX_PARTITIONS],1973vfloat4 rgbo_vectors[BLOCK_MAX_PARTITIONS]);19741975/**1976* @brief For a given 2 plane weight set recompute the endpoint colors.1977*1978* As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must1979* recompute the ideal colors for a specific weight set.1980*1981* @param blk The image block color data to compress.1982* @param bsd The block_size descriptor.1983* @param di The weight grid decimation table.1984* @param dec_weights_uquant_plane1 The quantized weight set for plane 1.1985* @param dec_weights_uquant_plane2 The quantized weight set for plane 2.1986* @param[in,out] ep The color endpoints (modifed in place).1987* @param[out] rgbs_vector The RGB+scale color for LDR blocks.1988* @param[out] rgbo_vector The RGB+offset color for HDR blocks.1989* @param plane2_component The component assigned to plane 2.1990*/1991void recompute_ideal_colors_2planes(1992const image_block& blk,1993const block_size_descriptor& bsd,1994const decimation_info& di,1995const uint8_t* dec_weights_uquant_plane1,1996const uint8_t* dec_weights_uquant_plane2,1997endpoints& ep,1998vfloat4& rgbs_vector,1999vfloat4& rgbo_vector,2000int plane2_component);20012002/**2003* @brief Expand the angular tables needed for the alternative to PCA that we use.2004*/2005void prepare_angular_tables();20062007/**2008* @brief Compute the angular endpoints for one plane for each block mode.2009*2010* @param only_always Only consider block modes that are always enabled.2011* @param bsd The block size descriptor for the current trial.2012* @param dec_weight_ideal_value The ideal decimated unquantized weight values.2013* @param max_weight_quant The maximum block mode weight quantization allowed.2014* @param[out] tmpbuf Preallocated scratch buffers for the compressor.2015*/2016void compute_angular_endpoints_1plane(2017bool only_always,2018const block_size_descriptor& bsd,2019const float* dec_weight_ideal_value,2020unsigned int max_weight_quant,2021compression_working_buffers& tmpbuf);20222023/**2024* @brief Compute the angular endpoints for two planes for each block mode.2025*2026* @param bsd The block size descriptor for the current trial.2027* @param dec_weight_ideal_value The ideal decimated unquantized weight values.2028* @param max_weight_quant The maximum block mode weight quantization allowed.2029* @param[out] tmpbuf Preallocated scratch buffers for the compressor.2030*/2031void compute_angular_endpoints_2planes(2032const block_size_descriptor& bsd,2033const float* dec_weight_ideal_value,2034unsigned int max_weight_quant,2035compression_working_buffers& tmpbuf);20362037/* ============================================================================2038Functionality for high level compression and decompression access.2039============================================================================ */20402041/**2042* @brief Compress an image block into a physical block.2043*2044* @param ctx The compressor context and configuration.2045* @param blk The image block color data to compress.2046* @param[out] pcb The physical compressed block output.2047* @param[out] tmpbuf Preallocated scratch buffers for the compressor.2048*/2049void compress_block(2050const astcenc_contexti& ctx,2051const image_block& blk,2052uint8_t pcb[16],2053compression_working_buffers& tmpbuf);20542055/**2056* @brief Decompress a symbolic block in to an image block.2057*2058* @param decode_mode The decode mode (LDR, HDR, etc).2059* @param bsd The block size information.2060* @param xpos The X coordinate of the block in the overall image.2061* @param ypos The Y coordinate of the block in the overall image.2062* @param zpos The Z coordinate of the block in the overall image.2063* @param[out] blk The decompressed image block color data.2064*/2065void decompress_symbolic_block(2066astcenc_profile decode_mode,2067const block_size_descriptor& bsd,2068int xpos,2069int ypos,2070int zpos,2071const symbolic_compressed_block& scb,2072image_block& blk);20732074/**2075* @brief Compute the error between a symbolic block and the original input data.2076*2077* This function is specialized for 2 plane and 1 partition search.2078*2079* In RGBM mode this will reject blocks that attempt to encode a zero M value.2080*2081* @param config The compressor config.2082* @param bsd The block size information.2083* @param scb The symbolic compressed encoding.2084* @param blk The original image block color data.2085*2086* @return Returns the computed error, or a negative value if the encoding2087* should be rejected for any reason.2088*/2089float compute_symbolic_block_difference_2plane(2090const astcenc_config& config,2091const block_size_descriptor& bsd,2092const symbolic_compressed_block& scb,2093const image_block& blk);20942095/**2096* @brief Compute the error between a symbolic block and the original input data.2097*2098* This function is specialized for 1 plane and N partition search.2099*2100* In RGBM mode this will reject blocks that attempt to encode a zero M value.2101*2102* @param config The compressor config.2103* @param bsd The block size information.2104* @param scb The symbolic compressed encoding.2105* @param blk The original image block color data.2106*2107* @return Returns the computed error, or a negative value if the encoding2108* should be rejected for any reason.2109*/2110float compute_symbolic_block_difference_1plane(2111const astcenc_config& config,2112const block_size_descriptor& bsd,2113const symbolic_compressed_block& scb,2114const image_block& blk);21152116/**2117* @brief Compute the error between a symbolic block and the original input data.2118*2119* This function is specialized for 1 plane and 1 partition search.2120*2121* In RGBM mode this will reject blocks that attempt to encode a zero M value.2122*2123* @param config The compressor config.2124* @param bsd The block size information.2125* @param scb The symbolic compressed encoding.2126* @param blk The original image block color data.2127*2128* @return Returns the computed error, or a negative value if the encoding2129* should be rejected for any reason.2130*/2131float compute_symbolic_block_difference_1plane_1partition(2132const astcenc_config& config,2133const block_size_descriptor& bsd,2134const symbolic_compressed_block& scb,2135const image_block& blk);21362137/**2138* @brief Convert a symbolic representation into a binary physical encoding.2139*2140* It is assumed that the symbolic encoding is valid and encodable, or2141* previously flagged as an error block if an error color it to be encoded.2142*2143* @param bsd The block size information.2144* @param scb The symbolic representation.2145* @param[out] pcb The physical compressed block output.2146*/2147void symbolic_to_physical(2148const block_size_descriptor& bsd,2149const symbolic_compressed_block& scb,2150uint8_t pcb[16]);21512152/**2153* @brief Convert a binary physical encoding into a symbolic representation.2154*2155* This function can cope with arbitrary input data; output blocks will be2156* flagged as an error block if the encoding is invalid.2157*2158* @param bsd The block size information.2159* @param pcb The physical compresesd block input.2160* @param[out] scb The output symbolic representation.2161*/2162void physical_to_symbolic(2163const block_size_descriptor& bsd,2164const uint8_t pcb[16],2165symbolic_compressed_block& scb);21662167/* ============================================================================2168Platform-specific functions.2169============================================================================ */2170/**2171* @brief Allocate an aligned memory buffer.2172*2173* Allocated memory must be freed by aligned_free.2174*2175* @param size The desired buffer size.2176* @param align The desired buffer alignment; must be 2^N, may be increased2177* by the implementation to a minimum allowable alignment.2178*2179* @return The memory buffer pointer or nullptr on allocation failure.2180*/2181template<typename T>2182T* aligned_malloc(size_t size, size_t align)2183{2184void* ptr;2185int error = 0;21862187// Don't allow this to under-align a type2188size_t min_align = astc::max(alignof(T), sizeof(void*));2189size_t real_align = astc::max(min_align, align);21902191#if defined(_WIN32)2192ptr = _aligned_malloc(size, real_align);2193#else2194error = posix_memalign(&ptr, real_align, size);2195#endif21962197if (error || (!ptr))2198{2199return nullptr;2200}22012202return static_cast<T*>(ptr);2203}22042205/**2206* @brief Free an aligned memory buffer.2207*2208* @param ptr The buffer to free.2209*/2210template<typename T>2211void aligned_free(T* ptr)2212{2213#if defined(_WIN32)2214_aligned_free(ptr);2215#else2216free(ptr);2217#endif2218}22192220#endif222122222223