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: errors instead of panics, any size, threads
gelenmedya18e438aa0026
diff --git a/crates/rf-jxl/src/ans.rs b/crates/rf-jxl/src/ans.rsindex cbd06adc..22cd09ba 100644--- a/crates/rf-jxl/src/ans.rs+++ b/crates/rf-jxl/src/ans.rs@@ -510,17 +510,6 @@ impl Codes {}}}-- /// 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 ----------------------------------------------------------------------------------------------diff --git a/crates/rf-jxl/src/lib.rs b/crates/rf-jxl/src/lib.rsindex 614e6609..fcf97ebf 100644--- a/crates/rf-jxl/src/lib.rs+++ b/crates/rf-jxl/src/lib.rs@@ -9,14 +9,18 @@mod ans;mod bits;mod modular;+mod par;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;+/// The biggest picture side the format can say.+pub const MAX_SIDE: u32 = 1 << 30;++/// Blocks per low-frequency group side (2048 pixels).+const LF_BLOCKS: usize = 256;/// The decoder's default parameters of its edge-preserving filter's strength: the factor on the quantization step, the/// scale of the first and the last pass, the border weight.@@ -57,6 +61,9 @@ pub struct Tuning {pub cfl: bool,/// And per 64x64 pixel tile.pub cfl_tiles: bool,+ /// Threads to encode with: 0 picks one for small pictures and all cores for big ones. The output is the same bytes+ /// whatever the number.+ pub threads: usize,}impl Tuning {@@ -86,6 +93,7 @@ impl Tuning {band_delta: [[0.0; 6]; 3],cfl: true,cfl_tiles: true,+ threads: 0,}}@@ -108,6 +116,7 @@ impl Tuning {"bqm" => self.b_qm_scale = v as u32,"cfl" => self.cfl = v > 0.0,"tiles" => self.cfl_tiles = v > 0.0,+ "threads" => self.threads = v as usize,"dcx" => self.dc_scale[0] = v,"dcy" => self.dc_scale[1] = v,"dcb" => self.dc_scale[2] = v,@@ -131,24 +140,62 @@ impl Tuning {}}+/// Why a picture could not be encoded.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Error {+ /// A side of zero pixels.+ EmptyPicture,+ /// The buffer holds fewer than `width * height * 4` bytes.+ BufferTooShort { needed: usize, got: usize },+ /// A side beyond what the format can say (2^30), or a picture that does not fit in memory.+ TooLarge,+}++impl std::fmt::Display for Error {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Error::EmptyPicture => write!(f, "the picture has no pixels"),+ Error::BufferTooShort { needed, got } => write!(f, "the pixel buffer holds {got} bytes, {needed} are needed"),+ Error::TooLarge => write!(f, "the picture is too big for JPEG XL"),+ }+ }+}++impl std::error::Error for Error {}+/// 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". Alpha is kept exactly.-///-/// 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> {+/// XL codestream. `quality` is 0..=100 like libjxl's, about 90 being "visually lossless" (81 is about as good as JPEG+/// quality 85). Alpha is kept exactly. Big pictures use all the cores; see `Tuning::threads`.+pub fn encode(width: u32, height: u32, rgba: &[u8], has_alpha: bool, quality: f32) -> Result<Vec<u8>, Error> {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");+pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuning: &Tuning) -> Result<Vec<u8>, Error> {+ if width == 0 || height == 0 {+ return Err(Error::EmptyPicture);+ }+ if width > MAX_SIDE || height > MAX_SIDE {+ return Err(Error::TooLarge);+ }let (w, h) = (width as usize, height as usize);- assert!(rgba.len() >= w * h * 4, "pixel buffer too short");+ let needed = w.checked_mul(h).and_then(|p| p.checked_mul(4)).ok_or(Error::TooLarge)?;+ if rgba.len() < needed {+ return Err(Error::BufferTooShort { needed, got: rgba.len() });+ }+ let threads = par::thread_count(tuning.threads, w * h);+ let started = std::time::Instant::now();+ let lap =|what: &str| {+ if tuning.verbose {+ eprintln!(" {what:<12} {:>8.3} ms", started.elapsed().as_secs_f64() * 1000.0);+ }+ };let (bw, bh) = (w.div_ceil(8), h.div_ceil(8));let planes = if has_alpha {- xyb::to_xyb(&fill_transparent(rgba, w, h), w, h, bw * 8, bh * 8)+ xyb::to_xyb(&fill_transparent(rgba, w, h), w, h, bw * 8, bh * 8, threads)} else {- xyb::to_xyb(rgba, w, h, bw * 8, bh * 8)+ xyb::to_xyb(rgba, w, h, bw * 8, bh * 8, threads)};+ lap("colour");// Quantization: blocks get a quant around 16, the global scale makes up the strength.let strength = tuning.strength / tuning.distance.max(0.01);@@ -179,7 +226,9 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin})});let weight = vardct::dct8_weights(&if custom_bands { bands } else { vardct::DCT8_BANDS });- let coefs = vardct::analyze(&planes, bw, bh);+ let coefs = vardct::analyze(&planes, bw, bh, threads);+ drop(planes);+ lap("dct");// How much of Y the decoder adds back to X and B: the format's defaults (nothing, all) or a fit to this picture,// in the form the header stores it (two 16-bit floats and, for the low frequencies, an offset in 84ths).let fit = if tuning.cfl { vardct::fit_cfl(&coefs) } else { [0.0, 1.0, 0.0, 1.0] };@@ -202,18 +251,26 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninlet quant_map = vec![raw_quant as u16; bw * bh];let tiles = (bw.div_ceil(8), bh.div_ceil(8));let tile_cfl = if tuning.cfl_tiles { vardct::fit_cfl_tiles(&coefs, bw, bh, [cfl[0], cfl[1]]) } else { vec![[0, 0]; tiles.0 * tiles.1] };- let blocks = vardct::quantize(&coefs, bw, bh, &quant_map, &tile_cfl, &q);+ let blocks = vardct::quantize(&coefs, bw, bh, &quant_map, &tile_cfl, &q, threads);+ drop(coefs);+ lap("quantize");+ // Low-frequency groups (256 x 256 blocks = 2048 pixels) and groups (32 x 32 blocks = 256 pixels).+ let (lfw, lfh) = (bw.div_ceil(LF_BLOCKS), bh.div_ceil(LF_BLOCKS));+ let n_lf = lfw * lfh;+ let (gw, gh) = (w.div_ceil(GROUP), h.div_ceil(GROUP));+ let n_groups = gw * gh;// The streams of modular data share one tree. Which leaf a value uses depends on the stream (the tree's second- // property: 0 the global one, 1 the low-frequency image, 3 the block metadata, 21 and up the groups' own) and- // the channel in it (the first property).+ // property: 0 the global one, 1.. the low-frequency groups', then the block metadata's from 2n + 1, and the groups'+ // own alpha from 3n + 18) and the channel in it (the first property).+ let n = n_lf as i32;let tree = Tree::new(T::Split(1,- 20,+ 3 * n + 17,grad(), // alpha of a groupBox::new(T::Split(1,- 2,+ 2 * n,// the block metadata: channels ytox, ytob, (type, quant), epfBox::new(T::Split(0,@@ -230,57 +287,84 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin)),)),));- 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 meta = [- Chan { w: tiles.0, h: tiles.1, data: tile_cfl.iter().map(|t| t[0]).collect() },- Chan { w: tiles.0, h: tiles.1, data: tile_cfl.iter().map(|t| t[1]).collect() },- Chan { w: nblocks, h: 2, data: (0..nblocks * 2).map(|i| if i < nblocks { 0 } else { blocks.quant[i - nblocks] 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 lf_rect = |lg: usize| {+ let (x0, y0) = (lg % lfw * LF_BLOCKS, lg / lfw * LF_BLOCKS);+ (x0, y0, (x0 + LF_BLOCKS).min(bw), (y0 + LF_BLOCKS).min(bh))+ };+ // per low-frequency group: the tokens of its low-frequency image and of its block metadata+ let lf_tokens: Vec<(Vec<ans::Token>, Vec<ans::Token>)> = par::par_map(n_lf, threads, |lg| {+ let (x0, y0, x1, y1) = lf_rect(lg);+ let mut dc_tokens = Vec::new();+ modular::encode_channels(&vardct::dc_channels(&blocks, x0, y0, x1, y1), 1 + lg as u32, &tree, &mut dc_tokens);+ let (lw, lh) = (x1 - x0, y1 - y0);+ let nb = lw * lh;+ let (tw, th) = (lw.div_ceil(8), lh.div_ceil(8));+ let mut tile = [Vec::with_capacity(tw * th), Vec::with_capacity(tw * th)];+ for ty in 0..th {+ for tx in 0..tw {+ let t = tile_cfl[(y0 / 8 + ty) * tiles.0 + x0 / 8 + tx];+ tile[0].push(t[0]);+ tile[1].push(t[1]);+ }+ }+ let [t0, t1] = tile;+ let mut qdata = vec![0i32; nb];+ qdata.reserve(nb);+ for y in y0..y1 {+ qdata.extend(blocks.quant[y * bw + x0..y * bw + x1].iter().map(|&v| v as i32 - 1));+ }+ let meta = [+ Chan { w: tw, h: th, data: t0 },+ Chan { w: tw, h: th, data: t1 },+ Chan { w: nb, h: 2, data: qdata },+ Chan { w: lw, h: lh, data: vec![tuning.epf_sharpness as i32; nb] },+ ];+ let mut meta_tokens = Vec::new();+ modular::encode_channels(&meta, 1 + 2 * n_lf as u32 + lg as u32, &tree, &mut meta_tokens);+ (dc_tokens, meta_tokens)+ });- let (gw, gh) = (w.div_ceil(GROUP), h.div_ceil(GROUP));// The alpha channel: in the global section when it is one group big, else in a stream of each group.let mut alpha_global: Vec<ans::Token> = Vec::new();let mut alpha_groups: Vec<Vec<ans::Token>> = Vec::new();if has_alpha {- let alpha: Vec<i32> = rgba.chunks_exact(4).take(w * h).map(|p| p[3] as i32).collect();- if gw * gh == 1 {+ if n_groups == 1 {+ let alpha: Vec<i32> = rgba.chunks_exact(4).take(w * h).map(|p| p[3] as i32).collect();let (pred, id) = tree.leaf_of(0, 0);modular::encode_gradient(&Chan { w, h, data: alpha }, pred, id, &mut alpha_global);} else {- for g in 0..gw * gh {+ alpha_groups = par::par_map(n_groups, threads, |g| {let (x0, y0) = (g % gw * GROUP, g / gw * GROUP);let (x1, y1) = ((x0 + GROUP).min(w), (y0 + GROUP).min(h));let mut data = Vec::with_capacity((x1 - x0) * (y1 - y0));for y in y0..y1 {- data.extend_from_slice(&alpha[y * w + x0..y * w + x1]);+ data.extend(rgba[(y * w + x0) * 4..(y * w + x1) * 4].chunks_exact(4).map(|p| p[3] as i32));}- let (pred, id) = tree.leaf_of(21 + g as u32, 0);+ let (pred, id) = tree.leaf_of(3 * n_lf as u32 + 18 + g as u32, 0);let mut t = Vec::new();modular::encode_gradient(&Chan { w: x1 - x0, h: y1 - y0, data }, pred, id, &mut t);- alpha_groups.push(t);- }+ t+ });}}- let mut leaf_streams: Vec<&[ans::Token]> = vec![&dc_tokens, &meta_tokens, &alpha_global];+ let mut leaf_streams: Vec<&[ans::Token]> = vec![&alpha_global];+ for (a, b) in &lf_tokens {+ leaf_streams.push(a);+ leaf_streams.push(b);+ }leaf_streams.extend(alpha_groups.iter().map(|t| t.as_slice()));let leaf_codes = ans::build_codes(tree.num_leaves, &leaf_streams);+ lap("lf+alpha");// The coefficients of each group.- let (bgw, bgh) = (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..bgh {- for gx in 0..bgw {- let mut t = Vec::new();- vardct::group_tokens(&blocks, gx, gy, &mut t);- group_tokens.push(t);- }- }+ let group_tokens: Vec<Vec<ans::Token>> = par::par_map(n_groups, threads, |g| {+ let mut t = Vec::new();+ vardct::group_tokens(&blocks, g % gw, g / gw, &mut t);+ t+ });+ lap("tokens");let ac_codes = ans::build_codes(vardct::NUM_AC_CONTEXTS, &group_tokens.iter().map(|t| t.as_slice()).collect::<Vec<_>>());+ lap("clusters");// --- the sectionslet mut lf_global = BitWriter::new();@@ -316,7 +400,7 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninif has_alpha {// the global modular stream: its header, and the alpha channel when it is small enough to be in itmodular::write_stream_header(&mut lf_global);- if gw * gh == 1 {+ if n_groups == 1 {leaf_codes.write_stream(&mut lf_global, &alpha_global);} else {// Nothing of the channels is in this section. jxl-rs (like libjxl) reads nothing more; jxl-oxide starts@@ -326,11 +410,16 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin}}- 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 lf_groups: Vec<BitWriter> = par::par_map(n_lf, threads, |lg| {+ let (x0, y0, x1, y1) = lf_rect(lg);+ let nb = (x1 - x0) * (y1 - y0);+ let mut b = BitWriter::new();+ b.put(0, 2); // extra precision+ modular::write_stream(&mut b, &leaf_codes, &lf_tokens[lg].0);+ b.put((nb - 1) as u64, ceil_log2(nb));+ modular::write_stream(&mut b, &leaf_codes, &lf_tokens[lg].1);+ b+ });let mut hf_global = BitWriter::new();if custom_bands {@@ -348,40 +437,25 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin} else {hf_global.put(1, 1); // default dequantization matrices}- hf_global.put(0, ceil_log2(gw * gh)); // one set of histograms+ hf_global.put(0, ceil_log2(n_groups)); // one set of histogramshf_global.put(2, 2); // the coefficient order is the natural oneac_codes.write_header(&mut hf_global);- // Groups of the coefficients (32 blocks = 256 pixels) are the groups of the file.- debug_assert_eq!((bgw, bgh), (gw, gh));- let hf_groups: Vec<BitWriter> = group_tokens- .iter()- .enumerate()- .map(|(g, t)| {- let mut b = BitWriter::new();- ac_codes.write_stream(&mut b, t);- if has_alpha && gw * gh > 1 {- modular::write_stream(&mut b, &leaf_codes, &alpha_groups[g]);- }- b- })- .collect();+ let hf_groups: Vec<BitWriter> = par::par_map(n_groups, threads, |g| {+ let mut b = BitWriter::new();+ ac_codes.write_stream(&mut b, &group_tokens[g]);+ if has_alpha && n_groups > 1 {+ modular::write_stream(&mut b, &leaf_codes, &alpha_groups[g]);+ }+ b+ });+ lap("streams");if tuning.verbose {- let per = dc_tokens.len() / 3;eprintln!(- "dc bytes Y {:.0} X {:.0} B {:.0}; meta {:.0}",- leaf_codes.estimate_bits(&dc_tokens[..per]) / 8.0,- leaf_codes.estimate_bits(&dc_tokens[per..2 * per]) / 8.0,- leaf_codes.estimate_bits(&dc_tokens[2 * per..]) / 8.0,- leaf_codes.estimate_bits(&meta_tokens) / 8.0- );- eprintln!(- "lf_global {} B (tree+leaf hist), lf_group {} B (dc {} tokens, meta {}), hf_global {} B, ac {} B in {} tokens",+ "lf_global {} B, lf groups {} B, hf_global {} B, ac {} B in {} tokens",lf_global.bit_len() / 8,- lf_group.bit_len() / 8,- dc_tokens.len(),- meta_tokens.len(),+ lf_groups.iter().map(|g| g.bit_len() / 8).sum::<usize>(),hf_global.bit_len() / 8,hf_groups.iter().map(|g| g.bit_len() / 8).sum::<usize>(),group_tokens.iter().map(|g| g.len()).sum::<usize>()@@ -459,15 +533,17 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninout.put(0, 1); // not permutedout.align();let mut sections: Vec<Vec<u8>> = Vec::new();- if gw * gh == 1 {+ if n_lf == 1 && n_groups == 1 {let mut all = lf_global;- all.append(&lf_group);+ all.append(&lf_groups[0]);all.append(&hf_global);all.append(&hf_groups[0]);sections.push(all.finish());} else {sections.push(lf_global.finish());- sections.push(lf_group.finish());+ for g in lf_groups {+ sections.push(g.finish());+ }sections.push(hf_global.finish());for g in hf_groups {sections.push(g.finish());@@ -482,10 +558,12 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin}out.align();let mut bytes = out.finish();+ bytes.reserve(sections.iter().map(|s| s.len()).sum());for s in sections {bytes.extend_from_slice(&s);}- bytes+ lap("done");+ Ok(bytes)}fn grad() -> Box<T> {diff --git a/crates/rf-jxl/src/par.rs b/crates/rf-jxl/src/par.rsnew file mode 100644index 00000000..dd108cf1--- /dev/null+++ b/crates/rf-jxl/src/par.rs@@ -0,0 +1,46 @@+//! A small parallel map over `0..n` with scoped threads. The results come back in order, so the output does not depend+//! on how many threads there were.++use std::sync::atomic::{AtomicUsize, Ordering};++pub fn par_map<T: Send>(n: usize, threads: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {+ let threads = threads.min(n);+ if threads <= 1 {+ return (0..n).map(f).collect();+ }+ let next = AtomicUsize::new(0);+ let parts: Vec<Vec<(usize, T)>> = std::thread::scope(|s| {+ let handles: Vec<_> = (0..threads)+ .map(|_| {+ s.spawn(|| {+ let mut mine = Vec::new();+ loop {+ let i = next.fetch_add(1, Ordering::Relaxed);+ if i >= n {+ break;+ }+ mine.push((i, f(i)));+ }+ mine+ })+ })+ .collect();+ handles.into_iter().map(|h| h.join().expect("an encoder thread panicked")).collect()+ });+ let mut out: Vec<Option<T>> = (0..n).map(|_| None).collect();+ for (i, v) in parts.into_iter().flatten() {+ out[i] = Some(v);+ }+ out.into_iter().map(|v| v.unwrap()).collect()+}++/// How many threads to use for a picture: what was asked for, or (0) all of them for big pictures and one for small.+pub fn thread_count(asked: usize, pixels: usize) -> usize {+ if asked > 0 {+ asked+ } else if pixels < 400_000 {+ 1+ } else {+ std::thread::available_parallelism().map_or(1, |n| n.get())+ }+}diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rsindex f3fcd02c..d95a3c91 100644--- a/crates/rf-jxl/src/vardct.rs+++ b/crates/rf-jxl/src/vardct.rs@@ -185,18 +185,19 @@ fn dequant_value(q: i32, c: usize) -> f32 {}/// The DCT of every block, X, Y, B. `planes` have `bw * 8` columns.-pub fn analyze(planes: &[Vec<f32>; 3], bw: usize, bh: usize) -> Vec<[[f32; 64]; 3]> {+pub fn analyze(planes: &[Vec<f32>; 3], bw: usize, bh: usize, threads: usize) -> Vec<[[f32; 64]; 3]> {let t = tables();let stride = bw * 8;- let mut out = vec![[[0f32; 64]; 3]; bw * bh];- for by in 0..bh {- for bx in 0..bw {+ let rows = crate::par::par_map(bh, threads, |by| {+ let mut row = vec![[[0f32; 64]; 3]; bw];+ for (bx, blk) in row.iter_mut().enumerate() {for c in 0..3 {- dct8x8(&t.dct, &planes[c][by * 8 * stride + bx * 8..], stride, &mut out[by * bw + bx][c]);+ dct8x8(&t.dct, &planes[c][by * 8 * stride + bx * 8..], stride, &mut blk[c]);}}- }- out+ row+ });+ rows.into_iter().flatten().collect()}/// 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@@ -249,7 +250,7 @@ pub fn fit_cfl_tiles(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, base: [f32; 2]}/// Quantization of all blocks, `quant` the quant of each.-pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile_cfl: &[[i32; 2]], q: &Quant) -> Blocks {+pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile_cfl: &[[i32; 2]], q: &Quant, threads: usize) -> Blocks {let tw = bw.div_ceil(8);let dm = [(1.0f32 / 1.25).powf(q.x_qm_scale as f32 - 2.0),@@ -270,14 +271,16 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tilelet inv_quant_lf = 65536.0 / (q.global_scale as f32 * q.quant_lf as f32);let lf_fac = [q.lf_quant[0] * inv_quant_lf, q.lf_quant[1] * inv_quant_lf, q.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 bi in 0..bw * bh {+ let rows = crate::par::par_map(bh, threads, |by| {+ let mut dcs = vec![[0i32; 3]; bw];+ let mut acs = vec![[[0i16; 64]; 3]; bw];+ for bx in 0..bw {+ let bi = by * bw + bx;let co = &co[bi];let rq = quant[bi] as f32;// low frequencies: Y first, X and B are coded relative to it (X not at all by default, B by 1.0)@@ -285,34 +288,54 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tilelet y_rec = qy as f32 * lf_fac[1];let qx = ((co[0][0] - y_rec * q.cfl[2]) / lf_fac[0]).round() as i32;let qb = ((co[2][0] - y_rec * q.cfl[3]) / lf_fac[2]).round() as i32;- dc[0][bi] = qy;- dc[1][bi] = qx;- dc[2][bi] = qb;+ dcs[bx] = [qy, qx, qb];// high frequencieslet mut y_rec_ac = [0f32; 64];for k in 1..64 {let qq = round(co[1][k] * inv_step1[1][k] * rq);- ac[bi][1][k] = qq.clamp(-32000, 32000) as i16;+ acs[bx][1][k] = qq.clamp(-32000, 32000) as i16;y_rec_ac[k] = dequant_value(qq, 1) * step1[1][k] / rq;}- let tile = tile_cfl[(bi / bw / 8) * tw + (bi % bw) / 8];+ 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);- ac[bi][0][k] = qq.clamp(-32000, 32000) as i16;+ 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);- ac[bi][2][k] = qq.clamp(-32000, 32000) as i16;+ acs[bx][2][k] = qq.clamp(-32000, 32000) as i16;}+ }+ (dcs, acs)+ });+ let mut dc = [Vec::with_capacity(bw * bh), Vec::with_capacity(bw * bh), Vec::with_capacity(bw * bh)];+ let mut ac = Vec::with_capacity(bw * bh);+ for (d, a) in rows {+ for v in d {+ for c in 0..3 {+ dc[c].push(v[c]);+ }+ }+ ac.extend(a);}Blocks { bw, bh, dc, ac, quant: quant.to_vec() }}/// 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()+/// Only the blocks `x0..x1` by `y0..y1` (a low-frequency group).+pub fn dc_channels(b: &Blocks, x0: usize, y0: usize, x1: usize, y1: usize) -> Vec<Chan> {+ b.dc+ .iter()+ .map(|d| {+ let mut data = Vec::with_capacity((x1 - x0) * (y1 - y0));+ for y in y0..y1 {+ data.extend_from_slice(&d[y * b.bw + x0..y * b.bw + x1]);+ }+ Chan { w: x1 - x0, h: y1 - y0, data }+ })+ .collect()}fn nonzero_bucket(n: usize) -> usize {diff --git a/crates/rf-jxl/src/xyb.rs b/crates/rf-jxl/src/xyb.rsindex bcd6c3dd..1c93387b 100644--- a/crates/rf-jxl/src/xyb.rs+++ b/crates/rf-jxl/src/xyb.rs@@ -64,45 +64,59 @@ fn cbrt_fast(x: f32) -> f32 {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] {+/// 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();- let mut planes = [vec![0f32; pw * ph], vec![0f32; pw * ph], vec![0f32; pw * ph]];+ let n = (y1 - y0) * pw;+ let mut planes = [vec![0f32; n], vec![0f32; n], vec![0f32; n]];let [m0, m1, m2, m3, m4, m5, m6, m7, m8] = t.mat;- for y in 0..h {+ let off = t.bias_cbrt.abs();+ for y in y0..y1 {let src = &rgba[y * w * 4..(y + 1) * w * 4];+ let base = (y - y0) * pw;+ let [px, py, pb] = &mut planes;+ let (px, py, pb) = (&mut px[base..base + pw], &mut py[base..base + pw], &mut pb[base..base + pw]);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;+ 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;+ px[x] = (lc - mc) * 0.5;+ py[x] = (lc + mc) * 0.5;+ pb[x] = sc;}- // repeat the last pixel to the rightfor x in w..pw {- for p in planes.iter_mut() {- p[y * pw + x] = p[y * pw + w - 1];- }+ px[x] = px[w - 1];+ py[x] = py[w - 1];+ pb[x] = pb[w - 1];}}- for y in h..ph {- for p in planes.iter_mut() {+ planes+}++/// The picture as three planes (X, Y, B), `pw` 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, threads: usize) -> [Vec<f32>; 3] {+ const BAND: usize = 32;+ let bands = crate::par::par_map(h.div_ceil(BAND), threads, |i| convert_rows(rgba, w, pw, i * BAND, ((i + 1) * BAND).min(h)));+ let mut planes = [Vec::with_capacity(pw * ph), Vec::with_capacity(pw * ph), Vec::with_capacity(pw * ph)];+ for b in bands {+ for (p, part) in planes.iter_mut().zip(b) {+ p.extend_from_slice(&part);+ }+ }+ for p in planes.iter_mut() {+ p.resize(pw * ph, 0.0);+ for y in h..ph {p.copy_within((h - 1) * pw..h * pw, y * pw);}}planes}+#[cfg(test)]mod tests {use super::*;@@ -120,7 +134,7 @@ mod tests {fn grey_has_no_colour_in_it() {// a grey pixel has equal cone responses: X is zero, B follows Ylet px = [128u8, 128, 128, 255];- let p = to_xyb(&px, 1, 1, 8, 8);+ let p = to_xyb(&px, 1, 1, 8, 8, 1);assert!(p[0][0].abs() < 1e-4, "X {}", p[0][0]);assert!((p[1][0] - p[2][0]).abs() < 1e-3, "Y {} B {}", p[1][0], p[2][0]);// and the padding repeats the pixeldiff --git a/crates/rf-jxl/tests/roundtrip.rs b/crates/rf-jxl/tests/roundtrip.rsindex 84a4e10a..ac5e2e14 100644--- a/crates/rf-jxl/tests/roundtrip.rs+++ b/crates/rf-jxl/tests/roundtrip.rs@@ -97,7 +97,7 @@ fn score(w: u32, h: u32, a_rgba: &[u8], b_rgb: &[u8]) -> f64 {}fn check(name: &str, w: u32, h: u32, px: &[u8], quality: f32, min: f64) {- let bytes = rf_jxl::encode(w, h, px, false, quality);+ let bytes = rf_jxl::encode(w, h, px, false, quality).unwrap();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}");@@ -141,7 +141,7 @@ fn the_ends_of_the_quality_scale() {check("quality 50", 128, 96, &px, 50.0, 40.0);check("quality 0", 128, 96, &px, 0.0, -50.0);// smaller files for lower qualities- let sizes: Vec<usize> = [100.0, 90.0, 70.0, 40.0, 10.0].iter().map(|&q| rf_jxl::encode(128, 96, &px, false, q).len()).collect();+ let sizes: Vec<usize> = [100.0, 90.0, 70.0, 40.0, 10.0].iter().map(|&q| rf_jxl::encode(128, 96, &px, false, q).unwrap().len()).collect();assert!(sizes.windows(2).all(|w| w[0] > w[1]), "{sizes:?}");}@@ -152,7 +152,7 @@ fn stripes_keep_their_direction() {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 bytes = rf_jxl::encode(w, h, &vertical, false, 90.0).unwrap();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<_>>());@@ -179,7 +179,7 @@ fn with_alpha(w: u32, h: u32) -> Vec<u8> {fn check_alpha(w: u32, h: u32) {let px = with_alpha(w, h);- let bytes = rf_jxl::encode(w, h, &px, true, 90.0);+ let bytes = rf_jxl::encode(w, h, &px, true, 90.0).unwrap();let d = jxl_image_rs_integration::JxlDecoder::new(Cursor::new(&bytes)).expect("jxl-rs reads the file");let rs_ok = image::DynamicImage::from_decoder(d).map(|i| i.to_rgba8().into_raw());eprintln!("jxl-rs on {w}x{h}: {}", if rs_ok.is_ok() { "ok".to_string() } else { format!("{:?}", rs_ok.as_ref().err()) });@@ -218,6 +218,69 @@ fn alpha_is_exact() {check_alpha(1, 1);}+/// For big pictures, where SSIMULACRA2 would take too long: both decoders must give the size and colours close to the+/// original (mean absolute error), and all threads give the very same bytes.+fn check_big(w: u32, h: u32, alpha: bool) {+ let px = if alpha { with_alpha(w, h) } else { synthetic(w, h, 9) };+ let tuned = |threads| {+ let mut t = rf_jxl::Tuning::from_quality(85.0);+ t.threads = threads;+ t+ };+ let one = rf_jxl::encode_tuned(w, h, &px, alpha, &tuned(1)).unwrap();+ let many = rf_jxl::encode_tuned(w, h, &px, alpha, &tuned(4)).unwrap();+ assert!(one == many, "{w}x{h}: one thread and four give different bytes");+ let rs = {+ let d = jxl_image_rs_integration::JxlDecoder::new(Cursor::new(&one)).expect("jxl-rs reads the file");+ image::DynamicImage::from_decoder(d).expect("jxl-rs decodes the picture").to_rgba8().into_raw()+ };+ let (ow, oh, ox) = decode_oxide(&one);+ assert_eq!((ow, oh), (w, h));+ for (who, a, stride) in [("jxl-rs", &rs, 4usize), ("jxl-oxide", &ox, 3usize)] {+ let (mut sum, mut n) = (0u64, 0u64);+ for (p, q) in px.chunks_exact(4).zip(a.chunks_exact(stride)) {+ if alpha {+ if stride == 4 {+ assert_eq!(p[3], q[3], "{who}: alpha must be exact");+ }+ if p[3] != 255 {+ continue;+ }+ }+ for i in 0..3 {+ sum += (p[i] as i32 - q[i] as i32).unsigned_abs() as u64;+ n += 1;+ }+ }+ let mean = sum as f64 / n.max(1) as f64;+ eprintln!("big {w}x{h} alpha {alpha}: {} bytes, {who} mean error {mean:.2}", one.len());+ assert!(mean < 6.0, "{who}: mean error {mean}");+ }+}++#[test]+fn just_over_one_low_frequency_group() {+ check_big(2049, 40, false);+ check_big(40, 2049, false);+ check_big(2100, 300, true);+}++#[test]+fn errors_instead_of_panics() {+ use rf_jxl::Error;+ assert_eq!(rf_jxl::encode(0, 5, &[], false, 80.0), Err(Error::EmptyPicture));+ assert_eq!(rf_jxl::encode(4, 4, &[0; 10], false, 80.0), Err(Error::BufferTooShort { needed: 64, got: 10 }));+ assert_eq!(rf_jxl::encode(u32::MAX, 4, &[], false, 80.0), Err(Error::TooLarge));+}++#[test]+#[ignore = "big: cargo test --release -p rf-jxl -- --ignored"]+fn very_big_pictures() {+ check_big(4096, 3072, false);+ check_big(5001, 2049, false);+ check_big(4200, 2300, true);+}+#[test]fn bigger_than_a_group() {check("synthetic", 600, 400, &synthetic(600, 400, 4), 90.0, 70.0);