diff --git a/AGENTS.md b/AGENTS.md index 7044b51..21e875a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,12 +16,13 @@ Don't modify this file. - Keep concise code clear: no cryptic names, excessive compression, clever tricks, or obfuscation. - Before adding code, reuse existing logic, remove redundancy, or simplify the design. Prefer deleting code over adding abstractions. -## Comments -- Do not write descriptive comments in .c implementation files. The code must explain itself through clear naming and straightforward logic. -- Do not add comments that restate what the code does, explain obvious implementation details, or introduce sections of code. -- Comments are allowed only when necessary to explain non-obvious reasoning, tricky algorithms, constraints, or workarounds. -- API documentation belongs in the .h header files. Document public functions, types, and parameters there when useful. -- Do not duplicate header documentation in the corresponding .c file. +## Feature efficiency = (Expected benefit % / Added LoC) × 1,000 +* Reject low-ROI changes, even when technically beneficial. +* Prefer skipping a feature over significantly increasing code size for negligible gains. +* Every additional line of code must justify its maintenance and readability cost. +* Avoid speculative features, unnecessary abstractions, and premature generalization. +* Before implementation, report the expected benefit, estimated LoC, and feature efficiency. +* If the ROI is poor, recommend not implementing the change. ## Memory - Libraries: no `malloc`/`free`; prefer caller-provided buffers. If a library needs more than the caller-provided buffer, return an error or a required-size value; don't allocate behind the caller's back. @@ -43,6 +44,14 @@ Don't modify this file. - Never sacrifice correctness or maintainability for unmeasured optimization. - Do not perform or interpret GPU profiling while the LLM is running. Request that the user collect and provide a standalone GPU profile instead. +## Comments +- Do not write descriptive comments in .c implementation files. The code must explain itself through clear naming and straightforward logic. +- Do not add comments that restate what the code does, explain obvious implementation details, or introduce sections of code. +- Comments are allowed only when necessary to explain non-obvious reasoning, tricky algorithms, constraints, or workarounds. +- Keep comments short and local. A comment explains at most one branch and sits on it: on the branch's `if` / `else` line or its first statement, at most 2 lines. A comment above a construct must never describe more than the line it sits on; a self-evident branch gets no comment. +- API documentation belongs in the .h header files. Document public functions, types, and parameters there when useful. +- Do not duplicate header documentation in the corresponding .c file. + ## Build - Config: `cmake -B build -S . -DCMAKE_BUILD_TYPE=Release` - Build: `cmake --build build` diff --git a/README.md b/README.md index a65b87f..740b418 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The compressor is CPU-side and can use significantly more computation than the d | Block type | Average compression from the image suite | |:-----: | :------------: | BC1 | 1.49:1 -| BC4 | 1.14:1 +| [BC4](logs/bc4_zip.md) | 1.36:1 | BC5 | 1.1:1 All compression ratio are better than zlib. @@ -56,7 +56,7 @@ The techniques are adapted to make GPU decompression fast and simple: * **Static symbol ranking.** Symbols are remapped so that the most frequently used symbols have the lowest indices. The rank table is generated from a histogram during compression. * **Parallel decompression.** The texture is divided into 64 independent tiles. 64 GPU threads decompress the tiles in parallel, with no dependency between threads. -Multiple independent Rice-Golomb models are used for the different data: endpoint color deltas (one set of red, green, blue per endpoint, red and blue each with one model per green-delta context bucket, and the second endpoint's green also contextual on the sign of the first endpoint's green — 16 color models, see Endpoints), top-table references, difference masks, and residual difference bytes (19 models in total). +Multiple independent Rice-Golomb models are used for the different data: endpoint color deltas (red and blue each with one model per green-delta context bucket per endpoint, and the second endpoint's green also contextual on the sign of the first endpoint's green — 16 distinct color models on 18 stream slots, see Endpoints), top-table references, difference masks, and residual difference bytes (21 models in total). ### Rice-Golomb model @@ -102,14 +102,14 @@ For example for a 1024x1024 texture : each thread will decode 32 blocks (in widt The 64 tiles lay out the block grid in an even split: tile `s` is `(tx, ty) = (s % gx, s / gx)` with bounds `x0 = tx * width_blocks / gx, x1 = (tx + 1) * width_blocks / gx` and the same for `y`, where `gx` is 8 / 4 / 2 / 1 for `width_blocks` of 32+ / 16+ / 8+ / less and `gy = 64 / gx` (both derived from the width, no header byte, no API change). The even split covers every row and column even when the block grid is not a multiple of the tile size, so images whose height in blocks is not a multiple of the tile row count no longer lose their trailing rows. -As the models are static, each thread just loads the same 19 models from the stream (`le_static_model_load`); the color context is derived from the current block's own decoded green delta, so there is no adaptive state to keep in sync between threads. +As the models are static, each thread just loads the same 21 models from the stream (`le_static_model_load`); the color context is derived from the current block's own decoded green delta, so there is no adaptive state to keep in sync between threads. As Rice encoding output is non-fixed, we stored in the stream 63 offsets (uint16_t), each a delta in dword units relative to the previous tile, so each thread knows where to start (tile 0 always starts the tile data, its implicit zero offset is not stored). ### Endpoints BC1 endpoints are predicted from the previous block's endpoints. -One set of three independent Rice-Golomb models is used per endpoint for the R, G, and B components; red and blue each carry one model per context bucket, and the second endpoint's green does as well (keyed on the sign of the first endpoint's green delta) — 16 color models in total. Each (channel, endpoint, context) model is fitted to the color deltas that occur in its context, so every block is priced by a model that matches its own regime. +One set of three independent Rice-Golomb models is used per endpoint for the R, G, and B components; red and blue each carry one model per context bucket, and the second endpoint's green does as well (keyed on the sign of the first endpoint's green delta) — 16 distinct color models in total (the stream keeps 18 slots: the first endpoint's green is uncontexted, its two extra slots are fixed dummy models, see the stream layout below). Each (channel, endpoint, context) model is fitted to the color deltas that occur in its context, so every block is priced by a model that matches its own regime. For each endpoint of each block: @@ -213,7 +213,7 @@ The 64 tiles are the even split of the block grid (see Multiple streams): `gx` i The output buffer must be at least `packed_bc1_maxsize(width, height)` bytes. This is a very rough bound: `(width/4) * (height/4) * 16`, i.e. 2× the standard BC1 texture size. In practice the stream is much smaller. ```text -* 19 static models, in order: for each endpoint (0, 1): red (3 context buckets), green (3 context buckets), blue (3 context buckets) — 16 color models — then top-table reference, difference mask, table difference. +* 21 static models, in order: for each endpoint (0, 1): red (3 context buckets), green (3 context buckets), blue (3 context buckets) — 18 color model slots, 16 distinct: the first endpoint's green is uncontexted and its two other slots are fixed dummy 1-symbol models — then top-table reference, difference mask, table difference. Each is 3 + num_symbols bytes, no padding (max 259 bytes). * Top table size: one uint8_t (number of entries − 1). * Flat index mode + value: one uint8_t (mode | value << 1), then padded to a 4-byte boundary. See Block indices → Flat blocks. @@ -243,7 +243,7 @@ Within a tile, the blocks are traversed in the zigzag row order. For each block: * Otherwise: top-table reference (8-bit index), difference mask (4 bits), and one difference byte per set mask bit. ``` -See Color-pair dictionary. The six color deltas, the top-table reference, the mask, and the difference bytes are all encoded with Rice-Golomb using one of the 19 static models; each red/blue uses the model of its (channel, endpoint, context) — the three-bucket green delta described in Endpoints — and each green uses the model of its (endpoint, context), the first endpoint uncontexted and the second contextual on the sign of the first endpoint's green delta. The dictionary flag and reference are raw bits, not Rice-Golomb symbols. +See Color-pair dictionary. The six color deltas, the top-table reference, the mask, and the difference bytes are all encoded with Rice-Golomb using one of the 21 static models; each red/blue uses the model of its (channel, endpoint, context) — the three-bucket green delta described in Endpoints — and each green uses the model of its (endpoint, context), the first endpoint uncontexted and the second contextual on the sign of the first endpoint's green delta. The dictionary flag and reference are raw bits, not Rice-Golomb symbols. ======= @@ -277,12 +277,21 @@ other blocks: pred = previous + top - top_previous (mod 256) `previous` is the chain-previous block in the BC1 zigzag order, `top` the block of the row above at the same column, `top_previous` the block above the chain-previous. All references stay inside the tile, so the 64 tiles remain independent. The tile seed is the per-endpoint average of the first block of each tile, stored in the stream header like the BC1 color seed. +#### Endpoint MTF-8 + +Optionally (a flag per channel, bit 4 of the flat-index header byte, decided in the first pass), the two endpoint deltas of a block are replaced by one symbol of a 9-symbol static model: an 8-entry move-to-front list of the last distinct (endpoint0, endpoint1) pairs of the tile's zigzag chain, cleared per tile. Rank 0..7 is the pair at that MTF position (the pair moves to the front); rank 8 is an escape that stores the two wrapped endpoint deltas exactly as above (the predictor is unchanged), and the new pair is inserted at the front of the list. The list is identical on the encoder and the decoder because every decoded pair is the same one, so the state stays in sync. The endpoint models are fitted on the escaped blocks only when the flag is set, on every block otherwise. + +The first pass prices the endpoint histogram with and without MTF (payload bits plus the model headers each stores; a disabled channel writes a dummy 1-symbol MTF model, the stream layout is fixed and the flag is read after the models) and keeps the cheaper per channel — no heuristic. Textures with many repeated endpoint pairs (atlas-style content) switch on, natural textures usually keep the deltas. + ### Indices The 16 3-bit indices of a block are encoded in raster order: ```text -index 0: 3 raw bits (no model) +index 0: the first index, encoded with a static 8-symbol model (one per channel), + replacing the previous raw 3-bit field; the Rice / raw fallback of the + fitter is the self-gate, so a near-uniform first index costs the same + 3 bits as raw and no flag is needed index i: symbol = prediction XOR index[i], encoded with a static 8-symbol Rice-Golomb model prediction = index[i-1] (left) index[i-4] (directly above, for the rows at offset 4, 8, 12) @@ -292,7 +301,7 @@ index i: symbol = prediction XOR index[i], encoded with a static 8-symbol Rice the missing neighbor defaulting to 0 ``` -That is an 8 x 8 matrix = 64 index models per channel. The context is derived from the already decoded indices themselves, so the model selection costs no stream bits. +That is an 8 x 8 matrix = 64 index models plus one first-index model per channel. The context is derived from the already decoded indices themselves, so the model selection costs no stream bits. The 8-symbol models use a compact rank table (8 entries instead of 256): `3 + num_symbols ≤ 11` bytes each in the stream. @@ -300,22 +309,44 @@ The 8-symbol models use a compact rank table (8 entries instead of 256): `3 + nu A block whose two endpoints are identical carries a uniform index word: all 16 indices hold the same 3-bit value. A per-channel flat index mode, decided once in the first pass, collapses this: mode 1 is selected for a channel when at least one block of that channel has identical endpoints and every such block holds the same 3-bit value, else mode 0. In mode 1 a flat block stores no index payload at all: the value, stored once per channel for the whole image in the stream header, is expanded to all 16 indices on decode, instead of the 15 contextual symbols; in mode 0, or for a non-flat block, the indices are stored as usual. The mode and the value share one header byte per channel (mode | value << 1) after the tile seeds. A decoder never needs the mode for a non-flat block, so the encoder and decoder always pick the same path; an encoder that leaves a non-uniform or a differing index word on a flat block forces mode 0 and round-trips byte-exact. +#### Index-word dictionary + +When a tile's index words repeat, a block's whole payload can be replaced by one symbol. Each channel of an enabled tile keeps a move-to-front list of at most 255 distinct 48-bit index words (the block's six index bytes): the stored symbol is the word's rank 0..254, and 255 is the escape — the full payload above is stored and the word is inserted at the front of the list. A rank hit copies the word at that list position into the block's indices. The list is cleared per tile, like the endpoint MTF-8, and the decoder rebuilds it exactly: a rank names a list position, never a word, so no lookup structure is needed on decode. + +The dictionary is gated per tile by one global per-channel decision, priced exactly in a third pre-pass: the tile is enabled when the hit payloads it skips, priced with the fitted index models, outweigh the rank symbols it adds, priced with the fitted rank model — one rank model per channel for the whole image, never a per-tile model. A channel with no enabled tile pays only the always-present rank model slot (a dummy 1-symbol model) and its 8-byte tile word. + ### Compressed stream As BC1, the stream does not include width, height or format: the BC4 / BC5 decompressors are separate entry points and know their own header. ```text -* 2 endpoint models per channel — 256-symbol static models, 3 + num_symbols bytes each, no padding (max 259). -* 64 index models per channel — 8-symbol static models, 3 + num_symbols bytes each, no padding (max 11). +* Per channel, in order: + - 2 endpoint models — 256-symbol static models, 3 + num_symbols bytes each, no padding (max 259). + Fitted on the MTF-escaped blocks when the channel's MTF-8 flag is set, on every block otherwise. + - 1 endpoint MTF-8 model — 9-symbol static model, 3 + num_symbols bytes, no padding (max 12). + A dummy 1-symbol model (4 bytes) when the flag is clear: the layout is fixed and the flag + is only readable after the model region, so the slot is always present. + - 1 first-index model — 8-symbol static model for the first index of each non-flat block, + 3 + num_symbols bytes, no padding (max 11). + - 1 index-word dictionary rank model — 256-symbol static model (ranks 0..254 + escape), + 3 + num_symbols bytes, no padding (max 259). A dummy 1-symbol model (4 bytes) when no tile + of the channel is enabled: the layout is fixed and the tile word is only readable after + the model region, so the slot is always present. + - 64 index models — 8-symbol static models, 3 + num_symbols bytes each, no padding (max 11). * Tile seed: 2 bytes per channel (endpoint 0, endpoint 1). -* Flat index mode + value: one uint8_t (mode | value << 1) per channel. See Indices → Flat blocks. +* Flat index mode + value + endpoint MTF-8 enable: one uint8_t (mode | value << 1 | mtf << 4) per channel. + See Indices → Flat blocks and Endpoints → Endpoint MTF-8. +* Padded to a 4-byte boundary. +* Index-word dictionary tile word: one uint64 per channel, a contiguous block (bit i = tile i: + the tile stores dictionary ranks instead of the index payload), u32-aligned so the GPU reads + it as words. See Indices → Index-word dictionary. * Padded to a 2-byte boundary. * 63 tile offsets (uint16_t each), relative deltas in dword units. Tile 0 always starts the tile data; its offset is zero and not stored. * Padded to a 4-byte boundary. * 64 tile bitstreams, each 4-byte aligned, each flushed independently. ``` -For BC5 the red channel's models and seed come first, then the green channel's, then the shared offsets and tiles. Within a tile the blocks follow the zigzag row order; per block the payload is the red channel complete, then the green one, and per channel: endpoint 0, endpoint 1, then either no index payload (a flat block in mode 1, the header value is expanded to all 16 indices on decode) or index 0 (3 raw bits) followed by indices 1..15 (each XORed with its intra-block prediction, as above). +For BC5 the red channel's models and seed come first, then the green channel's, then the shared offsets and tiles. Within a tile the blocks follow the zigzag row order; per block the payload is the red channel complete, then the green one, and per channel: with MTF-8 enabled, the 9-symbol MTF rank of the block's endpoint pair (0..7 = the pair at that position of the per-tile move-to-front list, 8 = the two wrapped endpoint deltas, the list updated in either case and cleared per tile); without it, the two wrapped endpoint deltas; then either no index payload (a flat block in mode 1, the header value is expanded to all 16 indices on decode), or, for an enabled tile, the 256-symbol rank of the block's 48-bit index word (0..254 = the word at that position of the per-tile move-to-front list is expanded into the block's indices, 255 = the full payload below, the word inserted at the front of the list), or index 0 with the first-index model followed by indices 1..15 (each XORed with its intra-block prediction, as above). ### Status @@ -327,10 +358,10 @@ For BC5 the red channel's models and seed come first, then the green channel's, Everything is validated byte-exact over all 64 tiles, on CPU and GPU: -* GPU roundtrips: the `bcp_decompress_bc4` / `bcp_decompress_bc5` Metal kernels decode the brick AO / normal maps (1024×1024, `images/bc4` / `images/bc5`) and the result is verified byte-identical to the stb-built textures, the same way the BC1 kernel is tested. +* GPU roundtrips: the `bcp_decompress_bc4` / `bcp_decompress_bc5` Metal kernels decode the brick AO / normal maps (1024×1024, `images/bc4` / `images/bc5`) and a synthetic 256×256 texture whose endpoint pairs and index words repeat within the tiles (the content class the real brick maps do not exercise; the repetition enables the index-word dictionary on those tiles, so the kernel's mirror of the per-tile list is exercised), the result verified byte-identical to the stb-built / generated textures, the same way the BC1 kernel is tested. The suite is run with the Metal validation layer on (`METAL_VALIDATION=1 ./build/unit_tests`). -* CPU: 8 synthetic 256×256 roundtrips (flat, checkerboard, gradient, SplitMix32 random, each as BC4 and BC5): the random pattern forces the raw-mode fallback and the full 64-context usage. -* CPU: 4 AO maps (`images/bc4`) and 4 normal maps (`images/bc5`), 1024×1024, converted per block with stb_dxt: the per-image ratio is printed to stdout (no CSV) and the suite average must stay above 1:1. Measured: **1.1351:1** average for BC4 (1.0921 – 1.1592 per image) and **1.0985:1** for BC5 (1.0630 – 1.1339 per image). BC5 compression ratio looks modest but zlib only achieves 1.010563:1 for the same images. +* CPU: 14 synthetic 256×256 roundtrips: the flat / checkerboard / gradient / SplitMix32 random patterns as BC4 and BC5 (including the flat-index mode variants and a per-column predictor), plus the endpoint-pair content classes — repeated pairs, asserted to compress strictly smaller than an all-distinct-pairs control with the same index words, all-distinct pairs, a half-repeated / half-distinct mix, and a BC5 with repeated red / distinct green (per-channel independence) — and the index-word dictionary classes: 8 cycling index words asserted to compress strictly smaller than an all-distinct-words control with the same endpoint pairs, all-distinct words (the dictionary must stay gated off), and cycling non-uniform words in mode-0 flat blocks. The tests check results only: byte-exact roundtrips and stream sizes, never the stream layout. The random pattern forces the raw-mode fallback and the full 64-context usage. +* CPU: 6 maps (`images/bc4`: 4 AO maps, a 4096×4096 roughness map, a 1748×1748 font atlas) and 4 normal maps (`images/bc5`), converted per block with stb_dxt: the per-image ratio is printed to stdout and logged to the hourly CSV, and the suite average must stay above 1.05. Measured: **1.3608:1** average for BC4 (1.0920 – 2.4040 per image, 2.4040 being the mostly-flat font atlas, where the endpoint MTF-8 flag and the index-word dictionary switch on) and **1.0985:1** for BC5 (1.0629 – 1.1339 per image). BC5 compression ratio looks modest but zlib only achieves 1.010563:1 for the same images. The 8-bit formats leave less headroom than BC1: the indices of these maps sit close to 3 near-uniform bits each, so most of the gain comes from the endpoint deltas. diff --git a/failed_experiments.md b/failed_experiments.md index b1831db..97670a0 100644 --- a/failed_experiments.md +++ b/failed_experiments.md @@ -45,6 +45,7 @@ Rice `k` and rank table per endpoint fits better. Kept. | 20 | Color-pair sliding dictionary: a 1-bit flag + a `ceil(log2(min(pos,256)))`-bit reference to a matching block within the last 256 replaces the six color deltas when the two endpoint colors exactly repeat, plus a per-strip enable flag | round-trips (CPU + GPU); forced version was a net loss (25 improved / 44 regressed), the per-strip version: 44 improved / 5 regressed / 25 flat, the flat ones byte-identical to the baseline | 1.4587 → 1.4654 (+0.46%) avg; 1.4020 → 1.4073 (+0.38%) byte-weighted; best +2.95% (wall2), worst −0.14% (kodim15) | **kept — this is the new baseline** (the per-strip flag turns the forced-match net loss into a net win) | | 21 | `bc4_index_family` endpoint-range thresholds: 30+ split variants on the 10-image bc4/bc5/bc3 suite (3-family 8/16 → 5/40; also 2- and 4-family splits) | round-trips (CPU + GPU); 10/10 images improved, best −1.04% (bc3 leak-stain alpha), worst −0.02%; 2- and 4-family counts all lose, the 3-family minimum is a wide plateau (t1 4..6 / t2 32..48 all ≥ −0.19%) | bc4 1.1244 → 1.1279, bc5 1.0756 → 1.0772, bc3 2.7149 → 2.7307 (suite averages); stream −0.235% overall | **kept — this is the new baseline for bc4/bc5/bc3** (the 74-image bc1 suite is untouched; the README's "obvious tuning lever" exercised) | | 22 | 8 x 8 tiles: the 64 streams become an even 8 x 8 tile of the block grid (bounds from one shared helper, `gx` 8/4/2/1 by width, `gy = 64/gx`); same walk inside a tile; the even split keeps the trailing rows of non-tile-multiple images (a breaking stream-format change) | round-trips (CPU + GPU); 62/74 BC1 images improve, worst −2.9% (horizontal-grain wood), best +9%; CPU + GPU decompression inside noise | bc1 1.4676 → 1.4905 (+1.6%); bc4 1.1342 → 1.1351, bc5 1.0995 → 1.0985 (neutral); bc3 2.8199 → 2.8787 (+2.1%) | **kept — this is the new baseline** (tiles replace full-width strips; no header byte / API change, stream layout is versioned by the compressor) | +| 25 | Per-image tile-layout search (all formats) + per-tile local reference alphabet (BC1): trial-encode every `gx` 1..64 and keep the smallest stream; promote the 8/16/32 most frequent references to the front of a permuted global alphabet per tile, exact-size gated by a stream flag | round-trips (CPU + GPU, including a forced-local GPU case); ASan + Metal validation clean; CPU decode inside noise; encoder ~3.2x slower | bc1 1.4907 → 1.4993 (+0.58%); bc4 1.2839 → 1.2876 (+0.29%); bc5 1.0985 → 1.1007 (+0.20%); bc3 4.2240 → 4.2972 (+1.73%) | **reverted** — below the +1.0% combined target and not worth ~700 LoC + 3.2x encoder time; the local alphabet alone contributes ~+0.1% | --- @@ -1058,6 +1059,93 @@ both are unmeasured, and the BC5 negative above is the stronger argument against --- +## 24. Stream-format validation from the plan's "16 color models" (the 18-model correction) + +**Idea:** the header-compression plan describes the BC1 stream as "16 color models ... 19 models +total", and its H1 validation requires the top-table byte *multiset* to be identical between the +baseline and new streams (only the order may change). Built a scratch driver (session scratchpad, +not the repo) that walks 19 model headers, then reads the top-table size byte and hashes the +table entries, run over the whole suite with a baseline and a new build. + +**Result:** the driver reported changed table multisets on 7 of the 74 BC1 images, and the +baseline stream appeared to hold a 16-entry table with an 8-symbol reference model while the +in-process encoder state said 255 entries — an apparent format corruption that no amount of +source reading reconciled (the encoder/decoder agree, every round-trip passes, the suite is +green). + +**Root cause:** the stream actually carries **18** color models, not 16. The encoder and decoder +loops store per endpoint red×3 + green×3 + blue×3 (three context buckets each) = 9 per endpoint +× 2 endpoints = 18, then reference + mask + difference = **21 models total**. The "16" in the +plan (and in older README / code comments) is an arithmetic slip; the scratch driver inherited +it, so its walk ended 13 bytes early: its "reference model" was really the 11th color model, its +"table size byte" was the mask model's count byte (0x0f → "16 entries"), and the "table" it +hashed was the difference model's alphabet — plausible-looking garbage that differs between +builds only where the 255-byte header shrink shifts the window. With the corrected walk (21 +models) **all 74 BC1 images have byte-identical table multisets** and identical per-component +payload bits, and the BC4/5 "diffs" were the same misparse (those formats have no top table; +their component-bit check had already passed for every image). + +**Kept:** the 18 / 21 counts are corrected in the README and the code comments. Any tool that +parses the stream (the plan's validation, the tile plan's encoder trials, future stream +differs) must walk 21 models for BC1 — the model headers are self-describing, but a wrong model +count does not fail loudly: the drift lands mid-alphabet and reads plausible garbage until +something compares against ground truth. + +--- + +## 25. Per-image tile layout search + per-tile local reference alphabet (implemented, measured, reverted) + +**Idea (plan/tile_layout_and_local_reference.md):** two decode-cheap features sharing one +evaluation mechanism. (1) Exp 22 fixed an 8 x 8 tile grid; replace it with a per-image search: +try every `gx = 1, 2, 4, 8, 16, 32, 64` with `gx <= width_blocks`, `gy = 64 / gx`, encode the full +stream for each and emit the smallest (8 x 8 wins a tie, then the lower `layout_log2`). (2) BC1 +per-tile local reference alphabet: count the references each tile emits, promote its 8 / 16 / 32 +most frequent ones to the front of a permuted copy of the global alphabet, fit a local +`(k, q_escape)` and use it only when `2 + 8*S + 16 + local payload` beats the global payload. +A stream flag selects all-global (zero extra bits) or per-tile decisions; the encoder computes +both exact sizes and emits the smaller one. + +**Stage 0 offline study** (`logs/study_layout_localref.csv`, the real pipeline with a forced +grid): per-tile reference entropy **7.043 bits** vs the global 7.49 (the concentration gate +passes), the local option wins on **61/74** images at 8 x 8, layout-only **+0.45%**, combined +**+0.514%** on the BC1 suite. + +**Result (74-image BC1 suite + the BC4 / BC5 / BC3 suites, all CPU + GPU round-trips byte-exact):** + +| suite | baseline (exp 22-24) | new | gain | +|---|---:|---:|---:| +| BC1 | 1.4907 | **1.4993** | **+0.58%** | +| BC4 | 1.2839 | **1.2876** | +0.29% | +| BC5 | 1.0985 | **1.1007** | +0.20% | +| BC3 | 4.2240 | **4.2972** | +1.73% | + +- The BC1 gain clears the layout-only fallback bar (**>= +0.4%**) and the combined +0.5% + floor, but misses the combined +1.0% acceptance target. The local alphabet contributes only + about +0.1% on top of the layout search (the study predicted +0.06%); it is exact-size gated, + so it cannot regress a stream, but it is the first thing to drop if the format is simplified. +- Encoder cost: the full unit-test binary goes 11.7 s -> 36.9 s wall (~3.2x), all of it in + compression (8 trial encodes + 2 model inits per image). CPU decompression is inside noise + (ground.png 2323.5 -> 2351.6 MiB/s). No scratch buffer is needed: the winning layout is + re-encoded once at the end. +- Header: the layout byte has zero net cost in practice (it sits in the existing 4-byte header + padding); BC5 can grow by 2 bytes in the worst parity case, covered by `packed_bc5_maxsize`. + `packed_bc1_maxsize` / `packed_bc4_maxsize` are raised by 4 / 2 bytes for the same reason. +- Validation: ASan clean, Metal validation layers clean, BC1 CPU and GPU decode identical, + including a new synthetic GPU case that forces the local alphabet on. + +**Reverted — not shipped.** The implementation worked (all CPU + GPU round-trips byte-exact, +ASan and Metal validation clean, deterministic), but the size gain does not justify the cost: +about **700 lines** changed in `src/bc_packed.c` (plus the Metal mirror and tests), a **3.2x** +encoder-time multiplier, a new header byte in every BC1 / BC4 / BC5 stream (BC3 twice), and a +format break (version 2.0.0) — for **+0.58%** on BC1, with the local-alphabet half of it worth +only ~+0.1%. This is below the plan's +1.0% combined acceptance target and too close to the ++0.5% floor to carry the complexity. The code, tests, shader changes and README updates were +reverted; the stage 0 study (`logs/study_layout_localref.csv`) and the numbers above remain as +the record. If this is ever revisited, start from the layout search alone (the +0.45% part) and +drop the per-tile local alphabet unless it grows beyond a marginal win. + +--- + ## Open thread (not a failed experiment, just a lead) The better-VQ-codebook lead is **resolved and closed**: exp. 13 measured the spatially-smooth diff --git a/images/bc4/Metal002_4K_Roughness.png b/images/bc4/Metal002_4K_Roughness.png new file mode 100644 index 0000000..1c0cbdb Binary files /dev/null and b/images/bc4/Metal002_4K_Roughness.png differ diff --git a/images/bc4/font_atlas.png b/images/bc4/font_atlas.png new file mode 100644 index 0000000..a69c845 Binary files /dev/null and b/images/bc4/font_atlas.png differ diff --git a/logs/bc4_zip.md b/logs/bc4_zip.md new file mode 100644 index 0000000..e73f602 --- /dev/null +++ b/logs/bc4_zip.md @@ -0,0 +1,46 @@ +# BC4 : bc_packed vs zip -9 baseline on raw standard BC4 + +General-purpose compressor baseline for the bc_packed BC4 stream ratios. Measured 2026-11-12 +on the six-image `images/bc4` suite (v1.0.2); the bc_packed column re-measured 2026-11-13 on +v2.0.0 (endpoint MTF-8 + first-index model), and again 2026-11-13 on v2.1.0 (index-word +dictionary), which switches on for the font atlas and stays off for the five real-content maps. + +**Method:** raw blocks built with stb_dxt v1.13 (`stb_compress_dxt_block`'s BC4 path, red +channel) exactly as the image suite builds them; `zip -9` per file; compressed size read from +the deflate entry (`unzip -v`), no container overhead. Ratio = raw bytes / compressed bytes — +the same numerator as the project's stream ratios, so the columns are directly comparable. + +| Image | Size | Raw bytes | zip -9 bytes | zip ratio | bc_packed ratio | bc_packed stream bytes | +|---|---|---:|---:|---:|---:|---:| +| grey_roof_tiles_02_ao_1k.png | 1024×1024 | 524,288 | 504,935 | 1.0383 | 1.1592 | 452,300 | +| patterned_cobblestone_ao_1k.png | 1024×1024 | 524,288 | 516,041 | 1.0160 | 1.0920 | 480,104 | +| red_brick_ao_1k.png | 1024×1024 | 524,288 | 495,479 | 1.0581 | 1.1550 | 453,944 | +| rough_wood_ao_1k.png | 1024×1024 | 524,288 | 516,923 | 1.0142 | 1.1351 | 461,880 | +| Metal002_4K_Roughness.png | 4096×4096 | 8,388,608 | 8,031,124 | 1.0445 | 1.2195 | 6,878,820 | +| font_atlas.png | 1748×1748 | 1,527,752 | 596,663 | 2.5605 | 2.4040 | 635,504 | +| **average (per image)** | | | | **1.2886** | **1.3608** | | +| **byte-weighted** | | 12,013,512 | 10,661,165 | **1.1268** | **1.2831** | 9,362,552 | + +## Notes + +- v2.1.0 stream deltas: the five real-content maps gain only the always-present dictionary + slot (4-byte dummy rank model + 8-byte tile word, +12 B each; red_brick +16 B — its model + region lands 1 byte off the 4-byte alignment of the tile word), the font atlas drops + 46,640 B. +- bc_packed beats zip -9 on the five real-content maps by +7.5% to +16.8% (byte-weighted + +13.9% across all six maps). AO / roughness content is ~99.9% unique 8-byte blocks + (red_brick: 65,442 / 65,536 distinct; the 4K roughness map: 1,047,560 / 1,048,576), which + leaves deflate no LZ material — only weak statistical compression. MTF-8 and the + index-word dictionary stay off for all five (the exact per-tile pricing keeps the plain + payload); their streams moved by header bytes only. +- zip -9 still wins on the font atlas, 2.5605 vs 2.4040: the v2.1.0 index-word dictionary + (enabled on the atlas tiles, one global rank model per channel) cut the gap from zip +14.3% + (v2.0.0) to +6.5%. The atlas's 57.5% byte-identical duplicate blocks (81,252 of 190,969 + distinct, scattered in raster order) now cost a rank hit instead of a full index payload; + what remains is the escape payload of the unique words plus the endpoint stream, where + deflate's 32 KB window still reaches farther than a per-tile list of 255 words. +- The atlas is a small share of the raw bytes (12.7%), so its zip advantage no longer flips + the simple per-image average (the metric the image suite reports): bc_packed ahead by + +5.6% (1.3608 vs 1.2886), up from +3.5% before the dictionary. The README's "all + compression ratios are better than zlib" claim holds for the BC4 suite average, as for the + original four AO maps, BC1, BC5, and BC4 on a byte-weighted basis. diff --git a/plan/bc4_index_dictionary.md b/plan/bc4_index_dictionary.md new file mode 100644 index 0000000..9ac2869 --- /dev/null +++ b/plan/bc4_index_dictionary.md @@ -0,0 +1,116 @@ +# Plan: BC4/BC5 per-tile index-word dictionary (MTF, exact match) + +Status: implemented and verified (2026-11-13). 51/51 tests pass (Release + ASan), GPU validation +layer clean (`METAL_VALIDATION=1`), font_atlas 682,144 B → 635,504 B (2.4040 vs the 2.406 gate), +BC4 suite average 1.3608, the five real-content maps +12/+16 B (header slot only). Decode +throughput and encode wall time measured within the §6 gates on this machine. + +Target: `font_atlas.png`, the only BC4 content class where bc_packed trails `zip -9` (596,663 B vs 682,144 B). +65 % of its non-flat blocks share their 48-bit index word with another block, which is what this change exploits. + +## 1. Mechanism + +- The unit is the 48-bit **index word** (the 6 index bytes of a block; the endpoints are coded as today). +- Per tile and per channel, a **255-entry move-to-front list** of exact index words, cleared per tile + (a GPU thread decodes one tile, so no cross-tile state is possible). +- Hit: emit the MTF rank, the whole index payload (first index + 15 contextual symbols) is skipped, and the + entry moves to the front. Miss: emit the escape, then the usual payload, insert at the front, evict the tail. +- Exact match only: no residual, no near match, no transmitted table, no seed list. + +## 2. Coding + +- One symbol of a 256-symbol static model per block that emits an index payload: + `rank 0..254` = dictionary entry, `255` = escape. The alphabet is full, so the Rice / raw fallback of + the fitter is a plain 8-bit symbol with no special case. +- **No per-block flag**: the escape *is* the flag. Measured 3.5-5 KB cheaper than a separate 2-symbol flag + model plus a rank model (a 2-symbol static Rice model is exactly 1 bit/symbol and never goes below). +- Applies to every block that emits an index payload, so flat blocks in mode 0 participate too; flat blocks + in mode 1 keep their free payload and never touch the list. + +## 3. Enabling (gating) + +- One plain `uint64_t` per channel, always written after the per-channel header bytes, u32-aligned so the + GPU reads it as words, as a contiguous block (the header bytes of every channel, then the tile word of + every channel — not interleaved): bit `i` = tile `i` uses its dictionary. Same shape as BC1's + `strip_dict_enable`, no flag, no conditional field. 8 bytes per channel (16 for BC5), and 0 payload cost + for an image where the gate disables every tile. +- The rank model slot is always in the model region, like the endpoint MTF-8 slot: a channel whose gate + disables every tile writes a dummy 1-symbol model (4 bytes, the decoder never reads from it), so a + non-qualifying channel pays exactly the 8-byte tile word + 4-byte dummy — never the full 259-byte model. +- Gate decision, per tile and channel, with both sides priced by the models the stream actually carries: + - The pass-2 simulation (§4) accumulates the global per-channel rank histogram (256 bins); the + end-of-pass-2 fit builds `bc4_dict_rank_model[c]` from it, next to the endpoint / index models. + - A dedicated pricing pass (the third read of the image; it cannot merge into pass 2 because the index + models are only fitted once that pass is done) re-simulates the dictionary per tile and prices each + tile: `saved` = payload bits of the tile's hit blocks (first index + 15 contextual symbols) under the + fitted index models; `paid` = the tile's own 256-bin rank histogram (a reused temp, discarded at the + tile end) priced under the fitted rank model, escape bin included. Enable when `saved > paid`. + - No estimate constants: the gate is priced with exactly the models that get written (the written rank + model is the pass-2 global fit; a channel with no enabled tile writes the dummy and no rank symbol + exists), so the simulator's exact per-tile pricing only cross-checks the expected size (all 6 BC4 + images, 64 tiles each, agree). + +## 4. Implementation + +- Dictionary state, new type next to `mtf_list`: `bc4_dict` = `uint8_t word[255][6]` (fixed slots) + + `uint8_t order[255]` (recency permutation, `order[i]` = slot of rank `i`) + `uint8_t count`. A hit copies + 6 bytes and shifts the permutation only (`memmove` of at most 255 B); the words never move, so a slot is + stable for the lifetime of the tile. +- Encoder lookup reuses BC1's hashmap: same `hashmap_entry` buffer (`ctx->hashmap`), same `hash32`, and the + linear-probe loop factored into one shared inline helper used by both `build_top_table` and the dictionary + (no second table implementation). The dictionary stores `key = hash32(word_lo) ^ hash32(word_hi)` and + `count = slot + 1`; the 6 bytes are compared before a hit is accepted, so a 32-bit hash collision only + costs a probe. Slot to rank is a scan of `order`, 1-byte compares, at most 255 B. +- `bcp_context` gains `hashmap_size` and a `hashmap_ensure(ctx, size)` helper: BC1 asks for `HASHMAP_SIZE`, + the BC4/BC5 dictionary for `BC4_DICT_MAP_SIZE` (1024 entries = 8 KB, load factor at most 0.25 against 255 + live entries), and an existing buffer is reused when it is already large enough. The table is cleared per + tile (8 KB) and an evicted word is removed with backward-shift deletion (~12 lines), so the map always + holds exactly the live dictionary. +- Encoder plumbing: the dictionary state lives in `bcp_compress_bc45` next to `mtf_list mtf[...]`; the + pass-2 simulation in `bc4_init_models` (dictionary cleared per tile, same zigzag walk as the histogram) + fills the global `dict` rank histogram of `bc4_hists` (256 bins per channel) and the end-of-pass-2 fit + builds `bc4_dict_rank_model[c]` from it; the pricing pass (third read of the image) fills + `bc4_dict_enable[c]` (one `uint64_t` per channel) and afterwards a channel whose gate disabled every + tile has its model replaced by the dummy 1-symbol one. +- Decoder: same state next to the endpoint MTF list in `bcp_decompress_bc45`, no map: `order[rank]` gives the + slot, the hit is a 6-byte copy plus the permutation shift. +- Stream: the rank model slot goes right after the first-index model of each channel, the tile word after the + per-channel header bytes (contiguous block, see §3). `packed_bc4_maxsize` grows by one channel's worth, + `8 + 3 + 256` = 267 bytes; `packed_bc5_maxsize` already doubles it, which covers both channels. + +## 5. Expected results (simulator, current encoder) + +Replica baseline 683,223 B against the real 682,144 B; the BC4 suite has 6 images. + +| font_atlas | bytes | ratio | change | +|---|---:|---:|---:| +| current encoder | 682,144 | 2.2396 | | +| with the dictionary, K=255 | ~634,900 | 2.406 | -48.3 KB, -7.1 % | + +- The other five BC4 images keep byte-identical tile data: the gate disables all 64 tiles on the four 1K AO + maps and on the 4K roughness map (measured 0-17 hits over 65k blocks, so 0 B of tile payload), leaving only + the 8-byte tile word + 4-byte dummy rank model = 12 bytes per channel as overhead. +- For reference, `zip -9` is 596,663 B (2.5605) on this image; the dictionary alone lands at 2.406. + +## 6. Gates + +- Round-trip CPU + GPU on the BC4 and BC5 suites, byte-exact over all 64 tiles (GPU kernel mirrors the list). +- Synthetic: a periodic-pattern BC4/BC5 image (dictionary must engage and round-trip), an all-distinct-index + image (must stay gated off and round-trip), a flat-mode-0 image with repeated flat words. +- ASan build clean; GPU validation layers clean. +- CPU decode speed within 5 % of the current 14540 MiB/s BC4 / 7868 MiB/s BC5 (one `memmove` per hit). +- Encode time within 15 %: the image is read three times (seed; histogram + dictionary simulation; gate + pricing) with an O(1) lookup; the only new buffers are the 8 KB map inside the existing hashmap + allocation and the reused 1 KB pricing temp, both stay in cache. +- GPU: per-tile state in the Metal kernel is 1.79 KB/channel (3.6 KB for BC5) of thread-local memory. If the + standalone GPU profile shows a regression, the fallback is a per-tile dictionary scratch in device memory, + which needs a new buffer in the GPU API: ask before doing it. +- `logs/bc4_zip.md` re-baselined, README BC4/BC5 Indices + Compressed stream updated. + +## 7. Design decisions and version + +- Rejected for this mechanism: seed table, near-match residuals, static per-image table, whole-block + dictionary, separate per-block flag, K > 255, transpose and half-promotion update policies. +- Version: 2.1.0 (new feature). The stream layout changes — breaking for a 2.0.0 stream — but v2 has never + been merged to main and is being prepared for main, so the change stays on the 2.x line and takes the + minor bump, not a major one. diff --git a/plan/header_compression.md b/plan/header_compression.md deleted file mode 100644 index 21210f2..0000000 --- a/plan/header_compression.md +++ /dev/null @@ -1,37 +0,0 @@ -# Plan: header compression - -Two payload-neutral header reductions, both riding along with the v2.0.0 format bump the tile plan already requires. - -## H1: rank-ordered top table, identity reference alphabet (-256 B, BC1) - -Store the table in reference hit-count order (descending; ties by pattern value ascending, preserving `nearest32` tie-break). The reference alphabet then becomes identity `0..count-1` and is never transmitted. - -- Measured: the alphabet is 253-256 B on every image (every entry hit) -> flat **-256 B**, no payload movement (the rank of the n-th most frequent centroid is n either way; exp 4 showed reordering the raw reference is a wash, which is what makes the alphabet free). -- Measured: 0 duplicate patterns and 0 zero-hit entries on the whole suite -> debug-build assert on uniqueness instead of a dedup pass; decoder rejects `table_size != reference count`. -- Reference model header shrinks to **3 bytes**: `count-1`, `k`, `q_escape`. Decoder sets `alphabet[i] = index[i] = i`. Table bytes unchanged: `4 * top_table_size`, raw, in rank order (no mode bits, no size field). - -**Validation (H1 must be payload-neutral):** per-component byte counts (reference, mask, difference, color) identical to baseline; table byte *multiset* identical (only order may change); header shrinks by exactly 256 B. If the reference payload moves, the sort/tie-break is wrong. - -## H2: omit the alphabet in raw mode when the set is a prefix (-218 B BC4 / -220 B BC5) - -Raw mode writes the rank at a fixed width `ceil(log2(num_symbols))`, so alphabet order never affects bit counts. If the present symbols are exactly `{0..num_symbols-1}`, force the identity (`alphabet[i] = i`, `index[s] = s`) and omit the alphabet. - -- Encoder: prefix check is a <=256-entry scan; otherwise fall back to writing the alphabet. Flag in **bit 6 of `k` (raw mode only)**; bit 7 is the raw flag, bits 0-3 the width, bits 4-5 stay free. -- `load_static_model` currently clamps `k & 0x7f`, which would destroy bit 6: extract the flag first, clamp only `k & 0x0f`. -- Force the identity in `le_static_model_init` right after the raw decision; nothing else reads a raw model's rank order (`le_symbol_cost` is width-only; the raw/Rice decision is unchanged). -- GPU (BC1 and BC4/BC5 loaders): skip the alphabet read, build the identity (~10 lines). -- Uniform across model types (8-symbol index, 16-symbol mask, 256-symbol endpoint/reference). `packed_bc*_maxsize` bounds only shrink; no constant change beyond the format bump. - -## Encoder / decoder flow - -- Encoder (BC1): `build_top_table` (unchanged) -> final reference pass (unchanged) -> sort by hit count (assert unique) -> fit reference model, identity alphabet, 3-byte header -> write table raw in rank order -> H2 identity rewrite for each raw model. -- Encoder (BC4 / BC5 / BC3): unchanged except H2. BC3 inherits both: H1 on the color half, H2 on both halves. -- Decoder (CPU / GPU): read model headers (raw with k bit 6 set => identity, no alphabet); load the reference model with `alphabet[i] = i`, require `table_size == reference count`; payload decode unchanged (marginally faster, one alphabet copy fewer). - -## Payoff - -- **H1**: -256 B per BC1 image -> +0.31% at 512^2, +0.19% at 768x512 / 512x768, +0.07% at 1024^2, **+0.176% suite average**. -- **H2**: -218 B per BC4 image, -220 B per BC5 -> +0.05% BC4, +0.02% BC5, ~0 BC1. -- Rejected (not worth a format path or GPU parse complexity, 0 to -20 B): shared color alphabets, packing, offsets, the 2 empty green headers. - -Total: **~+0.18% BC1, +0.05% BC4, +0.02% BC5**. Small but unconditional, payload-neutral, decoder-cheaper. The larger ratio work (tile-layout search, local reference alphabet) is in the companion tile plan. diff --git a/plan/tile_layout_and_local_reference.md b/plan/tile_layout_and_local_reference.md deleted file mode 100644 index 72f229d..0000000 --- a/plan/tile_layout_and_local_reference.md +++ /dev/null @@ -1,252 +0,0 @@ -# Plan: per-image tile-layout search + per-tile local reference alphabet - -Status: proposal, no code written yet. -Scope: BC1/BC4/BC5/BC3 (layout); local reference alphabet is BC1 only. -Baseline: 74-image BC1 suite **1.4907**, BC4 **1.1352**, BC5 **1.0985**, BC3 **3.9180** -([stats_2026-11-08_18_04.csv](../logs/stats_2026-11-08_18_04.csv)). -Format break: library version **2.0.0**; no public API change (`bcp_compress_*` / -`bcp_decompress_*`, `num_strips = 64` unchanged). - -Two decode-cheap features sharing one evaluation mechanism (per-tile histograms, per-image -exact-size gate, scratch buffer, header plumbing). The per-block loop is unchanged: layout is -read once per tile, the local reference model is built once per tile, and the block payload uses -the existing `le_encode_symbol` / `le_decode_symbol` path. - -1. **Per-image tile-layout search** — exp 22: 8x8 is +1.6% on average but per-image spread is - +9%..-2.9%; a per-image choice captures the variance (offline compression, trial encoding OK). -2. **Per-tile local reference alphabet** — the reference is ~17% of the stream with a - near-uniform global marginal (~7.49 bits); if a tile uses a concentrated subset of - centroids, a local alphabet cuts its reference code. Not exp 13/16 (no reorder/delta/centroids). - -**No regression by construction:** the fixed 8x8 layout and the global reference model are both -candidates; the emitted stream is the smallest actually-encoded one. - ---- - -## 1. Design - -### 1.1 Tile layout - -- Keep 64 independent tiles (GPU dispatch unchanged); store `layout_log2` in 0..6 in the header: - `gx = 1 << layout_log2`, `gy = 1 << (6 - layout_log2)`. -- Tile bounds use shifts, not division: - `x0 = (tx * width_blocks) >> layout_log2`, `x1 = ((tx + 1) * width_blocks) >> layout_log2`, - `y0 = (ty * height_blocks) >> (6 - layout_log2)`, `y1 = ...` (exp 22: the even split still - covers every row/column). -- Candidates: `gx in {1, 2, 4, 8, 16, 32, 64}`, filtered by `gx <= width_blocks` (height is - >= 64 blocks by the API's `height >= 256` requirement, so `gy <= height_blocks` always holds). - Default / tie-break: 8x8 (`layout_log2 = 3`). -- Encoder trial-encodes every valid candidate and keeps the smallest stream. Expect a 3-7x - encoder-time multiplier (document it); add proxy pruning only if that becomes a problem - (exp 7/8b: a proxy may prune, never decide). -- BC4 / BC5: same layout field and search; no local reference. -- BC3: each substream carries its own layout (halves are independent streams; the 64-call loop - covers each half exactly once), or a shared layout chosen by combined size — measure both, pick one. - -### 1.2 Per-tile local reference alphabet (BC1) - -1. Histogram pass accumulates `ref_hist[64][256]` (top-table indices, layout-independent - `nearest32` result) **counting only blocks that emit a reference** (flat-index mode 1 blocks - emit none). -2. Fit the global reference model from the all-blocks histogram, exactly as today. Its alphabet - is a *superset* of every tile's references, guaranteeing a lossless local alphabet. -3. Per tile, evaluate promotion sizes `S in {8, 16, 32}` (only sizes <= the global - `num_symbols`): - - `list` = the S most frequent references in the tile (ties: lower table index); if the tile - has fewer than S distinct references, fill with the least frequent global symbols not in the - list (never emitted; shifts tail ranks only). - - Local alphabet = `list[0..S-1]` followed by the global alphabet in existing order minus the - promoted symbols — a **permutation of the same symbol set**, so `num_symbols` and the - raw-mode width are unchanged. - - Fit local `(k, q_escape)` from the tile histogram. - - Cost = 2-bit size code + `8*S` list bits + 2 bytes `(k, q)` + exact tile payload under the - local model, compared against the no-local cost (2-bit code + payload under the global model). -4. Stream-level decision: Option A (flag = 0: all tiles use the global model, zero extra bits — - today's behavior) vs Option B (flag = 1: every tile writes the 2-bit size code; non-paying - tiles choose 0 and use the global model). Compute both totals, emit the smaller; the flag - lives in the header. -5. All-flat image (global reference model with zero symbols): no reference symbols, local - machinery skipped entirely. - ---- - -## 2. Stream format - -**Header bytes** (preferred, if [header_compression.md](header_compression.md) ships: the -flat-mode byte is `mode | (value << 1)` and only those bits are read, so BC1 has bits 3-7 free -and BC4/BC5 have bits 4-7 free per channel): - -- BC1: `layout_log2` in flat-byte bits 3-5, `ref_local_enabled` in bit 6 -> **zero net header - growth**, no new field. -- BC4 / BC5: `layout_log2` in spare bits of the per-channel flat bytes -> **zero net growth** - (BC5 avoids the +2 B of the fallback). - -Fallback (if the header plan does not ship): insert a separate `layout u8` after the flat-mode -byte (BC1: 3 bytes + 1 pad, zero net; BC4: 4 bytes, 2-aligned, zero net; BC5: 7 -> 8 bytes, -**+2 bytes**). Raise `packed_bc4_maxsize` / `packed_bc5_maxsize` by 2 bytes in that case -(`packed_bc3_maxsize` inherits); add a maxsize bound test. BC3: each substream carries its own -layout, size prefix unchanged. - -**Per-tile reference header** (BC1, at the start of each tile bitstream, only when -`ref_local_enabled`), written with `le_write_bits` / `le_write_byte` before the first block: - -| field | bits | -|---|---:| -| size code | 2 (0 = none, 1 = 8, 2 = 16, 3 = 32) | -| list | `size * 8` (top-table indices in local-frequency order; 0 bits for size code 0) | -| `k` | 8 (same encoding as the model header; bit 7 = raw) | -| `q_escape` | 8 (0..31) | - -When `ref_local_enabled = 0`, the tile bitstream has zero extra bits and is byte-identical to -the layout-only format. - -**Local alphabet construction** (encoder and decoder must match): - -```text -promoted[256] = false -local_alphabet[0..S-1] = list[0..S-1] -for i in 0..S-1: promoted[list[i]] = true -rank = S -for r in global_alphabet[0..global_num_symbols-1]: - if !promoted[global_alphabet[r]]: - local_alphabet[rank++] = global_alphabet[r] -assert(rank == global_num_symbols) -``` - -The encoder rebuilds `index[symbol] = rank`; CPU/GPU decoders only need `alphabet`. CPU decoder -validates each list entry (`< top_table_size`, present in the global alphabet, `S <= num_symbols`), -returns false on violation; the GPU keeps today's "garbage on corrupt streams" contract. - ---- - -## 3. Encoder - -```text -build_top_table() // layout-independent, once per image -flat mode scan // layout-independent - -best_size = SIZE_MAX -for each valid layout L: - init_static_models(L) // + layout_log2, per-tile ref hists and decisions - size = compress(L) - if size < best_size: keep (L, models, stream) in the scratch buffer -return the best stream -``` - -- `init_static_models` gains `layout_log2` plus `uint32_t ref_hist[64][256]` (64 KiB); the - global reference model is fitted first, then the Option A/B totals and per-tile decisions - (`ref_size[64]`, `ref_list[64][32]`, `ref_k[64]`, `ref_q[64]`) are stored in the context. -- The compress block loop changes only the model pointer for the reference symbol. -- **Scratch buffer:** one `output_length`-byte copy of the best stream, allocated through - `bcp_mem_interface` on first compress, freed in `bcp_terminate`, return 0 on allocation - failure (same mechanism as the 1 MiB hashmap; document the working memory). -- **Tie-break (determinism):** smaller size wins; on equality prefer 8x8, then lower - `layout_log2`, then Option A over Option B. -- BC3: each half runs its own search (or a BC3-level combined-size search if a shared layout is - chosen). - -## 4. New internal helpers (`src/bc_packed.c`, no public API) - -1. `tile_bounds_get(strip_index, width_blocks, height_blocks, layout_log2)` — shifts; replaces - the width-derived `gx` / division (CPU call sites and the Metal mirror). -2. `le_model_fit_kq(le_model*, const uint32_t* rank_histogram, uint32_t num_symbols)` — the - existing `(k, q_escape)` search factored out of `le_static_model_init`; the global init keeps - its frequency sort and calls it; the local model builds its alphabet order and calls it with - `rank_histogram[rank] = tile_hist[local_alphabet[rank]]`. -3. `ref_local_model_build(le_model* local, const le_model* global, const uint8_t* list, - uint32_t size, uint8_t k, uint8_t q_escape)` — the shared alphabet permutation. -4. `ref_local_cost(...)` — exact bit cost of a tile under the global or a local model, header - bits included; encoder-only. - -## 5. Decoders - -**CPU** (`bcp_decompress_bc1_impl`): read the layout after the flat-mode byte; validate -`layout_log2 <= 6` and `(1 << layout_log2) <= width_blocks`. After `le_begin_decode` per tile: if -the flag is set, read the size code; if non-zero, read list/`k`/`q` and build the local `le_model` -(stack copy), else use the global model. The block loop uses `reference_model` for -`le_decode_symbol`; everything else unchanged. Skip the local machinery when the global reference -model has zero symbols; keep existing overrun/status behavior plus the list validation. - -**GPU** (`src/bc_decompress.metal`, BC1 kernel): read the layout; `tile_grid_x = 1 << layout_log2`, -bounds via shifts. At tile start, if the flag is set, read size/list/`k`/`q` and overwrite a -thread-local `model_t` copy with the permuted alphabet (a 32-byte promotion bitmap in local -memory suffices). Per-block code unchanged. Extra thread memory ~260 B; no extra per-block work. -Mirror the layout read in the BC4 / BC5 kernels (no local reference there). - -**BC3:** no shader; the CPU BC3 decompressor calls the BC1/BC4 implementations, each reading its -own substream's layout; confirm the 64-call loop still covers each half exactly once. - ---- - -## 6. Implementation stages - -Each stage ends with a build, unit tests, and a measurement note. - -0. **Offline study** (no library change): full stream size per candidate layout vs 8x8; per-tile - reference support / entropy / top-S coverage; ideal local-alphabet cost incl. header bits; - per-image best layout and adoption rate; BC4/BC5 per-image best layout. - **Gate:** if per-tile reference entropy is ~7.4 bits (no concentration), drop feature 2 and - ship layout search only. -1. **Layout plumbing** (no search yet): `layout_log2` through context, `tile_bounds_get`, - encoder/decoder passes, all formats, Metal kernels; header bits at the positions above; - `packed_bc*_maxsize` bumps if the fallback byte is used. Fixed `layout_log2 = 3`; round-trips - must match the baseline (modulo any BC5 header growth). -2. **Layout search**: candidate loop + scratch buffer + deterministic tie-breaks; assert chosen - size <= forced-8x8 size; report encoder time. -3. **Local decisions, no emission**: accumulate `ref_hist`, compute Option A/B + per-tile - decisions, but emit the global model; validate the predicted global reference cost against the - actual reference bytes (exp 13's caution). -4. **Emit and decode local alphabets**: stream flag + per-tile headers; CPU/GPU byte-identical - output. -5. **Combined**: the layout search evaluates the full stream including the local option; run the - full suite (BC1/BC3/BC4/BC5 ratios, per-image deltas, total bytes, CPU/GPU throughput, - encoder time) with ablations layout-only / local-only / combined. -6. **Tuning** (only if Stage 5 is positive): promotion sizes (add 4?), per-tile `k/q` packing - (2 B -> 9 bits), global `k/q` refit on non-local blocks then one re-decision pass (exp 7), - list delta-coding vs the previous tile, two-stage proxy pruning. -7. **Docs / version**: README (format, search, local alphabet, encoder time, GPU notes), - `bc_packed.h` 2.0.0, [failed_experiments.md](../failed_experiments.md) entry (kept or - reverted) with measurements, new stats CSV in `logs/`. - -## 7. Tests - -New (behavior-level): `tile_layout_roundtrip` (synthetic stripes / checkerboard / random / -uniform; CPU+GPU byte-exact; size never above the fixed-8x8 baseline), `tile_layout_odd_dimensions` -(36x70 blocks, every block written once, per layout), `ref_local_mixed` (half the tiles repeating -few patterns, half unique), `ref_local_all_tiles`, `ref_local_flat_image` (zero reference symbols, -flag on), `ref_local_small_table` (1-entry top table), BC4/BC5/BC3 layout round-trips. - -Regression / validation: full existing suite (74 BC1, 4 BC4, 4 BC5, 2 BC3) + GPU round-trips; -ASan build clean; GPU validation layers clean; `packed_bc*_maxsize` worst-case bound test; CPU -decode benchmark (`ground.png`) within 2% of baseline, GPU within noise; two compressor runs -produce identical bytes. Do not weaken existing tests. - -## 8. Acceptance criteria - -- Combined: BC1 suite average >= **+1.0%**, no image regresses by > 0.1%, total stream bytes down. -- Layout-only fallback (if feature 2 fails its gate): >= **+0.4%** and BC4/BC5/BC3 non-regressing. -- CPU/GPU decompression within noise; no new per-block work; encoder-time multiplier and scratch - memory documented. -- If the combined gain is < +0.5%: record method + numbers in - [failed_experiments.md](../failed_experiments.md) and do **not** ship the format change. - -## 9. Open decisions (resolve in Stage 0 / 5) - -1. Is per-tile reference entropy actually below the global 7.49 bits? (decisive for feature 2) -2. Which promotion sizes pay (512^2 vs 1024^2)? Is 4 worth adding? -3. Is the per-tile `k/q` (beyond the alphabet permutation) worth its 2 header bytes? -4. BC3: per-half layouts or shared? Does the layout win come from the layout itself or from - re-decided predictor / dictionary flags (ablate by forcing the 8x8 flag choices)? - -## 10. Files expected to change - -| file | change | -|---|---| -| `src/bc_packed.c` | layout plumbing, per-tile reference histograms/decisions, helpers, trial loop, scratch buffer, CPU decoder | -| `src/bc_packed.h` | version 2.0.0 only | -| `src/bc_decompress.metal` | layout read + shifted bounds; local reference model build (BC1); layout read in BC4/BC5 | -| `tests/synthetic_tests.c` | new layout / local-reference tests | -| `tests/gpu_tests.cpp` | GPU round-trips for the new paths | -| `tests/image_tests.c` | suite thresholds / stats | -| `README.md` | stream format, layout search, local reference alphabet, encoder time | -| `failed_experiments.md` | exp 24 entry (kept or reverted) | diff --git a/src/bc_decompress.metal b/src/bc_decompress.metal index 6fbb7fb..6ff4997 100644 --- a/src/bc_decompress.metal +++ b/src/bc_decompress.metal @@ -28,8 +28,9 @@ // BC1 [19 static models][top table size u8][flat index mode + value u8][4-align][strip seed u32] // [strip predictor u64][strip dict enable u64][top table u32s][2-align][63 strip offsets u16, // deltas in dword units][4-align][strip bitstreams] -// BC4 / BC5 [2 endpoint models per channel][64 index models per channel][strip seed, 2 bytes per channel] -// [flat index mode + value, 1 byte per channel][2-align][63 strip offsets u16, deltas in dword units] +// BC4 / BC5 per channel: [2 endpoint models][endpoint MTF-8 model (9 symbols)][first-index model (8 +// symbols)][64 index models] then [strip seed, 2 bytes per channel][flat index mode + value +// + MTF-8 enable, 1 byte per channel][2-align][63 strip offsets u16, deltas in dword units] // [4-align][strip bitstreams] // // The flat index mode (bit 0 of the mode + value byte, the value in the upper bits) is decided once per @@ -38,6 +39,14 @@ // for BC4 / BC5). A block with identical endpoints then stores no index payload: the header value is // expanded to all 16 indices, instead of the full index payload. // +// The endpoint MTF-8 enable (bit 4 of the mode + value byte) is priced per channel: when enabled, each +// block's endpoints are written as one 9-symbol MTF rank (0..7 = the (endpoint0, endpoint1) pair at +// that position of the per-tile 8-entry move-to-front list, 8 = escape to the two endpoint deltas, +// the list updated in either case, cleared per tile); when disabled the two endpoint deltas are +// written as usual and the MTF model in the header is a dummy the decoder never reads from. The +// first index of a non-flat block is the symbol of the per-channel 8-symbol first-index model, +// instead of the raw 3-bit field. +// // On a corrupted stream the decode runs to completion and the output is garbage, mirroring the // CPU version which only reports the failure after the whole strip was decoded. A valid stream // always decodes bit-identically to the CPU version. @@ -52,6 +61,7 @@ constant uint LE_ALPHABET_SIZE = 256; constant uint BC4_INDEX_ALPHABET_SIZE = 8; // bc4/bc5 index models: 8 prediction values constant uint BC4_INDEX_DIM = 8; // bc4/bc5 index context: the 8 x 8 [left][top] matrix constant uint BC4_INDEX_CONTEXTS = BC4_INDEX_DIM * BC4_INDEX_DIM; +constant uint BC4_DICT_SIZE = 255; // bc4/bc5 index-word dictionary: list length, the rank model holds + 1 escape constant uint LE_MAX_K = 8; constant int COLOR_DELTA_OFFSET = 1 << 6; // 64: bias of the signed color deltas @@ -612,6 +622,87 @@ uint8_t bc4_index_context(uint8_t left, uint8_t top) return (uint8_t)(left * BC4_INDEX_DIM + top); } +// mirror of mtf_touch (src/bc_packed.c): move [pair] to the front of the 8-entry endpoint-pair +// MTF list, inserting it if new; the list holds distinct pairs, the oldest one is dropped once +// it is full. [list] must hold the 8 entries, [count] the number of valid ones +void mtf_touch(thread uint16_t* list, thread uint* count, uint16_t pair) +{ + uint at = 0; + bool found = false; + for (uint i = 0; i < *count; ++i) + { + if (list[i] == pair) + { + at = i; + found = true; + break; + } + } + + if (found) + { + for (uint j = at; j > 0; --j) + list[j] = list[j - 1]; + } + else if (*count < 8) + { + for (uint j = *count; j > 0; --j) + list[j] = list[j - 1]; + (*count)++; + } + else + { + for (uint j = 7; j > 0; --j) + list[j] = list[j - 1]; + } + + list[0] = pair; +} + +// mirror of bc4_dict_touch (src/bc_packed.c) without the lookup map: [rank] < BC4_DICT_SIZE +// promotes the list position (the permutation shifts only), otherwise [new_word] takes a +// fresh slot (the tail slot is evicted once the list is full). [word] holds the fixed slots, +// [order] the recency permutation, order[i] = slot of rank i, [count] the valid entries +void bc4_dict_touch(thread uint8_t* word, thread uint8_t* order, thread uint* count, + const thread uint8_t* new_word, uint rank) +{ + if (rank < BC4_DICT_SIZE) + { + uint8_t slot = order[rank]; + for (uint j = rank; j > 0; --j) + order[j] = order[j - 1]; + order[0] = slot; + return; + } + + uint c = *count; + uint slot = (c < BC4_DICT_SIZE) ? c : order[BC4_DICT_SIZE - 1]; + for (uint j = 0; j < 6; ++j) + word[slot * 6 + j] = new_word[j]; + for (uint j = (c < BC4_DICT_SIZE) ? c : BC4_DICT_SIZE - 1; j > 0; --j) + order[j] = order[j - 1]; + order[0] = (uint8_t)slot; + *count = (c < BC4_DICT_SIZE) ? c + 1 : BC4_DICT_SIZE; +} + +// mirror of bc4_decode_index_payload (src/bc_packed.c): the first index with its 8-symbol +// model, then each index xored with its intra-block prediction +void bc4_decode_index_payload(thread bit_stream_t* s, const thread model8_t* first_index, + const thread model8_t* index, thread uint8_t* idx) +{ + idx[0] = decode_symbol8(s, first_index); + + for (uint i = 1; i < 16; ++i) + { + // the missing neighbor of the pixel (first row, row start) defaults to 0 + uint8_t left = ((i & 3) == 0) ? 0 : idx[i - 1]; + uint8_t top = (i < 4) ? 0 : idx[i - 4]; + uint8_t p = ((i & 3) == 0) ? top : left; + + idx[i] = (uint8_t)(p ^ decode_symbol8(s, &index[bc4_index_context(left, top)])); + } +} + template void bc45_decode_strip(const device uint8_t* input, device uint8_t* output, @@ -633,9 +724,14 @@ void bc45_decode_strip(const device uint8_t* input, output += (uint64_t)grid_pos.y * image_size; //------------------------------------------------------------------------------------------------------------------------- - // load the static models: per channel, the 2 endpoint models (256 symbols) then the 64 - // compact index models (8 symbols) + // load the static models: per channel, the 2 endpoint models (256 symbols), the endpoint + // MTF-8 model (9 symbols, a dummy 1-symbol model when the channel's MTF is disabled), the + // first-index model (8 symbols), the index-word dictionary rank model (256 symbols, a dummy + // 1-symbol model when no tile of the channel is enabled) then the 64 compact index models model_t endpoint[NumChannels][2]; + model_t mtf[NumChannels]; + model_t dict_rank[NumChannels]; + model8_t first_index[NumChannels]; model8_t index[NumChannels][BC4_INDEX_CONTEXTS]; thread uint64_t pos = 0; @@ -645,6 +741,15 @@ void bc45_decode_strip(const device uint8_t* input, if (!load_model(input, length, &pos, &endpoint[c][e])) return; + if (!load_model(input, length, &pos, &mtf[c])) + return; + + if (!load_model8(input, length, &pos, &first_index[c])) + return; + + if (!load_model(input, length, &pos, &dict_rank[c])) + return; + for (uint i = 0; i < BC4_INDEX_CONTEXTS; ++i) if (!load_model8(input, length, &pos, &index[c][i])) return; @@ -661,17 +766,34 @@ void bc45_decode_strip(const device uint8_t* input, seed[c][e] = input[pos++]; } - // flat-index mode + value: one byte per channel (mode | value << 1), after the seeds, before the 2-align + // flat-index mode + value + endpoint MTF-8 enable: one byte per channel + // (mode | value << 1 | mtf << 4), after the seeds, before the 2-align if (pos + NumChannels > length) return; bool flat_mode[NumChannels]; uint8_t flat_value[NumChannels]; + bool mtf_enable[NumChannels]; for (uint c = 0; c < NumChannels; ++c) { uint8_t flat_byte = input[pos++]; flat_mode[c] = (flat_byte & 1) != 0; flat_value[c] = (flat_byte >> 1) & 7; + mtf_enable[c] = (flat_byte >> 4) != 0; + } + + // index-word dictionary enable: one uint64 per channel, bit i = tile i, a contiguous block + // after the header bytes + if (pos + 8 * NumChannels > length) + return; + + bool dict_enable[NumChannels]; + pos = (pos + 3) & ~(uint64_t)3; // u32-aligned in the stream, so read the words directly + for (uint c = 0; c < NumChannels; ++c) + { + uint64_t enable = (uint64_t)read_u32(input, pos) | ((uint64_t)read_u32(input, pos + 4) << 32); + pos += 8; + dict_enable[c] = ((enable >> strip_id) & 1) != 0; } //------------------------------------------------------------------------------------------------------------------------- @@ -715,6 +837,21 @@ void bc45_decode_strip(const device uint8_t* input, } } + // the MTF list is cleared per tile: one thread decodes one tile, so this is the whole state + uint16_t mtf_pair[2][8]; + uint mtf_count[2]; + for (uint c = 0; c < NumChannels; ++c) + mtf_count[c] = 0; + + // the index-word dictionary is cleared per tile too: the words stay in fixed slots and + // dict_order[c][i] is the slot of rank i, mirroring bc4_dict (src/bc_packed.c); the decoder + // keeps no lookup map (the rank names the list position directly) + thread uint8_t dict_word[NumChannels][BC4_DICT_SIZE][6]; + thread uint8_t dict_order[NumChannels][BC4_DICT_SIZE]; + thread uint dict_count[NumChannels]; + for (uint c = 0; c < NumChannels; ++c) + dict_count[c] = 0; + const tile_bounds tb = tile_bounds_get(strip_id, width_blocks, height_blocks); const uint tile_width = tb.x1 - tb.x0; @@ -744,38 +881,88 @@ void bc45_decode_strip(const device uint8_t* input, top_e[c][1] = (uint8_t)((top >> 8) & 0xFF); } - // endpoint payload: the two wrapped deltas against the strip-chain predictor + // endpoint payload: with MTF, the 9-symbol rank of the block's endpoint pair + // (0..7 = the pair at that list position, 8 = escape to the two wrapped deltas + // against the strip-chain predictor, the list updated in either case); without + // MTF, the two deltas only uint8_t e[2]; - for (uint j = 0; j < 2; ++j) + if (mtf_enable[c]) { - uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][j], top_e[c][j], top_prev_e[c][j]); + uint8_t rank = decode_symbol(&compressed_stream, &mtf[c]); + + if (rank < 8) + { + uint16_t pair = mtf_pair[c][rank]; + e[0] = (uint8_t)(pair & 0xFF); + e[1] = (uint8_t)(pair >> 8); + } + else + { + for (uint j = 0; j < 2; ++j) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][j], top_e[c][j], top_prev_e[c][j]); - e[j] = (uint8_t)(pred + decode_symbol(&compressed_stream, &endpoint[c][j])); + e[j] = (uint8_t)(pred + decode_symbol(&compressed_stream, &endpoint[c][j])); + } + } + + mtf_touch(mtf_pair[c], &mtf_count[c], (uint16_t)(((uint16_t)e[1] << 8) | (uint16_t)e[0])); + } + else + { + for (uint j = 0; j < 2; ++j) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][j], top_e[c][j], top_prev_e[c][j]); + + e[j] = (uint8_t)(pred + decode_symbol(&compressed_stream, &endpoint[c][j])); + } } - // a flat block (identical endpoints, reconstructed exactly like the encoder sees the - // source) in mode 1 stores no index payload: the header value is expanded to all 16 + // index payload: with the dictionary enabled for the tile, one 256-symbol rank of + // the block's 48-bit index word (0..254 = the word at that move-to-front position, + // expanded into the index field; 255 = the escape, the full payload below, the + // word inserted at the front of the list); otherwise the full payload. a flat + // block (identical endpoints, reconstructed exactly like the encoder sees the + // source) in mode 1 stores no index payload at all: the header value is expanded + // to all 16 if ((e[0] == e[1]) && flat_mode[c]) { for (uint i = 0; i < 16; ++i) idx[i] = flat_value[c]; } - else + else if (dict_enable[c]) { - // index payload: the first index in raw 3 bits, then each index xored with its - // intra-block prediction, contextual on the 8 x 8 [left][top] matrix - idx[0] = bs_read_bits(&compressed_stream, 3); + uint rank = decode_symbol(&compressed_stream, &dict_rank[c]); - for (uint i = 1; i < 16; ++i) + if (rank < BC4_DICT_SIZE) + { + const thread uint8_t* w = &dict_word[c][dict_order[c][rank]][0]; + uint64_t wv = 0; + for (uint j = 0; j < 6; ++j) + wv |= ((uint64_t)w[j]) << (8 * j); + for (uint i = 0; i < 16; ++i) + idx[i] = (uint8_t)((wv >> (3 * i)) & 7); + + bc4_dict_touch(&dict_word[c][0][0], &dict_order[c][0], &dict_count[c], w, rank); + } + else { - // the missing neighbor of the pixel (first row, row start) defaults to 0 - uint8_t left = ((i & 3) == 0) ? 0 : idx[i - 1]; - uint8_t top = (i < 4) ? 0 : idx[i - 4]; - uint8_t p = ((i & 3) == 0) ? top : left; + bc4_decode_index_payload(&compressed_stream, &first_index[c], &index[c][0], idx); - idx[i] = (uint8_t)(p ^ decode_symbol8(&compressed_stream, &index[c][bc4_index_context(left, top)])); + thread uint8_t w[6]; + uint64_t wv = 0; + for (uint i = 0; i < 16; ++i) + wv |= ((uint64_t)idx[i] & 7) << (3 * i); + for (uint j = 0; j < 6; ++j) + w[j] = (uint8_t)(wv >> (8 * j)); + + bc4_dict_touch(&dict_word[c][0][0], &dict_order[c][0], &dict_count[c], w, BC4_DICT_SIZE); } } + else + { + bc4_decode_index_payload(&compressed_stream, &first_index[c], &index[c][0], idx); + } // the standard block: two endpoints + the 48-bit little-endian index field, as two aligned u32 words uint64_t v = 0; diff --git a/src/bc_packed.c b/src/bc_packed.c index 5a62db1..f6bace9 100644 --- a/src/bc_packed.c +++ b/src/bc_packed.c @@ -37,21 +37,9 @@ static inline uint8_t le_ceil_log2(uint32_t n) //----------------------------------------------------------------------------------------------------------------------------- -// Static Rice-Golomb entropy coder, inlined from the lite_encoding library. -// -// Every model is static: the rank table, the Rice parameter k, and the raw-byte escape -// q_escape are derived from a histogram before encoding and never adapt during the stream. -// Only the static encode/decode path is kept: there is no move-to-front, no k trend, and -// no literal/delta helpers, because the compressor only ever encodes pre-ranked symbols. -// -// Bitstream: a 64-bit reservoir buffers bits to keep I/O at byte granularity. -// Each symbol is written as q = rank >> k unary ones, a zero, then k remainder bits; a rank -// whose q reaches q_escape is written as q_escape unary bits, a zero, then the raw rank byte. -// -// A near-uniform histogram makes Rice uneconomical, so such a model falls back to a raw -// fixed-width code: bit 7 of k is set and the lower bits hold ceil(log2(num_symbols)), the -// number of bits written per symbol. The decoder mirrors this and reads that many bits back. -// A single-symbol model keeps the Rice path, as a 0-bit raw code would emit an empty payload. +// Static Rice-Golomb entropy coder inlined from the lite_encoding library: every model is +// fitted from a histogram before encoding and never adapts, so only the static path is kept +// (no move-to-front, no k trend, no literal / delta helpers) //----------------------------------------------------------------------------------------------------------------------------- #define LE_ALPHABET_SIZE (256U) @@ -240,10 +228,8 @@ static inline uint8_t le_read_bits(le_stream* s, uint8_t num_bits) } //----------------------------------------------------------------------------------------------------------------------------- -// Builds a static model from a histogram: sorts symbols by frequency (most frequent first, -// ties broken by the lower symbol), then searches (k, q_escape) jointly to minimize the -// model's total bit count. With q_escape = Q, every rank with q = rank >> k >= Q is written -// as Q unary bits + a zero + a raw byte (Q + 9 bits); the others use normal rice (q + 1 + k bits). +// Builds a static model from [histogram]: ranks the symbols by frequency (most frequent first, +// ties by the lower symbol) and searches (k, q_escape) jointly to minimize the total bit count static inline void le_static_model_init(le_model *model, const uint32_t* histogram, uint32_t num_symbols) { assert(num_symbols && num_symbols <= LE_ALPHABET_SIZE); @@ -340,11 +326,9 @@ static inline void le_static_model_init(le_model *model, const uint32_t* histogr model->num_symbols = (uint16_t)i; - // a near-uniform histogram is cheaper with a raw fixed-width code: every symbol costs - // ceil(log2(num_symbols)) bits, which beats the best Rice code found above in that case. - // flag it in bit 7 of k and store the bit width in the lower bits. a single-symbol model - // is excluded: its raw cost is 0 bits, which would emit an empty payload and break the - // stream's strict length invariant, so it keeps the (lossless) 1-bit Rice path. + // near-uniform histograms are cheaper with a raw fixed-width code: bit 7 of k flags it, the + // lower bits hold the bit width. a single-symbol model keeps the Rice path: its raw cost is + // 0 bits, and an empty payload would break the stream's length invariant uint8_t raw_bits = le_ceil_log2(model->num_symbols); if ((model->num_symbols > 1) && (min_total_bits > (uint64_t)raw_bits * total_count)) { @@ -499,6 +483,19 @@ static inline uint32_t le_symbol_cost(const le_model* model, uint8_t value) #define BC4_INDEX_CONTEXTS (BC4_INDEX_DIM * BC4_INDEX_DIM) #define BCP_MAX_CHANNELS (2) +// bc4/bc5 endpoint MTF: the length of the per-tile move-to-front list of distinct +// (endpoint0, endpoint1) pairs; rank BC4_MTF_SIZE is the escape symbol, so the MTF model +// holds BC4_MTF_SIZE + 1 symbols +#define BC4_MTF_SIZE (8) + +// bc4/bc5 index-word dictionary: the length of the per-tile move-to-front list of distinct +// 48-bit index words (the 6 index bytes of a block); rank BC4_DICT_SIZE is the escape +// symbol, so the rank model holds BC4_DICT_SIZE + 1 symbols +#define BC4_DICT_SIZE (255U) +// per-channel capacity of the encoder's dictionary lookup map: a power of two, a 0.25 load +// factor against the 255 live entries +#define BC4_DICT_MAP_SIZE (1024U) + //----------------------------------------------------------------------------------------------------------------------------- // Structures @@ -512,6 +509,7 @@ typedef struct hashmap_entry struct bcp_context { hashmap_entry* hashmap; + uint32_t hashmap_size; // entry count of [hashmap], 0 = not allocated bcp_mem_interface mem; // contextual color models: red/blue carry one model per green-delta context bucket (the chroma deltas @@ -552,6 +550,24 @@ struct bcp_context // of the 15 contextual symbols; 0 → the indices are stored as usual. decided per channel in the uint8_t bc4_index_mode[BCP_MAX_CHANNELS]; // [channel] uint8_t bc4_index_value[BCP_MAX_CHANNELS]; // [channel] 3-bit value, expanded to all 16 indices, mode 1 only + + // per-channel endpoint MTF-8: a 9-symbol model (ranks 0..7 = the endpoint pair at that + // move-to-front position, 8 = escape to the two endpoint deltas), enabled by bit 4 of the + // per-channel header byte. the slot is always written (a dummy 1-symbol model when disabled, + // the layout is fixed); the endpoint models fit on the escaped blocks only when enabled + le_model bc4_mtf_model[BCP_MAX_CHANNELS]; // [channel] + uint8_t bc4_mtf_enable[BCP_MAX_CHANNELS]; // [channel] + + // per-channel first-index model: one 8-symbol static model for the first index of each non-flat + // block, replacing the raw 3-bit field; the Rice / raw fallback of le_static_model_init is the + // self-gate, no header flag + le_model bc4_first_index_model[BCP_MAX_CHANNELS]; // [channel] + + // per-channel index-word dictionary: bit t = 1 → tile t writes one 256-symbol rank of the + // block's 48-bit index word (0..254 = the word at that move-to-front position, 255 = the full + // index payload), decided per tile by pricing the skipped payload against the rank symbols + uint64_t bc4_dict_enable[BCP_MAX_CHANNELS]; // [channel] + le_model bc4_dict_rank_model[BCP_MAX_CHANNELS]; // [channel] }; typedef struct bc1_block @@ -651,10 +667,9 @@ typedef struct color_dict } color_dict; //---------------------------------------------------------------------------------------------------------------------------- -// searches the dictionary for an exact match of [pair] among the [position] previous blocks of the -// chain (at most COLOR_DICT_SIZE of them): returns the distance in blocks to the most recent match -// (1 = the immediately previous block, up to min(position, COLOR_DICT_SIZE)), or 0 if there is none. -// [dict] must hold the color pairs of chain positions [max(0, position - COLOR_DICT_SIZE) .. position - 1]. +// distance in blocks to the most recent exact match of [pair] among the [position] previous +// blocks of the chain (1 = the immediately previous block), 0 if there is none; [dict] holds +// the pairs of chain positions [position - min(position, COLOR_DICT_SIZE) .. position - 1] static inline uint32_t color_dict_match(const color_dict* dict, uint32_t position, uint32_t pair) { uint32_t limit = (position < COLOR_DICT_SIZE) ? position : COLOR_DICT_SIZE; @@ -850,6 +865,41 @@ static inline uint32_t hash32(uint32_t x) return x; } +//---------------------------------------------------------------------------------------------------------------------------- +// First slot of the linear probe chain of [key]: the existing entry with that key or the first +// empty one (count 0), [size] a power of two +static inline uint32_t hashmap_find(hashmap_entry* table, uint32_t size, uint32_t key) +{ + uint32_t index = hash32(key) & (size - 1); + while ((table[index].count != 0) && (table[index].key != key)) + index = (index + 1) & (size - 1); + return index; +} + +//---------------------------------------------------------------------------------------------------------------------------- +// Removes [key] and shifts the probed entries back over the freed slot (backward-shift +// deletion), a no-op when the key is absent +static inline void hashmap_remove(hashmap_entry* table, uint32_t size, uint32_t key) +{ + uint32_t index = hashmap_find(table, size, key); + if (table[index].count == 0) + return; + + table[index].count = 0; + uint32_t next = (index + 1) & (size - 1); + while (table[next].count != 0) + { + uint32_t home = hash32(table[next].key) & (size - 1); + if (((index - home) & (size - 1)) < ((next - home) & (size - 1))) + { + table[index] = table[next]; + table[next].count = 0; + index = next; + } + next = (next + 1) & (size - 1); + } +} + //---------------------------------------------------------------------------------------------------------------------------- // Returns (popcount << 16) | index of the table entry with the smallest XOR popcount against [bitfield]. // Ties are broken by the fewest differing bytes, then by the largest entry value. @@ -937,14 +987,10 @@ uint32_t nearest32(const uint32_t* table, uint32_t table_size, uint32_t bitfield } //---------------------------------------------------------------------------------------------------------------------------- -// One Lloyd refinement round of the top table: assigns every sampled block to its nearest centroid, -// accumulates the XOR difference bit by bit per centroid, and moves each centroid to the bitwise -// majority of its assigned blocks. -// -// [sample_step] of 1 assigns every block (a full round), a larger step samples one block in -// [sample_step] to keep the round cheap, and [start_offset] de-aliases consecutive rounds. -// The bucket feedback drops the skip while the accumulated popcount error is high, so a round -// adapts between the two: with [sample_step] 1 both branches advance by one block. +// One Lloyd refinement round of the top table: assigns every sampled block to its nearest +// centroid and moves each centroid to the bitwise majority of its assigned blocks. [sample_step] +// of 1 assigns every block, a larger step samples one block in [sample_step] ([start_offset] +// de-aliases consecutive rounds); the bucket feedback drops the skip while the popcount error is high static void vq_refine_round(const void* input, uint32_t num_blocks, uint32_t block_stride, uint32_t* centroids, uint32_t num_centroids, vq_cluster* clusters, uint32_t sample_step, uint32_t start_offset) { @@ -1031,6 +1077,23 @@ void vq_top_table(const void* input, uint32_t num_blocks, uint32_t block_stride, *num_entries = num_clusters; } +//---------------------------------------------------------------------------------------------------------------------------- +// Grows [ctx->hashmap] to at least [size] entries (never shrinks), reusing the existing +// buffer when it is already large enough +static bool hashmap_ensure(bcp_context* ctx, uint32_t size) +{ + if (ctx->hashmap_size >= size) + return true; + + hashmap_entry* table = (hashmap_entry*)ctx->mem.realloc_fn(ctx->hashmap, (size_t)ctx->hashmap_size * sizeof(hashmap_entry), (size_t)size * sizeof(hashmap_entry), ctx->mem.user); + if (table == NULL) + return false; + + ctx->hashmap = table; + ctx->hashmap_size = size; + return true; +} + //---------------------------------------------------------------------------------------------------------------------------- void build_top_table(hashmap_entry* hashmap, const void* input, uint32_t num_blocks, uint32_t block_stride, uint32_t* output, uint32_t* num_entries) { @@ -1043,25 +1106,9 @@ void build_top_table(hashmap_entry* hashmap, const void* input, uint32_t num_blo { const bc1_block* b = (const bc1_block*) input + i * block_stride; - uint32_t h = hash32(b->indices); - uint32_t index = h & (HASHMAP_SIZE - 1); - uint32_t first_index = index; - - bool inserted = false; - while (!inserted) - { - if ((hashmap[index].count == 0) || (hashmap[index].key == b->indices)) - { - hashmap[index].key = b->indices; - hashmap[index].count++; - inserted = true; - } - else - { - index = (index + 1) & (HASHMAP_SIZE - 1); - assert(index != first_index); - } - } + uint32_t index = hashmap_find(hashmap, HASHMAP_SIZE, b->indices); + hashmap[index].key = b->indices; + hashmap[index].count++; } // clear the table @@ -1254,14 +1301,9 @@ void init_static_models(bcp_context* ctx, const void* input, uint32_t width_bloc ctx->strip_predictor |= (uint64_t)1 << strip_index; } - // provisional histogram: every block's color deltas, the dictionary not involved, plus the index - // symbols (the dictionary does not touch the indices). the color models fit on this pass price - // the matched blocks in the per-strip dictionary decision below, the final color models are - // refit on the deltas that are actually emitted after the decision - // the flat-index mode is decided here too: mode 1 (a block with identical endpoints stores no - // index payload, the decoder expands the header value) only if at least one block has identical - // endpoints and every such block holds the same uniform index word, else mode 0 (garbage or - // differing indices on a flat block force the full encoding) + // provisional histogram: the color deltas with the dictionary not involved, so the models fit + // here can price the matched blocks in the per-strip dictionary decision; the final color + // models are refit on the deltas actually emitted bool flat_block = false; bool non_uniform_flat = false; bool divergent_flat = false; @@ -1291,6 +1333,8 @@ void init_static_models(bcp_context* ctx, const void* input, uint32_t width_bloc color_hists_add(&hist, current, color_reference); + // flat block: the flat-index mode is 1 only if every such block holds the same + // uniform index word, else mode 0 (garbage or differing words force the full encoding) if (current->color[0] == current->color[1]) { const uint8_t value = (uint8_t)(current->indices & 3); @@ -1338,9 +1382,8 @@ void init_static_models(bcp_context* ctx, const void* input, uint32_t width_bloc init_color_models(ctx, &hist); // per-strip color-pair dictionary enable: an enabled strip pays one flag bit per block, so it - // wins only when the savings of its matched blocks, the six deltas they would emit minus the - // reference they pay, exceed that. the matched blocks of an enabled strip emit no deltas, so - // their deltas are subtracted from the histogram before the final color models are refit + // wins only when its matched blocks save more deltas than that; they emit no deltas, so their + // deltas are subtracted from the histogram before the final color models are refit ctx->strip_dict_enable = 0; color_dict dict; color_hists matched; @@ -1532,6 +1575,168 @@ static inline void bc4_pack_indices(const uint8_t idx[16], bc4_block* b) b->indices[j] = (uint8_t)(v >> (8*j)); } +//----------------------------------------------------------------------------------------------------------------------------- +// MTF-8 list of the last distinct (endpoint0, endpoint1) pairs of a tile's zigzag chain, +// cleared per tile: pair = endpoint0 | endpoint1 << 8 +typedef struct mtf_list +{ + uint16_t pair[BC4_MTF_SIZE]; + uint32_t count; // distinct pairs seen so far in the tile, 0..BC4_MTF_SIZE +} mtf_list; + +//----------------------------------------------------------------------------------------------------------------------------- +// rank of [pair] in the MTF list, BC4_MTF_SIZE if absent (the escape symbol) +static inline uint32_t mtf_rank(const mtf_list* m, uint16_t pair) +{ + for (uint32_t i = 0; i < m->count; ++i) + if (m->pair[i] == pair) + return i; + + return BC4_MTF_SIZE; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// move [pair] to the front of the list, inserting it if new: the list holds distinct pairs, +// the oldest one is dropped once it is full +static inline void mtf_touch(mtf_list* m, uint16_t pair) +{ + int32_t at = -1; + for (uint32_t i = 0; i < m->count; ++i) + if (m->pair[i] == pair) + { + at = (int32_t)i; + break; + } + + if (at >= 0) + { + for (int32_t j = at; j > 0; --j) + m->pair[j] = m->pair[j - 1]; + } + else if (m->count < BC4_MTF_SIZE) + { + for (uint32_t j = m->count; j > 0; --j) + m->pair[j] = m->pair[j - 1]; + m->count++; + } + else + { + for (uint32_t j = BC4_MTF_SIZE - 1; j > 0; --j) + m->pair[j] = m->pair[j - 1]; + } + + m->pair[0] = pair; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// per-tile index-word dictionary: the 48-bit index words stay in fixed slots (stable for the +// lifetime of the tile) and [order] holds the recency permutation, order[i] = slot of rank i, +// so a touch shifts the permutation only +typedef struct bc4_dict +{ + uint8_t word[BC4_DICT_SIZE][6]; + uint8_t order[BC4_DICT_SIZE]; + uint8_t count; // distinct words seen so far in the tile, 0..BC4_DICT_SIZE +} bc4_dict; + +//----------------------------------------------------------------------------------------------------------------------------- +// 32-bit key of a 48-bit index word: the two halves hashed and xored, a collision only costs +// a probe (the 6 bytes are compared before a hit is accepted) +static inline uint32_t bc4_dict_key(const uint8_t* w) +{ + uint32_t lo = (uint32_t)w[0] | ((uint32_t)w[1] << 8) | ((uint32_t)w[2] << 16) | ((uint32_t)w[3] << 24); + uint32_t hi = (uint32_t)w[4] | ((uint32_t)w[5] << 8); + return hash32(lo) ^ hash32(hi); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// rank of the 48-bit [word] in the dictionary, BC4_DICT_SIZE if absent (the escape): [map] +// resolves the slot, the slot to rank scan of [order] is 1-byte compares +static inline uint32_t bc4_dict_lookup(const bc4_dict* d, const hashmap_entry* map, uint32_t map_size, const uint8_t* word) +{ + uint32_t key = bc4_dict_key(word); + uint32_t index = hashmap_find((hashmap_entry*)map, map_size, key); + + while (map[index].count != 0) + { + uint32_t slot = map[index].count - 1; + if (memcmp(d->word[slot], word, 6) == 0) + { + for (uint32_t rank = 0; rank < d->count; ++rank) + if (d->order[rank] == (uint8_t)slot) + return rank; + } + index = (index + 1) & (map_size - 1); + } + + return BC4_DICT_SIZE; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// Moves [word] to the front of the dictionary: on a hit ([rank] < BC4_DICT_SIZE) the +// permutation shifts only, on a miss the word takes a fresh slot (the tail slot is evicted +// and removed from [map] once the list is full); [map] = NULL on the decoder +static inline void bc4_dict_touch(bc4_dict* d, hashmap_entry* map, uint32_t map_size, const uint8_t* word, uint32_t rank) +{ + if (rank < BC4_DICT_SIZE) + { + uint8_t slot = d->order[rank]; + memmove(&d->order[1], &d->order[0], rank); + d->order[0] = slot; + return; + } + + uint32_t count = d->count; + uint32_t slot = (count < BC4_DICT_SIZE) ? count : d->order[BC4_DICT_SIZE - 1]; + + if (map && (count == BC4_DICT_SIZE)) + hashmap_remove(map, map_size, bc4_dict_key(d->word[slot])); + + memcpy(d->word[slot], word, 6); + memmove(&d->order[1], &d->order[0], (size_t)((count < BC4_DICT_SIZE) ? count : (BC4_DICT_SIZE - 1))); + d->order[0] = (uint8_t)slot; + d->count = (uint8_t)((count < BC4_DICT_SIZE) ? count + 1 : BC4_DICT_SIZE); + + if (map) + { + uint32_t key = bc4_dict_key(word); + hashmap_entry* at = &map[hashmap_find(map, map_size, key)]; + at->key = key; + at->count = (uint32_t)(slot + 1); + } +} + +//----------------------------------------------------------------------------------------------------------------------------- +// packs the per-channel header byte: flat-index mode (bit 0), the 3-bit flat value (bits 1..3), +// the endpoint MTF-8 enable (bit 4) +static inline uint8_t bc4_header_byte(uint8_t mode, uint8_t value, uint8_t mtf_enable) +{ + return (uint8_t)(mode | (value << 1) | (mtf_enable << 4)); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// unpacks a header byte written by bc4_header_byte into the [channel] fields of [ctx] +static inline void bc4_header_parse(bcp_context* ctx, uint32_t channel, uint8_t byte) +{ + ctx->bc4_index_mode[channel] = byte & 1; + ctx->bc4_index_value[channel] = (byte >> 1) & 7; + ctx->bc4_mtf_enable[channel] = (byte >> 4) & 1; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// total Rice / raw payload bits of [hist] under the static [model]: sum of the per-symbol cost, +// the same bits le_encode_symbol would write +static inline uint64_t model_total_cost(const le_model* model, const uint32_t* hist, uint32_t num_symbols) +{ + uint64_t bits = 0; + + for (uint32_t s = 0; s < num_symbols; ++s) + if (hist[s]) + bits += (uint64_t)hist[s] * le_symbol_cost(model, (uint8_t)s); + + return bits; +} + //----------------------------------------------------------------------------------------------------------------------------- // Per-channel histogram of the bc4/bc5 payload symbols: 2 endpoint models (256 symbols) + // 64 index models (8 symbols each) @@ -1539,19 +1744,25 @@ typedef struct bc4_hists { uint32_t endpoint[2][256]; uint32_t index[BC4_INDEX_CONTEXTS][8]; + uint32_t dict[BC4_DICT_SIZE + 1]; // rank histogram: ranks 0..254 + the escape } bc4_hists; //----------------------------------------------------------------------------------------------------------------------------- -// Fits the bc4/bc5 static models from [input]: the per-channel tile seed is the average of the -// first block of each tile in chain order (as BC1), then one histogram pass with the exact -// tile predictors of the encoder. there is no per-tile mode decision, so a single fit is final. -// the per-channel flat-index mode is also decided in the histogram pass: mode 1 (a block whose -// two endpoints are identical stores no index payload, the decoder expands the header value) only if -// at least one such block exists and every such block holds the same uniform 3-bit value, else mode -// 0 (garbage or differing indices on a flat block force the full 15-symbol encoding) +// gcc 13 misreports the per-strip MTF state as maybe-uninitialized in the ipa-constprop +// clones of this function; count is cleared per strip and pair is only read below count +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif static void bc4_init_models(bcp_context* ctx, const void* image, uint32_t width_blocks, uint32_t height_blocks, uint32_t num_strips, uint32_t num_channels, uint32_t block_stride) { + if (!hashmap_ensure(ctx, (uint32_t)BCP_MAX_CHANNELS * BC4_DICT_MAP_SIZE)) + return; + bc4_hists hist[BCP_MAX_CHANNELS] = { 0 }; + uint32_t esc_hist[BCP_MAX_CHANNELS][2][256] = { 0 }; // endpoint deltas of the MTF-escaped blocks + uint32_t mtf_hist[BCP_MAX_CHANNELS][BC4_MTF_SIZE + 1] = { 0 }; // MTF ranks 0..BC4_MTF_SIZE-1 + escape + uint32_t first_hist[BCP_MAX_CHANNELS][8] = { 0 }; // first index of the non-flat blocks uint32_t sums[BCP_MAX_CHANNELS][2] = { 0 }; uint8_t prev_e[BCP_MAX_CHANNELS][2], top_e[BCP_MAX_CHANNELS][2], top_prev_e[BCP_MAX_CHANNELS][2]; bool flat_block[BCP_MAX_CHANNELS] = { false, false }; @@ -1559,18 +1770,53 @@ static void bc4_init_models(bcp_context* ctx, const void* image, uint32_t width_ bool divergent_flat[BCP_MAX_CHANNELS] = { false, false }; uint8_t flat_value[BCP_MAX_CHANNELS] = { 0, 0 }; - // pass 1: tile seeds, the average of the first block of each tile in chain order + // pass 1: tile seeds (the average of the first block of each tile in chain order) and the + // per-channel flat-index mode, decided before pass 2, whose dictionary simulation only + // touches the blocks that store an index payload for(uint32_t strip_index=0; strip_indexendpoint[0]; + sums[c][1] += b->endpoint[1]; + } + + if (b->endpoint[0] == b->endpoint[1]) + { + uint8_t idx[16]; + bc4_unpack_indices(b, idx); + const uint8_t first = idx[0]; + if (!flat_block[c]) + flat_value[c] = first; + else if (first != flat_value[c]) + divergent_flat[c] = true; - sums[c][0] += b->endpoint[0]; - sums[c][1] += b->endpoint[1]; + for(uint32_t i=0; i<16; ++i) + { + if (idx[i] != first) + { + non_uniform_flat[c] = true; + break; + } + } + + flat_block[c] = true; + } + } + } } } @@ -1578,10 +1824,21 @@ static void bc4_init_models(bcp_context* ctx, const void* image, uint32_t width_ { for(uint32_t e=0; e<2; ++e) ctx->bc4_strip_seed[c][e] = (uint8_t)(sums[c][e] / num_strips); + + if (flat_block[c] && !non_uniform_flat[c] && !divergent_flat[c]) + { + ctx->bc4_index_mode[c] = 1; + ctx->bc4_index_value[c] = flat_value[c]; + } + else + { + ctx->bc4_index_mode[c] = 0; + ctx->bc4_index_value[c] = 0; + } } - // pass 2: histograms with the exact tile predictors of the encoder, plus the per-channel - // flat-index mode decision (see the function header) + // pass 2: histograms with the exact tile predictors of the encoder, plus the per-tile + // index-word dictionary simulation (the rank histogram of the payload-emitting blocks) for(uint32_t strip_index=0; strip_indexhashmap[c * BC4_DICT_MAP_SIZE + i].count = 0; + } + tile_bounds tb = tile_bounds_get(strip_index, width_blocks, height_blocks, num_strips); uint32_t tile_width = tb.x1 - tb.x0; @@ -1619,33 +1888,35 @@ static void bc4_init_models(bcp_context* ctx, const void* image, uint32_t width_ top_e[c][1] = t->endpoint[1]; } + uint16_t pair = (uint16_t)(b->endpoint[0] | (b->endpoint[1] << 8)); + uint32_t rank = mtf_rank(&mtf[c], pair); + // MTF-8 is priced in both variants: the rank histogram plus, on escape, the endpoint deltas + mtf_hist[c][rank]++; + mtf_touch(&mtf[c], pair); + for(uint32_t e=0; e<2; ++e) { uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); + uint8_t delta = delta_encode_wrap(pred, b->endpoint[e]); - hist[c].endpoint[e][delta_encode_wrap(pred, b->endpoint[e])]++; + hist[c].endpoint[e][delta]++; + if (rank >= BC4_MTF_SIZE) + esc_hist[c][e][delta]++; } bc4_unpack_indices(b, idx); + first_hist[c][idx[0]]++; - if (b->endpoint[0] == b->endpoint[1]) + // index-word dictionary simulation: a block that stores the index payload + // updates the per-tile list, a flat block in mode 1 never touches it + const bool flat = (b->endpoint[0] == b->endpoint[1]); + if (!(flat && ctx->bc4_index_mode[c])) { - const uint8_t first = idx[0]; - if (!flat_block[c]) - flat_value[c] = first; - else if (first != flat_value[c]) - divergent_flat[c] = true; - - for(uint32_t i=0; i<16; ++i) - { - if (idx[i] != first) - { - non_uniform_flat[c] = true; - break; - } - } + hashmap_entry* map = &ctx->hashmap[c * BC4_DICT_MAP_SIZE]; + uint32_t rank = bc4_dict_lookup(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices); - flat_block[c] = true; + hist[c].dict[rank]++; + bc4_dict_touch(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices, rank); } for(uint32_t i=1; i<16; ++i) @@ -1672,30 +1943,163 @@ static void bc4_init_models(bcp_context* ctx, const void* image, uint32_t width_ for(uint32_t c=0; cbc4_dict_enable[c] = 0; + // price the endpoint pass with and without MTF-8 against the models each one would fit: + // the payload bits plus the model headers they store (a disabled MTF writes a dummy + // 1-symbol model, the stream layout is fixed). the cheaper wins, per channel + le_model ep_no[2], ep_mtf[2], mtf_model; + for(uint32_t e=0; e<2; ++e) { - ctx->bc4_index_mode[c] = 1; - ctx->bc4_index_value[c] = flat_value[c]; + le_static_model_init(&ep_no[e], &hist[c].endpoint[e][0], 256); + le_static_model_init(&ep_mtf[e], &esc_hist[c][e][0], 256); } + le_static_model_init(&mtf_model, mtf_hist[c], BC4_MTF_SIZE + 1); + + uint64_t cost_no = (uint64_t)(3 + 1) * 8; // the dummy MTF model of a disabled channel + uint64_t cost_mtf = (uint64_t)(3 + mtf_model.num_symbols) * 8 + model_total_cost(&mtf_model, mtf_hist[c], BC4_MTF_SIZE + 1); + for(uint32_t e=0; e<2; ++e) + { + cost_no += (uint64_t)(3 + ep_no[e].num_symbols) * 8 + model_total_cost(&ep_no[e], &hist[c].endpoint[e][0], 256); + cost_mtf += (uint64_t)(3 + ep_mtf[e].num_symbols) * 8 + model_total_cost(&ep_mtf[e], &esc_hist[c][e][0], 256); + } + + ctx->bc4_mtf_enable[c] = (uint8_t)(cost_mtf < cost_no); + for(uint32_t e=0; e<2; ++e) + ctx->bc4_endpoint_model[c][e] = ctx->bc4_mtf_enable[c] ? ep_mtf[e] : ep_no[e]; + if (ctx->bc4_mtf_enable[c]) + ctx->bc4_mtf_model[c] = mtf_model; else + le_static_model_init(&ctx->bc4_mtf_model[c], NULL, BC4_MTF_SIZE + 1); // all-zero histogram: a dummy 1-symbol model, never used + + le_static_model_init(&ctx->bc4_first_index_model[c], first_hist[c], 8); + le_static_model_init(&ctx->bc4_dict_rank_model[c], hist[c].dict, BC4_DICT_SIZE + 1); + for(uint32_t i=0; ibc4_index_model[c][i], &hist[c].index[i][0], 8); + } + + // pass 3: gate the dictionary per tile: re-simulate the list, price the skipped hit + // payloads against the fitted index models and the rank symbols against the fitted rank + // model, enable the tile when the saved bits win + bc4_dict dict[BCP_MAX_CHANNELS]; + for(uint32_t strip_index=0; strip_indexbc4_index_mode[c] = 0; - ctx->bc4_index_value[c] = 0; + dict[c].count = 0; + saved[c] = 0; + for(uint32_t i=0; ihashmap[c * BC4_DICT_MAP_SIZE + i].count = 0; + } + memset(rank_temp, 0, sizeof(rank_temp)); + + tile_bounds tb = tile_bounds_get(strip_index, width_blocks, height_blocks, num_strips); + uint32_t tile_width = tb.x1 - tb.x0; + + for(uint32_t y = tb.y0; y < tb.y1; ++y) + { + for(uint32_t x = 0; x < tile_width; ++x) + { + uint32_t zigzag_x = tb.x0 + ((y & 1) ? x : tile_width - x - 1); + + for(uint32_t c=0; cendpoint[0] == b->endpoint[1]); + + if (flat && ctx->bc4_index_mode[c]) + continue; + + hashmap_entry* map = &ctx->hashmap[c * BC4_DICT_MAP_SIZE]; + uint32_t rank = bc4_dict_lookup(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices); + + rank_temp[rank]++; + if (rank < BC4_DICT_SIZE) + { + uint8_t idx[16]; + bc4_unpack_indices(b, idx); + + saved[c] += le_symbol_cost(&ctx->bc4_first_index_model[c], idx[0]); + for(uint32_t i=1; i<16; ++i) + { + uint8_t left = ((i & 3) == 0) ? 0 : idx[i-1]; + uint8_t top = (i < 4) ? 0 : idx[i-4]; + uint8_t p = ((i & 3) == 0) ? top : left; + + saved[c] += le_symbol_cost(&ctx->bc4_index_model[c][bc4_index_context(left, top)], p ^ idx[i]); + } + } + + bc4_dict_touch(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices, rank); + } + } + } + + for(uint32_t c=0; cbc4_dict_rank_model[c], (uint8_t)r); + + if (saved[c] > paid) + ctx->bc4_dict_enable[c] |= (uint64_t)1 << strip_index; } } for(uint32_t c=0; cbc4_endpoint_model[c][e], &hist[c].endpoint[e][0], 256); - for(uint32_t i=0; ibc4_index_model[c][i], &hist[c].index[i][0], 8); + if (ctx->bc4_dict_enable[c] == 0) + le_static_model_init(&ctx->bc4_dict_rank_model[c], NULL, BC4_DICT_SIZE + 1); // no tile enabled: a dummy 1-symbol model, never used + } +} +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif + +//----------------------------------------------------------------------------------------------------------------------------- +// Index payload of a block that stores indices: the first index with its 8-symbol model, then +// each index xored with its intra-block prediction (the 8 x 8 [left][top] context matrix) +static inline void bc4_encode_index_payload(le_stream* s, le_model* first_index, le_model* index_models, const uint8_t* idx) +{ + le_encode_symbol(s, first_index, idx[0]); + + for(uint32_t i=1; i<16; ++i) + { + uint8_t left = ((i & 3) == 0) ? 0 : idx[i-1]; + uint8_t top = (i < 4) ? 0 : idx[i-4]; + uint8_t p = ((i & 3) == 0) ? top : left; + + le_encode_symbol(s, &index_models[bc4_index_context(left, top)], p ^ idx[i]); + } +} + +//----------------------------------------------------------------------------------------------------------------------------- +// Mirror of bc4_encode_index_payload on decode +static inline void bc4_decode_index_payload(le_stream* s, le_model* first_index, le_model* index_models, uint8_t* idx) +{ + idx[0] = (uint8_t)le_decode_symbol(s, first_index); + + for(uint32_t i=1; i<16; ++i) + { + uint8_t left = ((i & 3) == 0) ? 0 : idx[i-1]; + uint8_t top = (i < 4) ? 0 : idx[i-4]; + uint8_t p = ((i & 3) == 0) ? top : left; + + idx[i] = (uint8_t)(p ^ le_decode_symbol(s, &index_models[bc4_index_context(left, top)])); } } //----------------------------------------------------------------------------------------------------------------------------- // Compresses a BC4 / BC5 texture: [image] holds (width/4) * (height/4) blocks, each // [num_channels] bc4_block (1 for BC4, red + green for BC5). shared by the two formats +// gcc 13 misreports the per-strip MTF state as maybe-uninitialized in the ipa-constprop +// clones of this function; count is cleared per strip and pair is only read below count +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t width, uint32_t height, uint8_t* output, size_t output_length, uint32_t* num_strips, uint32_t num_channels, uint32_t block_stride) { if ((width < 16) || (height < 256) || !image || !ctx || !output || !num_strips || (num_channels < 1) || (num_channels > BCP_MAX_CHANNELS)) @@ -1710,12 +2114,20 @@ static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t wi byte_stream stream = {.buffer = output, .length = output_length, .pos = 0}; - // store models: per channel, the 2 endpoint models (256 symbols) then the 64 index models (8 symbols) + // per channel: the 2 endpoint models, the MTF-8 model (a dummy 1-symbol model when disabled), + // the first-index model, the dictionary rank model (a dummy 1-symbol model when no tile is + // enabled) and the 64 index models for(uint32_t c=0; cbc4_endpoint_model[c][e], &stream)) return 0; + if (!save_static_model(&ctx->bc4_mtf_model[c], &stream)) + return 0; + if (!save_static_model(&ctx->bc4_first_index_model[c], &stream)) + return 0; + if (!save_static_model(&ctx->bc4_dict_rank_model[c], &stream)) + return 0; for(uint32_t i=0; ibc4_index_model[c][i], &stream)) return 0; @@ -1731,14 +2143,22 @@ static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t wi stream.buffer[stream.pos++] = ctx->bc4_strip_seed[c][e]; } - // flat-index mode + value, one byte per channel (mode | value << 1), written right after the - // seeds. the model region is always even-sized, so these bytes sit on an odd stream position and - // the 2-align below can never land on them and zero them, keeping the encoder and the decoder in - // agreement + // flat-index mode + value + endpoint MTF-8 enable, one byte per channel if (stream.pos + num_channels > stream.length) return 0; for(uint32_t c=0; cbc4_index_mode[c] | (ctx->bc4_index_value[c] << 1)); + stream.buffer[stream.pos++] = bc4_header_byte(ctx->bc4_index_mode[c], ctx->bc4_index_value[c], ctx->bc4_mtf_enable[c]); + + // index-word dictionary enable: one uint64 per channel, bit i = tile i, a contiguous + // block after the header bytes, u32-aligned so the GPU reads it as words + stream_align(&stream, sizeof(uint32_t)); + if (stream.pos + 8 * num_channels > stream.length) + return 0; + for(uint32_t c=0; cbc4_dict_enable[c] >> (j*8)) & 0xff); + } stream_align(&stream, sizeof(uint16_t)); size_t strips_offset_array_size = sizeof(uint16_t) * (*num_strips - 1); @@ -1778,6 +2198,19 @@ static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t wi } } + // the MTF list and the index-word dictionary are cleared per tile, mirroring the pre-pass + mtf_list mtf[BCP_MAX_CHANNELS]; + bc4_dict dict[BCP_MAX_CHANNELS]; + uint8_t dict_enable[BCP_MAX_CHANNELS]; + for(uint32_t c=0; cbc4_dict_enable[c] >> strip_index) & 1); + for(uint32_t i=0; ihashmap[c * BC4_DICT_MAP_SIZE + i].count = 0; + } + tile_bounds tb = tile_bounds_get(strip_index, width_blocks, height_blocks, *num_strips); uint32_t tile_width = tb.x1 - tb.x0; @@ -1802,34 +2235,61 @@ static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t wi top_e[c][1] = t->endpoint[1]; } - // endpoint payload: the two wrapped deltas against the strip-chain predictor - for(uint32_t e=0; e<2; ++e) + if (ctx->bc4_mtf_enable[c]) { - uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); + // the 9-symbol rank of the block's pair: 0..7 = the pair at that list position, + // 8 = escape to the two wrapped deltas; the list is updated in either case + uint16_t pair = (uint16_t)(b->endpoint[0] | (b->endpoint[1] << 8)); + uint32_t rank = mtf_rank(&mtf[c], pair); - le_encode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e], delta_encode_wrap(pred, b->endpoint[e])); + le_encode_symbol(&compressed_stream, &ctx->bc4_mtf_model[c], (uint8_t)rank); + mtf_touch(&mtf[c], pair); + + if (rank >= BC4_MTF_SIZE) + { + for(uint32_t e=0; e<2; ++e) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); + + le_encode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e], delta_encode_wrap(pred, b->endpoint[e])); + } + } } + else + { + for(uint32_t e=0; e<2; ++e) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); - // index payload: the first index in raw 3 bits, then each index xored with its - // intra-block prediction, contextual on the 8 x 8 [left][top] matrix - bc4_unpack_indices(b, idx); + le_encode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e], delta_encode_wrap(pred, b->endpoint[e])); + } + } - // a flat block (identical endpoints) in mode 1 stores no index payload: the - // decoder expands the header value to all 16 indices; otherwise the full - // 15 contextual symbols + // a flat block in mode 1 stores no index payload: the decoder expands the header value const bool flat = (b->endpoint[0] == b->endpoint[1]); if (!(flat && ctx->bc4_index_mode[c])) { - le_write_bits(&compressed_stream, idx[0], 3); - - for(uint32_t i=1; i<16; ++i) + if (dict_enable[c]) { - // the missing neighbor of the pixel (first row, row start) defaults to 0 - uint8_t left = ((i & 3) == 0) ? 0 : idx[i-1]; - uint8_t top = (i < 4) ? 0 : idx[i-4]; - uint8_t p = ((i & 3) == 0) ? top : left; + // one 256-symbol rank of the 48-bit index word + hashmap_entry* map = &ctx->hashmap[c * BC4_DICT_MAP_SIZE]; + uint32_t rank = bc4_dict_lookup(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices); + + le_encode_symbol(&compressed_stream, &ctx->bc4_dict_rank_model[c], (uint8_t)rank); - le_encode_symbol(&compressed_stream, &ctx->bc4_index_model[c][bc4_index_context(left, top)], p ^ idx[i]); + if (rank >= BC4_DICT_SIZE) + { + // escape: the full payload, the word goes to the front of the list + bc4_unpack_indices(b, idx); + bc4_encode_index_payload(&compressed_stream, &ctx->bc4_first_index_model[c], &ctx->bc4_index_model[c][0], idx); + } + + bc4_dict_touch(&dict[c], map, BC4_DICT_MAP_SIZE, b->indices, rank); + } + else + { + bc4_unpack_indices(b, idx); + bc4_encode_index_payload(&compressed_stream, &ctx->bc4_first_index_model[c], &ctx->bc4_index_model[c][0], idx); } } @@ -1857,6 +2317,9 @@ static size_t bcp_compress_bc45(bcp_context* ctx, const void* image, uint32_t wi return stream.pos; } +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif //----------------------------------------------------------------------------------------------------------------------------- // Decompresses one strip of a BC4 / BC5 stream: the mirror of bcp_compress_bc45, the strip-chain @@ -1871,12 +2334,19 @@ static bool bcp_decompress_bc45(bcp_context* ctx, const void* input, size_t inpu byte_stream stream = {.buffer = (uint8_t*)input, .length = input_length, .pos = 0}; - // load models: per channel, the 2 endpoint models then the 64 index models + // load models: per channel, the 2 endpoint models, the endpoint MTF-8 model, the first-index + // model, the index-word dictionary rank model then the 64 index models for(uint32_t c=0; cbc4_endpoint_model[c][e], &stream)) return false; + if (!load_static_model(&ctx->bc4_mtf_model[c], &stream)) + return false; + if (!load_static_model(&ctx->bc4_first_index_model[c], &stream)) + return false; + if (!load_static_model(&ctx->bc4_dict_rank_model[c], &stream)) + return false; for(uint32_t i=0; ibc4_index_model[c][i], &stream)) return false; @@ -1893,11 +2363,19 @@ static bool bcp_decompress_bc45(bcp_context* ctx, const void* input, size_t inpu if (stream.pos + num_channels > stream.length) return false; + for(uint32_t c=0; c stream.length) + return false; for(uint32_t c=0; cbc4_index_mode[c] = flat_byte & 1; - ctx->bc4_index_value[c] = (flat_byte >> 1) & 7; + ctx->bc4_dict_enable[c] = 0; + for(uint32_t j=0; j<8; ++j) + ctx->bc4_dict_enable[c] |= (uint64_t)stream.buffer[stream.pos++] << (j*8); } read_stream_align(&stream, sizeof(uint16_t)); @@ -1933,6 +2411,19 @@ static bool bcp_decompress_bc45(bcp_context* ctx, const void* input, size_t inpu } } + // the MTF list and the index-word dictionary are cleared per tile, one thread decodes one + // tile so this is the whole state; the decoder keeps no lookup map (the rank names the + // list position directly) + mtf_list mtf[BCP_MAX_CHANNELS]; + bc4_dict dict[BCP_MAX_CHANNELS]; + uint8_t dict_enable[BCP_MAX_CHANNELS]; + for(uint32_t c=0; cbc4_dict_enable[c] >> strip_index) & 1); + } + tile_bounds tb = tile_bounds_get(strip_index, width_blocks, height_blocks, num_strips); uint32_t tile_width = tb.x1 - tb.x0; @@ -1957,39 +2448,67 @@ static bool bcp_decompress_bc45(bcp_context* ctx, const void* input, size_t inpu top_e[c][1] = t->endpoint[1]; } - // endpoint payload: the two wrapped deltas against the strip-chain predictor - for(uint32_t e=0; e<2; ++e) + if (ctx->bc4_mtf_enable[c]) + { + uint32_t rank = le_decode_symbol(&compressed_stream, &ctx->bc4_mtf_model[c]); + + if (rank < BC4_MTF_SIZE) + { + b->endpoint[0] = (uint8_t)(mtf[c].pair[rank] & 0xFF); + b->endpoint[1] = (uint8_t)(mtf[c].pair[rank] >> 8); + } + else + { + for(uint32_t e=0; e<2; ++e) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); + + b->endpoint[e] = delta_decode_wrap(pred, le_decode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e])); + } + } + + mtf_touch(&mtf[c], (uint16_t)(b->endpoint[0] | (b->endpoint[1] << 8))); + } + else { - uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); + for(uint32_t e=0; e<2; ++e) + { + uint8_t pred = bc4_endpoint_predict(first_row, row_start, prev_e[c][e], top_e[c][e], top_prev_e[c][e]); - b->endpoint[e] = delta_decode_wrap(pred, le_decode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e])); + b->endpoint[e] = delta_decode_wrap(pred, le_decode_symbol(&compressed_stream, &ctx->bc4_endpoint_model[c][e])); + } } - // index payload: the first index in raw 3 bits, then each index xored with its - // intra-block prediction, contextual on the 8 x 8 [left][top] matrix - // a flat block (identical endpoints, reconstructed exactly like the encoder sees the - // source) in mode 1 stores no index payload: the header value is expanded to all 16 + // a flat block in mode 1 stores no index payload: the header value is expanded to all 16 indices const bool flat = (b->endpoint[0] == b->endpoint[1]); if (flat && ctx->bc4_index_mode[c]) { for(uint32_t i=0; i<16; ++i) idx[i] = ctx->bc4_index_value[c]; + + bc4_pack_indices(idx, b); } - else + else if (dict_enable[c]) { - idx[0] = le_read_bits(&compressed_stream, 3); + // one 256-symbol rank of the 48-bit index word + uint32_t rank = le_decode_symbol(&compressed_stream, &ctx->bc4_dict_rank_model[c]); - for(uint32_t i=1; i<16; ++i) + if (rank < BC4_DICT_SIZE) + memcpy(b->indices, dict[c].word[dict[c].order[rank]], 6); + else { - uint8_t left = ((i & 3) == 0) ? 0 : idx[i-1]; - uint8_t top = (i < 4) ? 0 : idx[i-4]; - uint8_t p = ((i & 3) == 0) ? top : left; - - idx[i] = (uint8_t)(p ^ le_decode_symbol(&compressed_stream, &ctx->bc4_index_model[c][bc4_index_context(left, top)])); + // escape: the full payload, the word goes to the front of the list + bc4_decode_index_payload(&compressed_stream, &ctx->bc4_first_index_model[c], &ctx->bc4_index_model[c][0], idx); + bc4_pack_indices(idx, b); } - } - bc4_pack_indices(idx, b); + bc4_dict_touch(&dict[c], NULL, 0, b->indices, rank); + } + else + { + bc4_decode_index_payload(&compressed_stream, &ctx->bc4_first_index_model[c], &ctx->bc4_index_model[c][0], idx); + bc4_pack_indices(idx, b); + } if (!first_row) { @@ -2048,16 +2567,16 @@ static size_t bcp_compress_bc1_impl(bcp_context* ctx, const void* bc1_image, uin const uint32_t height_blocks = height / 4; const uint32_t width_blocks = width / 4; - if (ctx->hashmap == NULL) - ctx->hashmap = ctx->mem.malloc_fn(sizeof(hashmap_entry) * HASHMAP_SIZE, ctx->mem.user); + if (!hashmap_ensure(ctx, HASHMAP_SIZE)) + return 0; build_top_table(ctx->hashmap, bc1_image, num_blocks, block_stride, ctx->top_table, &ctx->top_table_size); init_static_models(ctx, bc1_image, width_blocks, height_blocks, *num_strips, block_stride); byte_stream stream = {.buffer = output, .length = output_length, .pos = 0}; - // store models: per endpoint, the contextual red, green, and blue models (3 contexts each) — - // 16 color models — then the index models + // store models: per endpoint, the contextual red, green, and blue models (3 slots each) — + // 18 slots, 16 distinct: the first endpoint's green is uncontexted — then the index models for(uint32_t j=0; j<2; ++j) { for(uint32_t c=0; cdevice = MTL::CreateSystemDefaultDevice(); if (state->device == nullptr) { @@ -282,36 +288,15 @@ static void build_bc5_texture(const uint8_t* rgba, uint32_t width, uint32_t heig } //----------------------------------------------------------------------------------------------------------------------------- -// Full GPU roundtrip + throughput measurement of one image with one format: load the image, -// build the standard texture, compress it on the CPU, decode it on the GPU (64 threads, one per -// strip, over GPU_DECODE_RUNS tiled runs), verify the decoded image is byte-identical to the -// original texture, and print the measured GPU rate in MiB/s. Returns greatest's result. -static greatest_test_res metal_gpu_decompression(const char* image_file, const char* format_name, - const char* kernel_name, size_t block_bytes, - packed_maxsize_fn maxsize, bcp_compress_fn compress, - build_texture_fn build) +// GPU roundtrip + throughput measurement of a standard texture with one format: compress it on +// the CPU, decode it on the GPU (64 threads, one per strip, over GPU_DECODE_RUNS tiled runs), +// verify the decoded image is byte-identical to [original], and print the measured GPU rate in +// MiB/s. Returns greatest's result. +static greatest_test_res metal_gpu_roundtrip(const char* name, const uint8_t* original, size_t image_size, + uint32_t width, uint32_t height, + packed_maxsize_fn maxsize, bcp_compress_fn compress, + const char* kernel_name) { - // load the image and build the original standard texture - uint32_t width = 0, height = 0, channels = 0; - uint8_t* rgba = stbi_load(image_file, (int*)&width, (int*)&height, (int*)&channels, 4); - if (rgba == nullptr) - { - fprintf(stderr, "==> unable to load %s, run the test from the project root\n", image_file); - FAIL(); - } - - // constraints enforced by both the compressors and the compute kernels - ASSERT(width >= 16 && height >= 256 && (width & 3) == 0 && (height & 3) == 0); - - const uint32_t width_blocks = width / 4; - const uint32_t height_blocks = height / 4; - const size_t image_size = (size_t)width_blocks * height_blocks * block_bytes; - - uint8_t* original = (uint8_t*)malloc(image_size); - ASSERT(original != nullptr); - build(rgba, width, height, original); - stbi_image_free(rgba); - // compress the standard texture on the CPU bcp_context* ctx = bcp_init(nullptr); ASSERT(ctx != nullptr); @@ -325,8 +310,8 @@ static greatest_test_res metal_gpu_decompression(const char* image_file, const c ASSERT(compressed_length != 0); ASSERT(compressed_length <= compressed_size); - fprintf(stdout, "==> %s %ux%u : %u KiB %s, %zu bytes compressed\n", - image_file, width, height, (uint32_t)(image_size / 1024), format_name, compressed_length); + fprintf(stdout, "==> %s %ux%u : %u KiB, %zu bytes compressed\n", + name, width, height, (uint32_t)(image_size / 1024), compressed_length); // create the Metal objects: the device, the compiled shader, the pipeline, the queue metal_state state = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; @@ -407,34 +392,119 @@ static greatest_test_res metal_gpu_decompression(const char* image_file, const c free(decoded); free(compressed); bcp_terminate(ctx); - free(original); PASS(); } +//----------------------------------------------------------------------------------------------------------------------------- +// Full GPU roundtrip of one image file with one format: load the image, build the standard +// texture, then run the shared GPU roundtrip + throughput measurement +static greatest_test_res metal_gpu_decompression(const char* image_file, + const char* kernel_name, size_t block_bytes, + packed_maxsize_fn maxsize, bcp_compress_fn compress, + build_texture_fn build) +{ + // load the image and build the original standard texture + uint32_t width = 0, height = 0, channels = 0; + uint8_t* rgba = stbi_load(image_file, (int*)&width, (int*)&height, (int*)&channels, 4); + if (rgba == nullptr) + { + fprintf(stderr, "==> unable to load %s, run the test from the project root\n", image_file); + FAIL(); + } + + // constraints enforced by both the compressors and the compute kernels + ASSERT(width >= 16 && height >= 256 && (width & 3) == 0 && (height & 3) == 0); + + const uint32_t width_blocks = width / 4; + const uint32_t height_blocks = height / 4; + const size_t image_size = (size_t)width_blocks * height_blocks * block_bytes; + + uint8_t* original = (uint8_t*)malloc(image_size); + ASSERT(original != nullptr); + build(rgba, width, height, original); + stbi_image_free(rgba); + + greatest_test_res res = metal_gpu_roundtrip(image_file, original, image_size, (uint32_t)width, (uint32_t)height, + maxsize, compress, kernel_name); + + free(original); + return res; +} + + //----------------------------------------------------------------------------------------------------------------------------- // the three GPU roundtrips: the brick content of images/brick1 (BC1) and the brick AO / normal // maps of images/bc4 / images/bc5 (BC4 / BC5), each measured over GPU_DECODE_RUNS runs TEST metal_gpu_decompression_bc1(void) { - return metal_gpu_decompression(BC1_IMAGE_FILE, "BC1", "bcp_decompress_bc1", 8, + return metal_gpu_decompression(BC1_IMAGE_FILE, "bcp_decompress_bc1", 8, packed_bc1_maxsize, bcp_compress_bc1, build_bc1_texture); } TEST metal_gpu_decompression_bc4(void) { - return metal_gpu_decompression(BC4_IMAGE_FILE, "BC4", "bcp_decompress_bc4", 8, + return metal_gpu_decompression(BC4_IMAGE_FILE, "bcp_decompress_bc4", 8, packed_bc4_maxsize, bcp_compress_bc4, build_bc4_texture); } TEST metal_gpu_decompression_bc5(void) { - return metal_gpu_decompression(BC5_IMAGE_FILE, "BC5", "bcp_decompress_bc5", 16, + return metal_gpu_decompression(BC5_IMAGE_FILE, "bcp_decompress_bc5", 16, packed_bc5_maxsize, bcp_compress_bc5, build_bc5_texture); } +//----------------------------------------------------------------------------------------------------------------------------- +// Synthetic GPU roundtrip of the BC4 / BC5 content class the real brick maps do not exercise: +// endpoint pairs that repeat within the tiles, plus a skewed first index. Built in memory, +// no image file needed. +TEST metal_gpu_decompression_bc45_synthetic(void) +{ + const uint32_t width = 256, height = 256; + const uint32_t width_blocks = width / 4; + const uint32_t height_blocks = height / 4; + const uint32_t num_blocks = width_blocks * height_blocks; + + // 4 distinct endpoint pairs cycling in x (period 4 divides the row width, so it holds in the + // zigzag chain too): the MTF list is full after the first four blocks of each tile and the + // rest are rank hits. the rest of the indices are position-derived, the first is constant + bc4_block* bc4 = (bc4_block*)malloc(num_blocks * sizeof(bc4_block)); + bc4_block* bc5 = (bc4_block*)malloc(num_blocks * 2 * sizeof(bc4_block)); + ASSERT(bc4 != nullptr && bc5 != nullptr); + + for (uint32_t i = 0; i < num_blocks; ++i) + { + const uint32_t t = (i % width_blocks) & 3; + + bc4[i].endpoint[0] = (uint8_t)(0x10 + t * 0x20); + bc4[i].endpoint[1] = (uint8_t)(0x08 + t * 0x10); + + uint64_t v = 0; + for (uint32_t k = 1; k < 16; ++k) + v |= (uint64_t)(((i % width_blocks) ^ (i / width_blocks) ^ k) & 7) << (3 * k); + for (uint32_t j = 0; j < 6; ++j) + bc4[i].indices[j] = (uint8_t)(v >> (8 * j)); + + memcpy(&bc5[2 * i], &bc4[i], sizeof(bc4_block)); + bc5[2 * i + 1].endpoint[0] = (uint8_t)(bc4[i].endpoint[0] ^ 0x5A); + bc5[2 * i + 1].endpoint[1] = (uint8_t)(bc4[i].endpoint[1] ^ 0x5A); + for (uint32_t j = 0; j < 6; ++j) + bc5[2 * i + 1].indices[j] = (uint8_t)(bc4[i].indices[j] ^ 0x38); + } + + greatest_test_res res = metal_gpu_roundtrip("synthetic bc4", (const uint8_t*)bc4, num_blocks * 8, width, height, + packed_bc4_maxsize, bcp_compress_bc4, "bcp_decompress_bc4"); + if (res == GREATEST_TEST_RES_PASS) + res = metal_gpu_roundtrip("synthetic bc5", (const uint8_t*)bc5, num_blocks * 16, width, height, + packed_bc5_maxsize, bcp_compress_bc5, "bcp_decompress_bc5"); + + free(bc4); + free(bc5); + return res; +} + extern "C" { SUITE(suite_gpu) @@ -442,6 +512,7 @@ SUITE(suite_gpu) RUN_TEST(metal_gpu_decompression_bc1); RUN_TEST(metal_gpu_decompression_bc4); RUN_TEST(metal_gpu_decompression_bc5); + RUN_TEST(metal_gpu_decompression_bc45_synthetic); } } diff --git a/tests/image_tests.c b/tests/image_tests.c index e312271..7f2ccb3 100644 --- a/tests/image_tests.c +++ b/tests/image_tests.c @@ -1,6 +1,8 @@ #include "test_helpers.h" #include +#include #include +#include #include #include @@ -110,7 +112,7 @@ TEST test_all_images_in_folder(const char *dir_path) if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; - char file_path[1024]; + char file_path[PATH_MAX + NAME_MAX + 2]; snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, entry->d_name); // load and convert to bc1 @@ -179,16 +181,18 @@ TEST test_all_images_in_folder(const char *dir_path) //----------------------------------------------------------------------------------------------------------------------------- -// BC4 / BC5 image roundtrips on the hardcoded sets of images/bc4 (AO maps) and images/bc5 -// (normal maps, red + green channels). the filenames are hardcoded, the folder is not scanned, -// the per-image ratios are logged to the hourly CSV and printed to stdout: the average must -// stay above 1:1 +// BC4 / BC5 image roundtrips on the hardcoded sets of images/bc4 (AO, roughness and atlas maps) +// and images/bc5 (normal maps, red + green channels). the filenames are hardcoded, the folder is +// not scanned, the per-image ratios are logged to the hourly CSV and printed to stdout: the +// average must stay above 1.05 static const char* const bc4_image_filenames[] = { "images/bc4/grey_roof_tiles_02_ao_1k.png", "images/bc4/patterned_cobblestone_ao_1k.png", "images/bc4/red_brick_ao_1k.png", - "images/bc4/rough_wood_ao_1k.png" + "images/bc4/rough_wood_ao_1k.png", + "images/bc4/Metal002_4K_Roughness.png", + "images/bc4/font_atlas.png" }; static const char* const bc5_image_filenames[] = @@ -203,7 +207,8 @@ static greatest_test_res run_bc_image_suite(bool bc5) { const char* format = bc5 ? "bc5" : "bc4"; const char* const* filenames = bc5 ? bc5_image_filenames : bc4_image_filenames; - const uint32_t num_filenames = sizeof(bc4_image_filenames) / sizeof(bc4_image_filenames[0]); + const uint32_t num_filenames = bc5 ? sizeof(bc5_image_filenames) / sizeof(bc5_image_filenames[0]) + : sizeof(bc4_image_filenames) / sizeof(bc4_image_filenames[0]); bcp_context* ctx = bcp_init(NULL); ASSERT(ctx != NULL); diff --git a/tests/synthetic_tests.c b/tests/synthetic_tests.c index 9f5ba33..95d3df2 100644 --- a/tests/synthetic_tests.c +++ b/tests/synthetic_tests.c @@ -1023,6 +1023,326 @@ TEST bc45_random_splitmix32(void) } +//----------------------------------------------------------------------------------------------------------------------------- +// compresses [image] and returns the stream length (0 on failure): the size of the stream is +// the only stream property the tests compare, the content is never parsed +static size_t bc45_stream_length(const void* image, uint32_t width, uint32_t height, uint32_t num_channels) +{ + bcp_context* ctx = bcp_init(NULL); + if (!ctx) + return 0; + + size_t compressed_buffer_size = (num_channels == 1) ? packed_bc4_maxsize(width, height) : packed_bc5_maxsize(width, height); + uint8_t* compressed_buffer = malloc(compressed_buffer_size); + if (!compressed_buffer) + { + bcp_terminate(ctx); + return 0; + } + + uint32_t num_strips = 0; + size_t length = (num_channels == 1) ? bcp_compress_bc4(ctx, image, width, height, compressed_buffer, compressed_buffer_size, &num_strips) + : bcp_compress_bc5(ctx, image, width, height, compressed_buffer, compressed_buffer_size, &num_strips); + + free(compressed_buffer); + bcp_terminate(ctx); + return length; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// endpoint pairs cycle through four distinct values along every row (period 4 divides the row +// width, so it holds in the zigzag chain too), the index words are position-derived. the +// control keeps the same index words but uses all-distinct endpoint pairs: repeated endpoint +// pairs must compress, so the stream of the cycling image is strictly shorter. both images +// round-trip byte-exact, in BC4 and BC5 +TEST bc45_repeated_endpoint_pairs(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + bc4_block image16[TEST_BC45_BLOCKS * 2]; + bc4_block distinct[TEST_BC45_BLOCKS]; + uint32_t blocks_per_row = TEST_BC45_WIDTH / 4; + uint32_t rng_state = 0x7C3B5A2Du; + + for(uint32_t i=0; i> (8 * j)); + + // control: the same index words, no endpoint pair repeats + uint32_t pair = splitmix32(&rng_state); + distinct[i].endpoint[0] = (uint8_t)(pair & 0xFF); + distinct[i].endpoint[1] = (uint8_t)((pair >> 8) & 0xFF); + memcpy(distinct[i].indices, image[i].indices, sizeof(distinct[i].indices)); + + memcpy(&image16[2 * i], &image[i], sizeof(bc4_block)); // red channel + image16[2 * i + 1].endpoint[0] = (uint8_t)(image[i].endpoint[0] ^ 0x5A); + image16[2 * i + 1].endpoint[1] = (uint8_t)(image[i].endpoint[1] ^ 0x5A); + for(uint32_t j=0; j<6; ++j) + image16[2 * i + 1].indices[j] = (uint8_t)(image[i].indices[j] ^ 0x38); + } + + greatest_test_res res = bc45_roundtrip(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(image16, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 2); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + + size_t repeated_length = bc45_stream_length(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + size_t distinct_length = bc45_stream_length(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + ASSERT(repeated_length != 0 && distinct_length != 0); + ASSERT(repeated_length < distinct_length); + + PASS(); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// all-distinct endpoint pairs (a splitmix32 state is a permutation of the block index, so no +// pair repeats anywhere): the endpoint deltas carry full entropy, the worst case for the +// endpoint coding. the round-trip must stay byte-exact +TEST bc45_distinct_endpoint_pairs(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + uint32_t rng_state = 0x7C3B5A2Du; + + for(uint32_t i=0; i> 8) & 0xFF); + for(uint32_t j=0; j<6; ++j) + image[i].indices[j] = (uint8_t)((pair >> (4 * j)) & 0xFF); + } + + return bc45_roundtrip(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// half of the blocks repeat one endpoint pair, the other half all-distinct random pairs: +// repeated and never-repeated pairs in the same tiles. the round-trip must stay byte-exact +TEST bc45_mixed_endpoint_pairs(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + uint32_t rng_state = 0x15F2D84Eu; + + for(uint32_t i=0; i> 8) & 0xFF); + } + + for(uint32_t j=0; j<6; ++j) + image[i].indices[j] = (uint8_t)(i & 0xFF); + } + + return bc45_roundtrip(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// per-channel independence in one BC5 stream: the red channel cycles four endpoint pairs, +// the green channel uses all-distinct random pairs. both channels round-trip byte-exact +TEST bc45_per_channel_content(void) +{ + const uint32_t width = TEST_BC45_WIDTH; + const uint32_t height = TEST_BC45_HEIGHT; + const uint32_t blocks_per_row = width / 4; + const uint32_t num_blocks = (width / 4) * (height / 4); + + bc4_block* image16 = malloc(num_blocks * 2 * sizeof(bc4_block)); + if (!image16) + return GREATEST_TEST_RES_FAIL; + + uint32_t rng_state = 0x3D9C47B1u; + for(uint32_t i=0; i> 8) & 0xFF); + + for(uint32_t j=0; j<6; ++j) + { + image16[2 * i].indices[j] = (uint8_t)(i & 0xFF); + image16[2 * i + 1].indices[j] = (uint8_t)((pair >> (4 * j)) & 0xFF); + } + } + + greatest_test_res res = bc45_roundtrip(image16, width, height, 2); + free(image16); + return res; +} + +//----------------------------------------------------------------------------------------------------------------------------- +// index words cycle through 8 distinct values in block order (a tile's 8-block rows cover the +// whole period) and endpoint pairs cycle through four: nearly every block of a tile is a +// dictionary hit. the control keeps the same endpoint pairs but uses all-distinct index +// words: repeated words must compress, so the cycling image's stream is strictly shorter. +// both images round-trip byte-exact, in BC4 and BC5 +TEST bc45_repeated_index_words(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + bc4_block image16[TEST_BC45_BLOCKS * 2]; + bc4_block distinct[TEST_BC45_BLOCKS]; + uint32_t rng_state = 0x2A6E9C4Du; + + for(uint32_t i=0; i> (8 * j)); + + // control: the same endpoint pairs, all-distinct index words + memcpy(distinct[i].endpoint, image[i].endpoint, sizeof(distinct[i].endpoint)); + uint64_t w = 0; + for(uint32_t k=0; k<16; ++k) + w |= (uint64_t)(splitmix32(&rng_state) & 7) << (3 * k); + for(uint32_t j=0; j<6; ++j) + distinct[i].indices[j] = (uint8_t)(w >> (8 * j)); + + memcpy(&image16[2 * i], &image[i], sizeof(bc4_block)); // red channel + image16[2 * i + 1].endpoint[0] = (uint8_t)(image[i].endpoint[0] ^ 0x5A); + image16[2 * i + 1].endpoint[1] = (uint8_t)(image[i].endpoint[1] ^ 0x5A); + for(uint32_t j=0; j<6; ++j) + image16[2 * i + 1].indices[j] = (uint8_t)(image[i].indices[j] ^ 0x38); + } + + greatest_test_res res = bc45_roundtrip(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(image16, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 2); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + + size_t repeated_length = bc45_stream_length(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + size_t distinct_length = bc45_stream_length(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + ASSERT(repeated_length != 0 && distinct_length != 0); + ASSERT(repeated_length < distinct_length); + + PASS(); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// all-distinct index words (splitmix32 over 4096 blocks): no word repeats within any tile, +// so the dictionary must stay gated off. the round-trip must stay byte-exact, in BC4 and BC5 +TEST bc45_distinct_index_words(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + bc4_block image16[TEST_BC45_BLOCKS * 2]; + uint32_t rng_state = 0x51B7A02Fu; + + for(uint32_t i=0; i> (8 * j)); + + memcpy(&image16[2 * i], &image[i], sizeof(bc4_block)); // red channel + image16[2 * i + 1].endpoint[0] = (uint8_t)(image[i].endpoint[0] ^ 0x5A); + image16[2 * i + 1].endpoint[1] = (uint8_t)(image[i].endpoint[1] ^ 0x5A); + for(uint32_t j=0; j<6; ++j) + image16[2 * i + 1].indices[j] = (uint8_t)(image[i].indices[j] ^ 0x38); + } + + return bc45_both(image, image16, TEST_BC45_WIDTH, TEST_BC45_HEIGHT); +} + +//----------------------------------------------------------------------------------------------------------------------------- +// every block is flat (identical endpoints) with one of four non-uniform index words +// cycling: the non-uniform words force flat-index mode 0 (the full 15-symbol payload), and +// the repeating words make nearly every block a dictionary hit. the control uses +// all-distinct non-uniform words: repeated words must compress, so the cycling image's +// stream is strictly shorter. both images round-trip byte-exact, in BC4 and BC5 +TEST bc45_flat_repeated_words(void) +{ + bc4_block image[TEST_BC45_BLOCKS]; + bc4_block image16[TEST_BC45_BLOCKS * 2]; + bc4_block distinct[TEST_BC45_BLOCKS]; + uint32_t rng_state = 0x9E34F6C8u; + + for(uint32_t i=0; i> (8 * j)); + + // control: the same flat endpoints, all-distinct index words + memcpy(distinct[i].endpoint, image[i].endpoint, sizeof(distinct[i].endpoint)); + uint64_t w = 0; + for(uint32_t k=0; k<16; ++k) + w |= (uint64_t)(splitmix32(&rng_state) & 7) << (3 * k); + for(uint32_t j=0; j<6; ++j) + distinct[i].indices[j] = (uint8_t)(w >> (8 * j)); + + memcpy(&image16[2 * i], &image[i], sizeof(bc4_block)); // red channel + image16[2 * i + 1].endpoint[0] = (uint8_t)(image[i].endpoint[0] ^ 0x5A); + image16[2 * i + 1].endpoint[1] = (uint8_t)(image[i].endpoint[1] ^ 0x5A); + for(uint32_t j=0; j<6; ++j) + image16[2 * i + 1].indices[j] = (uint8_t)(image[i].indices[j] ^ 0x38); + } + + greatest_test_res res = bc45_roundtrip(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(image16, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 2); + if (res != GREATEST_TEST_RES_PASS) + return res; + res = bc45_roundtrip(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + if (res != GREATEST_TEST_RES_PASS) + return res; + + size_t repeated_length = bc45_stream_length(image, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + size_t distinct_length = bc45_stream_length(distinct, TEST_BC45_WIDTH, TEST_BC45_HEIGHT, 1); + ASSERT(repeated_length != 0 && distinct_length != 0); + ASSERT(repeated_length < distinct_length); + + PASS(); +} + + //----------------------------------------------------------------------------------------------------------------------------- // helper function to validate a bc3 roundtrip: the compressed stream fits the documented // maxsize and decompressing all strips reproduces the input byte-exact @@ -1207,39 +1527,6 @@ TEST bc3_random_splitmix32(void) //----------------------------------------------------------------------------------------------------------------------------- SUITE(suite_synthetic) { - (void)flat; - (void)checkerboard; - (void)bc45_flat; - (void)bc45_flat_uniform; - (void)bc45_flat_uniform_word; - (void)bc45_flat_divergent; - (void)bc45_checkerboard; - (void)bc45_gradient; - (void)bc45_random_splitmix32; - (void)bc3_flat; - (void)bc3_flat_uniform; - (void)bc3_checkerboard; - (void)bc3_gradient; - (void)bc3_random_splitmix32; - (void)gradient; - (void)random_splitmix32; - (void)color0_le_color1; - (void)identical_colors; - (void)identical_colors_uniform_value; - (void)identical_colors_divergent; - (void)identical_colors_garbage; - (void)identical_colors_mixed; - (void)strip_uniform_colors; - (void)all_distinct_indices; - (void)row_varying_colors; - (void)rare_index_pattern; - (void)color_context; - (void)color_dict_repeat; - (void)periodic_color_pairs; - (void)tile_uniform_colors; - (void)tile_column_predictor; - (void)odd_dimensions; - RUN_TEST(flat); RUN_TEST(checkerboard); RUN_TEST(gradient); @@ -1251,6 +1538,13 @@ SUITE(suite_synthetic) RUN_TEST(bc45_checkerboard); RUN_TEST(bc45_gradient); RUN_TEST(bc45_random_splitmix32); + RUN_TEST(bc45_repeated_endpoint_pairs); + RUN_TEST(bc45_distinct_endpoint_pairs); + RUN_TEST(bc45_mixed_endpoint_pairs); + RUN_TEST(bc45_per_channel_content); + RUN_TEST(bc45_repeated_index_words); + RUN_TEST(bc45_distinct_index_words); + RUN_TEST(bc45_flat_repeated_words); RUN_TEST(bc3_flat); RUN_TEST(bc3_flat_uniform); RUN_TEST(bc3_checkerboard);