astcenc_internal.h 79 KB

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