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.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
rf-jxl: faster writing (table cube root, even/odd DCT, reciprocal ANS)
gelenmedya56b47f02668d
diff --git a/crates/rf-jxl/src/ans.rs b/crates/rf-jxl/src/ans.rsindex 22cd09ba..fd731288 100644--- a/crates/rf-jxl/src/ans.rs+++ b/crates/rf-jxl/src/ans.rs@@ -57,6 +57,18 @@ fn entropy_bits(t: &[f32], counts: &[u32; ALPHA]) -> f32 {xlogx(t, total) - s}+/// Bits an ideal coder needs for the counts of `a` and `b` added, looking at the first `n` symbols only.+fn merged_bits(t: &[f32], a: &[u32; ALPHA], b: &[u32; ALPHA], n: usize) -> f32 {+ let mut total = 0u32;+ let mut s = 0.0;+ for k in 0..n {+ let c = a[k] + b[k];+ 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}@@ -80,6 +92,9 @@ struct ClusterCode {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>,+ /// Multipliers that divide a 32-bit state by each symbol's count with a multiplication and a shift (the shift is+ /// `ceil(log2(count))` plus 32).+ recip: [u64; ALPHA],}pub struct Codes {@@ -255,7 +270,14 @@ impl ClusterCode {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() };+ let mut recip = [0u64; ALPHA];+ for (r, &d) in recip.iter_mut().zip(dist.iter()) {+ if d > 0 {+ let l = 32 - (d as u32 - 1).leading_zeros(); // ceil(log2 d)+ *r = ((1u128 << (32 + l)) / d as u128) as u64 + 1;+ }+ }+ let mut c = ClusterCode { dist, form, inv_start: [0; ALPHA], inv: Vec::new(), recip };c.build_inverse();c}@@ -396,40 +418,34 @@ pub fn build_codes(num_contexts: usize, streams: &[&[Token]]) -> Codes {let mut clusters: Vec<[u32; ALPHA]> = Vec::new();let mut cluster_ent: Vec<f32> = Vec::new();let mut assign = vec![0usize; used.len()];+ // how many symbols (the highest one in use, plus one) each cluster spans, so loops need not run over the empty rest+ let mut cluster_hi: Vec<usize> = Vec::new();for &i in &order {let h = &used[i].1;+ let hi = h.iter().rposition(|&c| c > 0).map_or(1, |p| p + 1);let own = entropy_bits(t, h);// what a histogram of its own would cost in the header, about: a base and some bits per symbollet 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;+ let inc = merged_bits(t, c, h, hi.max(cluster_hi[j])) - cluster_ent[j] - own;if inc < best.0 {best = (inc, j);}}- if best.1 != usize::MAX && best.0 < header && clusters.len() + 1 > 0 {+ if best.1 != usize::MAX && (best.0 < header || clusters.len() >= 250) {let j = best.1;- for k in 0..ALPHA {+ for k in 0..hi {clusters[j][k] += h[k];}+ cluster_hi[j] = cluster_hi[j].max(hi);cluster_ent[j] = entropy_bits(t, &clusters[j]);assign[i] = j;- } else if clusters.len() < 250 {+ } else {clusters.push(*h);cluster_ent.push(own);+ cluster_hi.push(hi);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.@@ -495,8 +511,10 @@ impl Codes {words[i] = state & 0xffff;state >>= 16;}- let q = state / f;- let r = state % f;+ let l = 32 - (f - 1).leading_zeros();+ let q = ((state as u64 * c.recip[sym as usize]) >> (32 + l)) as u32;+ let r = state - q * f;+ debug_assert_eq!(q, 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);diff --git a/crates/rf-jxl/src/modular.rs b/crates/rf-jxl/src/modular.rsindex 3ae4f611..155623f2 100644--- a/crates/rf-jxl/src/modular.rs+++ b/crates/rf-jxl/src/modular.rs@@ -30,6 +30,7 @@ pub enum Node {pub struct Tree {pub nodes: Vec<Node>,pub num_leaves: usize,+ simple: bool,}impl Tree {@@ -55,7 +56,10 @@ impl Tree {}}}- Tree { nodes, num_leaves: leaves as usize }+ // Without a split on a neighbour's value (properties 3 and up) a row of a channel has one leaf, and the+ // tokens can be made without the work of the properties.+ let simple = !nodes.iter().any(|n| matches!(n, Node::Split { prop, .. } if *prop >= 3));+ Tree { nodes, num_leaves: leaves as usize, simple }}#[inline]@@ -135,6 +139,14 @@ pub fn encode_channels(chans: &[Chan], stream: u32, tree: &Tree, out: &mut Vec<Tlet 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 };+ if tree.simple {+ props[2] = y as i32;+ let (pred, id) = tree.walk(&props);+ if pred == PRED_GRADIENT {+ gradient_row(&ch.data, w, y, id, out);+ continue;+ }+ }for x in 0..w {// The neighbours the decoder uses, with its rules for the edges.let left = if x > 0 {@@ -182,24 +194,27 @@ pub fn encode_gradient(ch: &Chan, pred: u8, id: u32, out: &mut Vec<Token>) {let (w, h) = (ch.w, ch.h);out.reserve(w * h);for y in 0..h {- let row = &ch.data[y * w..(y + 1) * w];- for x in 0..w {- let left = if x > 0 {- row[x - 1]- } else if y > 0 {- ch.data[(y - 1) * w]- } else {- 0- };- let (top, topleft) = if y > 0 {- let t = &ch.data[(y - 1) * w..y * w];- (t[x], if x > 0 { t[x - 1] } else { left })- } else {- (left, left)- };- let guess = clamped_gradient(left, top, topleft);- out.push(Token { ctx: id, val: pack_signed(row[x].wrapping_sub(guess)) });+ gradient_row(&ch.data, w, y, id, out);+ }+}++/// The tokens of row `y` of an image `w` wide, predicted by the clamped gradient, edges as the decoder takes them.+fn gradient_row(data: &[i32], w: usize, y: usize, id: u32, out: &mut Vec<Token>) {+ let row = &data[y * w..(y + 1) * w];+ if y == 0 {+ let mut left = 0;+ for &v in row {+ out.push(Token { ctx: id, val: pack_signed(v.wrapping_sub(left)) });+ left = v;}+ return;+ }+ let top = &data[(y - 1) * w..y * w];+ // first pixel: left and top-left are the pixel above+ out.push(Token { ctx: id, val: pack_signed(row[0].wrapping_sub(top[0])) });+ for x in 1..w {+ let guess = clamped_gradient(row[x - 1], top[x], top[x - 1]);+ out.push(Token { ctx: id, val: pack_signed(row[x].wrapping_sub(guess)) });}}diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rsindex d95a3c91..4d6d5283 100644--- a/crates/rf-jxl/src/vardct.rs+++ b/crates/rf-jxl/src/vardct.rs@@ -123,25 +123,34 @@ fn tables() -> &'static Tables {/// 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];+ // The basis functions are even or odd around the middle, so a pass needs sums and differences of mirrored inputs+ // and half the multiplications: m[k][7 - n] = (-1)^k m[k][n].// columns: t[ky][x] = sum_y m[ky][y] * src[y][x]+ let mut sum = [[0f32; 8]; 4];+ let mut dif = [[0f32; 8]; 4];+ for y in 0..4 {+ let (a, b) = (&src[y * stride..y * stride + 8], &src[(7 - y) * stride..(7 - y) * stride + 8]);+ for x in 0..8 {+ sum[y][x] = a[x] + b[x];+ dif[y][x] = a[x] - b[x];+ }+ }+ let mut t = [[0f32; 8]; 8];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];- }+ let v = if ky % 2 == 0 { &sum } else { &dif };+ for x in 0..8 {+ t[ky][x] = m[ky][0] * v[0][x] + m[ky][1] * v[1][x] + m[ky][2] * v[2][x] + m[ky][3] * v[3][x];}}+ // rowsfor ky in 0..8 {+ let r = &t[ky];+ let s = [r[0] + r[7], r[1] + r[6], r[2] + r[5], r[3] + r[4]];+ let d = [r[0] - r[7], r[1] - r[6], r[2] - r[5], r[3] - r[4]];for kx in 0..8 {- let mut s = 0.0;- for x in 0..8 {- s += t[ky * 8 + x] * m[kx][x];- }+ let v = if kx % 2 == 0 { &s } else { &d };// the decoder keeps the horizontal frequency as the row of its coefficient array- out[kx * 8 + ky] = s;+ out[kx * 8 + ky] = m[kx][0] * v[0] + m[kx][1] * v[1] + m[kx][2] * v[2] + m[kx][3] * v[3];}}}@@ -200,18 +209,38 @@ pub fn analyze(planes: &[Vec<f32>; 3], bw: usize, bh: usize, threads: usize) ->rows.into_iter().flatten().collect()}+/// Sums over a block's high frequencies of Y*Y, Y*X and Y*B (eight at a time, so the additions do not wait for each+/// other).+fn ac_sums(b: &[[f32; 64]; 3]) -> [f32; 3] {+ let mut acc = [[0f32; 8]; 3];+ for k in (8..64).step_by(8) {+ for l in 0..8 {+ let y = b[1][k + l];+ acc[0][l] += y * y;+ acc[1][l] += y * b[0][k + l];+ acc[2][l] += y * b[2][k + l];+ }+ }+ // the first eight, without the DC+ for l in 1..8 {+ let y = b[1][l];+ acc[0][l] += y * y;+ acc[1][l] += y * b[0][l];+ acc[2][l] += y * b[2][l];+ }+ [acc[0].iter().sum(), acc[1].iter().sum(), acc[2].iter().sum()]+}+/// The best factor of Y to take off X and B, as the decoder can store it: a least squares fit over all blocks of the/// high frequencies and of the low ones, [X high, B high, X low, B low].pub fn fit_cfl(co: &[[[f32; 64]; 3]]) -> [f32; 4] {let (mut yy, mut yx, mut yb) = (0f64, 0f64, 0f64);let (mut dyy, mut dyx, mut dyb) = (0f64, 0f64, 0f64);for b in co {- for k in 1..64 {- let y = b[1][k] as f64;- yy += y * y;- yx += y * b[0][k] as f64;- yb += y * b[2][k] as f64;- }+ let s = ac_sums(b);+ yy += s[0] as f64;+ yx += s[1] as f64;+ yb += s[2] as f64;let y = b[1][0] as f64;dyy += y * y;dyx += y * b[0][0] as f64;@@ -229,12 +258,9 @@ pub fn fit_cfl_tiles(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, base: [f32; 2]for by in 0..bh {for bx in 0..bw {let s = &mut sums[(by / 8) * tw + bx / 8];- let b = &co[by * bw + bx];- for k in 1..64 {- let y = b[1][k] as f64;- s[0] += y * y;- s[1] += y * b[0][k] as f64;- s[2] += y * b[2][k] as f64;+ let p = ac_sums(&co[by * bw + bx]);+ for i in 0..3 {+ s[i] += p[i] as f64;}}}@@ -273,16 +299,28 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tilelet 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 }+ let r = (a + (1.0 - q.round_offset)) as i32; // a is not negative: truncating is flooring+ if v < 0.0 { -r } else { r }};+ // where a quantized luma value lands again (the decoder's bias applied), for the small ones+ let y_lut: Vec<f32> = (0..256).map(|a| dequant_value(a, 1)).collect();let rows = crate::par::par_map(bh, threads, |by| {let mut dcs = vec![[0i32; 3]; bw];let mut acs = vec![[[0i16; 64]; 3]; bw];+ let (mut cur_rq, mut scaled_inv, mut scaled_step) = (0f32, [[0f32; 64]; 3], [[0f32; 64]; 3]);for bx in 0..bw {let bi = by * bw + bx;let co = &co[bi];let rq = quant[bi] as f32;+ if rq != cur_rq {+ cur_rq = rq;+ for c in 0..3 {+ for k in 0..64 {+ scaled_inv[c][k] = inv_step1[c][k] * rq;+ scaled_step[c][k] = step1[c][k] / rq;+ }+ }+ }// 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];@@ -292,18 +330,20 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile// high frequencieslet mut y_rec_ac = [0f32; 64];for k in 1..64 {- let qq = round(co[1][k] * inv_step1[1][k] * rq);+ let qq = round(co[1][k] * scaled_inv[1][k]);acs[bx][1][k] = qq.clamp(-32000, 32000) as i16;- y_rec_ac[k] = dequant_value(qq, 1) * step1[1][k] / rq;+ let a = qq.unsigned_abs() as usize;+ let dq = if a < 256 { y_lut[a] } else { dequant_value(a as i32, 1) };+ y_rec_ac[k] = if qq < 0 { -dq } else { dq } * scaled_step[1][k];}let tile = tile_cfl[(by / 8) * tw + bx / 8];let (cx, cb) = (q.cfl[0] + tile[0] as f32 / 84.0, q.cfl[1] + tile[1] as f32 / 84.0);for k in 1..64 {let rx = co[0][k] - y_rec_ac[k] * cx;- let qq = round(rx * inv_step1[0][k] * rq);+ let qq = round(rx * scaled_inv[0][k]);acs[bx][0][k] = qq.clamp(-32000, 32000) as i16;let rb = co[2][k] - y_rec_ac[k] * cb;- let qq = round(rb * inv_step1[2][k] * rq);+ let qq = round(rb * scaled_inv[2][k]);acs[bx][2][k] = qq.clamp(-32000, 32000) as i16;}}diff --git a/crates/rf-jxl/src/xyb.rs b/crates/rf-jxl/src/xyb.rsindex 1c93387b..34fb2a95 100644--- a/crates/rf-jxl/src/xyb.rs+++ b/crates/rf-jxl/src/xyb.rs@@ -53,9 +53,9 @@ fn tables() -> &'static Tables {})}-/// 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 {+/// Cube root to a relative error of about 1e-6: a guess from the exponent bits, then Newton steps. The reference the+/// table below is made with and tested against.+fn cbrt_newton(x: f32) -> f32 {let bits = x.to_bits();let mut y = f32::from_bits(bits / 3 + 0x2a51_4c00);// y = (2y + x / y^2) / 3@@ -64,6 +64,25 @@ fn cbrt_fast(x: f32) -> f32 {y = (2.0 * y + x / (y * y)) * (1.0 / 3.0);y}++/// The cube root table: 256 steps per power of two from 2^-9 up to 2^3, read with linear interpolation.+const CBRT_BASE: u32 = 0x3b00_0000; // 2^-9+const CBRT_STEPS: usize = 12 * 256;++fn cbrt_table() -> &'static [f32] {+ static T: OnceLock<Vec<f32>> = OnceLock::new();+ T.get_or_init(|| (0..=CBRT_STEPS + 1).map(|i| cbrt_newton(f32::from_bits(CBRT_BASE + ((i as u32) << 15)))).collect())+}++/// Cube root for 2^-9 <= x < 2^3 (inputs here are never below the 0.0038 bias), to about 1e-6.+#[inline(always)]+fn cbrt_fast(t: &[f32], x: f32) -> f32 {+ let d = x.to_bits().wrapping_sub(CBRT_BASE);+ let i = ((d >> 15) as usize).min(CBRT_STEPS - 1);+ let frac = (d & 0x7fff) as f32 * (1.0 / 32768.0);+ let a = t[i];+ a + (t[i + 1] - a) * frac+}/// Rows `y0..y1` of the picture in XYB, `pw` floats per row, the columns past `w` repeating the last pixel.fn convert_rows(rgba: &[u8], w: usize, pw: usize, y0: usize, y1: usize) -> [Vec<f32>; 3] {let t = tables();@@ -71,6 +90,7 @@ fn convert_rows(rgba: &[u8], w: usize, pw: usize, y0: usize, y1: usize) -> [Vec<let mut planes = [vec![0f32; n], vec![0f32; n], vec![0f32; n]];let [m0, m1, m2, m3, m4, m5, m6, m7, m8] = t.mat;let off = t.bias_cbrt.abs();+ let ct = cbrt_table();for y in y0..y1 {let src = &rgba[y * w * 4..(y + 1) * w * 4];let base = (y - y0) * pw;@@ -80,9 +100,9 @@ fn convert_rows(rgba: &[u8], w: usize, pw: usize, y0: usize, y1: usize) -> [Vec<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 lc = cbrt_fast(m0 * r + m1 * g + m2 * b + BIAS) - off;- let mc = cbrt_fast(m3 * r + m4 * g + m5 * b + BIAS) - off;- let sc = cbrt_fast(m6 * r + m7 * g + m8 * b + BIAS) - off;+ let lc = cbrt_fast(ct, m0 * r + m1 * g + m2 * b + BIAS) - off;+ let mc = cbrt_fast(ct, m3 * r + m4 * g + m5 * b + BIAS) - off;+ let sc = cbrt_fast(ct, m6 * r + m7 * g + m8 * b + BIAS) - off;px[x] = (lc - mc) * 0.5;py[x] = (lc + mc) * 0.5;pb[x] = sc;@@ -125,7 +145,7 @@ mod tests {fn the_cube_root_is_close_enough() {for i in 0..2000 {let x = 0.0035 + i as f32 * 0.0006;- let (a, b) = (cbrt_fast(x), x.cbrt());+ let (a, b) = (cbrt_fast(cbrt_table(), x), x.cbrt());assert!((a - b).abs() < 2e-6, "{x}: {a} against {b}");}}