Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

rf-jxl: a first lossy JPEG XL encoder (VarDCT, 8x8 DCT, ANS)

gelenmedyaa6274e578b08
diff --git a/Cargo.lock b/Cargo.lock
index 3adfc31b..f81ba479 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -161,6 +161,21 @@ dependencies = [
"equator",
]
+[[package]]
+name = "alloc-no-stdlib"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
+
+[[package]]
+name = "alloc-stdlib"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
+dependencies = [
+ "alloc-no-stdlib",
+]
+
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -269,6 +284,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "array-init"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
+
[[package]]
name = "arraydeque"
version = "0.5.1"
@@ -570,6 +591,19 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "av-data"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fca67ba5d317924c02180c576157afd54babe48a76ebc66ce6d34bb8ba08308e"
+dependencies = [
+ "byte-slice-cast",
+ "bytes",
+ "num-derive",
+ "num-rational",
+ "num-traits",
+]
+
[[package]]
name = "av-scenechange"
version = "0.14.1"
@@ -802,6 +836,16 @@ dependencies = [
"piper",
]
+[[package]]
+name = "brotli-decompressor"
+version = "5.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+]
+
[[package]]
name = "bstr"
version = "1.13.1"
@@ -825,6 +869,12 @@ version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+[[package]]
+name = "byte-slice-cast"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7575182f7272186991736b70173b0ea045398f984bf5ebbb3804736ce1330c9d"
+
[[package]]
name = "bytemuck"
version = "1.25.2"
@@ -4198,6 +4248,237 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "jxl"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8379fc83d79477900c9aed78cb8370a556d834081bebcb771c6010381c4e230"
+dependencies = [
+ "array-init",
+ "byteorder",
+ "jxl_macros",
+ "jxl_simd",
+ "jxl_transforms",
+ "num-derive",
+ "num-traits",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "jxl-bitstream"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
+dependencies = [
+ "tracing",
+]
+
+[[package]]
+name = "jxl-coding"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
+dependencies = [
+ "jxl-bitstream",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-color"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-frame"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-grid"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
+dependencies = [
+ "tracing",
+]
+
+[[package]]
+name = "jxl-image"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-grid",
+ "jxl-oxide-common",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-image-rs-integration"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "040122e58dac2a6ac1ef70ba8630f35461870c5e7f94d62d7db27f09f96bbe97"
+dependencies = [
+ "bytemuck",
+ "image",
+ "jxl",
+]
+
+[[package]]
+name = "jxl-jbr"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
+dependencies = [
+ "brotli-decompressor",
+ "jxl-bitstream",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-modular"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-oxide"
+version = "0.12.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
+dependencies = [
+ "brotli-decompressor",
+ "jxl-bitstream",
+ "jxl-color",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-jbr",
+ "jxl-oxide-common",
+ "jxl-render",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-oxide-common"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
+dependencies = [
+ "jxl-bitstream",
+]
+
+[[package]]
+name = "jxl-render"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
+dependencies = [
+ "bytemuck",
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-color",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-threadpool"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
+dependencies = [
+ "rayon",
+ "rayon-core",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-vardct"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl_macros"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eeb27c06a9957bd9c8e65d0aeea0db6a555a9e1c85597e284f8304015c410c87"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jxl_simd"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a645451b4d34b4017caf24110a14eb737e275b5d3d121bc754e67727ee65af0e"
+
+[[package]]
+name = "jxl_transforms"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21c4b7f8957f5ba578b2e28cd5ebbc97dad58a3ad5ff26765da61e8dab8f1cad"
+dependencies = [
+ "jxl_simd",
+]
+
[[package]]
name = "kamadak-exif"
version = "0.6.2"
@@ -6466,6 +6747,16 @@ dependencies = [
"windows-core 0.62.2",
]
+[[package]]
+name = "rf-jxl"
+version = "1.0.6"
+dependencies = [
+ "image",
+ "jxl-image-rs-integration",
+ "jxl-oxide",
+ "ssimulacra2",
+]
+
[[package]]
name = "rf-nearby"
version = "1.0.6"
@@ -7369,6 +7660,19 @@ dependencies = [
"bitflags 2.13.2",
]
+[[package]]
+name = "ssimulacra2"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "700cb4e17f98c3f36756815b18dbec2b2e3c4f5028e9cdee3e23dd8c285e736c"
+dependencies = [
+ "num-traits",
+ "rayon",
+ "thiserror 2.0.21",
+ "yuvxyb",
+ "yuvxyb-math",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -9915,6 +10219,25 @@ dependencies = [
"synstructure 0.14.0",
]
+[[package]]
+name = "yuvxyb"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b06d0d0f23a00eadd02381cf0c84472295bbcd3e7e21ffd2225300c83d557867"
+dependencies = [
+ "av-data",
+ "log",
+ "num-traits",
+ "v_frame",
+ "yuvxyb-math",
+]
+
+[[package]]
+name = "yuvxyb-math"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00f1f60154ad4ef9871d606765c3ea037cde93bbd77536327b594de8f82df1cb"
+
[[package]]
name = "zbus"
version = "5.19.0"
diff --git a/Cargo.toml b/Cargo.toml
index 64202c31..3a665324 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
-members = ["crates/rf-core", "crates/rf-win", "crates/rf-app", "crates/rf-nearby", "crates/rf-archive", "crates/rf-dialog", "crates/rf-shellguard", "crates/rf-player", "crates/rustdecoder", "tools/gpustress"]
+members = ["crates/rf-core", "crates/rf-win", "crates/rf-app", "crates/rf-nearby", "crates/rf-archive", "crates/rf-dialog", "crates/rf-shellguard", "crates/rf-player", "crates/rustdecoder", "crates/rf-jxl", "tools/gpustress"]
# The macOS app (Swift in macos/, its Rust bridge in crates/rf-mac) is built on the Mac only, as a workspace of its own.
exclude = ["crates/rf-mac", "macos", "vendor/velopack"]
diff --git a/crates/rf-jxl/Cargo.toml b/crates/rf-jxl/Cargo.toml
new file mode 100644
index 00000000..7b858fe0
--- /dev/null
+++ b/crates/rf-jxl/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "rf-jxl"
+description = "A small JPEG XL encoder of our own for the thumbnail cache: lossy (VarDCT) pictures of up to a few thousand pixels, 8-bit RGB or RGBA."
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[dependencies]
+
+[dev-dependencies]
+# Reference decoders and a quality measure, only for the tests and the measuring tools.
+jxl-image-rs-integration = "0.8"
+jxl-oxide = "0.12"
+ssimulacra2 = "0.5"
+image.workspace = true
diff --git a/crates/rf-jxl/src/ans.rs b/crates/rf-jxl/src/ans.rs
new file mode 100644
index 00000000..bbeb308f
--- /dev/null
+++ b/crates/rf-jxl/src/ans.rs
@@ -0,0 +1,572 @@
+//! Entropy coding of JPEG XL: values become tokens ("hybrid uint": small values as they are, bigger ones as an
+//! exponent and the top two bits, the rest raw), the tokens are coded with asymmetric numeral systems (rANS) with
+//! one distribution per cluster of contexts. This writes the part the decoder reads in `Histograms::decode` and the
+//! symbol stream after it.
+//!
+//! The decoder is the reference for every detail here (the alias table that maps a state to a symbol, the way a
+//! distribution is stored); the encoder only has to produce what that decoder reads back.
+
+use crate::bits::{BitWriter, ceil_log2};
+
+/// log2 of the token alphabet's size. 64 tokens hold values up to 2^16, enough for everything we write.
+const LOG_ALPHA: usize = 6;
+const ALPHA: usize = 1 << LOG_ALPHA;
+const LOG_BUCKET: usize = 12 - LOG_ALPHA;
+const SUM: u32 = 1 << 12;
+/// What the decoder expects the state to be after it has read everything.
+const ANS_SIGNATURE: u32 = 0x13_0000;
+
+#[derive(Clone, Copy, Debug)]
+pub struct Token {
+ pub ctx: u32,
+ pub val: u32,
+}
+
+/// The value as (token, number of raw bits, the raw bits). Split exponent 4, two top bits in the token, no low bits.
+#[inline(always)]
+pub fn split_value(v: u32) -> (u32, u32, u32) {
+ if v < 16 {
+ (v, 0, 0)
+ } else {
+ let n = 31 - v.leading_zeros();
+ let nbits = n - 2;
+ (16 + ((n - 4) << 2) + ((v >> nbits) & 3), nbits, v & ((1 << nbits) - 1))
+ }
+}
+
+/// `v * log2(v)`, the building block of every entropy estimate here.
+fn xlogx_table() -> &'static [f32] {
+ use std::sync::OnceLock;
+ static T: OnceLock<Vec<f32>> = OnceLock::new();
+ T.get_or_init(|| (0..8192u32).map(|c| if c == 0 { 0.0 } else { c as f32 * (c as f32).log2() }).collect())
+}
+
+#[inline(always)]
+fn xlogx(t: &[f32], c: u32) -> f32 {
+ if (c as usize) < t.len() { t[c as usize] } else { c as f32 * (c as f32).log2() }
+}
+
+/// Bits an ideal coder needs for the counts as one distribution.
+fn entropy_bits(t: &[f32], counts: &[u32; ALPHA]) -> f32 {
+ let mut total = 0u32;
+ let mut s = 0.0;
+ for &c in counts {
+ total += c;
+ s += xlogx(t, c);
+ }
+ xlogx(t, total) - s
+}
+
+fn num_symbols(counts: &[u32; ALPHA]) -> u32 {
+ counts.iter().filter(|&&c| c > 0).count() as u32
+}
+
+/// How a cluster's distribution is written in the header.
+#[derive(Clone, Debug)]
+enum Form {
+ Single(u8),
+ Two(u8, u8, u16),
+ /// `omit` is the symbol whose count is left out of the header (it gets what the others leave of 4096); the header
+ /// still names it by `omit_class`, the biggest class of all.
+ Complex { shift: u32, alphabet: usize, omit: usize, omit_class: u32 },
+}
+
+#[derive(Clone)]
+struct ClusterCode {
+ /// Distribution summing to 4096.
+ dist: [u16; ALPHA],
+ form: Form,
+ /// For each symbol where its offsets start in `inv`.
+ inv_start: [u16; ALPHA],
+ /// Maps (symbol, offset within the symbol's share) to the state slot the decoder turns back into them.
+ inv: Vec<u16>,
+}
+
+pub struct Codes {
+ context_map: Vec<u8>,
+ clusters: Vec<ClusterCode>,
+}
+
+// --- the distribution of one cluster ----------------------------------------------------------------------------
+
+/// Counts scaled to a total of 4096, each used symbol keeping at least 1.
+fn normalize(counts: &[u32; ALPHA]) -> [u16; ALPHA] {
+ let total: u64 = counts.iter().map(|&c| c as u64).sum();
+ let mut d = [0u16; ALPHA];
+ let mut sum = 0i32;
+ for i in 0..ALPHA {
+ if counts[i] > 0 {
+ let v = ((counts[i] as u64 * SUM as u64 + total / 2) / total).max(1) as u16;
+ d[i] = v;
+ sum += v as i32;
+ }
+ }
+ let mut diff = SUM as i32 - sum;
+ // The excess or the shortage goes to the biggest symbols, one at a time when it does not fit in one.
+ while diff != 0 {
+ let mut b = 0;
+ for i in 0..ALPHA {
+ if d[i] > d[b] {
+ b = i;
+ }
+ }
+ let take = if diff > 0 { diff } else { -((d[b] as i32 - 1).min(-diff)) };
+ d[b] = (d[b] as i32 + take) as u16;
+ diff -= take;
+ if take == 0 {
+ break;
+ }
+ }
+ d
+}
+
+/// The class a stored count has: 0 for none, 1 for one, else 1 + floor(log2) (its "prefix" symbol in the header).
+fn class_of(d: u16) -> u32 {
+ if d == 0 { 0 } else if d == 1 { 1 } else { 16 - d.leading_zeros() }
+}
+
+/// How many mantissa bits a count of that class is stored with at this `shift`.
+fn mantissa_bits(class: u32, shift: u32) -> u32 {
+ let zeros = class as i32 - 1;
+ (shift as i32 - ((12 - zeros) >> 1)).clamp(0, zeros) as u32
+}
+
+/// The distribution rounded to what `shift` can store, the biggest class's symbol taking what is left over.
+/// None when that does not work out.
+fn quantize(dist: &[u16; ALPHA], shift: u32) -> Option<([u16; ALPHA], usize, u32)> {
+ let mut q = *dist;
+ let mut omit = usize::MAX;
+ let mut omit_class = 0;
+ for i in 0..ALPHA {
+ let c = class_of(q[i]);
+ if c > 1 {
+ let keep = mantissa_bits(c, shift);
+ let drop = (c - 1) - keep;
+ q[i] = (q[i] >> drop) << drop;
+ }
+ if c > omit_class {
+ omit_class = c;
+ omit = i;
+ }
+ }
+ if omit == usize::MAX {
+ return None;
+ }
+ let others: u32 = q.iter().enumerate().filter(|&(i, _)| i != omit).map(|(_, &v)| v as u32).sum();
+ if others >= SUM {
+ return None;
+ }
+ q[omit] = (SUM - others) as u16;
+ Some((q, omit, omit_class))
+}
+
+/// Bits the header spends on a "complex" distribution.
+fn complex_header_bits(q: &[u16; ALPHA], shift: u32, alphabet: usize, omit: usize, omit_class: u32) -> u32 {
+ let len = shift_len(shift);
+ let mut bits = len + if len < 3 { 1 } else { 0 } + len;
+ bits += u8_bits(alphabet as u32 - 3);
+ for (i, &v) in q.iter().enumerate().take(alphabet) {
+ let c = if i == omit { omit_class } else { class_of(v) };
+ bits += PREFIX_CODES[c as usize].1;
+ if i != omit && c > 1 {
+ bits += mantissa_bits(c, shift);
+ }
+ }
+ bits
+}
+
+fn shift_len(shift: u32) -> u32 {
+ match shift {
+ 0 => 0,
+ 1..=2 => 1,
+ 3..=6 => 2,
+ _ => 3,
+ }
+}
+
+fn u8_bits(v: u32) -> u32 {
+ if v == 0 { 1 } else { 1 + 3 + (31 - v.leading_zeros()) }
+}
+
+fn put_u8(bw: &mut BitWriter, v: u32) {
+ if v == 0 {
+ bw.put(0, 1);
+ } else {
+ let n = 31 - v.leading_zeros();
+ bw.put(1, 1);
+ bw.put(n as u64, 3);
+ bw.put((v - (1 << n)) as u64, n);
+ }
+}
+
+/// (code, bit count) of the prefix code that stores a count's class, read off the decoder's lookup table.
+const PREFIX_CODES: [(u32, u32); 14] = [
+ (17, 5),
+ (11, 4),
+ (15, 4),
+ (3, 4),
+ (9, 4),
+ (7, 4),
+ (4, 3),
+ (2, 3),
+ (5, 3),
+ (6, 3),
+ (0, 3),
+ (33, 6),
+ (1, 7),
+ (65, 7),
+];
+
+impl ClusterCode {
+ fn new(counts: &[u32; ALPHA]) -> ClusterCode {
+ let nsym = num_symbols(counts);
+ let max_sym = counts.iter().rposition(|&c| c > 0).unwrap_or(0);
+ let mut dist = [0u16; ALPHA];
+ let form;
+ if nsym <= 1 {
+ dist[max_sym] = SUM as u16;
+ form = Form::Single(max_sym as u8);
+ } else if nsym == 2 {
+ let first = counts.iter().position(|&c| c > 0).unwrap();
+ let total = counts[first] + counts[max_sym];
+ let p = ((counts[first] as u64 * SUM as u64 + total as u64 / 2) / total as u64).clamp(1, SUM as u64 - 1) as u16;
+ dist[first] = p;
+ dist[max_sym] = SUM as u16 - p;
+ form = Form::Two(first as u8, max_sym as u8, p);
+ } else {
+ let norm = normalize(counts);
+ let alphabet = max_sym + 1;
+ // The cheapest shift: each count's precision against the header's size.
+ let mut best: Option<(f32, u32, [u16; ALPHA], usize, u32)> = None;
+ let t = xlogx_table();
+ for shift in 0..=13u32 {
+ let Some((q, omit, omit_class)) = quantize(&norm, shift) else { continue };
+ let mut bits = complex_header_bits(&q, shift, alphabet.max(3), omit, omit_class) as f32;
+ for i in 0..ALPHA {
+ if counts[i] > 0 {
+ bits += counts[i] as f32 * (12.0 - xlogx(t, q[i] as u32) / q[i] as f32);
+ }
+ }
+ if best.as_ref().is_none_or(|b| bits < b.0) {
+ best = Some((bits, shift, q, omit, omit_class));
+ }
+ }
+ let (_, shift, q, omit, omit_class) = best.expect("some shift always works");
+ dist = q;
+ form = Form::Complex { shift, alphabet: alphabet.max(3), omit, omit_class };
+ }
+ let mut c = ClusterCode { dist, form, inv_start: [0; ALPHA], inv: Vec::new() };
+ c.build_inverse();
+ c
+ }
+
+ /// The decoder's alias table, turned around: for each symbol and offset the state slot that decodes to it.
+ fn build_inverse(&mut self) {
+ if let Form::Single(_) = self.form {
+ return;
+ }
+ #[derive(Clone, Copy, Default)]
+ struct B {
+ dist: u16,
+ alias_symbol: u16,
+ alias_offset: u16,
+ alias_cutoff: u16,
+ }
+ let bucket_size = 1u16 << LOG_BUCKET;
+ let mut b = [B::default(); ALPHA];
+ for i in 0..ALPHA {
+ b[i] = B { dist: self.dist[i], alias_symbol: i as u16, alias_offset: 0, alias_cutoff: self.dist[i] };
+ }
+ let mut under = Vec::new();
+ let mut over = Vec::new();
+ for (i, x) in b.iter().enumerate() {
+ match x.dist.cmp(&bucket_size) {
+ std::cmp::Ordering::Less => under.push(i),
+ std::cmp::Ordering::Greater => over.push(i),
+ _ => {}
+ }
+ }
+ while !under.is_empty() && !over.is_empty() {
+ let o = over.pop().unwrap();
+ let u = under.pop().unwrap();
+ let by = bucket_size - b[u].alias_cutoff;
+ b[o].alias_cutoff -= by;
+ b[u].alias_symbol = o as u16;
+ b[u].alias_offset = b[o].alias_cutoff;
+ match b[o].alias_cutoff.cmp(&bucket_size) {
+ std::cmp::Ordering::Less => under.push(o),
+ std::cmp::Ordering::Greater => over.push(o),
+ _ => {}
+ }
+ }
+ let mut start = 0u16;
+ for s in 0..ALPHA {
+ self.inv_start[s] = start;
+ start += self.dist[s];
+ }
+ self.inv = vec![0; SUM as usize];
+ for idx in 0..SUM as usize {
+ let i = idx >> LOG_BUCKET;
+ let pos = (idx & (bucket_size as usize - 1)) as u16;
+ let (sym, off) = if b[i].alias_cutoff == bucket_size || pos < b[i].alias_cutoff {
+ (i, pos)
+ } else {
+ (b[i].alias_symbol as usize, b[i].alias_offset - b[i].alias_cutoff + pos)
+ };
+ debug_assert!(off < self.dist[sym]);
+ self.inv[(self.inv_start[sym] + off) as usize] = idx as u16;
+ }
+ }
+
+ fn write(&self, bw: &mut BitWriter) {
+ match &self.form {
+ Form::Single(s) => {
+ bw.put(0b01, 2); // bits 1, 0
+ put_u8(bw, *s as u32);
+ }
+ Form::Two(a, b, p) => {
+ bw.put(0b11, 2);
+ put_u8(bw, *a as u32);
+ put_u8(bw, *b as u32);
+ bw.put(*p as u64, 12);
+ }
+ Form::Complex { shift, alphabet, omit, omit_class } => {
+ let (omit, omit_class) = (*omit, *omit_class);
+ bw.put(0, 2);
+ let len = shift_len(*shift);
+ for _ in 0..len {
+ bw.put(1, 1);
+ }
+ if len < 3 {
+ bw.put(0, 1);
+ }
+ bw.put((*shift - ((1 << len) - 1)) as u64, len);
+ put_u8(bw, *alphabet as u32 - 3);
+ for i in 0..*alphabet {
+ let c = if i == omit { omit_class } else { class_of(self.dist[i]) };
+ let (code, n) = PREFIX_CODES[c as usize];
+ bw.put(code as u64, n);
+ }
+ for i in 0..*alphabet {
+ let c = class_of(self.dist[i]);
+ if i != omit && c > 1 {
+ let keep = mantissa_bits(c, *shift);
+ let drop = (c - 1) - keep;
+ let m = (self.dist[i] >> drop) & ((1 << keep) - 1);
+ bw.put(m as u64, keep);
+ }
+ }
+ }
+ }
+ }
+}
+
+// --- clustering the contexts --------------------------------------------------------------------------------------
+
+/// Builds the codes for `num_contexts` contexts from all the tokens that will be coded with them.
+pub fn build_codes(num_contexts: usize, streams: &[&[Token]]) -> Codes {
+ let t = xlogx_table();
+ // Counts for the contexts in use, found through a slot table (most contexts are never used).
+ let mut slot = vec![u16::MAX; num_contexts];
+ let mut used: Vec<(usize, [u32; ALPHA])> = Vec::new();
+ for s in streams {
+ for tok in s.iter() {
+ let c = tok.ctx as usize;
+ let k = split_value(tok.val).0 as usize;
+ debug_assert!(k < ALPHA, "token {k} out of the alphabet");
+ let k = k.min(ALPHA - 1);
+ if slot[c] == u16::MAX {
+ slot[c] = used.len() as u16;
+ used.push((c, [0; ALPHA]));
+ }
+ used[slot[c] as usize].1[k] += 1;
+ }
+ }
+ if used.is_empty() {
+ used.push((0, {
+ let mut c = [0; ALPHA];
+ c[0] = 1;
+ c
+ }));
+ }
+ // Biggest first, each joins the cluster it costs the least or starts one when joining would cost more than a
+ // histogram's header.
+ let mut order: Vec<usize> = (0..used.len()).collect();
+ order.sort_by_key(|&i| std::cmp::Reverse(used[i].1.iter().sum::<u32>()));
+ let mut clusters: Vec<[u32; ALPHA]> = Vec::new();
+ let mut cluster_ent: Vec<f32> = Vec::new();
+ let mut assign = vec![0usize; used.len()];
+ for &i in &order {
+ let h = &used[i].1;
+ let own = entropy_bits(t, h);
+ let header = 24.0 + 5.0 * num_symbols(h) as f32;
+ let mut best = (f32::MAX, usize::MAX);
+ for (j, c) in clusters.iter().enumerate() {
+ let mut m = *c;
+ for k in 0..ALPHA {
+ m[k] += h[k];
+ }
+ let inc = entropy_bits(t, &m) - cluster_ent[j] - own;
+ if inc < best.0 {
+ best = (inc, j);
+ }
+ }
+ if best.1 != usize::MAX && best.0 < header && clusters.len() + 1 > 0 {
+ let j = best.1;
+ for k in 0..ALPHA {
+ clusters[j][k] += h[k];
+ }
+ cluster_ent[j] = entropy_bits(t, &clusters[j]);
+ assign[i] = j;
+ } else if clusters.len() < 250 {
+ clusters.push(*h);
+ cluster_ent.push(own);
+ assign[i] = clusters.len() - 1;
+ } else {
+ let j = best.1;
+ for k in 0..ALPHA {
+ clusters[j][k] += h[k];
+ }
+ cluster_ent[j] = entropy_bits(t, &clusters[j]);
+ assign[i] = j;
+ }
+ }
+ // Contexts that are never used take the neighbour's cluster, which keeps the map in long runs.
+ let mut context_map = vec![0u8; num_contexts];
+ let mut filled = vec![false; num_contexts];
+ for (i, (c, _)) in used.iter().enumerate() {
+ context_map[*c] = assign[i] as u8;
+ filled[*c] = true;
+ }
+ let mut prev = None;
+ for c in 0..num_contexts {
+ if filled[c] {
+ prev = Some(context_map[c]);
+ } else if let Some(p) = prev {
+ context_map[c] = p;
+ }
+ }
+ if let Some(first) = filled.iter().position(|&f| f) {
+ for c in 0..first {
+ context_map[c] = context_map[first];
+ }
+ }
+ let clusters = clusters.iter().map(ClusterCode::new).collect();
+ Codes { context_map, clusters }
+}
+
+impl Codes {
+ /// What the decoder's `Histograms::decode` reads: no LZ77, the context map, ANS with the 64-token alphabet, the
+ /// uint configuration and the distributions.
+ pub fn write_header(&self, bw: &mut BitWriter) {
+ bw.put(0, 1); // no LZ77
+ if self.context_map.len() > 1 {
+ write_context_map(bw, &self.context_map, self.clusters.len());
+ }
+ bw.put(0, 1); // ANS, not prefix codes
+ bw.put((LOG_ALPHA - 5) as u64, 2);
+ for _ in &self.clusters {
+ // split exponent 4, 2 bits of the exponent's mantissa in the token, none of the low bits
+ bw.put(4, ceil_log2(LOG_ALPHA + 1));
+ bw.put(2, ceil_log2(5));
+ bw.put(0, ceil_log2(3));
+ }
+ for c in &self.clusters {
+ c.write(bw);
+ }
+ }
+
+ /// The tokens as a stream: the ANS state the decoder starts from, then for each token the 16 bits its state
+ /// takes in (when it does) and the raw bits.
+ pub fn write_stream(&self, bw: &mut BitWriter, tokens: &[Token]) {
+ const NONE: u32 = 1 << 16;
+ let mut words = vec![NONE; tokens.len()];
+ let mut state: u32 = ANS_SIGNATURE;
+ for (i, tok) in tokens.iter().enumerate().rev() {
+ let (sym, _, _) = split_value(tok.val);
+ let c = &self.clusters[self.context_map[tok.ctx as usize] as usize];
+ if let Form::Single(_) = c.form {
+ continue;
+ }
+ let f = c.dist[sym as usize] as u32;
+ debug_assert!(f > 0, "symbol {sym} has no probability");
+ if (state as u64) >= ((f as u64) << 20) {
+ words[i] = state & 0xffff;
+ state >>= 16;
+ }
+ let q = state / f;
+ let r = state % f;
+ state = (q << 12) + c.inv[(c.inv_start[sym as usize] as u32 + r) as usize] as u32;
+ }
+ bw.put(state as u64, 32);
+ for (i, tok) in tokens.iter().enumerate() {
+ if words[i] != NONE {
+ bw.put(words[i] as u64, 16);
+ }
+ let (_, n, bits) = split_value(tok.val);
+ if n > 0 {
+ bw.put(bits as u64, n);
+ }
+ }
+ }
+
+ /// Bits the tokens take (not counting the header), for choosing between ways of coding.
+ pub fn estimate_bits(&self, tokens: &[Token]) -> f64 {
+ let mut bits = 0f64;
+ for tok in tokens {
+ let (sym, n, _) = split_value(tok.val);
+ let c = &self.clusters[self.context_map[tok.ctx as usize] as usize];
+ bits += n as f64 + 12.0 - (c.dist[sym as usize].max(1) as f64).log2();
+ }
+ bits
+ }
+}
+
+// --- the context map ----------------------------------------------------------------------------------------------
+
+fn move_to_front(map: &[u8]) -> Vec<u8> {
+ let mut mtf: Vec<u8> = (0..=255).collect();
+ map.iter()
+ .map(|&v| {
+ let i = mtf.iter().position(|&x| x == v).unwrap();
+ mtf.remove(i);
+ mtf.insert(0, v);
+ i as u8
+ })
+ .collect()
+}
+
+pub fn write_context_map(bw: &mut BitWriter, map: &[u8], num_clusters: usize) {
+ if num_clusters == 1 {
+ bw.put(1, 1);
+ bw.put(0, 2);
+ return;
+ }
+ let bits_per = ceil_log2(num_clusters);
+ let simple_cost = 3 + map.len() as u32 * bits_per;
+ // The general way: the entries as tokens of a small code of their own, with or without move to front.
+ let mut best: Option<BitWriter> = None;
+ for mtf in [false, true] {
+ let vals: Vec<u8> = if mtf { move_to_front(map) } else { map.to_vec() };
+ let toks: Vec<Token> = vals.iter().map(|&v| Token { ctx: 0, val: v as u32 }).collect();
+ let codes = build_codes(1, &[&toks]);
+ let mut w = BitWriter::new();
+ w.put(0, 1); // not simple
+ w.put(mtf as u64, 1);
+ codes.write_header(&mut w);
+ codes.write_stream(&mut w, &toks);
+ if best.as_ref().is_none_or(|b| w.bit_len() < b.bit_len()) {
+ best = Some(w);
+ }
+ }
+ let best = best.unwrap();
+ if bits_per <= 3 && simple_cost <= best.bit_len() as u32 {
+ bw.put(1, 1);
+ bw.put(bits_per as u64, 2);
+ for &v in map {
+ bw.put(v as u64, bits_per);
+ }
+ } else {
+ bw.append(&best);
+ }
+}
diff --git a/crates/rf-jxl/src/bits.rs b/crates/rf-jxl/src/bits.rs
new file mode 100644
index 00000000..1022f774
--- /dev/null
+++ b/crates/rf-jxl/src/bits.rs
@@ -0,0 +1,103 @@
+//! Writing bits the way JPEG XL wants them: least significant bit first.
+
+#[derive(Default, Clone)]
+pub struct BitWriter {
+ buf: Vec<u8>,
+ acc: u64,
+ nbits: u32,
+}
+
+impl BitWriter {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Puts the low `n` bits of `v` (n up to 32).
+ #[inline]
+ pub fn put(&mut self, v: u64, n: u32) {
+ debug_assert!(n <= 32 && (n == 0 || v >> n == 0), "value {v} does not fit {n} bits");
+ self.acc |= v << self.nbits;
+ self.nbits += n;
+ if self.nbits >= 32 {
+ self.buf.extend_from_slice(&(self.acc as u32).to_le_bytes());
+ self.acc >>= 32;
+ self.nbits -= 32;
+ }
+ }
+
+ pub fn put_bool(&mut self, b: bool) {
+ self.put(b as u64, 1);
+ }
+
+ /// Number of bits written so far.
+ pub fn bit_len(&self) -> usize {
+ self.buf.len() * 8 + self.nbits as usize
+ }
+
+ /// Pads with zero bits up to the next byte.
+ pub fn align(&mut self) {
+ let pad = (8 - self.nbits % 8) % 8;
+ self.put(0, pad);
+ }
+
+ /// The bytes written; the last byte is padded with zeros.
+ pub fn finish(mut self) -> Vec<u8> {
+ self.align();
+ while self.nbits > 0 {
+ self.buf.push(self.acc as u8);
+ self.acc >>= 8;
+ self.nbits = self.nbits.saturating_sub(8);
+ }
+ self.buf
+ }
+
+ /// Another writer's bits, appended bit by bit (neither needs to be aligned).
+ pub fn append(&mut self, other: &BitWriter) {
+ for &b in &other.buf {
+ self.put(b as u64, 8);
+ }
+ let mut acc = other.acc;
+ let mut n = other.nbits;
+ while n > 0 {
+ let k = n.min(16);
+ self.put(acc & ((1 << k) - 1), k);
+ acc >>= k;
+ n -= k;
+ }
+ }
+}
+
+/// One of the four forms of the headers' "u32" integers; 2 bits say which one is used.
+pub enum U32Form {
+ Val(u32),
+ Bits(u32),
+ BitsOffset(u32, u32),
+}
+
+/// Writes `v` with the first of the four forms that can hold it.
+pub fn put_u32(bw: &mut BitWriter, v: u32, forms: [U32Form; 4]) {
+ for (sel, f) in forms.iter().enumerate() {
+ match *f {
+ U32Form::Val(x) if x == v => {
+ bw.put(sel as u64, 2);
+ return;
+ }
+ U32Form::Bits(n) if n >= 32 || v >> n == 0 => {
+ bw.put(sel as u64, 2);
+ bw.put(v as u64, n);
+ return;
+ }
+ U32Form::BitsOffset(n, off) if v >= off && (n >= 32 || (v - off) >> n == 0) => {
+ bw.put(sel as u64, 2);
+ bw.put((v - off) as u64, n);
+ return;
+ }
+ _ => {}
+ }
+ }
+ panic!("u32 {v} fits none of the forms");
+}
+
+pub fn ceil_log2(v: usize) -> u32 {
+ if v <= 1 { 0 } else { usize::BITS - (v - 1).leading_zeros() }
+}
diff --git a/crates/rf-jxl/src/lib.rs b/crates/rf-jxl/src/lib.rs
new file mode 100644
index 00000000..346ecfb4
--- /dev/null
+++ b/crates/rf-jxl/src/lib.rs
@@ -0,0 +1,306 @@
+//! A small JPEG XL encoder of our own, made for the thumbnail cache: pictures from a few pixels to about two thousand
+//! on a side, 8-bit RGB or RGBA, written once and read many times.
+//!
+//! Lossy pictures are coded the way the format's VarDCT mode does it: the picture in the XYB colour space, 8x8 DCT
+//! blocks, quantized, the coefficients coded with context-modelled ANS. The decoder is the reference for every
+//! detail; this crate only writes what such a decoder reads back (the tests check it against jxl-rs and jxl-oxide).
+
+mod ans;
+mod bits;
+mod modular;
+mod vardct;
+mod xyb;
+
+use bits::{BitWriter, U32Form, ceil_log2, put_u32};
+use modular::{Chan, T, Tree};
+
+/// The biggest picture side the encoder takes (one low-frequency group, which is 2048 pixels).
+pub const MAX_SIDE: u32 = 2048;
+
+/// Settings for experiments; `encode` uses the defaults.
+#[derive(Clone, Debug)]
+pub struct Tuning {
+ /// Butteraugli-like distance: 1.0 is "visually the same", bigger is smaller and worse.
+ pub distance: f32,
+ /// Quantization strength at distance 1 (the product of global scale and block quant over 65536).
+ pub strength: f32,
+ /// The low-frequency image's step relative to the finest high-frequency one.
+ pub dc_mult: f32,
+ /// Below this fraction of a step a coefficient becomes zero (0.5 is plain rounding).
+ pub round_threshold: f32,
+ /// Smoothing the decoder applies (0 to 3 passes of its edge-preserving filter).
+ pub epf_iters: u32,
+ pub gaborish: bool,
+ pub epf_sharpness: u8,
+}
+
+impl Tuning {
+ /// The mapping from the 0..=100 quality scale (90 is about distance 1) used by libjxl.
+ pub fn from_quality(quality: f32) -> Tuning {
+ let q = quality.clamp(0.0, 100.0);
+ let distance = if q >= 100.0 {
+ 0.01
+ } else if q >= 30.0 {
+ 0.1 + (100.0 - q) * 0.09
+ } else {
+ 6.4 + 2.5f32.powf((30.0 - q) / 5.0) * 0.1 - 0.1
+ };
+ Tuning { distance, strength: 1.0, dc_mult: 0.55, round_threshold: 0.5, epf_iters: 2, gaborish: true, epf_sharpness: 4 }
+ }
+}
+
+/// Encodes 8-bit RGBA pixels (4 bytes each, row after row; the alpha byte is used only when `has_alpha`) as a bare JPEG
+/// XL codestream. `quality` is 0..=100 like libjxl's, about 90 being "visually lossless".
+///
+/// Panics when the picture is empty, bigger than `MAX_SIDE` or the buffer is too short.
+pub fn encode(width: u32, height: u32, rgba: &[u8], has_alpha: bool, quality: f32) -> Vec<u8> {
+ encode_tuned(width, height, rgba, has_alpha, &Tuning::from_quality(quality))
+}
+
+pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuning: &Tuning) -> Vec<u8> {
+ assert!(width >= 1 && height >= 1 && width <= MAX_SIDE && height <= MAX_SIDE, "size {width}x{height} is not supported");
+ let (w, h) = (width as usize, height as usize);
+ assert!(rgba.len() >= w * h * 4, "pixel buffer too short");
+ let (bw, bh) = (w.div_ceil(8), h.div_ceil(8));
+ let planes = xyb::to_xyb(rgba, w, h, bw * 8, bh * 8);
+
+ // Quantization: a block quant of 8 for every block, the global scale makes up the strength.
+ let strength = tuning.strength / tuning.distance.max(0.01);
+ let raw_quant = 8u32;
+ let global_scale = ((strength * 65536.0 / raw_quant as f32).round() as u32).clamp(1, 8193 + 65535);
+ let quant_lf = ((raw_quant as f32 * 1.09 / tuning.dc_mult).round() as u32).clamp(1, 65536);
+ let q = vardct::Quant {
+ global_scale,
+ raw_quant,
+ quant_lf,
+ round_offset: tuning.round_threshold,
+ x_qm_scale: 3,
+ b_qm_scale: 2,
+ };
+ let blocks = vardct::quantize(&planes, bw, bh, &q);
+
+ // The streams of modular data share one tree.
+ let tree = Tree::new(T::Split(
+ 1,
+ 2,
+ // the block metadata (stream 3): channels ytox, ytob, (type, quant), epf
+ Box::new(T::Split(
+ 0,
+ 2,
+ Box::new(T::Leaf(modular::PRED_GRADIENT)),
+ Box::new(T::Split(
+ 0,
+ 1,
+ Box::new(T::Split(2, 0, Box::new(T::Leaf(modular::PRED_GRADIENT)), Box::new(T::Leaf(modular::PRED_GRADIENT)))),
+ Box::new(T::Leaf(modular::PRED_GRADIENT)),
+ )),
+ )),
+ Box::new(T::Split(
+ 1,
+ 0,
+ // the low-frequency image (stream 1): channels Y, X, B
+ Box::new(T::Split(
+ 0,
+ 1,
+ Box::new(T::Leaf(modular::PRED_GRADIENT)),
+ Box::new(T::Split(0, 0, Box::new(T::Leaf(modular::PRED_GRADIENT)), Box::new(T::Leaf(modular::PRED_GRADIENT)))),
+ )),
+ // the global stream (stream 0): alpha
+ Box::new(T::Leaf(modular::PRED_GRADIENT)),
+ )),
+ ));
+ let mut dc_tokens = Vec::new();
+ modular::encode_channels(&vardct::dc_channels(&blocks), 1, &tree, &mut dc_tokens);
+ let mut meta_tokens = Vec::new();
+ let nblocks = bw * bh;
+ let tiles = (bw.div_ceil(8), bh.div_ceil(8));
+ let meta = [
+ Chan { w: tiles.0, h: tiles.1, data: vec![0; tiles.0 * tiles.1] },
+ Chan { w: tiles.0, h: tiles.1, data: vec![0; tiles.0 * tiles.1] },
+ Chan { w: nblocks, h: 2, data: (0..nblocks * 2).map(|i| if i < nblocks { 0 } else { raw_quant as i32 - 1 }).collect() },
+ Chan { w: bw, h: bh, data: vec![tuning.epf_sharpness as i32; nblocks] },
+ ];
+ modular::encode_channels(&meta, 3, &tree, &mut meta_tokens);
+ let leaf_codes = ans::build_codes(tree.num_leaves, &[&dc_tokens, &meta_tokens]);
+
+ // The coefficients of each group.
+ let (gw, gh) = (bw.div_ceil(vardct::GROUP_BLOCKS), bh.div_ceil(vardct::GROUP_BLOCKS));
+ let mut group_tokens: Vec<Vec<ans::Token>> = Vec::new();
+ for gy in 0..gh {
+ for gx in 0..gw {
+ let mut t = Vec::new();
+ vardct::group_tokens(&blocks, gx, gy, &mut t);
+ group_tokens.push(t);
+ }
+ }
+ let ac_codes = ans::build_codes(vardct::NUM_AC_CONTEXTS, &group_tokens.iter().map(|t| t.as_slice()).collect::<Vec<_>>());
+
+ // --- the sections
+ let mut lf_global = BitWriter::new();
+ lf_global.put(1, 1); // default LF quantization factors
+ put_global_scale(&mut lf_global, global_scale);
+ put_quant_lf(&mut lf_global, quant_lf);
+ // the block context map: Y has its own contexts, X and B share theirs
+ lf_global.put(0, 1);
+ lf_global.put(0, 12); // no thresholds on the LF values
+ lf_global.put(0, 4); // none on the quantization
+ let ctx_map: Vec<u8> = (0..3 * 13).map(|i| if i < 13 { 0 } else { 1 }).collect();
+ ans::write_context_map(&mut lf_global, &ctx_map, 2);
+ lf_global.put(1, 1); // default colour correlation
+ lf_global.put(1, 1); // a global tree
+ tree.write(&mut lf_global);
+ leaf_codes.write_header(&mut lf_global);
+
+ let mut lf_group = BitWriter::new();
+ lf_group.put(0, 2); // extra precision
+ modular::write_stream(&mut lf_group, &leaf_codes, &dc_tokens);
+ lf_group.put((nblocks - 1) as u64, ceil_log2(nblocks));
+ modular::write_stream(&mut lf_group, &leaf_codes, &meta_tokens);
+
+ let mut hf_global = BitWriter::new();
+ hf_global.put(1, 1); // default dequantization matrices
+ hf_global.put(0, ceil_log2(gw * gh)); // one set of histograms
+ hf_global.put(2, 2); // the coefficient order is the natural one
+ ac_codes.write_header(&mut hf_global);
+
+ let hf_groups: Vec<BitWriter> = group_tokens
+ .iter()
+ .map(|t| {
+ let mut b = BitWriter::new();
+ ac_codes.write_stream(&mut b, t);
+ b
+ })
+ .collect();
+
+ // --- the file
+ let mut out = BitWriter::new();
+ out.put(0xff, 8);
+ out.put(0x0a, 8);
+ out.put(0, 1); // not "small"
+ put_u32(&mut out, height - 1, [U32Form::Bits(9), U32Form::Bits(13), U32Form::Bits(18), U32Form::Bits(30)]);
+ out.put(0, 3); // the width is given
+ put_u32(&mut out, width - 1, [U32Form::Bits(9), U32Form::Bits(13), U32Form::Bits(18), U32Form::Bits(30)]);
+ if has_alpha {
+ // not all default: 8-bit, one extra channel (alpha, all default), XYB, sRGB
+ out.put(0, 1);
+ out.put(0, 1); // no extra fields
+ out.put(0, 1); // integer samples
+ out.put(0, 2); // 8 bits
+ out.put(1, 1); // 16 bits are enough for modular
+ out.put(1, 2); // one extra channel
+ out.put(1, 1); // alpha with the defaults
+ out.put(1, 1); // XYB
+ out.put(1, 1); // sRGB
+ out.put(0, 2); // no extensions
+ } else {
+ out.put(1, 1);
+ }
+ out.put(1, 1); // default transform data
+ out.align();
+
+ // frame header
+ out.put(0, 1); // not all default
+ out.put(0, 2); // regular frame
+ out.put(0, 1); // VarDCT
+ out.put(0, 2); // no flags
+ out.put(0, 2); // no upsampling
+ if has_alpha {
+ out.put(0, 2);
+ }
+ out.put(q.x_qm_scale as u64, 3);
+ out.put(q.b_qm_scale as u64, 3);
+ out.put(0, 2); // one pass
+ out.put(0, 1); // no crop
+ out.put(0, 2); // blending: replace
+ if has_alpha {
+ out.put(0, 2);
+ }
+ out.put(1, 1); // last frame
+ out.put(0, 2); // no name
+ // restoration filter
+ out.put(0, 1);
+ out.put(tuning.gaborish as u64, 1);
+ if tuning.gaborish {
+ out.put(0, 1);
+ }
+ out.put(tuning.epf_iters as u64, 2);
+ if tuning.epf_iters > 0 {
+ out.put(0, 1); // sharpness table
+ out.put(0, 1); // weights
+ out.put(0, 1); // sigma
+ }
+ out.put(0, 2); // no extensions
+ out.put(0, 2); // frame header extensions
+
+ // table of contents
+ let single = gw * gh == 1;
+ out.put(0, 1); // not permuted
+ out.align();
+ let mut sections: Vec<Vec<u8>> = Vec::new();
+ if single {
+ let mut all = lf_global;
+ all.append(&lf_group);
+ all.append(&hf_global);
+ all.append(&hf_groups[0]);
+ sections.push(all.finish());
+ } else {
+ sections.push(lf_global.finish());
+ sections.push(lf_group.finish());
+ sections.push(hf_global.finish());
+ for g in hf_groups {
+ sections.push(g.finish());
+ }
+ }
+ for s in &sections {
+ put_u32(
+ &mut out,
+ s.len() as u32,
+ [U32Form::Bits(10), U32Form::BitsOffset(14, 1024), U32Form::BitsOffset(22, 17408), U32Form::BitsOffset(30, 4211712)],
+ );
+ }
+ out.align();
+ let mut bytes = out.finish();
+ for s in sections {
+ bytes.extend_from_slice(&s);
+ }
+ bytes
+}
+
+fn put_global_scale(bw: &mut BitWriter, v: u32) {
+ match v {
+ 1..=2048 => {
+ bw.put(0, 2);
+ bw.put((v - 1) as u64, 11);
+ }
+ 2049..=4096 => {
+ bw.put(1, 2);
+ bw.put((v - 2049) as u64, 11);
+ }
+ 4097..=8192 => {
+ bw.put(2, 2);
+ bw.put((v - 4097) as u64, 12);
+ }
+ _ => {
+ bw.put(3, 2);
+ bw.put((v - 8193) as u64, 16);
+ }
+ }
+}
+
+fn put_quant_lf(bw: &mut BitWriter, v: u32) {
+ match v {
+ 16 => bw.put(0, 2),
+ 1..=32 => {
+ bw.put(1, 2);
+ bw.put((v - 1) as u64, 5);
+ }
+ 33..=256 => {
+ bw.put(2, 2);
+ bw.put((v - 1) as u64, 8);
+ }
+ _ => {
+ bw.put(3, 2);
+ bw.put((v - 1) as u64, 16);
+ }
+ }
+}
diff --git a/crates/rf-jxl/src/modular.rs b/crates/rf-jxl/src/modular.rs
new file mode 100644
index 00000000..6998076d
--- /dev/null
+++ b/crates/rf-jxl/src/modular.rs
@@ -0,0 +1,182 @@
+//! The modular part of JPEG XL, as far as we use it: whole-number images (the low-frequency image, the block
+//! metadata, the alpha channel) predicted pixel by pixel, the prediction picked by a small decision tree whose leaves
+//! also pick the distribution the residual is coded with.
+//!
+//! One tree is shared by all the streams of a frame (the "global tree"); it tells them apart through the channel
+//! number and the stream number, which are the tree's first two properties.
+
+use crate::ans::{Codes, Token, build_codes};
+use crate::bits::BitWriter;
+
+pub const PRED_ZERO: u8 = 0;
+pub const PRED_WEST: u8 = 1;
+pub const PRED_NORTH: u8 = 2;
+pub const PRED_GRADIENT: u8 = 5;
+
+/// A tree as it is built: the left branch is taken when the property is bigger than the value.
+pub enum T {
+ Leaf(u8),
+ Split(u8, i32, Box<T>, Box<T>),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum Node {
+ Split { prop: u8, val: i32, left: u32, right: u32 },
+ Leaf { pred: u8, id: u32 },
+}
+
+/// The tree with its nodes in the order the format stores them: breadth first, a node's two children one after the
+/// other.
+pub struct Tree {
+ pub nodes: Vec<Node>,
+ pub num_leaves: usize,
+}
+
+impl Tree {
+ pub fn new(t: T) -> Tree {
+ let mut nodes: Vec<Node> = Vec::new();
+ let mut queue: std::collections::VecDeque<(T, usize)> = std::collections::VecDeque::new();
+ queue.push_back((t, 0));
+ nodes.push(Node::Leaf { pred: 0, id: 0 });
+ let mut leaves = 0;
+ while let Some((t, at)) = queue.pop_front() {
+ match t {
+ T::Leaf(pred) => {
+ nodes[at] = Node::Leaf { pred, id: leaves };
+ leaves += 1;
+ }
+ T::Split(prop, val, l, r) => {
+ let left = nodes.len() as u32;
+ nodes.push(Node::Leaf { pred: 0, id: 0 });
+ nodes.push(Node::Leaf { pred: 0, id: 0 });
+ nodes[at] = Node::Split { prop, val, left, right: left + 1 };
+ queue.push_back((*l, left as usize));
+ queue.push_back((*r, left as usize + 1));
+ }
+ }
+ }
+ Tree { nodes, num_leaves: leaves as usize }
+ }
+
+ #[inline]
+ fn walk(&self, props: &[i32; 16]) -> (u8, u32) {
+ let mut at = 0;
+ loop {
+ match self.nodes[at] {
+ Node::Split { prop, val, left, right } => {
+ at = if props[prop as usize] > val { left as usize } else { right as usize };
+ }
+ Node::Leaf { pred, id } => return (pred, id),
+ }
+ }
+ }
+
+ /// The tree as the decoder reads it: its own small code, then the nodes as tokens.
+ pub fn write(&self, bw: &mut BitWriter) {
+ let mut toks = Vec::new();
+ for n in &self.nodes {
+ match *n {
+ Node::Split { prop, val, .. } => {
+ toks.push(Token { ctx: 1, val: prop as u32 + 1 });
+ toks.push(Token { ctx: 0, val: pack_signed(val) });
+ }
+ Node::Leaf { pred, .. } => {
+ toks.push(Token { ctx: 1, val: 0 });
+ toks.push(Token { ctx: 2, val: pred as u32 });
+ toks.push(Token { ctx: 3, val: 0 }); // offset
+ toks.push(Token { ctx: 4, val: 0 }); // multiplier, log2
+ toks.push(Token { ctx: 5, val: 0 }); // multiplier, bits
+ }
+ }
+ }
+ let codes = build_codes(6, &[&toks]);
+ codes.write_header(bw);
+ codes.write_stream(bw, &toks);
+ }
+}
+
+#[inline(always)]
+pub fn pack_signed(v: i32) -> u32 {
+ ((v << 1) ^ (v >> 31)) as u32
+}
+
+/// One channel of whole numbers.
+pub struct Chan {
+ pub w: usize,
+ pub h: usize,
+ pub data: Vec<i32>,
+}
+
+fn clamped_gradient(l: i32, t: i32, tl: i32) -> i32 {
+ let (l, t, tl) = (l as i64, t as i64, tl as i64);
+ let min = l.min(t);
+ let max = l.max(t);
+ let g = l + t - tl;
+ (if tl < min { max } else if tl > max { min } else { g }) as i32
+}
+
+/// Codes the channels of one stream: for each pixel the residual of the tree's prediction, as a token whose context
+/// is the leaf. `stream` is the frame's number for the stream (the tree's second property).
+pub fn encode_channels(chans: &[Chan], stream: u32, tree: &Tree, out: &mut Vec<Token>) {
+ for (ci, ch) in chans.iter().enumerate() {
+ let (w, h) = (ch.w, ch.h);
+ let mut props = [0i32; 16];
+ props[0] = ci as i32;
+ props[1] = stream as i32;
+ for y in 0..h {
+ let row = &ch.data[y * w..(y + 1) * w];
+ let top_row = if y > 0 { Some(&ch.data[(y - 1) * w..y * w]) } else { None };
+ let toptop_row = if y > 1 { Some(&ch.data[(y - 2) * w..(y - 1) * w]) } else { None };
+ for x in 0..w {
+ // The neighbours the decoder uses, with its rules for the edges.
+ let left = if x > 0 {
+ row[x - 1]
+ } else if let Some(t) = top_row {
+ t[0]
+ } else {
+ 0
+ };
+ let top = top_row.map_or(left, |t| t[x]);
+ let topleft = if x > 0 && y > 0 { top_row.unwrap()[x - 1] } else { left };
+ let topright = if x + 1 < w && y > 0 { top_row.unwrap()[x + 1] } else { top };
+ let leftleft = if x > 1 { row[x - 2] } else { left };
+ let toptop = toptop_row.map_or(top, |t| t[x]);
+ props[2] = y as i32;
+ props[3] = x as i32;
+ props[4] = top.wrapping_abs();
+ props[5] = left.wrapping_abs();
+ props[6] = top;
+ props[7] = left;
+ props[9] = left.wrapping_add(top).wrapping_sub(topleft);
+ props[10] = left.wrapping_sub(topleft);
+ props[11] = topleft.wrapping_sub(top);
+ props[12] = top.wrapping_sub(topright);
+ props[13] = top.wrapping_sub(toptop);
+ props[14] = left.wrapping_sub(leftleft);
+ let (pred, id) = tree.walk(&props);
+ let guess = match pred {
+ PRED_ZERO => 0,
+ PRED_WEST => left,
+ PRED_NORTH => top,
+ PRED_GRADIENT => clamped_gradient(left, top, topleft),
+ _ => panic!("predictor {pred} not implemented"),
+ };
+ out.push(Token { ctx: id, val: pack_signed(row[x].wrapping_sub(guess)) });
+ }
+ }
+ }
+}
+
+/// The start of every modular stream that uses the global tree: no own tree, default weighted-predictor
+/// parameters, no transforms.
+pub fn write_stream_header(bw: &mut BitWriter) {
+ bw.put(1, 1);
+ bw.put(1, 1);
+ bw.put(0, 2);
+}
+
+/// A complete stream: its header and the tokens.
+pub fn write_stream(bw: &mut BitWriter, codes: &Codes, tokens: &[Token]) {
+ write_stream_header(bw);
+ codes.write_stream(bw, tokens);
+}
diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rs
new file mode 100644
index 00000000..ba66a58a
--- /dev/null
+++ b/crates/rf-jxl/src/vardct.rs
@@ -0,0 +1,331 @@
+//! The lossy transform: 8x8 DCT blocks of the XYB planes, quantized, and the tokens the coefficients become.
+//!
+//! Numbers here come from the decoder's way of undoing each step (dequantization with its default weights, the bias
+//! it applies to small values, the colour-from-luma terms); the encoder just runs those steps forward.
+
+use std::sync::OnceLock;
+
+use crate::ans::Token;
+use crate::modular::{Chan, pack_signed};
+
+pub const BLOCK: usize = 8;
+/// Blocks per group side (groups are 256 pixels).
+pub const GROUP_BLOCKS: usize = 32;
+
+/// How the decoder weighs the coefficients of the 8x8 DCT, X, Y and B (the "distance band" parameters of the
+/// default library table).
+const DCT8_BANDS: [[f32; 6]; 3] = [
+ [3150.0, 0.0, -0.4, -0.4, -0.4, -2.0],
+ [560.0, 0.0, -0.3, -0.3, -0.3, -0.3],
+ [512.0, -2.0, -1.0, 0.0, -1.0, -2.0],
+];
+
+/// The low-frequency image's quantization factors, X, Y, B.
+const LF_QUANT: [f32; 3] = [1.0 / 4096.0, 1.0 / 512.0, 1.0 / 256.0];
+/// Where small quantized values land again (X, Y, B), and the pull toward zero of the bigger ones.
+const QUANT_BIAS: [f32; 3] = [1.0 - 0.05465007330715401, 1.0 - 0.07005449891748593, 1.0 - 0.049935103337343655];
+const QUANT_BIAS_NUM: f32 = 0.145;
+
+pub const COEFF_FREQ_CONTEXT: [usize; 64] = [
+ 0xBAD, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 30, 32, 32, 34, 34, 36, 36, 38, 38, 40, 40, 42, 42, 44,
+ 44, 46, 46, 46, 46, 48, 48, 48, 48, 50, 50, 50, 50, 52, 52, 52, 52, 54, 54, 54, 54, 56, 56, 56, 56, 58, 58, 58, 58, 60, 60,
+ 60, 60,
+];
+
+pub const COEFF_NUM_NONZERO_CONTEXT: [usize; 64] = [
+ 0xBAD, 0, 62, 124, 124, 186, 186, 186, 186, 246, 246, 246, 246, 304, 304, 304, 304, 304, 304, 304, 304, 360, 360, 360, 360,
+ 360, 360, 360, 360, 360, 360, 360, 360, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
+ 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, 412,
+];
+
+const NON_ZERO_BUCKETS: usize = 37;
+const ZERO_DENSITY_CONTEXT_COUNT: usize = 458;
+/// Block contexts we use: one for Y, one shared by X and B.
+pub const NUM_BLOCK_CONTEXTS: usize = 2;
+pub const NUM_AC_CONTEXTS: usize = NUM_BLOCK_CONTEXTS * (NON_ZERO_BUCKETS + ZERO_DENSITY_CONTEXT_COUNT);
+
+struct Tables {
+ /// The order the coefficients are coded in: position k holds the raster index (y * 8 + x).
+ order: [u8; 64],
+ /// 1 / (the decoder's weight), channel by channel (X, Y, B): the unscaled dequantization step.
+ weight: [[f32; 64]; 3],
+ /// The forward DCT's matrix: row k is the k-th basis function, scaled so the DC is the mean.
+ dct: [[f32; 8]; 8],
+}
+
+fn tables() -> &'static Tables {
+ static T: OnceLock<Tables> = OnceLock::new();
+ T.get_or_init(|| {
+ // The decoder's natural order for a square 8x8 block: diagonals, alternating direction.
+ let mut order = [0u8; 64];
+ let mut cur = 1;
+ for i in 0..8usize {
+ for j in 0..=i {
+ let (mut x, mut y) = (j, i - j);
+ if i % 2 != 0 {
+ std::mem::swap(&mut x, &mut y);
+ }
+ if x < 1 && y < 1 {
+ order[0] = 0;
+ } else {
+ order[cur] = (y * 8 + x) as u8;
+ cur += 1;
+ }
+ }
+ }
+ for ir in 1..8usize {
+ let i = 8 - ir - 1;
+ for j in 0..=i {
+ let (mut x, mut y) = (7 - (i - j), 7 - j);
+ if i % 2 != 0 {
+ std::mem::swap(&mut x, &mut y);
+ }
+ order[cur] = (y * 8 + x) as u8;
+ cur += 1;
+ }
+ }
+ // The weights: bands interpolated by the distance from the DC corner.
+ let mut weight = [[0f32; 64]; 3];
+ let mult = |v: f32| if v > 0.0 { 1.0 + v } else { 1.0 / (1.0 - v) };
+ for c in 0..3 {
+ let mut bands = [0f32; 17];
+ bands[0] = DCT8_BANDS[c][0];
+ for i in 1..6 {
+ bands[i] = bands[i - 1] * mult(DCT8_BANDS[c][i]);
+ }
+ let scale = 5.0 / (std::f32::consts::SQRT_2 + 1e-6);
+ let rcp = scale / 7.0;
+ for y in 0..8 {
+ for x in 0..8 {
+ let (dx, dy) = (x as f32 * rcp, y as f32 * rcp);
+ let d = (dx * dx + dy * dy).sqrt();
+ let idx = d.floor();
+ let frac = d - idx;
+ let idx = idx as usize;
+ let (a, b) = (bands[idx], bands[idx + 1]);
+ weight[c][y * 8 + x] = 1.0 / ((b / a).powf(frac) * a);
+ }
+ }
+ }
+ let mut dct = [[0f32; 8]; 8];
+ for (k, row) in dct.iter_mut().enumerate() {
+ let s = if k == 0 { 1.0 } else { std::f64::consts::SQRT_2 };
+ for (n, v) in row.iter_mut().enumerate() {
+ *v = (s / 8.0 * ((2 * n + 1) as f64 * k as f64 * std::f64::consts::PI / 16.0).cos()) as f32;
+ }
+ }
+ Tables { order, weight, dct }
+ })
+}
+
+/// Forward 8x8 DCT of `src` (row `stride`) into `out` (raster order, row = vertical frequency).
+#[inline(always)]
+fn dct8x8(m: &[[f32; 8]; 8], src: &[f32], stride: usize, out: &mut [f32; 64]) {
+ let mut t = [0f32; 64];
+ // columns: t[ky][x] = sum_y m[ky][y] * src[y][x]
+ for ky in 0..8 {
+ for y in 0..8 {
+ let mk = m[ky][y];
+ let row = &src[y * stride..y * stride + 8];
+ for x in 0..8 {
+ t[ky * 8 + x] += mk * row[x];
+ }
+ }
+ }
+ for ky in 0..8 {
+ for kx in 0..8 {
+ let mut s = 0.0;
+ for x in 0..8 {
+ s += t[ky * 8 + x] * m[kx][x];
+ }
+ // the decoder keeps the horizontal frequency as the row of its coefficient array
+ out[kx * 8 + ky] = s;
+ }
+ }
+}
+
+/// Everything that is decided before the coefficients are looked at.
+#[derive(Clone, Debug)]
+pub struct Quant {
+ /// The frame's global scale and the per-block factor all blocks get (the block's `quant`).
+ pub global_scale: u32,
+ pub raw_quant: u32,
+ /// The low-frequency image's extra divisor.
+ pub quant_lf: u32,
+ /// Rounding: values below `round_offset` of a step become zero, the rest round to nearest.
+ pub round_offset: f32,
+ pub x_qm_scale: u32,
+ pub b_qm_scale: u32,
+}
+
+impl Quant {
+ /// Overall quantization strength: step = 1 / (strength * weight) before the X and B multipliers.
+ fn strength(&self) -> f32 {
+ self.global_scale as f32 * self.raw_quant as f32 / 65536.0
+ }
+}
+
+/// The quantized picture, block by block.
+pub struct Blocks {
+ pub bw: usize,
+ pub bh: usize,
+ /// Low-frequency image in the order the format codes it: Y, X, B.
+ pub dc: [Vec<i32>; 3],
+ /// AC coefficients, `[block][channel X, Y, B][raster index]`, the DC position holding 0.
+ pub ac: Vec<[[i16; 64]; 3]>,
+}
+
+#[inline(always)]
+fn dequant_value(q: i32, c: usize) -> f32 {
+ let qf = q as f32;
+ if q.abs() < 2 { qf * QUANT_BIAS[c] } else { qf - QUANT_BIAS_NUM / qf }
+}
+
+/// DCT and quantization of all blocks. `planes` are X, Y, B with `bw * 8` columns.
+pub fn quantize(planes: &[Vec<f32>; 3], bw: usize, bh: usize, q: &Quant) -> Blocks {
+ let t = tables();
+ let stride = bw * 8;
+ let strength = q.strength();
+ let dm = [
+ (1.0f32 / 1.25).powf(q.x_qm_scale as f32 - 2.0),
+ 1.0,
+ (1.0f32 / 1.25).powf(q.b_qm_scale as f32 - 2.0),
+ ];
+ // quantization step of each coefficient, and its inverse
+ let mut inv_step = [[0f32; 64]; 3];
+ let mut step = [[0f32; 64]; 3];
+ for c in 0..3 {
+ for k in 0..64 {
+ step[c][k] = t.weight[c][k] * dm[c] / strength;
+ inv_step[c][k] = 1.0 / step[c][k];
+ }
+ }
+ // low-frequency steps
+ let inv_quant_lf = 65536.0 / (q.global_scale as f32 * q.quant_lf as f32);
+ let lf_fac = [LF_QUANT[0] * inv_quant_lf, LF_QUANT[1] * inv_quant_lf, LF_QUANT[2] * inv_quant_lf];
+
+ let mut dc = [vec![0i32; bw * bh], vec![0i32; bw * bh], vec![0i32; bw * bh]];
+ let mut ac = vec![[[0i16; 64]; 3]; bw * bh];
+ let round = |v: f32| -> i32 {
+ let a = v.abs();
+ let r = (a + 1.0 - q.round_offset).floor();
+ if v < 0.0 { -(r as i32) } else { r as i32 }
+ };
+ for by in 0..bh {
+ for bx in 0..bw {
+ let mut co = [[0f32; 64]; 3];
+ for c in 0..3 {
+ dct8x8(&t.dct, &planes[c][by * 8 * stride + bx * 8..], stride, &mut co[c]);
+ }
+ let bi = by * bw + bx;
+ // low frequencies: Y first, X and B are coded relative to it (X not at all by default, B by 1.0)
+ let qy = (co[1][0] / lf_fac[1]).round() as i32;
+ let y_rec = qy as f32 * lf_fac[1];
+ let qx = (co[0][0] / lf_fac[0]).round() as i32;
+ let qb = ((co[2][0] - y_rec) / lf_fac[2]).round() as i32;
+ dc[0][bi] = qy;
+ dc[1][bi] = qx;
+ dc[2][bi] = qb;
+ // high frequencies
+ let mut y_rec_ac = [0f32; 64];
+ for k in 1..64 {
+ let qq = round(co[1][k] * inv_step[1][k]);
+ ac[bi][1][k] = qq.clamp(-32000, 32000) as i16;
+ y_rec_ac[k] = dequant_value(qq, 1) * step[1][k];
+ }
+ for k in 1..64 {
+ let qq = round(co[0][k] * inv_step[0][k]);
+ ac[bi][0][k] = qq.clamp(-32000, 32000) as i16;
+ let rb = co[2][k] - y_rec_ac[k];
+ let qq = round(rb * inv_step[2][k]);
+ ac[bi][2][k] = qq.clamp(-32000, 32000) as i16;
+ }
+ }
+ }
+ Blocks { bw, bh, dc, ac }
+}
+
+/// The three channels of the low-frequency image, coded in the order Y, X, B.
+pub fn dc_channels(b: &Blocks) -> Vec<Chan> {
+ b.dc.iter().map(|d| Chan { w: b.bw, h: b.bh, data: d.clone() }).collect()
+}
+
+fn nonzero_bucket(n: usize) -> usize {
+ if n < 8 {
+ n
+ } else if n < 64 {
+ 4 + n / 2
+ } else {
+ 36
+ }
+}
+
+/// The tokens of one 256x256 group's coefficients, `gx`, `gy` its place in groups.
+pub fn group_tokens(b: &Blocks, gx: usize, gy: usize, out: &mut Vec<Token>) {
+ let t = tables();
+ let x0 = gx * GROUP_BLOCKS;
+ let y0 = gy * GROUP_BLOCKS;
+ let x1 = (x0 + GROUP_BLOCKS).min(b.bw);
+ let y1 = (y0 + GROUP_BLOCKS).min(b.bh);
+ // number of nonzero coefficients of the block above and to the left, per channel
+ let mut nz_row = [[0u8; GROUP_BLOCKS]; 3];
+ for by in y0..y1 {
+ for bx in x0..x1 {
+ let blk = &b.ac[by * b.bw + bx];
+ let (lx, ly) = (bx - x0, by - y0);
+ for c in [1usize, 0, 2] {
+ let predicted = if lx == 0 {
+ if ly == 0 { 32 } else { nz_row[c][0] as usize }
+ } else if ly == 0 {
+ nz_row[c][lx - 1] as usize
+ } else {
+ (nz_row[c][lx] as usize + nz_row[c][lx - 1] as usize).div_ceil(2)
+ };
+ let block_ctx = if c == 1 { 0 } else { 1 };
+ let co = &blk[c];
+ let mut nz = 0usize;
+ for k in 1..64 {
+ if co[t.order[k] as usize] != 0 {
+ nz += 1;
+ }
+ }
+ out.push(Token { ctx: (nonzero_bucket(predicted) * NUM_BLOCK_CONTEXTS + block_ctx) as u32, val: nz as u32 });
+ nz_row[c][lx] = nz as u8;
+ if nz == 0 {
+ continue;
+ }
+ let hist_off = NUM_BLOCK_CONTEXTS * NON_ZERO_BUCKETS + ZERO_DENSITY_CONTEXT_COUNT * block_ctx;
+ let mut prev = if nz > 64 / 16 { 0 } else { 1 };
+ let mut left = nz;
+ for k in 1..64 {
+ let v = co[t.order[k] as usize] as i32;
+ let ctx = hist_off + COEFF_NUM_NONZERO_CONTEXT[left] + COEFF_FREQ_CONTEXT[k] + prev;
+ out.push(Token { ctx: ctx as u32, val: pack_signed(v) });
+ if v == 0 {
+ prev = 0;
+ } else {
+ left -= 1;
+ if left == 0 {
+ break;
+ }
+ prev = 1;
+ }
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn natural_order_matches_the_decoders() {
+ let t = tables();
+ let head = [0u8, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7];
+ assert_eq!(&t.order[..head.len()], &head);
+ let tail = [58u8, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63];
+ assert_eq!(&t.order[48..], &tail);
+ }
+}
diff --git a/crates/rf-jxl/src/xyb.rs b/crates/rf-jxl/src/xyb.rs
new file mode 100644
index 00000000..ea00252b
--- /dev/null
+++ b/crates/rf-jxl/src/xyb.rs
@@ -0,0 +1,104 @@
+//! From 8-bit sRGB to the XYB colour space JPEG XL codes lossy pictures in: a mix of the linear light into three
+//! cone-like responses, a cube root (with a small bias so black is not infinitely steep), then X = (L - M) / 2,
+//! Y = (L + M) / 2 and B = S.
+//!
+//! The mix is the inverse of the decoder's default matrix, which is how the format defines it.
+
+use std::sync::OnceLock;
+
+/// The decoder's default "opsin inverse" matrix: XYB's linear cone values back to linear RGB.
+const INVERSE: [f64; 9] = [
+ 11.031566901960783,
+ -9.866943921568629,
+ -0.16462299647058826,
+ -3.254147380392157,
+ 4.418770392156863,
+ -0.16462299647058826,
+ -3.6588512862745097,
+ 2.7129230470588235,
+ 1.9459282392156863,
+];
+const BIAS: f32 = 0.0037930732552754493;
+
+struct Tables {
+ /// sRGB byte to linear light.
+ lin: [f32; 256],
+ /// Linear RGB to the cone values (the inverse matrix, inverted).
+ mat: [f32; 9],
+ bias_cbrt: f32,
+}
+
+fn tables() -> &'static Tables {
+ static T: OnceLock<Tables> = OnceLock::new();
+ T.get_or_init(|| {
+ let mut lin = [0f32; 256];
+ for (i, v) in lin.iter_mut().enumerate() {
+ let c = i as f64 / 255.0;
+ *v = (if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }) as f32;
+ }
+ let m = &INVERSE;
+ let det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
+ let inv = [
+ (m[4] * m[8] - m[5] * m[7]) / det,
+ (m[2] * m[7] - m[1] * m[8]) / det,
+ (m[1] * m[5] - m[2] * m[4]) / det,
+ (m[5] * m[6] - m[3] * m[8]) / det,
+ (m[0] * m[8] - m[2] * m[6]) / det,
+ (m[2] * m[3] - m[0] * m[5]) / det,
+ (m[3] * m[7] - m[4] * m[6]) / det,
+ (m[1] * m[6] - m[0] * m[7]) / det,
+ (m[0] * m[4] - m[1] * m[3]) / det,
+ ];
+ Tables { lin, mat: inv.map(|v| v as f32), bias_cbrt: BIAS.cbrt() }
+ })
+}
+
+/// Cube root to a relative error of about 1e-6: a guess from the exponent bits, then Newton steps.
+#[inline(always)]
+fn cbrt_fast(x: f32) -> f32 {
+ let bits = x.to_bits();
+ let mut y = f32::from_bits(bits / 3 + 0x2a51_4c00);
+ // y = (2y + x / y^2) / 3
+ y = (2.0 * y + x / (y * y)) * (1.0 / 3.0);
+ y = (2.0 * y + x / (y * y)) * (1.0 / 3.0);
+ y = (2.0 * y + x / (y * y)) * (1.0 / 3.0);
+ y
+}
+
+/// The picture as three planes (X, Y, B), `stride` floats per row, the rows past `h` and the columns past `w` filled
+/// by repeating the edge up to `pw` x `ph`. `rgba` has 4 bytes per pixel.
+pub fn to_xyb(rgba: &[u8], w: usize, h: usize, pw: usize, ph: usize) -> [Vec<f32>; 3] {
+ let t = tables();
+ let mut planes = [vec![0f32; pw * ph], vec![0f32; pw * ph], vec![0f32; pw * ph]];
+ let [m0, m1, m2, m3, m4, m5, m6, m7, m8] = t.mat;
+ for y in 0..h {
+ let src = &rgba[y * w * 4..(y + 1) * w * 4];
+ for x in 0..w {
+ let r = t.lin[src[x * 4] as usize];
+ let g = t.lin[src[x * 4 + 1] as usize];
+ let b = t.lin[src[x * 4 + 2] as usize];
+ let l = m0 * r + m1 * g + m2 * b + BIAS;
+ let m = m3 * r + m4 * g + m5 * b + BIAS;
+ let s = m6 * r + m7 * g + m8 * b + BIAS;
+ let lc = cbrt_fast(l.max(0.0)) - t.bias_cbrt.abs();
+ let mc = cbrt_fast(m.max(0.0)) - t.bias_cbrt.abs();
+ let sc = cbrt_fast(s.max(0.0)) - t.bias_cbrt.abs();
+ let i = y * pw + x;
+ planes[0][i] = (lc - mc) * 0.5;
+ planes[1][i] = (lc + mc) * 0.5;
+ planes[2][i] = sc;
+ }
+ // repeat the last pixel to the right
+ for x in w..pw {
+ for p in planes.iter_mut() {
+ p[y * pw + x] = p[y * pw + w - 1];
+ }
+ }
+ }
+ for y in h..ph {
+ for p in planes.iter_mut() {
+ p.copy_within((h - 1) * pw..h * pw, y * pw);
+ }
+ }
+ planes
+}
diff --git a/crates/rf-jxl/tests/roundtrip.rs b/crates/rf-jxl/tests/roundtrip.rs
new file mode 100644
index 00000000..d47ab977
--- /dev/null
+++ b/crates/rf-jxl/tests/roundtrip.rs
@@ -0,0 +1,157 @@
+//! The encoder against two independent decoders: what they read back must be the picture, close enough that
+//! SSIMULACRA2 calls it good.
+
+use std::io::Cursor;
+
+use ssimulacra2::{ColorPrimaries, Rgb, TransferCharacteristic, compute_frame_ssimulacra2};
+
+/// A picture with a bit of everything: smooth colour, a ramp, hard edges, a texture and some noise. Made from a
+/// formula, so nothing of anyone's is in the tests.
+fn synthetic(w: u32, h: u32, seed: u32) -> Vec<u8> {
+ let mut rng = seed.wrapping_mul(2654435761).wrapping_add(12345);
+ let mut next = move || {
+ rng ^= rng << 13;
+ rng ^= rng >> 17;
+ rng ^= rng << 5;
+ rng
+ };
+ let mut px = Vec::with_capacity((w * h * 4) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32);
+ let mut r = 255.0 * fx;
+ let mut g = 255.0 * (0.5 + 0.5 * (fx * 6.0 + fy * 3.0).sin());
+ let mut b = 255.0 * fy;
+ if (fx - 0.5).powi(2) + (fy - 0.5).powi(2) < 0.04 {
+ r = 230.0;
+ g = 60.0;
+ b = 40.0;
+ }
+ if x % 16 < 8 && fy > 0.7 {
+ r = 20.0;
+ g = 20.0;
+ b = 30.0;
+ }
+ if fy < 0.2 {
+ let n = (next() % 41) as f32 - 20.0;
+ r += n;
+ g += n;
+ b += n;
+ }
+ px.extend_from_slice(&[r.clamp(0.0, 255.0) as u8, g.clamp(0.0, 255.0) as u8, b.clamp(0.0, 255.0) as u8, 255]);
+ }
+ }
+ px
+}
+
+fn solid(w: u32, h: u32, c: [u8; 3]) -> Vec<u8> {
+ (0..w * h).flat_map(|_| [c[0], c[1], c[2], 255]).collect()
+}
+
+fn noise(w: u32, h: u32) -> Vec<u8> {
+ let mut s = 0x1234_5678u32;
+ (0..w * h * 4)
+ .map(|i| {
+ s ^= s << 13;
+ s ^= s >> 17;
+ s ^= s << 5;
+ if i % 4 == 3 { 255 } else { (s >> 8) as u8 }
+ })
+ .collect()
+}
+
+fn gradient(w: u32, h: u32) -> Vec<u8> {
+ (0..w * h).flat_map(|i| [(i % w * 255 / w.max(1)) as u8, (i / w * 255 / h.max(1)) as u8, 128, 255]).collect()
+}
+
+fn decode_oxide(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
+ let mut img = jxl_oxide::JxlImage::builder().read(Cursor::new(bytes)).expect("jxl-oxide reads the file");
+ img.request_color_encoding(jxl_oxide::EnumColourEncoding::srgb(jxl_oxide::RenderingIntent::Relative));
+ let r = img.render_frame(0).expect("jxl-oxide decodes the frame");
+ let fb = r.image_all_channels();
+ let ch = fb.channels();
+ let rgb = fb
+ .buf()
+ .chunks_exact(ch)
+ .flat_map(|c| [c[0], c[1], c[2]].map(|v| (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8))
+ .collect();
+ (fb.width() as u32, fb.height() as u32, rgb)
+}
+
+fn decode_jxl_rs(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
+ let d = jxl_image_rs_integration::JxlDecoder::new(Cursor::new(bytes)).expect("jxl-rs reads the file");
+ let img = image::DynamicImage::from_decoder(d).expect("jxl-rs decodes the picture").to_rgb8();
+ (img.width(), img.height(), img.into_raw())
+}
+
+fn score(w: u32, h: u32, a_rgba: &[u8], b_rgb: &[u8]) -> f64 {
+ let a: Vec<[f32; 3]> = a_rgba.chunks_exact(4).map(|c| [c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0]).collect();
+ let b: Vec<[f32; 3]> = b_rgb.chunks_exact(3).map(|c| [c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0]).collect();
+ let mk = |d| Rgb::new(d, w as usize, h as usize, TransferCharacteristic::SRGB, ColorPrimaries::BT709).unwrap();
+ if w < 8 || h < 8 {
+ // too small for the metric: compare the numbers
+ let worst = a.iter().zip(&b).flat_map(|(p, q)| (0..3).map(|i| (p[i] - q[i]).abs())).fold(0.0f32, f32::max);
+ return 100.0 - worst as f64 * 100.0;
+ }
+ compute_frame_ssimulacra2(mk(a), mk(b)).unwrap()
+}
+
+fn check(name: &str, w: u32, h: u32, px: &[u8], quality: f32, min: f64) {
+ let bytes = rf_jxl::encode(w, h, px, false, quality);
+ for (who, dec) in [("jxl-oxide", decode_oxide as fn(&[u8]) -> _), ("jxl-rs", decode_jxl_rs)] {
+ let (dw, dh, rgb) = dec(&bytes);
+ assert_eq!((dw, dh), (w, h), "{name}: {who} says the size is {dw}x{dh}");
+ let s = score(w, h, px, &rgb);
+ eprintln!("{name:<14} {w}x{h} q{quality}: {} bytes, {who} SSIMULACRA2 {s:.1}", bytes.len());
+ assert!(s > min, "{name}: {who} scores {s:.1}, wanted more than {min}");
+ }
+}
+
+#[test]
+fn synthetic_photo_like() {
+ check("synthetic", 256, 256, &synthetic(256, 256, 1), 90.0, 70.0);
+ check("synthetic", 200, 150, &synthetic(200, 150, 2), 90.0, 70.0);
+}
+
+#[test]
+fn odd_sizes() {
+ for (w, h) in [(1, 1), (7, 13), (8, 8), (9, 9), (17, 31), (64, 3), (3, 64), (100, 99)] {
+ // the metric looks at a few pixels only on very narrow pictures: be easier on those
+ check("odd", w, h, &synthetic(w, h, 3), 90.0, if w.min(h) < 8 { 40.0 } else { 60.0 });
+ }
+}
+
+#[test]
+fn flat_colours() {
+ check("flat white", 64, 64, &solid(64, 64, [255, 255, 255]), 90.0, 85.0);
+ check("flat black", 64, 64, &solid(64, 64, [0, 0, 0]), 90.0, 85.0);
+ check("flat colour", 64, 64, &solid(64, 64, [200, 40, 90]), 90.0, 85.0);
+}
+
+#[test]
+fn gradients_and_noise() {
+ check("gradient", 256, 256, &gradient(256, 256), 90.0, 70.0);
+ check("noise", 128, 128, &noise(128, 128), 90.0, 30.0);
+}
+
+#[test]
+fn stripes_keep_their_direction() {
+ let (w, h) = (64u32, 64u32);
+ // brightness varies along x only / along y only, one frequency per block
+ let vertical: Vec<u8> = (0..w * h).flat_map(|i| { let x = (i % w) as f32; let v = (128.0 + 60.0 * (x * std::f32::consts::PI / 8.0).cos()) as u8; [v, v, v, 255] }).collect();
+ let horizontal: Vec<u8> = (0..w * h).flat_map(|i| { let y = (i / w) as f32; let v = (128.0 + 60.0 * (y * std::f32::consts::PI / 8.0).cos()) as u8; [v, v, v, 255] }).collect();
+ {
+ let bytes = rf_jxl::encode(w, h, &vertical, false, 90.0);
+ let (_, _, rgb) = decode_oxide(&bytes);
+ eprintln!("orig row0: {:?}", (0..16).map(|x| vertical[x * 4]).collect::<Vec<_>>());
+ eprintln!("dec row0: {:?}", (0..16).map(|x| rgb[x * 3]).collect::<Vec<_>>());
+ eprintln!("dec row5: {:?}", (0..16).map(|x| rgb[(5 * 64 + x) * 3]).collect::<Vec<_>>());
+ }
+ check("vertical stripes", w, h, &vertical, 90.0, 60.0);
+ check("horizontal stripes", w, h, &horizontal, 90.0, 60.0);
+}
+
+#[test]
+fn bigger_than_a_group() {
+ check("synthetic", 600, 400, &synthetic(600, 400, 4), 90.0, 70.0);
+}