astcenc_internal.h 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228
  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. vmask4 u8_mask(false);
  1351. // Decode mode writing to a unorm8 output value
  1352. if (blk.decode_unorm8)
  1353. {
  1354. u8_mask = vmask4(true);
  1355. }
  1356. // SRGB writing to a unorm8 RGB value
  1357. else if (decode_mode == ASTCENC_PRF_LDR_SRGB)
  1358. {
  1359. u8_mask = vmask4(true, true, true, false);
  1360. }
  1361. return u8_mask;
  1362. }
  1363. /**
  1364. * @brief Setup computation of regional averages in an image.
  1365. *
  1366. * This must be done by only a single thread per image, before any thread calls
  1367. * @c compute_averages().
  1368. *
  1369. * Results are written back into @c img->input_alpha_averages.
  1370. *
  1371. * @param img The input image data, also holds output data.
  1372. * @param alpha_kernel_radius The kernel radius (in pixels) for alpha mods.
  1373. * @param swz Input data component swizzle.
  1374. * @param[out] ag The average variance arguments to init.
  1375. *
  1376. * @return The number of tasks in the processing stage.
  1377. */
  1378. unsigned int init_compute_averages(
  1379. const astcenc_image& img,
  1380. unsigned int alpha_kernel_radius,
  1381. const astcenc_swizzle& swz,
  1382. avg_args& ag);
  1383. /**
  1384. * @brief Compute averages for a pixel region.
  1385. *
  1386. * The routine computes both in a single pass, using a summed-area table to decouple the running
  1387. * time from the averaging/variance kernel size.
  1388. *
  1389. * @param[out] ctx The compressor context storing the output data.
  1390. * @param arg The input parameter structure.
  1391. */
  1392. void compute_pixel_region_variance(
  1393. astcenc_contexti& ctx,
  1394. const pixel_region_args& arg);
  1395. /**
  1396. * @brief Load a single image block from the input image.
  1397. *
  1398. * @param decode_mode The compression color profile.
  1399. * @param img The input image data.
  1400. * @param[out] blk The image block to populate.
  1401. * @param bsd The block size information.
  1402. * @param xpos The block X coordinate in the input image.
  1403. * @param ypos The block Y coordinate in the input image.
  1404. * @param zpos The block Z coordinate in the input image.
  1405. * @param swz The swizzle to apply on load.
  1406. */
  1407. void load_image_block(
  1408. astcenc_profile decode_mode,
  1409. const astcenc_image& img,
  1410. image_block& blk,
  1411. const block_size_descriptor& bsd,
  1412. unsigned int xpos,
  1413. unsigned int ypos,
  1414. unsigned int zpos,
  1415. const astcenc_swizzle& swz);
  1416. /**
  1417. * @brief Load a single image block from the input image.
  1418. *
  1419. * This specialized variant can be used only if the block is 2D LDR U8 data,
  1420. * with no swizzle.
  1421. *
  1422. * @param decode_mode The compression color profile.
  1423. * @param img The input image data.
  1424. * @param[out] blk The image block to populate.
  1425. * @param bsd The block size information.
  1426. * @param xpos The block X coordinate in the input image.
  1427. * @param ypos The block Y coordinate in the input image.
  1428. * @param zpos The block Z coordinate in the input image.
  1429. * @param swz The swizzle to apply on load.
  1430. */
  1431. void load_image_block_fast_ldr(
  1432. astcenc_profile decode_mode,
  1433. const astcenc_image& img,
  1434. image_block& blk,
  1435. const block_size_descriptor& bsd,
  1436. unsigned int xpos,
  1437. unsigned int ypos,
  1438. unsigned int zpos,
  1439. const astcenc_swizzle& swz);
  1440. /**
  1441. * @brief Store a single image block to the output image.
  1442. *
  1443. * @param[out] img The output image data.
  1444. * @param blk The image block to export.
  1445. * @param bsd The block size information.
  1446. * @param xpos The block X coordinate in the input image.
  1447. * @param ypos The block Y coordinate in the input image.
  1448. * @param zpos The block Z coordinate in the input image.
  1449. * @param swz The swizzle to apply on store.
  1450. */
  1451. void store_image_block(
  1452. astcenc_image& img,
  1453. const image_block& blk,
  1454. const block_size_descriptor& bsd,
  1455. unsigned int xpos,
  1456. unsigned int ypos,
  1457. unsigned int zpos,
  1458. const astcenc_swizzle& swz);
  1459. /* ============================================================================
  1460. Functionality for computing endpoint colors and weights for a block.
  1461. ============================================================================ */
  1462. /**
  1463. * @brief Compute ideal endpoint colors and weights for 1 plane of weights.
  1464. *
  1465. * The ideal endpoints define a color line for the partition. For each texel the ideal weight
  1466. * defines an exact position on the partition color line. We can then use these to assess the error
  1467. * introduced by removing and quantizing the weight grid.
  1468. *
  1469. * @param blk The image block color data to compress.
  1470. * @param pi The partition info for the current trial.
  1471. * @param[out] ei The endpoint and weight values.
  1472. */
  1473. void compute_ideal_colors_and_weights_1plane(
  1474. const image_block& blk,
  1475. const partition_info& pi,
  1476. endpoints_and_weights& ei);
  1477. /**
  1478. * @brief Compute ideal endpoint colors and weights for 2 planes of weights.
  1479. *
  1480. * The ideal endpoints define a color line for the partition. For each texel the ideal weight
  1481. * defines an exact position on the partition color line. We can then use these to assess the error
  1482. * introduced by removing and quantizing the weight grid.
  1483. *
  1484. * @param bsd The block size information.
  1485. * @param blk The image block color data to compress.
  1486. * @param plane2_component The component assigned to plane 2.
  1487. * @param[out] ei1 The endpoint and weight values for plane 1.
  1488. * @param[out] ei2 The endpoint and weight values for plane 2.
  1489. */
  1490. void compute_ideal_colors_and_weights_2planes(
  1491. const block_size_descriptor& bsd,
  1492. const image_block& blk,
  1493. unsigned int plane2_component,
  1494. endpoints_and_weights& ei1,
  1495. endpoints_and_weights& ei2);
  1496. /**
  1497. * @brief Compute the optimal unquantized weights for a decimation table.
  1498. *
  1499. * After computing ideal weights for the case for a complete weight grid, we we want to compute the
  1500. * ideal weights for the case where weights exist only for some texels. We do this with a
  1501. * steepest-descent grid solver which works as follows:
  1502. *
  1503. * First, for each actual weight, perform a weighted averaging of the texels affected by the weight.
  1504. * Then, set step size to <some initial value> and attempt one step towards the original ideal
  1505. * weight if it helps to reduce error.
  1506. *
  1507. * @param ei The non-decimated endpoints and weights.
  1508. * @param di The selected weight decimation.
  1509. * @param[out] dec_weight_ideal_value The ideal values for the decimated weight set.
  1510. */
  1511. void compute_ideal_weights_for_decimation(
  1512. const endpoints_and_weights& ei,
  1513. const decimation_info& di,
  1514. float* dec_weight_ideal_value);
  1515. /**
  1516. * @brief Compute the optimal quantized weights for a decimation table.
  1517. *
  1518. * We test the two closest weight indices in the allowed quantization range and keep the weight that
  1519. * is the closest match.
  1520. *
  1521. * @param di The selected weight decimation.
  1522. * @param low_bound The lowest weight allowed.
  1523. * @param high_bound The highest weight allowed.
  1524. * @param dec_weight_ideal_value The ideal weight set.
  1525. * @param[out] dec_weight_quant_uvalue The output quantized weight as a float.
  1526. * @param[out] dec_weight_uquant The output quantized weight as encoded int.
  1527. * @param quant_level The desired weight quant level.
  1528. */
  1529. void compute_quantized_weights_for_decimation(
  1530. const decimation_info& di,
  1531. float low_bound,
  1532. float high_bound,
  1533. const float* dec_weight_ideal_value,
  1534. float* dec_weight_quant_uvalue,
  1535. uint8_t* dec_weight_uquant,
  1536. quant_method quant_level);
  1537. /**
  1538. * @brief Compute the error of a decimated weight set for 1 plane.
  1539. *
  1540. * After computing ideal weights for the case with one weight per texel, we want to compute the
  1541. * error for decimated weight grids where weights are stored at a lower resolution. This function
  1542. * computes the error of the reduced grid, compared to the full grid.
  1543. *
  1544. * @param eai The ideal weights for the full grid.
  1545. * @param di The selected weight decimation.
  1546. * @param dec_weight_quant_uvalue The quantized weights for the decimated grid.
  1547. *
  1548. * @return The accumulated error.
  1549. */
  1550. float compute_error_of_weight_set_1plane(
  1551. const endpoints_and_weights& eai,
  1552. const decimation_info& di,
  1553. const float* dec_weight_quant_uvalue);
  1554. /**
  1555. * @brief Compute the error of a decimated weight set for 2 planes.
  1556. *
  1557. * After computing ideal weights for the case with one weight per texel, we want to compute the
  1558. * error for decimated weight grids where weights are stored at a lower resolution. This function
  1559. * computes the error of the reduced grid, compared to the full grid.
  1560. *
  1561. * @param eai1 The ideal weights for the full grid and plane 1.
  1562. * @param eai2 The ideal weights for the full grid and plane 2.
  1563. * @param di The selected weight decimation.
  1564. * @param dec_weight_quant_uvalue_plane1 The quantized weights for the decimated grid plane 1.
  1565. * @param dec_weight_quant_uvalue_plane2 The quantized weights for the decimated grid plane 2.
  1566. *
  1567. * @return The accumulated error.
  1568. */
  1569. float compute_error_of_weight_set_2planes(
  1570. const endpoints_and_weights& eai1,
  1571. const endpoints_and_weights& eai2,
  1572. const decimation_info& di,
  1573. const float* dec_weight_quant_uvalue_plane1,
  1574. const float* dec_weight_quant_uvalue_plane2);
  1575. /**
  1576. * @brief Pack a single pair of color endpoints as effectively as possible.
  1577. *
  1578. * The user requests a base color endpoint mode in @c format, but the quantizer may choose a
  1579. * delta-based representation. It will report back the format variant it actually used.
  1580. *
  1581. * @param color0 The input unquantized color0 endpoint for absolute endpoint pairs.
  1582. * @param color1 The input unquantized color1 endpoint for absolute endpoint pairs.
  1583. * @param rgbs_color The input unquantized RGBS variant endpoint for same chroma endpoints.
  1584. * @param rgbo_color The input unquantized RGBS variant endpoint for HDR endpoints.
  1585. * @param format The desired base format.
  1586. * @param[out] output The output storage for the quantized colors/
  1587. * @param quant_level The quantization level requested.
  1588. *
  1589. * @return The actual endpoint mode used.
  1590. */
  1591. uint8_t pack_color_endpoints(
  1592. vfloat4 color0,
  1593. vfloat4 color1,
  1594. vfloat4 rgbs_color,
  1595. vfloat4 rgbo_color,
  1596. int format,
  1597. uint8_t* output,
  1598. quant_method quant_level);
  1599. /**
  1600. * @brief Unpack a single pair of encoded endpoints.
  1601. *
  1602. * Endpoints must be unscrambled and converted into the 0-255 range before calling this functions.
  1603. *
  1604. * @param decode_mode The decode mode (LDR, HDR, etc).
  1605. * @param format The color endpoint mode used.
  1606. * @param input The raw array of encoded input integers. The length of this array
  1607. * depends on @c format; it can be safely assumed to be large enough.
  1608. * @param[out] rgb_hdr Is the endpoint using HDR for the RGB channels?
  1609. * @param[out] alpha_hdr Is the endpoint using HDR for the A channel?
  1610. * @param[out] output0 The output color for endpoint 0.
  1611. * @param[out] output1 The output color for endpoint 1.
  1612. */
  1613. void unpack_color_endpoints(
  1614. astcenc_profile decode_mode,
  1615. int format,
  1616. const uint8_t* input,
  1617. bool& rgb_hdr,
  1618. bool& alpha_hdr,
  1619. vint4& output0,
  1620. vint4& output1);
  1621. /**
  1622. * @brief Unpack an LDR RGBA color that uses delta encoding.
  1623. *
  1624. * @param input0 The packed endpoint 0 color.
  1625. * @param input1 The packed endpoint 1 color deltas.
  1626. * @param[out] output0 The unpacked endpoint 0 color.
  1627. * @param[out] output1 The unpacked endpoint 1 color.
  1628. */
  1629. void rgba_delta_unpack(
  1630. vint4 input0,
  1631. vint4 input1,
  1632. vint4& output0,
  1633. vint4& output1);
  1634. /**
  1635. * @brief Unpack an LDR RGBA color that uses direct encoding.
  1636. *
  1637. * @param input0 The packed endpoint 0 color.
  1638. * @param input1 The packed endpoint 1 color.
  1639. * @param[out] output0 The unpacked endpoint 0 color.
  1640. * @param[out] output1 The unpacked endpoint 1 color.
  1641. */
  1642. void rgba_unpack(
  1643. vint4 input0,
  1644. vint4 input1,
  1645. vint4& output0,
  1646. vint4& output1);
  1647. /**
  1648. * @brief Unpack a set of quantized and decimated weights.
  1649. *
  1650. * TODO: Can we skip this for non-decimated weights now that the @c scb is
  1651. * already storing unquantized weights?
  1652. *
  1653. * @param bsd The block size information.
  1654. * @param scb The symbolic compressed encoding.
  1655. * @param di The weight grid decimation table.
  1656. * @param is_dual_plane @c true if this is a dual plane block, @c false otherwise.
  1657. * @param[out] weights_plane1 The output array for storing the plane 1 weights.
  1658. * @param[out] weights_plane2 The output array for storing the plane 2 weights.
  1659. */
  1660. void unpack_weights(
  1661. const block_size_descriptor& bsd,
  1662. const symbolic_compressed_block& scb,
  1663. const decimation_info& di,
  1664. bool is_dual_plane,
  1665. int weights_plane1[BLOCK_MAX_TEXELS],
  1666. int weights_plane2[BLOCK_MAX_TEXELS]);
  1667. /**
  1668. * @brief Identify, for each mode, which set of color endpoint produces the best result.
  1669. *
  1670. * Returns the best @c tune_candidate_limit best looking modes, along with the ideal color encoding
  1671. * combination for each. The modified quantization level can be used when all formats are the same,
  1672. * as this frees up two additional bits of storage.
  1673. *
  1674. * @param pi The partition info for the current trial.
  1675. * @param blk The image block color data to compress.
  1676. * @param ep The ideal endpoints.
  1677. * @param qwt_bitcounts Bit counts for different quantization methods.
  1678. * @param qwt_errors Errors for different quantization methods.
  1679. * @param tune_candidate_limit The max number of candidates to return, may be less.
  1680. * @param start_block_mode The first block mode to inspect.
  1681. * @param end_block_mode The last block mode to inspect.
  1682. * @param[out] partition_format_specifiers The best formats per partition.
  1683. * @param[out] block_mode The best packed block mode indexes.
  1684. * @param[out] quant_level The best color quant level.
  1685. * @param[out] quant_level_mod The best color quant level if endpoints are the same.
  1686. * @param[out] tmpbuf Preallocated scratch buffers for the compressor.
  1687. *
  1688. * @return The actual number of candidate matches returned.
  1689. */
  1690. unsigned int compute_ideal_endpoint_formats(
  1691. const partition_info& pi,
  1692. const image_block& blk,
  1693. const endpoints& ep,
  1694. const int8_t* qwt_bitcounts,
  1695. const float* qwt_errors,
  1696. unsigned int tune_candidate_limit,
  1697. unsigned int start_block_mode,
  1698. unsigned int end_block_mode,
  1699. uint8_t partition_format_specifiers[TUNE_MAX_TRIAL_CANDIDATES][BLOCK_MAX_PARTITIONS],
  1700. int block_mode[TUNE_MAX_TRIAL_CANDIDATES],
  1701. quant_method quant_level[TUNE_MAX_TRIAL_CANDIDATES],
  1702. quant_method quant_level_mod[TUNE_MAX_TRIAL_CANDIDATES],
  1703. compression_working_buffers& tmpbuf);
  1704. /**
  1705. * @brief For a given 1 plane weight set recompute the endpoint colors.
  1706. *
  1707. * As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must
  1708. * recompute the ideal colors for a specific weight set.
  1709. *
  1710. * @param blk The image block color data to compress.
  1711. * @param pi The partition info for the current trial.
  1712. * @param di The weight grid decimation table.
  1713. * @param dec_weights_uquant The quantized weight set.
  1714. * @param[in,out] ep The color endpoints (modifed in place).
  1715. * @param[out] rgbs_vectors The RGB+scale vectors for LDR blocks.
  1716. * @param[out] rgbo_vectors The RGB+offset vectors for HDR blocks.
  1717. */
  1718. void recompute_ideal_colors_1plane(
  1719. const image_block& blk,
  1720. const partition_info& pi,
  1721. const decimation_info& di,
  1722. const uint8_t* dec_weights_uquant,
  1723. endpoints& ep,
  1724. vfloat4 rgbs_vectors[BLOCK_MAX_PARTITIONS],
  1725. vfloat4 rgbo_vectors[BLOCK_MAX_PARTITIONS]);
  1726. /**
  1727. * @brief For a given 2 plane weight set recompute the endpoint colors.
  1728. *
  1729. * As we quantize and decimate weights the optimal endpoint colors may change slightly, so we must
  1730. * recompute the ideal colors for a specific weight set.
  1731. *
  1732. * @param blk The image block color data to compress.
  1733. * @param bsd The block_size descriptor.
  1734. * @param di The weight grid decimation table.
  1735. * @param dec_weights_uquant_plane1 The quantized weight set for plane 1.
  1736. * @param dec_weights_uquant_plane2 The quantized weight set for plane 2.
  1737. * @param[in,out] ep The color endpoints (modifed in place).
  1738. * @param[out] rgbs_vector The RGB+scale color for LDR blocks.
  1739. * @param[out] rgbo_vector The RGB+offset color for HDR blocks.
  1740. * @param plane2_component The component assigned to plane 2.
  1741. */
  1742. void recompute_ideal_colors_2planes(
  1743. const image_block& blk,
  1744. const block_size_descriptor& bsd,
  1745. const decimation_info& di,
  1746. const uint8_t* dec_weights_uquant_plane1,
  1747. const uint8_t* dec_weights_uquant_plane2,
  1748. endpoints& ep,
  1749. vfloat4& rgbs_vector,
  1750. vfloat4& rgbo_vector,
  1751. int plane2_component);
  1752. /**
  1753. * @brief Expand the angular tables needed for the alternative to PCA that we use.
  1754. */
  1755. void prepare_angular_tables();
  1756. /**
  1757. * @brief Compute the angular endpoints for one plane for each block mode.
  1758. *
  1759. * @param only_always Only consider block modes that are always enabled.
  1760. * @param bsd The block size descriptor for the current trial.
  1761. * @param dec_weight_ideal_value The ideal decimated unquantized weight values.
  1762. * @param max_weight_quant The maximum block mode weight quantization allowed.
  1763. * @param[out] tmpbuf Preallocated scratch buffers for the compressor.
  1764. */
  1765. void compute_angular_endpoints_1plane(
  1766. bool only_always,
  1767. const block_size_descriptor& bsd,
  1768. const float* dec_weight_ideal_value,
  1769. unsigned int max_weight_quant,
  1770. compression_working_buffers& tmpbuf);
  1771. /**
  1772. * @brief Compute the angular endpoints for two planes for each block mode.
  1773. *
  1774. * @param bsd The block size descriptor for the current trial.
  1775. * @param dec_weight_ideal_value The ideal decimated unquantized weight values.
  1776. * @param max_weight_quant The maximum block mode weight quantization allowed.
  1777. * @param[out] tmpbuf Preallocated scratch buffers for the compressor.
  1778. */
  1779. void compute_angular_endpoints_2planes(
  1780. const block_size_descriptor& bsd,
  1781. const float* dec_weight_ideal_value,
  1782. unsigned int max_weight_quant,
  1783. compression_working_buffers& tmpbuf);
  1784. /* ============================================================================
  1785. Functionality for high level compression and decompression access.
  1786. ============================================================================ */
  1787. /**
  1788. * @brief Compress an image block into a physical block.
  1789. *
  1790. * @param ctx The compressor context and configuration.
  1791. * @param blk The image block color data to compress.
  1792. * @param[out] pcb The physical compressed block output.
  1793. * @param[out] tmpbuf Preallocated scratch buffers for the compressor.
  1794. */
  1795. void compress_block(
  1796. const astcenc_contexti& ctx,
  1797. const image_block& blk,
  1798. uint8_t pcb[16],
  1799. compression_working_buffers& tmpbuf);
  1800. /**
  1801. * @brief Decompress a symbolic block in to an image block.
  1802. *
  1803. * @param decode_mode The decode mode (LDR, HDR, etc).
  1804. * @param bsd The block size information.
  1805. * @param xpos The X coordinate of the block in the overall image.
  1806. * @param ypos The Y coordinate of the block in the overall image.
  1807. * @param zpos The Z coordinate of the block in the overall image.
  1808. * @param[out] blk The decompressed image block color data.
  1809. */
  1810. void decompress_symbolic_block(
  1811. astcenc_profile decode_mode,
  1812. const block_size_descriptor& bsd,
  1813. int xpos,
  1814. int ypos,
  1815. int zpos,
  1816. const symbolic_compressed_block& scb,
  1817. image_block& blk);
  1818. /**
  1819. * @brief Compute the error between a symbolic block and the original input data.
  1820. *
  1821. * This function is specialized for 2 plane and 1 partition search.
  1822. *
  1823. * In RGBM mode this will reject blocks that attempt to encode a zero M value.
  1824. *
  1825. * @param config The compressor config.
  1826. * @param bsd The block size information.
  1827. * @param scb The symbolic compressed encoding.
  1828. * @param blk The original image block color data.
  1829. *
  1830. * @return Returns the computed error, or a negative value if the encoding
  1831. * should be rejected for any reason.
  1832. */
  1833. float compute_symbolic_block_difference_2plane(
  1834. const astcenc_config& config,
  1835. const block_size_descriptor& bsd,
  1836. const symbolic_compressed_block& scb,
  1837. const image_block& blk);
  1838. /**
  1839. * @brief Compute the error between a symbolic block and the original input data.
  1840. *
  1841. * This function is specialized for 1 plane and N partition search.
  1842. *
  1843. * In RGBM mode this will reject blocks that attempt to encode a zero M value.
  1844. *
  1845. * @param config The compressor config.
  1846. * @param bsd The block size information.
  1847. * @param scb The symbolic compressed encoding.
  1848. * @param blk The original image block color data.
  1849. *
  1850. * @return Returns the computed error, or a negative value if the encoding
  1851. * should be rejected for any reason.
  1852. */
  1853. float compute_symbolic_block_difference_1plane(
  1854. const astcenc_config& config,
  1855. const block_size_descriptor& bsd,
  1856. const symbolic_compressed_block& scb,
  1857. const image_block& blk);
  1858. /**
  1859. * @brief Compute the error between a symbolic block and the original input data.
  1860. *
  1861. * This function is specialized for 1 plane and 1 partition search.
  1862. *
  1863. * In RGBM mode this will reject blocks that attempt to encode a zero M value.
  1864. *
  1865. * @param config The compressor config.
  1866. * @param bsd The block size information.
  1867. * @param scb The symbolic compressed encoding.
  1868. * @param blk The original image block color data.
  1869. *
  1870. * @return Returns the computed error, or a negative value if the encoding
  1871. * should be rejected for any reason.
  1872. */
  1873. float compute_symbolic_block_difference_1plane_1partition(
  1874. const astcenc_config& config,
  1875. const block_size_descriptor& bsd,
  1876. const symbolic_compressed_block& scb,
  1877. const image_block& blk);
  1878. /**
  1879. * @brief Convert a symbolic representation into a binary physical encoding.
  1880. *
  1881. * It is assumed that the symbolic encoding is valid and encodable, or
  1882. * previously flagged as an error block if an error color it to be encoded.
  1883. *
  1884. * @param bsd The block size information.
  1885. * @param scb The symbolic representation.
  1886. * @param[out] pcb The physical compressed block output.
  1887. */
  1888. void symbolic_to_physical(
  1889. const block_size_descriptor& bsd,
  1890. const symbolic_compressed_block& scb,
  1891. uint8_t pcb[16]);
  1892. /**
  1893. * @brief Convert a binary physical encoding into a symbolic representation.
  1894. *
  1895. * This function can cope with arbitrary input data; output blocks will be
  1896. * flagged as an error block if the encoding is invalid.
  1897. *
  1898. * @param bsd The block size information.
  1899. * @param pcb The physical compresesd block input.
  1900. * @param[out] scb The output symbolic representation.
  1901. */
  1902. void physical_to_symbolic(
  1903. const block_size_descriptor& bsd,
  1904. const uint8_t pcb[16],
  1905. symbolic_compressed_block& scb);
  1906. /* ============================================================================
  1907. Platform-specific functions.
  1908. ============================================================================ */
  1909. /**
  1910. * @brief Allocate an aligned memory buffer.
  1911. *
  1912. * Allocated memory must be freed by aligned_free.
  1913. *
  1914. * @param size The desired buffer size.
  1915. * @param align The desired buffer alignment; must be 2^N, may be increased
  1916. * by the implementation to a minimum allowable alignment.
  1917. *
  1918. * @return The memory buffer pointer or nullptr on allocation failure.
  1919. */
  1920. template<typename T>
  1921. T* aligned_malloc(size_t size, size_t align)
  1922. {
  1923. void* ptr;
  1924. int error = 0;
  1925. // Don't allow this to under-align a type
  1926. size_t min_align = astc::max(alignof(T), sizeof(void*));
  1927. size_t real_align = astc::max(min_align, align);
  1928. #if defined(_WIN32)
  1929. ptr = _aligned_malloc(size, real_align);
  1930. #else
  1931. error = posix_memalign(&ptr, real_align, size);
  1932. #endif
  1933. if (error || (!ptr))
  1934. {
  1935. return nullptr;
  1936. }
  1937. return static_cast<T*>(ptr);
  1938. }
  1939. /**
  1940. * @brief Free an aligned memory buffer.
  1941. *
  1942. * @param ptr The buffer to free.
  1943. */
  1944. template<typename T>
  1945. void aligned_free(T* ptr)
  1946. {
  1947. #if defined(_WIN32)
  1948. _aligned_free(ptr);
  1949. #else
  1950. free(ptr);
  1951. #endif
  1952. }
  1953. #endif