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: 16x16 blocks in quiet areas, skip the decoder's LF smoothing

gelenmedya33aafcbac8ed
diff --git a/crates/rf-jxl/src/lib.rs b/crates/rf-jxl/src/lib.rs
index fcf97ebf..1f040be0 100644
--- a/crates/rf-jxl/src/lib.rs
+++ b/crates/rf-jxl/src/lib.rs
@@ -64,6 +64,16 @@ pub struct Tuning {
/// 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,
+ /// Use 16x16 blocks where the picture is smooth: when the four 8x8 blocks have at most `big_max_nonzero` nonzero
+ /// coefficients, and the big block costs less than the small ones (its price times `big_bias`).
+ pub big_blocks: bool,
+ pub big_max_nonzero: usize,
+ pub big_bias: f32,
+ /// Smaller pictures than this many pixels keep to 8x8 blocks: they are too detailed for 16x16 ones to pay, and
+ /// finding out costs time.
+ pub big_min_pixels: usize,
+ /// Tell the decoder not to smooth the low-frequency image.
+ pub skip_lf_smoothing: bool,
}
impl Tuning {
@@ -94,6 +104,11 @@ impl Tuning {
cfl: true,
cfl_tiles: true,
threads: 0,
+ big_blocks: true,
+ big_max_nonzero: 120,
+ big_bias: 0.9,
+ big_min_pixels: 300_000,
+ skip_lf_smoothing: true,
}
}
@@ -117,6 +132,11 @@ impl Tuning {
"cfl" => self.cfl = v > 0.0,
"tiles" => self.cfl_tiles = v > 0.0,
"threads" => self.threads = v as usize,
+ "big" => self.big_blocks = v > 0.0,
+ "bigmax" => self.big_max_nonzero = v as usize,
+ "bigbias" => self.big_bias = v,
+ "bigmin" => self.big_min_pixels = v as usize,
+ "lfsmooth" => self.skip_lf_smoothing = v == 0.0,
"dcx" => self.dc_scale[0] = v,
"dcy" => self.dc_scale[1] = v,
"dcb" => self.dc_scale[2] = v,
@@ -227,7 +247,6 @@ 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, 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).
@@ -251,8 +270,9 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
let 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, threads);
- drop(coefs);
+ let big = (tuning.big_blocks && w * h >= tuning.big_min_pixels).then_some(vardct::BigParams { max_nonzero: tuning.big_max_nonzero, bias: tuning.big_bias });
+ let blocks = vardct::quantize(&planes, &coefs, bw, bh, &quant_map, &tile_cfl, &q, big.as_ref(), threads);
+ drop((planes, coefs));
lap("quantize");
// Low-frequency groups (256 x 256 blocks = 2048 pixels) and groups (32 x 32 blocks = 256 pixels).
@@ -292,7 +312,7 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
(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 lf_tokens: Vec<(Vec<ans::Token>, Vec<ans::Token>, usize)> = 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);
@@ -308,20 +328,19 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
}
}
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));
- }
+ // one entry per block that starts here: its transform, then its quant
+ let (mut qdata, quants) = blocks.meta(x0, y0, x1, y1);
+ let count = qdata.len();
+ qdata.extend(quants);
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: count, 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)
+ (dc_tokens, meta_tokens, count)
});
// The alpha channel: in the global section when it is one group big, else in a stream of each group.
@@ -348,7 +367,7 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
}
}
let mut leaf_streams: Vec<&[ans::Token]> = vec![&alpha_global];
- for (a, b) in &lf_tokens {
+ for (a, b, _) in &lf_tokens {
leaf_streams.push(a);
leaf_streams.push(b);
}
@@ -382,8 +401,9 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
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| (i / 13).min(1) as u8).collect();
- ans::write_context_map(&mut lf_global, &ctx_map, 2);
+ // (the map has a row of 13 block shapes for each of Y, X and B; the 16x16 DCT is shape 2)
+ let ctx_map: Vec<u8> = (0..3 * 13).map(|i| (i / 13).min(1) as u8 + 2 * (i % 13 == 2) as u8).collect();
+ ans::write_context_map(&mut lf_global, &ctx_map, 4);
if tuning.cfl {
lf_global.put(0, 1);
lf_global.put(0, 2); // colour factor 84
@@ -416,7 +436,7 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
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));
+ b.put((lf_tokens[lg].2 - 1) as u64, ceil_log2(nb)); // how many blocks start here, minus one
modular::write_stream(&mut b, &leaf_codes, &lf_tokens[lg].1);
b
});
@@ -492,7 +512,12 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
out.put(0, 1); // not all default
out.put(0, 2); // regular frame
out.put(0, 1); // VarDCT
- out.put(0, 2); // no flags
+ if tuning.skip_lf_smoothing {
+ out.put(2, 2); // flags: 128 = skip the decoder's smoothing of the low-frequency image
+ out.put(128 - 17, 8);
+ } else {
+ out.put(0, 2); // no flags
+ }
out.put(0, 2); // no upsampling
if has_alpha {
out.put(0, 2);
diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rs
index 4d6d5283..48af8d09 100644
--- a/crates/rf-jxl/src/vardct.rs
+++ b/crates/rf-jxl/src/vardct.rs
@@ -40,75 +40,99 @@ pub const COEFF_NUM_NONZERO_CONTEXT: [usize; 64] = [
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_BLOCK_CONTEXTS: usize = 4;
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],
- /// The forward DCT's matrix: row k is the k-th basis function, scaled so the DC is the mean.
+ /// The order the 8x8 coefficients are coded in: position k holds the storage index (x * 8 + y).
+ order8: Vec<u16>,
+ /// The forward DCT matrix: row k is the k-th basis function, scaled so the DC is the mean.
dct: [[f32; 8]; 8],
+ /// The same for the 16x16 DCT: its coding order, matrix and 1 / weights (X, Y, B).
+ order16: Vec<u16>,
+ dct16: [[f32; 16]; 16],
+ weight16: [[f32; 256]; 3],
}
/// 1 / the decoder's weight of each coefficient, from the band parameters (as the decoder reads them: the first value
/// of a channel is the weight of the DC corner, the rest are steps from one band to the next).
pub fn dct8_weights(params: &[[f32; 6]; 3]) -> [[f32; 64]; 3] {
- let mut weight = [[0f32; 64]; 3];
+ std::array::from_fn(|c| {
+ let w = band_weights(8, &params[c]);
+ std::array::from_fn(|i| w[i])
+ })
+}
+
+/// 1 / weight of each coefficient of an `n` x `n` DCT for one channel: the bands (each the one before times a step) are
+/// interpolated by the distance from the DC corner.
+fn band_weights(n: usize, params: &[f32]) -> Vec<f32> {
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] = params[c][0];
- for i in 1..6 {
- bands[i] = bands[i - 1] * mult(params[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 bands = [0f32; 17];
+ bands[0] = params[0];
+ for i in 1..params.len() {
+ bands[i] = bands[i - 1] * mult(params[i]);
+ }
+ let scale = (params.len() - 1) as f32 / (std::f32::consts::SQRT_2 + 1e-6);
+ let rcp = scale / (n - 1) as f32;
+ let mut weight = vec![0f32; n * n];
+ for y in 0..n {
+ for x in 0..n {
+ 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[y * n + x] = 1.0 / ((b / a).powf(frac) * a);
}
}
weight
}
-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;
- }
+/// The decoder's default band parameters for the 16x16 DCT.
+const DCT16_BANDS: [[f32; 7]; 3] = [
+ [8996.8725711814115328, -1.3000777393353804, -0.49424529824571225, -0.439093774457103443, -0.6350101832695744, -0.90177264050827612, -1.6162099239887414],
+ [3191.48366296844234752, -0.67424582104194355, -0.80745813428471001, -0.44925837484843441, -0.35865440981033403, -0.31322389111877305, -0.37615025315725483],
+ [1157.50408145487200256, -2.0531423165804414, -1.4, -0.50687130033378396, -0.42708730624733904, -1.4856834539296244, -4.9209142884401604],
+];
+
+/// The decoder's natural coefficient order of a square block `side` blocks wide (1 or 2): position k holds the storage
+/// index; the first `side * side` are the lowest frequencies, which the low-frequency image carries.
+fn natural_order(side: usize) -> Vec<u16> {
+ let n = 8 * side;
+ let mut order = vec![0u16; n * n];
+ let mut cur = side * side;
+ for i in 0..n {
+ for j in 0..=i {
+ let (mut x, mut y) = (j, i - j);
+ if i % 2 != 0 {
+ std::mem::swap(&mut x, &mut y);
}
- }
- 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;
+ if x < side && y < side {
+ order[y * side + x] = (y * n + x) as u16;
+ } else {
+ order[cur] = (y * n + x) as u16;
cur += 1;
}
}
+ }
+ for ir in 1..n {
+ let i = n - ir - 1;
+ for j in 0..=i {
+ let (mut x, mut y) = (n - 1 - (i - j), n - 1 - j);
+ if i % 2 != 0 {
+ std::mem::swap(&mut x, &mut y);
+ }
+ order[cur] = (y * n + x) as u16;
+ cur += 1;
+ }
+ }
+ order
+}
+
+fn tables() -> &'static Tables {
+ static T: OnceLock<Tables> = OnceLock::new();
+ T.get_or_init(|| {
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 };
@@ -116,7 +140,18 @@ fn tables() -> &'static Tables {
*v = (s / 8.0 * ((2 * n + 1) as f64 * k as f64 * std::f64::consts::PI / 16.0).cos()) as f32;
}
}
- Tables { order, dct }
+ let mut dct16 = [[0f32; 16]; 16];
+ for (k, row) in dct16.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 / 16.0 * ((2 * n + 1) as f64 * k as f64 * std::f64::consts::PI / 32.0).cos()) as f32;
+ }
+ }
+ let weight16 = std::array::from_fn(|c| {
+ let w = band_weights(16, &DCT16_BANDS[c]);
+ std::array::from_fn(|i| w[i])
+ });
+ Tables { dct, order8: natural_order(1), order16: natural_order(2), dct16, weight16 }
})
}
@@ -185,6 +220,30 @@ pub struct Blocks {
pub ac: Vec<[[i16; 64]; 3]>,
/// The quant of every block (1 to 256).
pub quant: Vec<u16>,
+ /// What each 8x8 position is: 0 a block of its own, 1 the top left of a 16x16 block, 2 another part of one.
+ pub kind: Vec<u8>,
+ /// For the positions of kind 1, where their coefficients are in `ac16` (the other entries are `u32::MAX`).
+ pub idx16: Vec<u32>,
+ /// The coefficients of the 16x16 blocks, `[channel X, Y, B][storage index]`, the lowest four holding 0.
+ pub ac16: Vec<Box<[[i16; 256]; 3]>>,
+}
+
+impl Blocks {
+ /// The block metadata of the blocks `x0..x1` by `y0..y1`, one entry per block that starts there, in raster order:
+ /// its transform (0 for 8x8, 4 for 16x16) and quant - 1.
+ pub fn meta(&self, x0: usize, y0: usize, x1: usize, y1: usize) -> (Vec<i32>, Vec<i32>) {
+ let (mut types, mut quants) = (Vec::new(), Vec::new());
+ for y in y0..y1 {
+ for x in x0..x1 {
+ let i = y * self.bw + x;
+ if self.kind[i] != 2 {
+ types.push(if self.kind[i] == 1 { 4 } else { 0 });
+ quants.push(self.quant[i] as i32 - 1);
+ }
+ }
+ }
+ (types, quants)
+ }
}
#[inline(always)]
@@ -275,8 +334,80 @@ pub fn fit_cfl_tiles(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, base: [f32; 2]
.collect()
}
-/// 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, threads: usize) -> Blocks {
+/// Forward 16x16 DCT of `src` (row `stride`) into `out`: storage index kx * 16 + ky, as for the 8x8 one.
+fn dct16x16(m: &[[f32; 16]; 16], src: &[f32], stride: usize, out: &mut [f32; 256]) {
+ let mut sum = [[0f32; 16]; 8];
+ let mut dif = [[0f32; 16]; 8];
+ for y in 0..8 {
+ let (a, b) = (&src[y * stride..y * stride + 16], &src[(15 - y) * stride..(15 - y) * stride + 16]);
+ for x in 0..16 {
+ sum[y][x] = a[x] + b[x];
+ dif[y][x] = a[x] - b[x];
+ }
+ }
+ let mut t = [[0f32; 16]; 16];
+ for ky in 0..16 {
+ let v = if ky % 2 == 0 { &sum } else { &dif };
+ let mk = &m[ky];
+ for x in 0..16 {
+ let mut s = 0.0;
+ for y in 0..8 {
+ s += mk[y] * v[y][x];
+ }
+ t[ky][x] = s;
+ }
+ }
+ for ky in 0..16 {
+ let r = &t[ky];
+ let mut s = [0f32; 8];
+ let mut d = [0f32; 8];
+ for n in 0..8 {
+ s[n] = r[n] + r[15 - n];
+ d[n] = r[n] - r[15 - n];
+ }
+ for kx in 0..16 {
+ let v = if kx % 2 == 0 { &s } else { &d };
+ let mk = &m[kx];
+ let mut acc = 0.0;
+ for n in 0..8 {
+ acc += mk[n] * v[n];
+ }
+ out[kx * 16 + ky] = acc;
+ }
+ }
+}
+
+/// The 2x2 low-frequency values (the entries of the low-frequency image under a 16x16 block) that make the decoder's
+/// own conversion give the block's lowest 2x2 coefficients `c` (storage index kx * 16 + ky). Returns [y][x].
+fn lf_from_llf(c: &[f32; 256]) -> [[f32; 2]; 2] {
+ // the decoder turns two values into a mean and a difference scaled by 0.554469 (the second is not the plain half
+ // difference, which makes the low frequencies of the big block match the small blocks' means); this undoes it
+ const K: f32 = 1.0 / (2.0 * 0.554469);
+ let a = |ky: usize| [c[ky] + c[16 + ky] * K, c[ky] - c[16 + ky] * K]; // over x, for each vertical frequency
+ let (a0, a1) = (a(0), a(1));
+ let mut l = [[0f32; 2]; 2];
+ for x in 0..2 {
+ l[0][x] = a0[x] + a1[x] * K;
+ l[1][x] = a0[x] - a1[x] * K;
+ }
+ l
+}
+
+/// Quantization of all blocks, `quant` the quant of each. With `big` blocks that are quiet enough are coded as one
+/// 16x16 DCT when that looks cheaper.
+#[allow(clippy::too_many_arguments)]
+pub fn quantize(
+ planes: &[Vec<f32>; 3],
+ co: &[[[f32; 64]; 3]],
+ bw: usize,
+ bh: usize,
+ quant: &[u16],
+ tile_cfl: &[[i32; 2]],
+ q: &Quant,
+ big: Option<&BigParams>,
+ threads: usize,
+) -> Blocks {
+ let t = tables();
let tw = bw.div_ceil(8);
let dm = [
(1.0f32 / 1.25).powf(q.x_qm_scale as f32 - 2.0),
@@ -287,11 +418,17 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile
let unit = q.global_scale as f32 / 65536.0;
let mut inv_step1 = [[0f32; 64]; 3];
let mut step1 = [[0f32; 64]; 3];
+ let mut inv_step16 = [[0f32; 256]; 3];
+ let mut step16 = [[0f32; 256]; 3];
for c in 0..3 {
for k in 0..64 {
step1[c][k] = q.weight[c][k] * dm[c] / unit;
inv_step1[c][k] = 1.0 / step1[c][k];
}
+ for k in 0..256 {
+ step16[c][k] = t.weight16[c][k] * dm[c] / unit;
+ inv_step16[c][k] = 1.0 / step16[c][k];
+ }
}
// low-frequency steps
let inv_quant_lf = 65536.0 / (q.global_scale as f32 * q.quant_lf as f32);
@@ -304,64 +441,170 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile
};
// 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;
+ // the low-frequency values of a block: Y first, X and B are coded relative to it
+ let lf_quant_of = |v: [f32; 3]| -> [i32; 3] {
+ let qy = (v[1] / lf_fac[1]).round() as i32;
+ let y_rec = qy as f32 * lf_fac[1];
+ let qx = ((v[0] - y_rec * q.cfl[2]) / lf_fac[0]).round() as i32;
+ let qb = ((v[2] - y_rec * q.cfl[3]) / lf_fac[2]).round() as i32;
+ [qy, qx, qb]
+ };
+ // a rough price in bits of coded coefficients
+ let price = |v: i16| if v == 0 { 0.0 } else { 6.0 + 2.0 * (v.unsigned_abs() as f32).log2().floor() };
+
+ // Two rows of blocks at a time, so that a 16x16 block can be chosen over four 8x8 ones.
+ let pairs = crate::par::par_map(bh.div_ceil(2), threads, |pr| {
+ let rows = if (2 * pr + 1) < bh { 2 } else { 1 };
+ let mut dcs = vec![[0i32; 3]; bw * rows];
+ let mut acs = vec![[[0i16; 64]; 3]; bw * rows];
+ let mut kinds = vec![0u8; bw * rows];
+ let mut bigs: Vec<(usize, Box<[[i16; 256]; 3]>)> = Vec::new();
+ let (mut cur_rq, mut scaled_inv, mut scaled_step) = (0f32, [[0f32; 64]; 3], [[0f32; 64]; 3]);
+ for r in 0..rows {
+ let by = 2 * pr + r;
+ for bx in 0..bw {
+ let bi = by * bw + bx;
+ let o = r * 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;
+ }
+ }
+ }
+ dcs[o] = lf_quant_of([co[0][0], co[1][0], co[2][0]]);
+ // high frequencies
+ let mut y_rec_ac = [0f32; 64];
+ for k in 1..64 {
+ let qq = round(co[1][k] * scaled_inv[1][k]);
+ acs[o][1][k] = qq.clamp(-32000, 32000) as i16;
+ 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 * scaled_inv[0][k]);
+ acs[o][0][k] = qq.clamp(-32000, 32000) as i16;
+ let rb = co[2][k] - y_rec_ac[k] * cb;
+ let qq = round(rb * scaled_inv[2][k]);
+ acs[o][2][k] = qq.clamp(-32000, 32000) as i16;
}
}
}
- // 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] - 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;
- dcs[bx] = [qy, qx, qb];
- // high frequencies
- let mut y_rec_ac = [0f32; 64];
- for k in 1..64 {
- let qq = round(co[1][k] * scaled_inv[1][k]);
- acs[bx][1][k] = qq.clamp(-32000, 32000) as i16;
- 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 * 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 * scaled_inv[2][k]);
- acs[bx][2][k] = qq.clamp(-32000, 32000) as i16;
+ // 16x16 blocks where the four 8x8 ones are quiet and one big one costs less
+ if let (Some(bp), 2) = (big, rows) {
+ let by = 2 * pr;
+ for bx in (0..bw.saturating_sub(1)).step_by(2) {
+ let (o0, o1) = (bx, bw + bx);
+ let blocks = [o0, o0 + 1, o1, o1 + 1];
+ let (mut nz, mut cost8) = (0usize, 0f32);
+ for &o in &blocks {
+ for c in 0..3 {
+ for k in 1..64 {
+ let v = acs[o][c][k];
+ if v != 0 {
+ nz += 1;
+ cost8 += price(v);
+ }
+ }
+ }
+ }
+ if nz > bp.max_nonzero {
+ continue;
+ }
+ cost8 += 12.0 * 3.0; // the number-of-nonzeros tokens of the 12 channels of blocks
+ let rq16 = quant[by * bw + bx] as f32;
+ if (0..4).any(|i| quant[by * bw + bx + (i & 1) + (i >> 1) * bw] as f32 != rq16) {
+ continue;
+ }
+ let mut c16 = [[0f32; 256]; 3];
+ for c in 0..3 {
+ dct16x16(&t.dct16, &planes[c][by * 8 * bw * 8 + bx * 8..], bw * 8, &mut c16[c]);
+ }
+ // low frequencies: the 2x2 entries that stand for the block's lowest coefficients
+ let lf: [[[f32; 2]; 2]; 3] = std::array::from_fn(|c| lf_from_llf(&c16[c]));
+ // high frequencies
+ let mut a16 = Box::new([[0i16; 256]; 3]);
+ let mut y_rec = [0f32; 256];
+ let order = &t.order16;
+ for &k in &order[4..] {
+ let k = k as usize;
+ let qq = round(c16[1][k] * inv_step16[1][k] * rq16);
+ a16[1][k] = qq.clamp(-32000, 32000) as i16;
+ let a = qq.unsigned_abs() as usize;
+ let dq = if a < 256 { y_lut[a] } else { dequant_value(a as i32, 1) };
+ y_rec[k] = if qq < 0 { -dq } else { dq } * step16[1][k] / rq16;
+ }
+ 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);
+ let (mut nz16, mut cost16) = (0usize, 0f32);
+ for &k in &order[4..] {
+ let k = k as usize;
+ let qx = round((c16[0][k] - y_rec[k] * cx) * inv_step16[0][k] * rq16);
+ a16[0][k] = qx.clamp(-32000, 32000) as i16;
+ let qb = round((c16[2][k] - y_rec[k] * cb) * inv_step16[2][k] * rq16);
+ a16[2][k] = qb.clamp(-32000, 32000) as i16;
+ for c in 0..3 {
+ if a16[c][k] != 0 {
+ nz16 += 1;
+ cost16 += price(a16[c][k]);
+ }
+ }
+ }
+ let _ = nz16;
+ cost16 += 3.0 * 3.0;
+ if cost16 * bp.bias >= cost8 {
+ continue;
+ }
+ // take it: the low-frequency entries of the four positions, the coefficients with the first one
+ for (i, &o) in blocks.iter().enumerate() {
+ let (yy, xx) = (i >> 1, i & 1);
+ dcs[o] = lf_quant_of([lf[0][yy][xx], lf[1][yy][xx], lf[2][yy][xx]]);
+ kinds[o] = 2;
+ acs[o] = [[0; 64]; 3];
+ }
+ kinds[o0] = 1;
+ bigs.push((bx, a16));
+ }
}
- }
- (dcs, acs)
+ (dcs, acs, kinds, bigs)
});
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 {
+ let mut kind = Vec::with_capacity(bw * bh);
+ let mut idx16 = vec![u32::MAX; bw * bh];
+ let mut ac16 = Vec::new();
+ for (pr, (d, a, k, bigs)) in pairs.into_iter().enumerate() {
for v in d {
for c in 0..3 {
dc[c].push(v[c]);
}
}
ac.extend(a);
+ kind.extend(k);
+ for (bx, blk) in bigs {
+ idx16[2 * pr * bw + bx] = ac16.len() as u32;
+ ac16.push(blk);
+ }
}
- Blocks { bw, bh, dc, ac, quant: quant.to_vec() }
+ Blocks { bw, bh, dc, ac, quant: quant.to_vec(), kind, idx16, ac16 }
}
+/// When to take a 16x16 block instead of four 8x8 ones.
+#[derive(Clone, Copy, Debug)]
+pub struct BigParams {
+ /// Only where the four 8x8 blocks have at most this many nonzero coefficients.
+ pub max_nonzero: usize,
+ /// The big block must cost less than the small ones divided by this.
+ pub bias: f32,
+}
/// The three channels of the low-frequency image, coded in the order Y, X, B.
/// Only the blocks `x0..x1` by `y0..y1` (a low-frequency group).
@@ -395,11 +638,15 @@ pub fn group_tokens(b: &Blocks, gx: usize, gy: usize, out: &mut Vec<Token>) {
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
+ // the number of nonzero coefficients (in blocks' worth) 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 bi = by * b.bw + bx;
+ let kind = b.kind[bi];
+ if kind == 2 {
+ continue;
+ }
let (lx, ly) = (bx - x0, by - y0);
for c in [1usize, 0, 2] {
let predicted = if lx == 0 {
@@ -409,25 +656,30 @@ pub fn group_tokens(b: &Blocks, gx: usize, gy: usize, out: &mut Vec<Token>) {
} 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;
- }
- }
+ let block_ctx = (if c == 1 { 0 } else { 1 }) + 2 * (kind as usize);
+ // the coefficients in coding order, the number of the first coded one, and the size in blocks (log2)
+ let (co, order, first, log_blocks): (&[i16], &[u16], usize, usize) = if kind == 1 {
+ (&b.ac16[b.idx16[bi] as usize][c], &t.order16, 4, 2)
+ } else {
+ (&b.ac[bi][c], &t.order8, 1, 0)
+ };
+ let n = order.len();
+ let nz = order[first..].iter().filter(|&&k| co[k as usize] != 0).count();
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;
+ let covered = 1 << (log_blocks / 2);
+ let stored = nz.div_ceil(1 << log_blocks) as u8;
+ for e in &mut nz_row[c][lx..lx + covered] {
+ *e = stored;
+ }
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 prev = if nz > n / 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;
+ for k in first..n {
+ let v = co[order[k] as usize] as i32;
+ let ctx = hist_off + COEFF_NUM_NONZERO_CONTEXT[((left - 1) >> log_blocks) + 1] + COEFF_FREQ_CONTEXT[k >> log_blocks] + prev;
out.push(Token { ctx: ctx as u32, val: pack_signed(v) });
if v == 0 {
prev = 0;
@@ -451,9 +703,9 @@ mod tests {
#[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);
+ let head = [0u16, 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.order8[..head.len()], &head);
+ let tail = [58u16, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63];
+ assert_eq!(&t.order8[48..], &tail);
}
}
diff --git a/crates/rf-jxl/tests/roundtrip.rs b/crates/rf-jxl/tests/roundtrip.rs
index ac5e2e14..061aa633 100644
--- a/crates/rf-jxl/tests/roundtrip.rs
+++ b/crates/rf-jxl/tests/roundtrip.rs
@@ -258,8 +258,39 @@ fn check_big(w: u32, h: u32, alpha: bool) {
}
}
+#[test]
+fn sixteen_by_sixteen_blocks_decode_right() {
+ // smooth pictures with a few edges, with the big blocks taken wherever they are not clearly worse
+ let mut t = rf_jxl::Tuning::from_quality(85.0);
+ t.big_min_pixels = 0;
+ t.big_bias = 1.3;
+ t.big_max_nonzero = 1000;
+ for (name, w, h, px) in [
+ ("gradient", 256u32, 256u32, gradient(256, 256)),
+ ("synthetic", 300, 200, synthetic(300, 200, 11)),
+ ("odd", 77, 51, synthetic(77, 51, 12)),
+ ("flat", 64, 64, solid(64, 64, [30, 90, 200])),
+ ] {
+ let big = rf_jxl::encode_tuned(w, h, &px, false, &t).unwrap();
+ let mut small = t.clone();
+ small.big_blocks = false;
+ let small = rf_jxl::encode_tuned(w, h, &px, false, &small).unwrap();
+ assert_ne!(big, small, "{name}: no 16x16 block was taken");
+ for (who, dec) in [("jxl-oxide", decode_oxide as fn(&[u8]) -> _), ("jxl-rs", decode_jxl_rs)] {
+ let (_, _, rgb) = dec(&big);
+ let s = score(w, h, &px, &rgb);
+ let (_, _, rgb) = dec(&small);
+ let s_small = score(w, h, &px, &rgb);
+ eprintln!("{name:<10} {w}x{h}: {} bytes ({} with 8x8 only), {who} SSIMULACRA2 {s:.1} ({s_small:.1})", big.len(), small.len());
+ // about as good as the same picture in 8x8 blocks
+ assert!(s > s_small - 3.0, "{name}: {who} scores {s:.1} against {s_small:.1}");
+ }
+ }
+}
+
#[test]
fn just_over_one_low_frequency_group() {
+ check_big(700, 500, false);
check_big(2049, 40, false);
check_big(40, 2049, false);
check_big(2100, 300, true);