upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/bcpack.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src/bcpack.cpp')
-rw-r--r--runtime/src/bcpack.cpp1673
1 files changed, 405 insertions, 1268 deletions
diff --git a/runtime/src/bcpack.cpp b/runtime/src/bcpack.cpp
index 961fae34e..bb4646787 100644
--- a/runtime/src/bcpack.cpp
+++ b/runtime/src/bcpack.cpp
@@ -1,1286 +1,423 @@
1// BCPack decoder (bcpack.h), ported from VIctory's victory-formats (victory/crates/victory-formats/src/bcpack.rs, 1// C++ port of tools/bcpack.py. The build derives the model and BCn format
2// GPL-3.0-or-later, Marvisak and contributors); the table loading follows bcpack_tables() in 2// constants from that same reference.
3// victory/crates/victory-hle/src/modules/dstorage.rs. Leonida is GPL-3.0-or-later too.
4//
5// The arithmetic is VIctory's step for step (wrapping u8, u16 and u32 sums, the same shifts and casts), so the blocks
6// are bit-exact. What differs is the plumbing around it:
7// - A block is rebuilt as soon as the lanes have delivered its record, instead of after a first pass that keeps every
8// record (1.5-2 times the output size). The lanes deliver records strictly in order, so the blocks are the same;
9// only a failing stream may leave some blocks written.
10// - Symbol 0's bucket is folded into the other buckets' arithmetic when the tables are parsed (first slot 1,
11// frequency f0 - 1, reciprocal 0), which takes a data-dependent branch out of the decode step.
12// - Nothing allocates while decoding; the 256-block history is on the stack.
13// Speed: one core decodes the title's chunks at about 65 MB/s of BC1 and 30 MB/s of BC7, a little ahead of VIctory's
14// build (Ryzen 5 7600X, MSVC 2022, RelWithDebInfo). Writing the lane step's read, the byte handout or the delivery
15// without branches, and stepping all lanes of a round before handing out its bytes, were each measured slower: the
16// loop is bound by each lane's chain of states, which predicted branches keep short.
17#include "bcpack.h" 3#include "bcpack.h"
18 4#include "bcpack_stream.h"
19#include "bcpack_decode.h"
20
21#include <algorithm> 5#include <algorithm>
22#include <atomic> 6#include <array>
23#include <bit> 7#include <bit>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring> 8#include <cstring>
27#include <fstream>
28#include <new>
29#include <string>
30#include <system_error>
31#include <utility>
32#include <vector>
33
34#if defined(_WIN32)
35#ifndef NOMINMAX
36#define NOMINMAX
37#endif
38#ifndef WIN32_LEAN_AND_MEAN
39#define WIN32_LEAN_AND_MEAN
40#endif
41#include <windows.h>
42#endif
43
44#if defined(_MSC_VER)
45#define BCPACK_INLINE __forceinline
46#define BCPACK_NOINLINE __declspec(noinline)
47#else
48#define BCPACK_INLINE inline __attribute__((always_inline))
49#define BCPACK_NOINLINE __attribute__((noinline))
50#endif
51
52namespace rt::bcpack {
53namespace format {
54
55constexpr unsigned kModels = 128;
56constexpr unsigned kBuckets = 9;
57constexpr unsigned kHistory = 256;
58constexpr unsigned kDictionary = 255;
59// rANS: decode while the state is above this, read while below.
60constexpr std::uint32_t kLow = 1u << 24;
61// Input bytes per schedule round.
62constexpr unsigned kRoundBytes = 8;
63
64// Endpoints and indices of BC1, BC3, BC4 and BC5: small unsigned values, summed per element modulo its width.
65struct Plain {
66 std::uint8_t ep[8];
67 std::uint8_t ix[32];
68};
69
70struct Bc6Ep {
71 // Endpoint 0 R G B, then endpoints 1-3, left-aligned and biased.
72 std::uint16_t e[4][3];
73};
74
75struct Bc6Ix {
76 std::uint8_t mode;
77 std::int16_t ix[16];
78};
79
80struct Bc6Entry {
81 Bc6Ep ep;
82 Bc6Ix ix;
83};
84
85struct Bc7Ep {
86 std::uint16_t ctrl;
87 // Per subset: R0 R1 G0 G1 B0 B1 A0 A1, left-aligned.
88 std::uint16_t rows[3][8];
89};
90
91struct Bc7Ix {
92 std::uint8_t bits[2];
93 std::int16_t ix[2][16];
94};
95
96struct Bc7Entry {
97 Bc7Ep ep;
98 Bc7Ix ix;
99};
100
101// One of the 128 static rANS models over 65536 slots. Bucket 0 holds symbol 0; bucket b > 0 holds 2^(b-1) symbols
102// of one frequency, from its first slot on.
103struct Model {
104 // ceil(2^32 / f): exact division for the offsets inside a bucket. 0 for bucket 0, whose quotient is always 0.
105 std::uint64_t recip[kBuckets];
106 // Each bucket's first slot: 1 for bucket 0 (slot 0 is never used; VIctory keeps 0 there and subtracts 1 itself),
107 // 65536 past the model's last bucket and once more at the end, so a bucket always has a next start.
108 std::uint32_t start[kBuckets + 1];
109 // The frequency of each of the bucket's symbols: f0 - 1 for symbol 0, which owns slots 1 .. f0 - 1.
110 std::uint32_t freq[kBuckets];
111 // The bucket of the first slot of each 256-slot window: the search for a slot's bucket starts there and seldom
112 // moves on.
113 std::uint8_t bucket[256];
114};
115
116} // namespace format
117
118using namespace format;
119
120// The format's constant tables.
121struct Tables {
122 Model models[kModels];
123 std::uint8_t rank1[256];
124 std::uint8_t rank3a[64];
125 std::uint8_t rank3c[256];
126 std::uint8_t rank4[64];
127 std::uint8_t rank5[64];
128 std::uint16_t ctrl7[512];
129 Plain bc1[kDictionary];
130 Plain bc3[kDictionary];
131 Plain bc4[kDictionary];
132 Plain bc5[kDictionary];
133 Bc6Entry bc6[kDictionary];
134 Bc7Entry bc7[kDictionary];
135};
136
137void TablesDeleter::operator()(const Tables* tables) const {
138 delete tables;
139}
140 9
10namespace leonida::bcpack {
141namespace { 11namespace {
142 12using namespace detail;
143// Bytes of the table file: the model frequencies, the five rank tables, the BC7 control words, then per format 255 13
144// dictionary entries of BC1 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H 25 + 33 B, BC7 50 + 66 B. 14void color(uint8_t *dst, const int *e, int a, int b, int c, int d) {
145static_assert(kTablesSize == kModels * kBuckets * 2 + 256 + 64 + 256 + 64 + 64 + 512 * 2 + 15 for (int i = 0; i < 2; ++i, e += 3) {
146 kDictionary * (6 + 16 + 8 + 32 + 2 + 16 + 4 + 32 + 25 + 33 + 50 + 66)); 16 const int rgb = (e[0] << 11) | (e[1] << 5) | e[2];
147 17 dst[i * 2] = uint8_t(rgb);
148// Lane widths (symbol bits - 1 at the full alphabet) in stream order; docs/textures.md lists the symbol bits. 18 dst[i * 2 + 1] = uint8_t(rgb >> 8);
149constexpr std::uint8_t kBc1Lanes[12] = {7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7}; 19 }
150constexpr std::uint8_t kBc3Lanes[12] = {3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7}; 20 dst[4] = uint8_t((a & 15) | (b << 4));
151constexpr std::uint8_t kBc4Lanes[12] = {7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5}; 21 dst[5] = uint8_t((a >> 4) | (b & 240));
152constexpr std::uint8_t kBc5Lanes[12] = {3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5}; 22 dst[6] = uint8_t((c & 15) | (d << 4));
153constexpr std::uint8_t kBc6Lanes[16] = {3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4}; 23 dst[7] = uint8_t((c >> 4) | (d & 240));
154constexpr std::uint8_t kBc7Lanes[16] = {3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4}; 24}
155 25
156std::string utf8(const std::filesystem::path& path) { 26struct Endpoints {
157 const std::u8string s = path.u8string(); 27 int v[8]{};
158 return std::string(s.begin(), s.end());
159}
160
161BCPACK_INLINE void store_le16(std::uint8_t* p, std::uint16_t v) {
162 p[0] = static_cast<std::uint8_t>(v);
163 p[1] = static_cast<std::uint8_t>(v >> 8);
164}
165
166BCPACK_INLINE void store_le32(std::uint8_t* p, std::uint32_t v) {
167 if constexpr (std::endian::native == std::endian::little) {
168 std::memcpy(p, &v, 4);
169 } else {
170 for (unsigned k = 0; k < 4; ++k) p[k] = static_cast<std::uint8_t>(v >> (8 * k));
171 }
172}
173
174BCPACK_INLINE void store_le64(std::uint8_t* p, std::uint64_t v) {
175 if constexpr (std::endian::native == std::endian::little) {
176 std::memcpy(p, &v, 8);
177 } else {
178 for (unsigned k = 0; k < 8; ++k) p[k] = static_cast<std::uint8_t>(v >> (8 * k));
179 }
180}
181
182// Lanes.
183
184struct Lane {
185 std::uint32_t x;
186 std::uint32_t left;
187 // The byte taken for the next step, or -1.
188 std::int16_t latch;
189 // A symbol decoded but not yet delivered, or -1.
190 std::int16_t out;
191 // Symbol bits - 1 at the full alphabet.
192 std::uint8_t width;
193 // 0 header, 1 length (low byte), 2 length high byte, 3 payload.
194 std::uint8_t phase;
195 std::uint8_t model;
196 bool long_form;
197 bool reset;
198 bool need;
199 bool stalled;
200};
201
202// One step: take the latched byte (header, length or payload) and decode at most one symbol.
203BCPACK_INLINE void step(Lane& lane, const Tables& t) {
204 if (lane.phase != 3) {
205 if (lane.latch < 0) return;
206 const std::uint32_t b = static_cast<std::uint8_t>(lane.latch);
207 lane.latch = -1;
208 lane.need = true;
209 switch (lane.phase) {
210 case 0:
211 // The top two bits shrink the alphabet; width >= 3.
212 lane.model = static_cast<std::uint8_t>((lane.width - (b >> 6)) * 16 + (b & 15));
213 lane.reset = (b & 0x10) != 0;
214 lane.long_form = (b & 0x20) != 0;
215 lane.left = 0;
216 lane.phase = 1;
217 break;
218 case 1:
219 if (lane.long_form) {
220 lane.left = b;
221 lane.phase = 2;
222 } else {
223 lane.left = b + 1;
224 lane.phase = 3;
225 }
226 break;
227 default:
228 lane.left = ((b << 8) | lane.left) + 257;
229 lane.phase = 3;
230 break;
231 }
232 return;
233 }
234 std::uint32_t x = lane.x;
235 if (x < kLow && lane.latch >= 0) {
236 lane.left -= 1;
237 x = (x << 8) | static_cast<std::uint8_t>(lane.latch);
238 lane.latch = -1;
239 }
240 lane.need = lane.left != 0 && lane.latch < 0;
241 if (x > kLow) {
242 const Model& m = t.models[lane.model];
243 const std::uint32_t slot = x & 0xffff;
244 // The bucket: starts are ascending, and 65536 past the model's last.
245 unsigned b = m.bucket[slot >> 8];
246 while (m.start[b + 1] <= slot) ++b;
247 // Offset and frequency are below 2^16, where the reciprocal divides exactly. Bucket 0: offset slot - 1
248 // (wrapping at slot 0, as VIctory's does), quotient 0, frequency f0 - 1.
249 const std::uint32_t offset = slot - m.start[b];
250 const std::uint32_t q = static_cast<std::uint32_t>((std::uint64_t{offset} * m.recip[b]) >> 32);
251 const std::uint32_t f = m.freq[b];
252 lane.x = (x >> 16) * f + (offset - q * f);
253 lane.out = static_cast<std::int16_t>((((1u << b) >> 1) + q) & 0xff);
254 } else if (lane.left != 0) {
255 // At exactly 2^24 the lane neither reads nor decodes again; only a lane that has delivered its symbols may
256 // end up there.
257 lane.x = x;
258 } else {
259 // The fragment ends; a byte read in this step does not reach the carried state.
260 lane.phase = 0;
261 lane.need = lane.latch < 0;
262 if (lane.reset) lane.x = 0;
263 }
264}
265
266// Input from a buffer: past its end nothing arrives.
267struct BufferFetch {
268 const std::uint8_t* p;
269 const std::uint8_t* end;
270 BCPACK_INLINE int operator()(unsigned) { return p < end ? *p++ : -1; }
271}; 28};
272 29
273// Input from a caller's function (unpack_records). 30bool rebuild_classic(unsigned codec, size_t i, const Symbols &a,
274struct CallbackFetch { 31 const Symbols &b, array<Endpoints, 256> &past,
275 int (*fn)(void*, unsigned); 32 uint8_t *dst, bool allow_fitted, Quality &quality) {
276 void* context; 33 const bool single = codec == 1 || codec == 4;
277 int operator()(unsigned lane) { 34 if (a[1] || b[1])
278 const int b = fn(context, lane); 35 return false;
279 return b < 0 ? -1 : (b & 0xff); 36 const unsigned distance = unzig(single ? a[0] : interleave(a[0], b[0])) & 255;
280 } 37 Endpoints e;
281}; 38 const int count = codec == 1 ? 6 : codec == 3 ? 8 : codec == 4 ? 2 : 4;
282 39 if (!distance) {
283// Decodes Per symbols per block on each of the N lanes, handing each block's record (N * Per symbols, lane j's at 40 if (codec != 1)
284// j * Per) to `sink` once all its symbols are there, taking input from `fetch` (given the lane that takes the byte) 41 fill_n(e.v, codec == 5 ? 4 : 2, 128);
285// in the order of the schedule: each round the lanes step in order and take at most 8 bytes between them. 42 } else if (distance <= i) {
286template <unsigned N, unsigned Per, class Fetch, class Sink> 43 e = past[(i - distance) & 255];
287BCPACK_INLINE Error run_lanes(const Tables& t, const std::uint8_t* widths, std::size_t blocks, Fetch& fetch, 44 } else {
288 Sink& sink) { 45 const unsigned slot = (i - distance) & 255;
289 Lane lanes[N]; 46 const Seed &seed = codec == 1 ? history1[slot]
290 for (unsigned j = 0; j < N; ++j) { 47 : codec == 3 ? history3[slot]
291 lanes[j] = Lane{}; 48 : codec == 4 ? history4[slot]
292 lanes[j].latch = -1; 49 : history5[slot];
293 lanes[j].out = -1; 50 if (seed.values[0] < 0 || (seed.fitted && !allow_fitted))
294 lanes[j].width = widths[j]; 51 return false;
295 lanes[j].need = true; 52 if (seed.fitted)
296 } 53 quality = Quality::fitted;
297 constexpr std::uint32_t kFull = (1u << N) - 1; 54 copy_n(seed.values, count, e.v);
298 std::uint8_t record[N * Per]; 55 }
299 const std::size_t total = blocks * Per; 56 const int alpha = codec == 1 ? 0 : codec == 5 ? 4 : 2;
300 std::size_t pos = 0; 57 for (int k = 0; k < count; ++k) {
301 // pos % Per: which of its block's symbols each lane delivers now. 58 const int coord = k - alpha;
302 unsigned h = 0; 59 const int mask = coord < 0 ? 255 : coord % 3 == 1 ? 63 : 31;
303 std::uint32_t done = 0; 60 const int symbol = single ? a[2 + k]
304 unsigned idle = 0; 61 : coord < 0 ? (k % 2 ? b : a)[2 + k / 2]
305 while (pos < total) { 62 : (coord < 3 ? a : b)[7 + coord % 3];
306 unsigned taken = 0; 63 e.v[k] = (e.v[k] + unzig(symbol)) & mask;
307 bool moved = false; 64 }
308 for (unsigned j = 0; j < N; ++j) { 65 past[i & 255] = e;
309 Lane& lane = lanes[j]; 66 for (int ch = 0; ch < alpha / 2; ++ch) {
310 const std::uint32_t bit = 1u << j; 67 const auto *pairs = codec == 3 ? pair3 : codec == 4 ? pair4 : pair5;
311 const unsigned before = taken; 68 uint64_t bits = 0;
312 if (!lane.stalled) step(lane, t); 69 for (int row = 0; row < 4; ++row) {
313 const bool waiting = lane.out >= 0 && (done & bit) != 0; 70 const int lane =
314 if (lane.need && !waiting && taken < kRoundBytes) { 71 codec == 4 ? 4 + 2 * row : (codec == 3 ? 3 : 4 + 4 * ch) + row;
315 // Past the end nothing arrives; in a valid stream only finished lanes ask there. 72 const int right = single ? a[lane + 1] : b[lane];
316 const int b = fetch(j); 73 bits |= uint64_t(pairs[a[lane]] | (pairs[right] << 6)) << (12 * row);
317 if (b >= 0) { 74 }
318 lane.latch = static_cast<std::int16_t>(b); 75 *dst++ = uint8_t(e.v[ch * 2]);
319 ++taken; 76 *dst++ = uint8_t(e.v[ch * 2 + 1]);
320 } 77 for (int j = 0; j < 6; ++j)
321 } 78 *dst++ = uint8_t(bits >> (8 * j));
322 lane.stalled = (lane.need && before >= kRoundBytes) || waiting; 79 }
323 if (!lane.stalled && lane.out >= 0) { 80 if (codec == 1)
324 record[j * Per + h] = static_cast<std::uint8_t>(lane.out); 81 color(dst, e.v, quad1[a[8]], quad1[a[9]], quad1[a[10]], quad1[a[11]]);
325 lane.out = -1; 82 if (codec == 3)
326 done |= bit; 83 color(dst, e.v + 2, quad3[a[10]], quad3[b[10]], quad3[a[11]], quad3[b[11]]);
327 moved = true; 84 return true;
328 } 85}
329 } 86
330 if (done == kFull) { 87struct BitWriter {
331 ++pos; 88 uint8_t *dst;
332 if (++h == Per) { 89 int pos{}, violations{};
333 h = 0; 90 void put(int value, int bits) {
334 if (const Error error = sink(static_cast<const std::uint8_t*>(record))) return error; 91 while (bits > 0) {
335 } 92 const int n = min(bits, 8 - pos % 8);
336 done = 0; 93 dst[pos / 8] |= uint8_t((value & ((1 << n) - 1)) << (pos % 8));
337 moved = true; 94 value >>= n;
338 } 95 bits -= n;
339 // Nothing read and nothing delivered for a few rounds: no lane can go on. 96 pos += n;
340 idle = (taken > 0 || moved) ? 0 : idle + 1; 97 }
341 if (idle > 3) return "the stream ends early or is corrupt"; 98 }
342 }
343 return nullptr;
344}
345
346// Blocks.
347
348struct References {
349 unsigned ep;
350 unsigned ix;
351};
352
353// Two 4-bit symbols, the first on the even bits.
354BCPACK_INLINE std::uint8_t interleave(std::uint8_t a, std::uint8_t b) {
355 const auto spread = [](unsigned v) {
356 return (v & 1) | ((v >> 1 & 1) << 2) | ((v >> 2 & 1) << 4) | ((v >> 3 & 1) << 6);
357 };
358 return static_cast<std::uint8_t>(spread(a) | (spread(b) << 1));
359}
360
361// The record's endpoint and index references.
362BCPACK_INLINE References references(const std::uint8_t* s, bool paired) {
363 std::uint8_t d;
364 std::uint8_t ix;
365 if (paired) {
366 d = interleave(s[0], s[1]);
367 ix = interleave(s[2], s[3]);
368 } else {
369 d = s[0];
370 ix = s[1];
371 }
372 const std::uint8_t delta = static_cast<std::uint8_t>((d >> 1) ^ (0u - (d & 1u)));
373 return {static_cast<std::uint8_t>(ix + delta), ix};
374}
375
376// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first block into the dictionary.
377template <class T>
378BCPACK_INLINE const T& pick(std::size_t i, unsigned r, const T* history, const T* dictionary, const T& zero) {
379 if (r == 0) return zero;
380 if (r <= i) return history[(i - r) % kHistory];
381 return dictionary[r - i - 1];
382}
383
384// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits.
385BCPACK_INLINE std::uint8_t zz(std::uint8_t v, unsigned bits) {
386 const unsigned mask = (1u << bits) - 1;
387 return static_cast<std::uint8_t>(((v >> 1) ^ ((v & 1) ? mask : 0u)) & mask);
388}
389
390constexpr std::uint8_t mask_of(unsigned bits) {
391 return static_cast<std::uint8_t>((1u << bits) - 1);
392}
393
394// 2-bit index residuals: one symbol per 2x2 quad.
395BCPACK_INLINE void quads(const std::uint8_t* rank, const std::uint8_t* s, std::uint8_t* ix) {
396 for (unsigned q = 0; q < 4; ++q) {
397 const unsigned v = rank[s[q]];
398 const unsigned base = (q >> 1) * 8 + (q & 1) * 2;
399 ix[base + 0] = static_cast<std::uint8_t>(v & 3);
400 ix[base + 1] = static_cast<std::uint8_t>(v >> 2 & 3);
401 ix[base + 4] = static_cast<std::uint8_t>(v >> 4 & 3);
402 ix[base + 5] = static_cast<std::uint8_t>(v >> 6 & 3);
403 }
404}
405
406// 3-bit index residuals: one symbol per two pixels in raster order.
407BCPACK_INLINE void pairs(const std::uint8_t* rank, const std::uint8_t* s, unsigned symbols, std::uint8_t* ix) {
408 for (unsigned k = 0; k < symbols; ++k) {
409 const unsigned v = rank[s[k] & 63];
410 ix[2 * k] = static_cast<std::uint8_t>(v & 7);
411 ix[2 * k + 1] = static_cast<std::uint8_t>(v >> 4 & 7);
412 }
413}
414
415// Indices along the endpoint line -> BC1 and BC4 codes.
416constexpr std::uint32_t kBc1Code[4] = {0, 2, 3, 1};
417constexpr std::uint64_t kBc4Code[8] = {0, 2, 3, 4, 5, 6, 7, 1};
418
419BCPACK_INLINE void bc1_color(const std::uint8_t* ep, const std::uint8_t* ix, std::uint8_t* out) {
420 const auto c0 = static_cast<std::uint16_t>((ep[0] << 11) | (ep[1] << 5) | ep[2]);
421 const auto c1 = static_cast<std::uint16_t>((ep[3] << 11) | (ep[4] << 5) | ep[5]);
422 std::uint32_t bits = 0;
423 for (unsigned p = 0; p < 16; ++p) bits |= kBc1Code[ix[p] & 3] << (2 * p);
424 store_le16(out, c0);
425 store_le16(out + 2, c1);
426 store_le32(out + 4, bits);
427}
428
429// BC4 half: endpoints are kept 128 below their stored value.
430BCPACK_INLINE void bc4_alpha(std::uint8_t e0, std::uint8_t e1, const std::uint8_t* ix, std::uint8_t* out) {
431 std::uint64_t bits = 0;
432 for (unsigned p = 0; p < 16; ++p) bits |= kBc4Code[ix[p] & 7] << (16 + 3 * p);
433 const std::uint64_t v = std::uint64_t{static_cast<std::uint8_t>(e0 ^ 0x80)} |
434 std::uint64_t{static_cast<std::uint8_t>(e1 ^ 0x80)} << 8 | bits;
435 store_le64(out, v);
436}
437
438// The plain formats: the record's residuals, the element widths and the BCn packing.
439struct Bc1 {
440 static constexpr unsigned kBlock = 8;
441 static constexpr bool kPaired = false;
442 static constexpr std::uint8_t kEp[8] = {5, 6, 5, 5, 6, 5, 0, 0};
443 static constexpr unsigned ix_bits(unsigned k) { return k < 16 ? 2 : 0; }
444 static const Plain* dictionary(const Tables& t) { return t.bc1; }
445 static void residual(const Tables& t, const std::uint8_t* s, Plain& v) {
446 constexpr unsigned kBits[6] = {5, 6, 5, 5, 6, 5};
447 for (unsigned k = 0; k < 6; ++k) v.ep[k] = zz(s[2 + k], kBits[k]);
448 quads(t.rank1, s + 8, v.ix);
449 }
450 static void pack(const Plain& v, std::uint8_t* out) { bc1_color(v.ep, v.ix, out); }
451};
452
453struct Bc3 {
454 static constexpr unsigned kBlock = 16;
455 static constexpr bool kPaired = true;
456 static constexpr std::uint8_t kEp[8] = {5, 6, 5, 5, 6, 5, 8, 8};
457 static constexpr unsigned ix_bits(unsigned k) { return k < 16 ? 3 : 2; }
458 static const Plain* dictionary(const Tables& t) { return t.bc3; }
459 static void residual(const Tables& t, const std::uint8_t* s, Plain& v) {
460 // Colour lanes carry each channel's two endpoints together.
461 v.ep[0] = zz(s[14], 5);
462 v.ep[1] = zz(s[16], 6);
463 v.ep[2] = zz(s[18], 5);
464 v.ep[3] = zz(s[15], 5);
465 v.ep[4] = zz(s[17], 6);
466 v.ep[5] = zz(s[19], 5);
467 v.ep[6] = zz(s[4], 8);
468 v.ep[7] = zz(s[5], 8);
469 pairs(t.rank3a, s + 6, 8, v.ix);
470 quads(t.rank3c, s + 20, v.ix + 16);
471 }
472 static void pack(const Plain& v, std::uint8_t* out) {
473 bc4_alpha(v.ep[6], v.ep[7], v.ix, out);
474 bc1_color(v.ep, v.ix + 16, out + 8);
475 }
476};
477
478struct Bc4 {
479 static constexpr unsigned kBlock = 8;
480 static constexpr bool kPaired = false;
481 static constexpr std::uint8_t kEp[8] = {8, 8, 0, 0, 0, 0, 0, 0};
482 static constexpr unsigned ix_bits(unsigned k) { return k < 16 ? 3 : 0; }
483 static const Plain* dictionary(const Tables& t) { return t.bc4; }
484 static void residual(const Tables& t, const std::uint8_t* s, Plain& v) {
485 v.ep[0] = zz(s[2], 8);
486 v.ep[1] = zz(s[3], 8);
487 pairs(t.rank4, s + 4, 8, v.ix);
488 }
489 static void pack(const Plain& v, std::uint8_t* out) { bc4_alpha(v.ep[0], v.ep[1], v.ix, out); }
490};
491
492struct Bc5 {
493 static constexpr unsigned kBlock = 16;
494 static constexpr bool kPaired = true;
495 static constexpr std::uint8_t kEp[8] = {8, 8, 8, 8, 0, 0, 0, 0};
496 static constexpr unsigned ix_bits(unsigned) { return 3; }
497 static const Plain* dictionary(const Tables& t) { return t.bc5; }
498 static void residual(const Tables& t, const std::uint8_t* s, Plain& v) {
499 for (unsigned k = 0; k < 4; ++k) v.ep[k] = zz(s[4 + k], 8);
500 pairs(t.rank5, s + 8, 16, v.ix);
501 }
502 static void pack(const Plain& v, std::uint8_t* out) {
503 bc4_alpha(v.ep[0], v.ep[1], v.ix, out);
504 bc4_alpha(v.ep[2], v.ep[3], v.ix + 16, out + 8);
505 }
506};
507
508constexpr Plain kZeroPlain{};
509
510template <class F>
511struct PlainSink {
512 const Tables& t;
513 std::uint8_t* out;
514 std::size_t i = 0;
515 // Only entries of blocks already rebuilt are ever read, so none needs clearing first.
516 Plain history[kHistory];
517
518 PlainSink(const Tables& tables, std::uint8_t* dst) : t(tables), out(dst) {}
519
520 Error operator()(const std::uint8_t* s) {
521 const References r = references(s, F::kPaired);
522 const Plain* dictionary = F::dictionary(t);
523 const std::uint8_t* ep_ref = pick(i, r.ep, history, dictionary, kZeroPlain).ep;
524 const std::uint8_t* ix_ref = pick(i, r.ix, history, dictionary, kZeroPlain).ix;
525 Plain v{};
526 F::residual(t, s, v);
527 for (unsigned k = 0; k < 8; ++k)
528 v.ep[k] = static_cast<std::uint8_t>((v.ep[k] + ep_ref[k]) & mask_of(F::kEp[k]));
529 for (unsigned k = 0; k < 32; ++k)
530 v.ix[k] = static_cast<std::uint8_t>((v.ix[k] + ix_ref[k]) & mask_of(F::ix_bits(k)));
531 history[i % kHistory] = v;
532 F::pack(v, out);
533 out += F::kBlock;
534 ++i;
535 return nullptr;
536 }
537}; 99};
538 100
539// A byte's even and odd bits as two zigzag-coded 4-bit residuals. 101// Endpoints and indices have independent predictors, with distances limited to
540BCPACK_INLINE void nibbles(unsigned b, bool odd_first, std::int16_t pair[2]) { 102// eight bits.
541 const auto half = [](unsigned v) { 103struct BptcState {
542 return (v & 1) | ((v >> 2 & 1) << 1) | ((v >> 4 & 1) << 2) | ((v >> 6 & 1) << 3); 104 array<int, 24> ep{};
543 }; 105 array<int, 32> ix{};
544 const auto z = [](unsigned u) { return static_cast<std::int16_t>((u >> 1) ^ (0u - (u & 1))); }; 106 int ep_root = -1, ix_root = -1;
545 const std::int16_t even = z(half(b));
546 const std::int16_t odd = z(half(b >> 1));
547 pair[0] = odd_first ? odd : even;
548 pair[1] = odd_first ? even : odd;
549}
550
551// Index residual plus reference, both left-aligned to 16 bits at their own widths, back to `bits` bits (signed).
552BCPACK_INLINE std::int16_t add_index(std::int16_t cur, unsigned bits, std::int16_t ref, unsigned ref_bits) {
553 const auto up = [](std::int16_t v, unsigned b) -> std::uint16_t {
554 return (b == 0 || b > 16) ? 0 : static_cast<std::uint16_t>(static_cast<std::uint16_t>(v) << (16 - b));
555 };
556 const auto sum = static_cast<std::int16_t>(static_cast<std::uint16_t>(up(cur, bits) + up(ref, ref_bits)));
557 return bits == 0 ? std::int16_t{0} : static_cast<std::int16_t>(sum >> (16 - bits));
558}
559
560// Little-endian bit writer for one 128-bit block; bits past 128 are dropped.
561struct Bits {
562 std::uint64_t lo = 0;
563 std::uint64_t hi = 0;
564 unsigned at = 0;
565
566 BCPACK_INLINE void put(std::uint64_t value, unsigned n) {
567 if (n > 0 && at < 128) {
568 const std::uint64_t v = n >= 64 ? value : value & ((std::uint64_t{1} << n) - 1);
569 if (at < 64) {
570 lo |= v << at;
571 if (at > 0) hi |= v >> (64 - at);
572 } else {
573 hi |= v << (at - 64);
574 }
575 }
576 at += n;
577 }
578
579 BCPACK_INLINE void store(std::uint8_t* out) const {
580 store_le64(out, lo);
581 store_le64(out + 8, hi);
582 }
583}; 107};
584 108int mod_bits(int v, int n) { return v & ((1 << n) - 1); }
585// BC7. 109
586 110void index_row(int a, int b, int row, int bits, const int *ref, int *value,
587// Public BC7 anchor indices: second subset of two; second and third of three. 111 int *history) {
588constexpr std::uint8_t kAnchor2[64] = {15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 112 for (int x = 0; x < 4; ++x) {
589 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 113 const int s = (x < 2 ? a : b) >> ((x % 2) ^ (row < 3));
590 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 114 const int delta =
591 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15}; 115 (s & 1) | ((s >> 1) & 2) | ((s >> 2) & 4) | ((s >> 3) & 8);
592constexpr std::uint8_t kAnchor3A[64] = {3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 116 const int p = 4 * row + x;
593 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 117 value[p] = mod_bits((ref[p] >> (4 - bits)) + unzig(delta), bits);
594 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 118 history[p] = value[p] << (4 - bits);
595 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3}; 119 }
596constexpr std::uint8_t kAnchor3B[64] = {15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 120}
597 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 121
598 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 122bool put_indices(BitWriter &writer, const int *values, int bits,
599 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8}; 123 int anchor1 = -1, int anchor2 = -1) {
600 124 for (int p = 0; p < 16; ++p) {
601// Endpoint bits of R G B A per mode (public), before p-bits and rotation. 125 const int n = bits - (p == 0 || p == anchor1 || p == anchor2);
602constexpr std::uint8_t kBc7Bits[8][4] = {{4, 4, 4, 0}, {6, 6, 6, 0}, {5, 5, 5, 0}, {7, 7, 7, 0}, 126 if (values[p] >> n)
603 {5, 5, 5, 6}, {7, 7, 7, 8}, {7, 7, 7, 7}, {5, 5, 5, 5}}; 127 ++writer.violations;
604// Index bits of the primary and secondary sets per mode. 128 writer.put(values[p], n);
605constexpr std::uint8_t kBc7Index[8][2] = {{3, 0}, {3, 0}, {2, 0}, {2, 0}, {3, 2}, {2, 2}, {4, 0}, {2, 0}}; 129 }
606 130 return true;
607constexpr bool pbits(unsigned mode) { 131}
608 return mode == 0 || mode == 1 || mode == 3 || mode == 6 || mode == 7; 132
609} 133bool bc6(const Symbols &a, const Symbols &b, const BptcState &ep,
610 134 const BptcState &ix, BptcState &next, BitWriter &writer) {
611// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha with the rotated channel. 135 if (a[15] >= 14)
612BCPACK_INLINE void bc7_precision(unsigned ctrl, std::uint8_t p[4]) { 136 return false;
613 const unsigned mode = ctrl & 7; 137 const auto &m = bc6Modes[a[15]];
614 const unsigned rot = ctrl >> 3 & 3; 138 const int partition = min<int>(b[15], 31), base_shift = 16 - m.base;
615 for (unsigned k = 0; k < 4; ++k) p[k] = kBc7Bits[mode][k]; 139 int fields[3][4]{};
616 if (rot != 0) { 140 for (int c = 0; c < 3; ++c) {
617 std::swap(p[3], p[rot - 1]); 141 const int n = m.delta[c], shift = max(0, 6 - n);
618 } else if (pbits(mode)) { 142 const auto *ref = &ep.ep[c * 4];
619 p[0] = static_cast<std::uint8_t>(p[0] + 1); 143 const int w = mod_bits((ref[0] >> base_shift) +
620 } 144 unzig(interleave(a[2 + c], b[2 + c], 8)),
621} 145 m.base);
622 146 const int x = mod_bits(
623void bc7_pack(const Bc7Ep& ep, const Bc7Ix& ix, const std::uint8_t prec[4], std::uint8_t* out) { 147 (ref[1] >> (10 - n)) + unzig(interleave(a[5 + c], b[5 + c], 5)), n);
624 const unsigned ctrl = ep.ctrl; 148 const int y = mod_bits((ref[2] >> shift) + unzig(a[8 + c]), n);
625 const unsigned mode = ctrl & 7; 149 const int z = mod_bits((ref[3] >> shift) + unzig(b[8 + c]), n);
626 const unsigned subsets = (ctrl & 0xff) >> 6; 150 auto *state = &next.ep[c * 4];
627 const unsigned part = ctrl >> 8 & 63; 151 state[0] = w << base_shift;
628 const unsigned rot = ctrl >> 3 & 3; 152 state[1] = x << (10 - n);
629 Bits w; 153 if (m.regions == 2) {
630 w.put(std::uint64_t{1} << mode, mode + 1); 154 state[2] = y << shift;
631 switch (mode) { 155 state[3] = z << shift;
632 case 0:
633 w.put(part, 4);
634 break;
635 case 1:
636 case 2:
637 case 3:
638 case 7:
639 w.put(part, 6);
640 break;
641 case 4:
642 w.put(rot, 2);
643 w.put(ctrl >> 5 & 1, 1);
644 break;
645 case 5:
646 w.put(rot, 2);
647 break;
648 default:
649 break;
650 }
651 const unsigned ends = 2 * subsets;
652 // A precision of 0 would shift by 16; VIctory's release build shifts by 0 there (the shift count wraps), and so
653 // does this. No control code of the pinned tables gets there.
654 const auto field = [&](unsigned row, unsigned col, unsigned p) -> std::uint64_t {
655 return static_cast<unsigned>(ep.rows[row][col]) >> ((16 - p) & 15);
656 };
657 unsigned order[4] = {0, 1, 2, 3};
658 if (rot != 0) std::swap(order[3], order[rot - 1]);
659 for (const unsigned ch : order) {
660 const unsigned p = prec[ch];
661 if (p == 0) continue;
662 const unsigned drop = (ch == 0 && pbits(mode)) ? 1 : 0;
663 for (unsigned e = 0; e < ends; ++e) w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, p - drop);
664 }
665 if (mode == 1) {
666 for (unsigned row = 0; row < subsets; ++row) w.put(field(row, 0, prec[0]) & 1, 1);
667 } else if (pbits(mode)) {
668 for (unsigned e = 0; e < ends; ++e) w.put(field(e / 2, e % 2, prec[0]) & 1, 1);
669 }
670 unsigned anchors[3] = {0, 0, 0};
671 unsigned count = 1;
672 if (subsets == 2) {
673 anchors[1] = kAnchor2[part];
674 count = 2;
675 } else if (subsets == 3) {
676 anchors[1] = kAnchor3A[part];
677 anchors[2] = kAnchor3B[part];
678 count = 3;
679 }
680 const auto indices = [&](unsigned set) {
681 const unsigned bits = ix.bits[set];
682 for (unsigned p = 0; p < 16; ++p) {
683 bool anchor = false;
684 for (unsigned a = 0; a < count; ++a) anchor = anchor || anchors[a] == p;
685 w.put(static_cast<std::uint16_t>(ix.ix[set][p]), bits - (anchor ? 1 : 0));
686 }
687 };
688 if (mode == 4) {
689 indices(1);
690 indices(0);
691 } else if (mode == 5) {
692 indices(0);
693 indices(1);
694 } else { 156 } else {
695 indices(0); 157 const int v = mod_bits(w, n) ^ (m.transformed << (n - 1));
696 } 158 state[2] = n >= 6 ? v >> (n - 6) : v << shift;
697 w.store(out); 159 state[3] = state[1] >> 4;
698} 160 }
699 161 fields[c][0] = w;
700constexpr Bc7Entry kZeroBc7{}; 162 if (a[15] >= 12) {
701 163 fields[c][0] &= 1023;
702struct Bc7Sink { 164 for (int bit = 10; bit < m.base; ++bit)
703 const Tables& t; 165 fields[c][0] |= ((w >> bit) & 1) << (m.base + 9 - bit);
704 std::uint8_t* out; 166 }
705 std::size_t i = 0; 167 fields[c][1] = x;
706 Bc7Entry history[kHistory]; 168 fields[c][2] = y;
707 169 fields[c][3] = z;
708 Bc7Sink(const Tables& tables, std::uint8_t* dst) : t(tables), out(dst) {} 170 }
709 171 writer.put(m.code, m.code < 2 ? 2 : 5);
710 Error operator()(const std::uint8_t* s) { 172 for (int j = 0; j < m.count; ++j) {
711 const References r = references(s, true); 173 const auto &f = bc6Plan[m.first + j];
712 const unsigned ctrl = t.ctrl7[(s[31] & 15u) << 5 | (s[30] & 31u)]; 174 writer.put((f[0] < 0 ? partition : fields[f[0]][f[1]]) >> f[2], 1);
713 if (ctrl == 0) return "unused BC7 control code"; 175 }
714 const unsigned mode = ctrl & 7; 176 int values[16];
715 const unsigned subsets = (ctrl & 0xff) >> 6; 177 const int bits = m.regions == 2 ? 3 : 4;
716 std::uint8_t prec[4]; 178 for (int y = 0; y < 4; ++y)
717 bc7_precision(ctrl, prec); 179 index_row(a[11 + y], b[11 + y], y, bits, ix.ix.data(), values,
718 const bool three = subsets == 3; 180 next.ix.data());
719 const std::uint8_t or0_10 = three ? 0 : s[10], or0_11 = three ? 0 : s[11]; 181 return put_indices(writer, values, bits,
720 const std::uint8_t or0_18 = three ? 0 : s[18], or0_19 = three ? 0 : s[19]; 182 m.regions == 2 ? anchor2[partition] : -1);
721 const std::uint8_t if3_10 = three ? s[10] : 0, if3_11 = three ? s[11] : 0; 183}
722 const std::uint8_t if3_18 = three ? s[18] : 0, if3_19 = three ? s[19] : 0; 184
723 const std::uint8_t stored[3][8] = { 185bool bc7(const Symbols &a, const Symbols &b, const BptcState &ep,
724 {s[4], s[5], s[6], s[7], s[8], s[9], or0_10, or0_11}, 186 const BptcState &ix, BptcState &next, BitWriter &writer) {
725 {s[12], s[13], s[14], s[15], s[16], s[17], or0_18, or0_19}, 187 if (a[15] >= 32 || b[15] >= 16)
726 {s[20], s[21], if3_10, if3_11, if3_18, if3_19, 0, 0}, 188 return false;
727 }; 189 const auto &cfg = bc7Config[a[15] * 16 + b[15]];
728 const Bc7Ep& rep = pick(i, r.ep, history, t.bc7, kZeroBc7).ep; 190 const auto [tag, part, rot, isel] = cfg;
729 Bc7Entry entry{}; 191 const int mode = tag & 127;
730 entry.ep.ctrl = static_cast<std::uint16_t>(ctrl); 192 if (mode > 7 || part >= 64)
731 // Rows the reference lacks build on its first row. 193 return false;
732 const unsigned common = std::min(subsets, (rep.ctrl & 0xffu) >> 6); 194 const auto &f = bc7_formats[mode];
733 const unsigned columns = prec[3] > 0 ? 8 : 6; 195 int widths[4] = {f.color, f.color, f.color, f.alpha};
734 for (unsigned c = 0; c < columns; ++c) { 196 if (rot)
735 const unsigned p = prec[c / 2]; 197 swap(widths[rot - 1], widths[3]);
736 if (p == 0) continue; 198 constexpr int lane[3][4] = {{2, 3, 4, 5}, {6, 7, 8, 9}, {10, 5, 9, -1}};
737 const auto mask = static_cast<std::uint16_t>(0xffffu << (16 - p)); 199 int v[3][2][4]{};
738 for (unsigned row = 0; row < subsets; ++row) { 200 for (int sub = 0; sub < f.subsets; ++sub) {
739 const unsigned v = stored[row][c]; 201 for (int end = 0; end < 2; ++end) {
740 const auto residual = static_cast<std::uint16_t>(((v >> 1) ^ ((v & 1) ? 0xffffu : 0u)) << (16 - p)); 202 for (int c = 0; c < 4; ++c) {
741 const auto base = static_cast<std::uint16_t>(rep.rows[row < common ? row : 0][c] & mask); 203 if (!widths[c] || lane[sub][c] < 0)
742 entry.ep.rows[row][c] = static_cast<std::uint16_t>(base + residual); 204 continue;
743 } 205 const int n = widths[c] + (f.pbits && c == 0);
744 } 206 const int k = 8 * sub + 4 * end + c;
745 const std::uint8_t* bits = kBc7Index[mode]; 207 v[sub][end][c] = mod_bits(
746 const Bc7Ix& rx = pick(i, r.ix, history, t.bc7, kZeroBc7).ix; 208 (ep.ep[k] >> (8 - n)) + unzig((end ? b : a)[lane[sub][c]]), n);
747 entry.ix.bits[0] = bits[0]; 209 next.ep[k] = v[sub][end][c] << (8 - n);
748 entry.ix.bits[1] = bits[1]; 210 }
749 constexpr unsigned kOffsets[2][4] = {{22, 24, 26, 28}, {12, 14, 16, 20}}; 211 }
750 for (unsigned set = 0; set < 2; ++set) { 212 if (f.pbits == 2 && ((v[sub][0][0] ^ v[sub][1][0]) & 1))
751 if (bits[set] == 0) continue; 213 ++writer.violations;
752 for (unsigned k = 0; k < 4; ++k) { 214 }
753 const unsigned o = kOffsets[set][k]; 215 for (int sub = f.subsets; sub < 3; ++sub)
754 for (unsigned b = 0; b < 2; ++b) { 216 copy_n(next.ep.begin(), 8, next.ep.begin() + 8 * sub);
755 std::int16_t pair[2]; 217 int primary[16], secondary[16];
756 nibbles(s[o + b], k < 3, pair); 218 constexpr int second_rows[] = {6, 7, 8, 10};
757 for (unsigned h = 0; h < 2; ++h) { 219 const bool two = mode == 4 || mode == 5;
758 const unsigned p = 4 * k + 2 * b + h; 220 for (int y = 0; y < 4; ++y) {
759 entry.ix.ix[set][p] = add_index(pair[h], bits[set], rx.ix[set][p], rx.bits[set]); 221 index_row(a[11 + y], b[11 + y], y, f.index, ix.ix.data(), primary,
760 } 222 next.ix.data());
761 } 223 if (two)
762 } 224 index_row(a[second_rows[y]], b[second_rows[y]], y, 2, ix.ix.data() + 16,
763 } 225 secondary, next.ix.data() + 16);
764 history[i % kHistory] = entry; 226 }
765 bc7_pack(entry.ep, entry.ix, prec, out); 227 if (mode == 0 && part == 0 &&
766 out += 16; 228 ranges::all_of(next.ep, [](int v) { return !v; }) &&
767 ++i; 229 ranges::all_of(primary, [](int v) { return !v; }))
768 return nullptr;
769 }
770};
771
772// BC6H.
773
774// Bits of endpoint 0, then of the other endpoints' R, G, B, per mode 1-14.
775constexpr std::uint8_t kBc6Bits[15][4] = {{0, 0, 0, 0}, {10, 5, 5, 5}, {7, 6, 6, 6}, {11, 5, 4, 4},
776 {11, 4, 5, 4}, {11, 4, 4, 5}, {9, 5, 5, 5}, {8, 6, 5, 5},
777 {8, 5, 6, 5}, {8, 5, 5, 6}, {6, 6, 6, 6}, {10, 10, 10, 10},
778 {11, 9, 9, 9}, {12, 8, 8, 8}, {16, 4, 4, 4}};
779
780// Mode code and its width, modes 1-14.
781struct Bc6Code {
782 std::uint8_t code;
783 std::uint8_t bits;
784};
785constexpr Bc6Code kBc6Code[15] = {{0, 0}, {0, 2}, {1, 2}, {2, 5}, {6, 5}, {10, 5}, {14, 5}, {18, 5},
786 {22, 5}, {26, 5}, {30, 5}, {3, 5}, {7, 5}, {11, 5}, {15, 5}};
787
788// A run of the public BC6H layout: `len` bits of channel `ch` (0-2; 3 is the partition) of endpoint `ep`, from bit
789// `first` up.
790struct Run {
791 std::uint8_t ch;
792 std::uint8_t ep;
793 std::uint8_t first;
794 std::uint8_t len;
795};
796
797// The header after the mode bits, per mode 1-14 (mode m's runs are kBc6Runs[kBc6RunStart[m] ..
798// kBc6RunStart[m + 1]]). Modes 13 and 14 write the high base bits in ascending order (what the console's packer
799// does). Generated from VIctory's BC6_LAYOUT; every mode's mode bits, runs and indices add up to 128 bits.
800constexpr Run kBc6Runs[246] = {
801 // mode 1
802 {1, 2, 4, 1}, {2, 2, 4, 1}, {2, 3, 4, 1}, {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 5},
803 {1, 3, 4, 1}, {1, 2, 0, 4}, {1, 1, 0, 5}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 5}, {2, 3, 1, 1}, {2, 2, 0, 4},
804 {0, 2, 0, 5}, {2, 3, 2, 1}, {0, 3, 0, 5}, {2, 3, 3, 1}, {3, 0, 0, 5},
805 // mode 2
806 {1, 2, 5, 1}, {1, 3, 4, 1}, {1, 3, 5, 1}, {0, 0, 0, 7}, {2, 3, 0, 1}, {2, 3, 1, 1}, {2, 2, 4, 1}, {1, 0, 0, 7},
807 {2, 2, 5, 1}, {2, 3, 2, 1}, {1, 2, 4, 1}, {2, 0, 0, 7}, {2, 3, 3, 1}, {2, 3, 5, 1}, {2, 3, 4, 1}, {0, 1, 0, 6},
808 {1, 2, 0, 4}, {1, 1, 0, 6}, {1, 3, 0, 4}, {2, 1, 0, 6}, {2, 2, 0, 4}, {0, 2, 0, 6}, {0, 3, 0, 6}, {3, 0, 0, 5},
809 // mode 3
810 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 5}, {0, 0, 10, 1}, {1, 2, 0, 4}, {1, 1, 0, 4},
811 {1, 0, 10, 1}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 4}, {2, 0, 10, 1}, {2, 3, 1, 1}, {2, 2, 0, 4}, {0, 2, 0, 5},
812 {2, 3, 2, 1}, {0, 3, 0, 5}, {2, 3, 3, 1}, {3, 0, 0, 5},
813 // mode 4
814 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 4}, {0, 0, 10, 1}, {1, 3, 4, 1}, {1, 2, 0, 4},
815 {1, 1, 0, 5}, {1, 0, 10, 1}, {1, 3, 0, 4}, {2, 1, 0, 4}, {2, 0, 10, 1}, {2, 3, 1, 1}, {2, 2, 0, 4}, {0, 2, 0, 4},
816 {2, 3, 0, 1}, {2, 3, 2, 1}, {0, 3, 0, 4}, {1, 2, 4, 1}, {2, 3, 3, 1}, {3, 0, 0, 5},
817 // mode 5
818 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 4}, {0, 0, 10, 1}, {2, 2, 4, 1}, {1, 2, 0, 4},
819 {1, 1, 0, 4}, {1, 0, 10, 1}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 5}, {2, 0, 10, 1}, {2, 2, 0, 4}, {0, 2, 0, 4},
820 {2, 3, 1, 1}, {2, 3, 2, 1}, {0, 3, 0, 4}, {2, 3, 4, 1}, {2, 3, 3, 1}, {3, 0, 0, 5},
821 // mode 6
822 {0, 0, 0, 9}, {2, 2, 4, 1}, {1, 0, 0, 9}, {1, 2, 4, 1}, {2, 0, 0, 9}, {2, 3, 4, 1}, {0, 1, 0, 5}, {1, 3, 4, 1},
823 {1, 2, 0, 4}, {1, 1, 0, 5}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 5}, {2, 3, 1, 1}, {2, 2, 0, 4}, {0, 2, 0, 5},
824 {2, 3, 2, 1}, {0, 3, 0, 5}, {2, 3, 3, 1}, {3, 0, 0, 5},
825 // mode 7
826 {0, 0, 0, 8}, {1, 3, 4, 1}, {2, 2, 4, 1}, {1, 0, 0, 8}, {2, 3, 2, 1}, {1, 2, 4, 1}, {2, 0, 0, 8}, {2, 3, 3, 1},
827 {2, 3, 4, 1}, {0, 1, 0, 6}, {1, 2, 0, 4}, {1, 1, 0, 5}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 5}, {2, 3, 1, 1},
828 {2, 2, 0, 4}, {0, 2, 0, 6}, {0, 3, 0, 6}, {3, 0, 0, 5},
829 // mode 8
830 {0, 0, 0, 8}, {2, 3, 0, 1}, {2, 2, 4, 1}, {1, 0, 0, 8}, {1, 2, 5, 1}, {1, 2, 4, 1}, {2, 0, 0, 8}, {1, 3, 5, 1},
831 {2, 3, 4, 1}, {0, 1, 0, 5}, {1, 3, 4, 1}, {1, 2, 0, 4}, {1, 1, 0, 6}, {1, 3, 0, 4}, {2, 1, 0, 5}, {2, 3, 1, 1},
832 {2, 2, 0, 4}, {0, 2, 0, 5}, {2, 3, 2, 1}, {0, 3, 0, 5}, {2, 3, 3, 1}, {3, 0, 0, 5},
833 // mode 9
834 {0, 0, 0, 8}, {2, 3, 1, 1}, {2, 2, 4, 1}, {1, 0, 0, 8}, {2, 2, 5, 1}, {1, 2, 4, 1}, {2, 0, 0, 8}, {2, 3, 5, 1},
835 {2, 3, 4, 1}, {0, 1, 0, 5}, {1, 3, 4, 1}, {1, 2, 0, 4}, {1, 1, 0, 5}, {2, 3, 0, 1}, {1, 3, 0, 4}, {2, 1, 0, 6},
836 {2, 2, 0, 4}, {0, 2, 0, 5}, {2, 3, 2, 1}, {0, 3, 0, 5}, {2, 3, 3, 1}, {3, 0, 0, 5},
837 // mode 10
838 {0, 0, 0, 6}, {1, 3, 4, 1}, {2, 3, 0, 1}, {2, 3, 1, 1}, {2, 2, 4, 1}, {1, 0, 0, 6}, {1, 2, 5, 1}, {2, 2, 5, 1},
839 {2, 3, 2, 1}, {1, 2, 4, 1}, {2, 0, 0, 6}, {1, 3, 5, 1}, {2, 3, 3, 1}, {2, 3, 5, 1}, {2, 3, 4, 1}, {0, 1, 0, 6},
840 {1, 2, 0, 4}, {1, 1, 0, 6}, {1, 3, 0, 4}, {2, 1, 0, 6}, {2, 2, 0, 4}, {0, 2, 0, 6}, {0, 3, 0, 6}, {3, 0, 0, 5},
841 // mode 11
842 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 10}, {1, 1, 0, 10}, {2, 1, 0, 10},
843 // mode 12
844 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 9}, {0, 0, 10, 1}, {1, 1, 0, 9}, {1, 0, 10, 1},
845 {2, 1, 0, 9}, {2, 0, 10, 1},
846 // mode 13
847 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 8}, {0, 0, 10, 2}, {1, 1, 0, 8}, {1, 0, 10, 2},
848 {2, 1, 0, 8}, {2, 0, 10, 2},
849 // mode 14
850 {0, 0, 0, 10}, {1, 0, 0, 10}, {2, 0, 0, 10}, {0, 1, 0, 4}, {0, 0, 10, 6}, {1, 1, 0, 4}, {1, 0, 10, 6},
851 {2, 1, 0, 4}, {2, 0, 10, 6},
852};
853constexpr std::uint16_t kBc6RunStart[16] = {0, 0, 20, 44, 63, 84, 105, 125, 145, 167, 189, 213, 219, 228, 237, 246};
854
855constexpr bool bc6_layout_fills_128_bits() {
856 for (unsigned mode = 1; mode <= 14; ++mode) {
857 unsigned n = kBc6Code[mode].bits + (mode < 11 ? 46 : 63);
858 for (unsigned r = kBc6RunStart[mode]; r < kBc6RunStart[mode + 1]; ++r) n += kBc6Runs[r].len;
859 if (n != 128) return false;
860 }
861 return true; 230 return true;
862}
863static_assert(bc6_layout_fills_128_bits());
864
865constexpr unsigned bc6_index_bits(unsigned mode) {
866 return mode >= 1 && mode <= 10 ? 3 : mode >= 11 && mode <= 14 ? 4 : 0;
867}
868
869constexpr Bc6Entry kZeroBc6{{}, {11, {}}};
870 231
871struct Bc6Sink { 232 writer.put(1 << mode, mode + 1);
872 const Tables& t; 233 writer.put(part, f.partition);
873 std::uint8_t* out; 234 if (two)
874 std::size_t i = 0; 235 writer.put(rot, 2);
875 Bc6Entry history[kHistory]; 236 if (mode == 4)
876 237 writer.put(isel, 1);
877 Bc6Sink(const Tables& tables, std::uint8_t* dst) : t(tables), out(dst) {} 238 for (int c = 0; c < 4; ++c) {
878 239 const int src = rot && c == rot - 1 ? 3 : rot && c == 3 ? rot - 1 : c;
879 static std::uint16_t z(unsigned v) { return static_cast<std::uint16_t>((v >> 1) ^ (0u - (v & 1))); } 240 for (int sub = 0; sub < f.subsets; ++sub)
880 241 for (int end = 0; end < 2; ++end)
881 static unsigned wide(unsigned a, unsigned b) { 242 writer.put(v[sub][end][src] >> (f.pbits && src == 0),
882 unsigned acc = 0; 243 c == 3 ? f.alpha : f.color);
883 for (unsigned k = 0; k < 8; ++k) acc |= (a >> k & 1) << (2 * k) | (b >> k & 1) << (2 * k + 1); 244 }
884 return acc; 245 if (f.pbits) {
885 } 246 for (int sub = 0; sub < f.subsets; ++sub)
886 247 for (int end = 0; end < (f.pbits == 1 ? 2 : 1); ++end)
887 Error operator()(const std::uint8_t* s) { 248 writer.put(v[sub][end][0], 1);
888 const References r = references(s, true); 249 }
889 const auto mode = static_cast<std::uint8_t>(s[30] + 1); 250 const int anc1 = f.subsets == 2 ? anchor2[part]
890 if (mode < 1 || mode > 14) return "BC6H mode out of range"; 251 : f.subsets == 3 ? anchor3a[part]
891 const bool two = mode < 11; 252 : -1;
892 unsigned shift[4]; 253 const int anc2 = f.subsets == 3 ? anchor3b[part] : -1;
893 for (unsigned k = 0; k < 4; ++k) shift[k] = 16u - kBc6Bits[mode][k]; 254 if (mode == 4)
894 std::uint16_t res[4][3]; 255 return put_indices(writer, secondary, 2) &&
895 for (unsigned c = 0; c < 3; ++c) { 256 put_indices(writer, primary, f.index);
896 res[0][c] = z(wide(s[4 + 2 * c], s[5 + 2 * c])); 257 return put_indices(writer, primary, f.index, anc1, anc2) &&
897 res[1][c] = z(wide(s[10 + 2 * c], s[11 + 2 * c])); 258 (!two || put_indices(writer, secondary, 2));
898 // Only the two-region modes use the residuals of endpoints 2 and 3. 259}
899 res[2][c] = z(s[16 + 2 * c]); 260
900 res[3][c] = z(s[17 + 2 * c]); 261// A predictor can influence later blocks through either independent reference
901 } 262// chain. A bit-depth gap discovered during the first 256 blocks also affects
902 const Bc6Ep& rep = pick(i, r.ep, history, t.bc6, kZeroBc6).ep; 263// earlier uses of the slot.
903 Bc6Entry entry{}; 264struct Coverage {
904 // Endpoint 0 at the base precision, the others per channel; the reference is cut by the mask after the sum. 265 array<bool, 256> missing_ep{}, missing_ix{};
905 const auto mask = [](unsigned sh) { return static_cast<std::uint16_t>(0xffffu << sh); }; 266 size_t lost{}, inconsistent{}, limit{};
906 for (unsigned c = 0; c < 3; ++c) 267 bool lost_endpoints{}, lost_indices{};
907 entry.ep.e[0][c] = static_cast<std::uint16_t>( 268 void note_missing(const BptcState &block) {
908 (rep.e[0][c] + static_cast<std::uint16_t>(res[0][c] << shift[0])) & mask(shift[0])); 269 const bool ep = block.ep_root >= 0 && missing_ep[block.ep_root];
909 const unsigned others = two ? 3 : 1; 270 const bool ix = block.ix_root >= 0 && missing_ix[block.ix_root];
910 for (unsigned k = 1; k <= others; ++k) 271 lost += ep || ix;
911 for (unsigned c = 0; c < 3; ++c) 272 lost_endpoints |= ep;
912 entry.ep.e[k][c] = static_cast<std::uint16_t>( 273 lost_indices |= ix;
913 (rep.e[k][c] + static_cast<std::uint16_t>(res[k][c] << shift[1 + c])) & mask(shift[1 + c])); 274 }
914 if (!two) {
915 for (unsigned c = 0; c < 3; ++c)
916 entry.ep.e[2][c] = static_cast<std::uint16_t>((entry.ep.e[0][c] >> shift[0]) << shift[1]);
917 for (unsigned c = 0; c < 3; ++c) entry.ep.e[3][c] = entry.ep.e[1][c];
918 }
919 const Bc6Ix& rx = pick(i, r.ix, history, t.bc6, kZeroBc6).ix;
920 const unsigned bits = bc6_index_bits(mode);
921 const unsigned ref_bits = bc6_index_bits(rx.mode);
922 entry.ix.mode = mode;
923 for (unsigned k = 0; k < 8; ++k) {
924 std::int16_t pair[2];
925 nibbles(s[22 + k], k < 6, pair);
926 for (unsigned h = 0; h < 2; ++h) {
927 const unsigned p = 2 * k + h;
928 entry.ix.ix[p] = add_index(pair[h], bits, rx.ix[p], ref_bits);
929 }
930 }
931 history[i % kHistory] = entry;
932 // Fields: the working value has its top bit flipped.
933 const auto field = [&](unsigned k, unsigned c) -> std::uint64_t {
934 const unsigned sh = k == 0 ? shift[0] : shift[1 + c];
935 return static_cast<std::uint16_t>(entry.ep.e[k][c] ^ 0x8000) >> sh;
936 };
937 Bits w;
938 w.put(kBc6Code[mode].code, kBc6Code[mode].bits);
939 const unsigned part = s[31] & 31u;
940 for (unsigned n = kBc6RunStart[mode]; n < kBc6RunStart[mode + 1]; ++n) {
941 const Run& run = kBc6Runs[n];
942 if (run.ch == 3) {
943 w.put(part, 5);
944 } else {
945 w.put(field(run.ep, run.ch) >> run.first, run.len);
946 }
947 }
948 const unsigned anchor = two ? kAnchor2[part] : 0;
949 for (unsigned p = 0; p < 16; ++p) {
950 const bool short_index = p == 0 || p == anchor;
951 const auto v = static_cast<std::uint16_t>(static_cast<std::uint16_t>(entry.ix.ix[p]) + (1u << (bits - 1)));
952 w.put(v, bits - (short_index ? 1 : 0));
953 }
954 w.store(out);
955 out += 16;
956 ++i;
957 return nullptr;
958 }
959};
960
961// A record per block, for unpack_records.
962template <unsigned Stride>
963struct RecordSink {
964 std::uint8_t* out;
965 Error operator()(const std::uint8_t* record) {
966 std::memcpy(out, record, Stride);
967 out += Stride;
968 return nullptr;
969 }
970}; 275};
971 276
972// One format's decode, in a function of its own so that only its history is on the stack. 277bool rebuild_bptc(unsigned codec, size_t i, size_t blocks, const Symbols &a,
973template <unsigned N, unsigned Per, class Sink> 278 const Symbols &b, array<BptcState, 256> &past, uint8_t *dest,
974BCPACK_NOINLINE Error decode_as(const Tables& t, const std::uint8_t* widths, std::size_t blocks, 279 const Calibration *history, bool allow_fitted,
975 const std::uint8_t* src, std::size_t src_size, std::uint8_t* dst) { 280 Quality &quality, Coverage &coverage, const char*& reason) {
976 BufferFetch fetch{src, src + src_size}; 281 const unsigned di = interleave(a[1], b[1]);
977 Sink sink(t, dst); 282 const unsigned de = (di + unzig(interleave(a[0], b[0]))) & 255;
978 return run_lanes<N, Per>(t, widths, blocks, fetch, sink); 283 if ((di > i || de > i) && !history) {
979} 284 reason = "missing-profile";
980 285 return false;
981} // namespace 286 }
982 287 const int islot = di > i ? int(256 + i - di) : -1;
983TablesPtr parse_tables(const std::uint8_t* bytes, std::size_t size, Error* error) { 288 const int eslot = de > i ? int(256 + i - de) : -1;
984 const auto fail = [&](Error why) { 289 bool fitted = false;
985 if (error) *error = why; 290 BptcState zero{};
986 return TablesPtr(); 291 if (codec == 6) {
987 }; 292 for (int c = 0; c < 3; ++c) {
988 if (!bytes || size != kTablesSize) return fail("table file has the wrong size"); 293 zero.ep[4 * c] = 32768;
989 std::unique_ptr<Tables> t(new (std::nothrow) Tables()); 294 zero.ep[4 * c + 1] = 512;
990 if (!t) return fail("out of memory for the tables"); 295 zero.ep[4 * c + 2] = zero.ep[4 * c + 3] = 32;
991 const std::uint8_t* p = bytes; 296 }
992 const auto u8 = [&p] { return *p++; }; 297 zero.ix.fill(8);
993 const auto u16 = [&p] { 298 }
994 const auto v = static_cast<std::uint16_t>(p[0] | p[1] << 8); 299 if (codec == 6) {
995 p += 2; 300 if (a[15] >= 14)
996 return v; 301 return false;
997 }; 302 const auto &m = bc6Modes[a[15]];
998 for (unsigned m = 0; m < kModels; ++m) { 303 if (eslot >= 0) {
999 Model& model = t->models[m]; 304 const auto &row = history->bc6[eslot];
1000 std::uint32_t f[kBuckets]; 305 for (int c = 0; c < 3; ++c) {
1001 for (unsigned b = 0; b < kBuckets; ++b) f[b] = u16(); 306 const int needs[] = {m.base, m.delta[c],
1002 // Model 16 g + shape has g + 2 buckets; bucket b > 0 holds 2^(b-1) symbols. 307 m.regions == 2 ? m.delta[c] : 0,
1003 const unsigned used = m / 16 + 2; 308 m.regions == 2 ? m.delta[c] : 0};
1004 std::uint32_t start[kBuckets + 1]; 309 for (int k = 0; k < 4; ++k) {
1005 std::uint32_t at = 0; 310 const int j = 4 * c + k;
1006 for (unsigned b = 0; b < used; ++b) { 311 zero.ep[j] = row.ep[2 * j] | (row.ep[2 * j + 1] << 8);
1007 if (f[b] == 0) return fail("a model has an empty bucket"); 312 fitted |= row.ep_confirmed[j] < needs[k];
1008 start[b] = at;
1009 at += f[b] << (b > 0 ? b - 1 : 0);
1010 }
1011 if (at != 1u << 16) return fail("a model does not tile 65536");
1012 for (unsigned b = used; b <= kBuckets; ++b) start[b] = 1u << 16;
1013 for (unsigned window = 0; window < 256; ++window) {
1014 const std::uint32_t first = window << 8;
1015 unsigned bucket = 0;
1016 for (unsigned b = 1; b <= kBuckets; ++b) bucket += start[b] <= first ? 1 : 0;
1017 model.bucket[window] = static_cast<std::uint8_t>(bucket);
1018 }
1019 for (unsigned b = 0; b <= kBuckets; ++b) model.start[b] = start[b];
1020 for (unsigned b = 0; b < kBuckets; ++b) {
1021 model.freq[b] = f[b];
1022 model.recip[b] = b > 0 && b < used ? ((std::uint64_t{1} << 32) + f[b] - 1) / f[b] : 0;
1023 }
1024 model.start[0] = 1;
1025 model.freq[0] = f[0] - 1;
1026 }
1027 const auto bytes_into = [&p](std::uint8_t* dst, std::size_t n) {
1028 std::memcpy(dst, p, n);
1029 p += n;
1030 };
1031 bytes_into(t->rank1, sizeof t->rank1);
1032 bytes_into(t->rank3a, sizeof t->rank3a);
1033 bytes_into(t->rank3c, sizeof t->rank3c);
1034 bytes_into(t->rank4, sizeof t->rank4);
1035 bytes_into(t->rank5, sizeof t->rank5);
1036 for (std::uint16_t& c : t->ctrl7) c = u16();
1037 const auto plain = [&](Plain* dictionary, unsigned ep, unsigned ix) {
1038 for (unsigned k = 0; k < kDictionary; ++k) {
1039 for (unsigned v = 0; v < ep; ++v) dictionary[k].ep[v] = u8();
1040 for (unsigned v = 0; v < ix; ++v) dictionary[k].ix[v] = u8();
1041 }
1042 };
1043 plain(t->bc1, 6, 16);
1044 plain(t->bc3, 8, 32);
1045 plain(t->bc4, 2, 16);
1046 plain(t->bc5, 4, 32);
1047 for (Bc6Entry& e : t->bc6) {
1048 // The endpoint entry's mode byte plays no part in decoding.
1049 u8();
1050 for (unsigned v = 0; v < 12; ++v) e.ep.e[v / 3][v % 3] = u16();
1051 e.ix.mode = u8();
1052 for (std::int16_t& v : e.ix.ix) v = static_cast<std::int16_t>(u16());
1053 }
1054 for (Bc7Entry& e : t->bc7) {
1055 e.ep.ctrl = u16();
1056 for (unsigned v = 0; v < 24; ++v) e.ep.rows[v / 8][v % 8] = u16();
1057 e.ix.bits[0] = u8();
1058 e.ix.bits[1] = u8();
1059 // Unused: the widths again in all entries but the first.
1060 u16();
1061 // Only 15 slots for set 1, which no entry uses (0 bits).
1062 for (unsigned v = 0; v < 31; ++v) e.ix.ix[v / 16][v % 16] = static_cast<std::int16_t>(u16());
1063 }
1064 if (p != bytes + size) return fail("table layout does not add up");
1065 return TablesPtr(t.release());
1066}
1067
1068bool layout(unsigned bc, Layout* out) {
1069 switch (bc) {
1070 case 1:
1071 *out = {kBc1Lanes, 12, 1, 8};
1072 return true;
1073 case 3:
1074 *out = {kBc3Lanes, 12, 2, 16};
1075 return true;
1076 case 4:
1077 *out = {kBc4Lanes, 12, 1, 8};
1078 return true;
1079 case 5:
1080 *out = {kBc5Lanes, 12, 2, 16};
1081 return true;
1082 case 6:
1083 *out = {kBc6Lanes, 16, 2, 16};
1084 return true;
1085 case 7:
1086 *out = {kBc7Lanes, 16, 2, 16};
1087 return true;
1088 default:
1089 return false;
1090 }
1091}
1092
1093Error decode(unsigned bc, const std::uint8_t* src, std::size_t src_size, std::uint8_t* dst, std::size_t dst_size,
1094 const Tables& tables) {
1095 Layout l{};
1096 if (!layout(bc, &l)) return "unsupported BC format";
1097 if (dst_size == 0 || dst_size % l.block_bytes != 0) return "destination is not a whole number of blocks";
1098 if (!dst) return "no destination";
1099 if (!src && src_size != 0) return "no source";
1100 const std::size_t blocks = dst_size / l.block_bytes;
1101 switch (bc) {
1102 case 1:
1103 return decode_as<12, 1, PlainSink<Bc1>>(tables, l.widths, blocks, src, src_size, dst);
1104 case 3:
1105 return decode_as<12, 2, PlainSink<Bc3>>(tables, l.widths, blocks, src, src_size, dst);
1106 case 4:
1107 return decode_as<12, 1, PlainSink<Bc4>>(tables, l.widths, blocks, src, src_size, dst);
1108 case 5:
1109 return decode_as<12, 2, PlainSink<Bc5>>(tables, l.widths, blocks, src, src_size, dst);
1110 case 6:
1111 return decode_as<16, 2, Bc6Sink>(tables, l.widths, blocks, src, src_size, dst);
1112 default:
1113 return decode_as<16, 2, Bc7Sink>(tables, l.widths, blocks, src, src_size, dst);
1114 }
1115}
1116
1117Error unpack_records(unsigned bc, const Tables& tables, std::size_t blocks, int (*fetch)(void* context, unsigned lane),
1118 void* context, std::uint8_t* records) {
1119 Layout l{};
1120 if (!layout(bc, &l)) return "unsupported BC format";
1121 if (blocks == 0) return nullptr;
1122 if (!fetch || !records) return "no input or no output";
1123 CallbackFetch input{fetch, context};
1124 if (l.lanes == 12 && l.per == 1) {
1125 RecordSink<12> sink{records};
1126 return run_lanes<12, 1>(tables, l.widths, blocks, input, sink);
1127 }
1128 if (l.lanes == 12) {
1129 RecordSink<24> sink{records};
1130 return run_lanes<12, 2>(tables, l.widths, blocks, input, sink);
1131 }
1132 RecordSink<32> sink{records};
1133 return run_lanes<16, 2>(tables, l.widths, blocks, input, sink);
1134}
1135
1136void sha256(const void* data, std::size_t size, std::uint8_t digest[32]) {
1137 static constexpr std::uint32_t k[64] = {
1138 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1139 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1140 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1141 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1142 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1143 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1144 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1145 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
1146 std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
1147 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
1148 const auto compress = [&h](const std::uint8_t* block) {
1149 std::uint32_t w[64];
1150 for (unsigned i = 0; i < 16; ++i)
1151 w[i] = std::uint32_t{block[4 * i]} << 24 | std::uint32_t{block[4 * i + 1]} << 16 |
1152 std::uint32_t{block[4 * i + 2]} << 8 | block[4 * i + 3];
1153 for (unsigned i = 16; i < 64; ++i) {
1154 const std::uint32_t s0 = std::rotr(w[i - 15], 7) ^ std::rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
1155 const std::uint32_t s1 = std::rotr(w[i - 2], 17) ^ std::rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
1156 w[i] = w[i - 16] + s0 + w[i - 7] + s1;
1157 }
1158 std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
1159 for (unsigned i = 0; i < 64; ++i) {
1160 const std::uint32_t t1 =
1161 hh + (std::rotr(e, 6) ^ std::rotr(e, 11) ^ std::rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i];
1162 const std::uint32_t t2 =
1163 (std::rotr(a, 2) ^ std::rotr(a, 13) ^ std::rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
1164 hh = g;
1165 g = f;
1166 f = e;
1167 e = d + t1;
1168 d = c;
1169 c = b;
1170 b = a;
1171 a = t1 + t2;
1172 }
1173 h[0] += a;
1174 h[1] += b;
1175 h[2] += c;
1176 h[3] += d;
1177 h[4] += e;
1178 h[5] += f;
1179 h[6] += g;
1180 h[7] += hh;
1181 };
1182 const auto* bytes = static_cast<const std::uint8_t*>(data);
1183 std::size_t n = size;
1184 for (; n >= 64; n -= 64, bytes += 64) compress(bytes);
1185 std::uint8_t tail[128] = {};
1186 if (n != 0) std::memcpy(tail, bytes, n);
1187 tail[n] = 0x80;
1188 const std::size_t padded = n + 9 <= 64 ? 64 : 128;
1189 const std::uint64_t bit_count = std::uint64_t{size} * 8;
1190 for (unsigned i = 0; i < 8; ++i) tail[padded - 1 - i] = static_cast<std::uint8_t>(bit_count >> (8 * i));
1191 compress(tail);
1192 if (padded == 128) compress(tail + 64);
1193 for (unsigned i = 0; i < 8; ++i)
1194 for (unsigned j = 0; j < 4; ++j) digest[4 * i + j] = static_cast<std::uint8_t>(h[i] >> (24 - 8 * j));
1195}
1196
1197TablesPtr load_tables(const std::filesystem::path& path, std::string* error) {
1198 const auto fail = [&](std::string why) {
1199 if (error) *error = std::move(why);
1200 return TablesPtr();
1201 };
1202 std::ifstream in(path, std::ios::binary);
1203 if (!in) return fail("cannot open " + utf8(path));
1204 // One byte more than the file should hold tells a longer file apart without reading it all.
1205 std::vector<std::uint8_t> bytes(kTablesSize + 1);
1206 in.read(reinterpret_cast<char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
1207 const auto n = static_cast<std::size_t>(in.gcount());
1208 if (n != kTablesSize)
1209 return fail(utf8(path) + " is not the BCPack table file (" +
1210 (n > kTablesSize ? std::string("larger than") : std::to_string(n) + " bytes,") + " expected " +
1211 std::to_string(kTablesSize) + " bytes)");
1212 std::uint8_t digest[32];
1213 sha256(bytes.data(), n, digest);
1214 static constexpr char kHex[] = "0123456789ABCDEF";
1215 std::string hex;
1216 for (const std::uint8_t b : digest) {
1217 hex += kHex[b >> 4];
1218 hex += kHex[b & 15];
1219 }
1220 if (hex != kTablesSha256) return fail(utf8(path) + " has SHA-256 " + hex + ", not the pinned " + kTablesSha256);
1221 Error why = nullptr;
1222 TablesPtr tables = parse_tables(bytes.data(), n, &why);
1223 if (!tables) return fail(utf8(path) + ": " + why);
1224 return tables;
1225}
1226
1227std::filesystem::path tables_path() {
1228#if defined(_WIN32)
1229 std::wstring value(32768, L'\0');
1230 DWORD n = GetEnvironmentVariableW(L"LEONIDA_BCPACK_TABLES", value.data(), static_cast<DWORD>(value.size()));
1231 if (n != 0 && n < value.size()) {
1232 value.resize(n);
1233 return std::filesystem::path(value);
1234 }
1235 std::wstring self(32768, L'\0');
1236 n = GetModuleFileNameW(nullptr, self.data(), static_cast<DWORD>(self.size()));
1237 if (n != 0 && n < self.size()) {
1238 self.resize(n);
1239 return std::filesystem::path(self).parent_path() / kTablesFile;
1240 }
1241 return {};
1242#else
1243 if (const char* value = std::getenv(kTablesVariable); value && *value) return std::filesystem::path(value);
1244 std::error_code ec;
1245 const std::filesystem::path self = std::filesystem::read_symlink("/proc/self/exe", ec);
1246 if (!ec && !self.empty()) return self.parent_path() / kTablesFile;
1247 return {};
1248#endif
1249}
1250
1251const Tables* process_tables() {
1252 // Loaded once, by the first caller, and kept for the life of the process (VIctory's OnceLock).
1253 static const Tables* const tables = [] {
1254 const std::filesystem::path path = tables_path();
1255 std::string why = "cannot find the executable's folder";
1256 TablesPtr loaded;
1257 if (!path.empty()) loaded = load_tables(path, &why);
1258 if (loaded) {
1259 std::fprintf(stderr, "[rt] bcpack: format tables from %s\n", utf8(path).c_str());
1260 } else {
1261 std::fprintf(stderr,
1262 "[rt] bcpack: BCPack requests fail: %s. Set %s to the verified %s (SHA-256 %s) or put it "
1263 "next to the executable (logged once)\n",
1264 why.c_str(), kTablesVariable, kTablesFile, kTablesSha256);
1265 } 313 }
1266 return loaded.release(); 314 }
1267 }(); 315 fitted |= row.ep_class != 3;
1268 return tables; 316 coverage.missing_ep[eslot] |= !row.ep_class;
1269} 317 }
1270 318 if (islot >= 0) {
1271} // namespace rt::bcpack 319 const auto &row = history->bc6[islot];
1272 320 copy(row.ix.begin(), row.ix.end(), zero.ix.begin());
1273bool leonida_bcpack_decode(std::uint32_t format, const std::uint8_t* src, std::size_t src_size, std::uint8_t* dst, 321 fitted |=
1274 std::size_t dst_size) { 322 row.ix_class != 3 || ranges::any_of(row.ix_confirmed, [&](int n) {
1275 const rt::bcpack::Tables* tables = rt::bcpack::process_tables(); 323 return n < (m.regions == 2 ? 3 : 4);
1276 if (!tables) return false; 324 });
1277 const rt::bcpack::Error error = rt::bcpack::decode(format, src, src_size, dst, dst_size, *tables); 325 coverage.missing_ix[islot] |= !row.ix_class;
1278 if (!error) return true; 326 }
1279 // VIctory warns for every failed request; the first few are enough to see what goes wrong. 327 } else {
1280 static std::atomic<unsigned> reported{0}; 328 if (a[15] >= 32 || b[15] >= 16)
1281 if (reported.fetch_add(1, std::memory_order_relaxed) < 16) 329 return false;
1282 std::fprintf(stderr, 330 const auto &cfg = bc7Config[a[15] * 16 + b[15]];
1283 "[rt] bcpack: a BC%u request (%zu bytes packed, %zu decoded) fails: %s (first 16 logged)\n", 331 const unsigned mode = cfg[0] & 127;
1284 format, src_size, dst_size, error); 332 if (mode >= 8 || cfg[1] >= 64)
333 return false;
334 if (cfg[0] & 128)
335 fitted = true;
336 const auto &format = bc7_formats[mode];
337 if (eslot >= 0) {
338 const auto &row = history->bc7[eslot];
339 copy(row.ep.begin(), row.ep.end(), zero.ep.begin());
340 int width[] = {format.color, format.color, format.color, format.alpha};
341 if (cfg[2])
342 swap(width[3], width[cfg[2] - 1]);
343 width[0] += format.pbits != 0;
344 for (int j = 0; j < 8 * format.subsets; ++j) {
345 const int need = width[j % 4];
346 fitted |= row.ep_confirmed[j] < need || row.ep_bits[j] < need;
347 coverage.missing_ep[eslot] |= row.ep_bits[j] < min(need, 4);
348 }
349 }
350 if (islot >= 0) {
351 const auto &row = history->bc7[islot];
352 copy(row.ix.begin(), row.ix.end(), zero.ix.begin());
353 for (int j = 0; j < (mode == 4 || mode == 5 ? 32 : 16); ++j) {
354 int need = j < 16 ? format.index : 2;
355 fitted |= row.ix_confirmed[j] < need || row.ix_bits[j] < need;
356 coverage.missing_ix[islot] |= row.ix_bits[j] < need;
357 }
358 }
359 }
360 if (fitted) {
361 if (!allow_fitted) {
362 reason = "unconfirmed-predictor";
363 return false;
364 }
365 quality = Quality::fitted;
366 }
367 const auto &ep = de && eslot < 0 ? past[(i - de) & 255] : zero;
368 const auto &ix = di && islot < 0 ? past[(i - di) & 255] : zero;
369 auto &next = past[i & 255];
370 next = {};
371 next.ep_root = eslot >= 0 ? eslot : ep.ep_root;
372 next.ix_root = islot >= 0 ? islot : ix.ix_root;
373 fill_n(dest, 16, 0);
374 BitWriter writer{dest};
375 const bool valid = codec == 6 ? bc6(a, b, ep, ix, next, writer)
376 : bc7(a, b, ep, ix, next, writer);
377 coverage.inconsistent +=
378 codec == 6 ? writer.violations : int(writer.violations != 0);
379 if (i + 1 == min<size_t>(256, blocks)) {
380 for (size_t k = 0; k <= i; ++k)
381 coverage.note_missing(past[k]);
382 } else if (i >= 256)
383 coverage.note_missing(next);
384 if (!valid) return false;
385 if (coverage.lost > coverage.limit) {
386 reason = coverage.lost_endpoints && coverage.lost_indices ? "missing-endpoint-and-index" :
387 coverage.lost_endpoints ? "missing-endpoint" : "missing-index";
1285 return false; 388 return false;
1286} 389 }
390 if (coverage.inconsistent > coverage.limit) { reason = "anchor-or-pbit"; return false; }
391 return true;
392}
393} // namespace
394
395Quality decode(unsigned codec, std::span<const uint8_t> source,
396 std::span<uint8_t> output, bool allow_fitted,
397 const Calibration *history, const char** failure, bool fast_entropy) {
398 const char* reason = "bcpack-stream";
399 if (failure) *failure = reason;
400 Quality quality = Quality::confirmed;
401 if (!codec || codec == 2 || codec > 7)
402 return Quality::failed;
403 const bool single = codec == 1 || codec == 4;
404 const unsigned block_size = single ? 8 : 16;
405 if (output.size() % block_size)
406 return Quality::failed;
407 array<Endpoints, 256> classic{};
408 array<BptcState, 256> bptc{};
409 Coverage coverage{};
410 coverage.limit = allow_fitted && history
411 ? max<size_t>(2, output.size() / block_size / 1024)
412 : 0;
413 const bool valid = visit_blocks(codec, source, output.size(), [&](size_t i, const Symbols &first, const Symbols &tuple) {
414 auto *dst = output.data() + i * block_size;
415 if (codec >= 6)
416 return rebuild_bptc(codec, i, output.size() / block_size, first, tuple, bptc, dst, history, allow_fitted, quality, coverage, reason);
417 return rebuild_classic(codec, i, first, tuple, classic, dst, allow_fitted, quality);
418 }, fast_entropy);
419 if (valid && (!coverage.inconsistent || quality == Quality::fitted)) return quality;
420 if (failure) *failure = coverage.inconsistent && valid ? "anchor-or-pbit" : reason;
421 return Quality::failed;
422}
423} // namespace leonida::bcpack