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: alpha channel, no gaborish, a quant map hook

gelenmedya122a09e1ccac
diff --git a/crates/rf-jxl/src/lib.rs b/crates/rf-jxl/src/lib.rs
index 346ecfb4..300090c1 100644
--- a/crates/rf-jxl/src/lib.rs
+++ b/crates/rf-jxl/src/lib.rs
@@ -2,8 +2,9 @@
//! 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).
+//! blocks, quantized, the coefficients coded with context-modelled ANS. An alpha channel is coded without loss as a
+//! modular channel. 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;
@@ -17,6 +18,9 @@ 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;
+/// Pixels per group side.
+const GROUP: usize = 256;
+
/// Settings for experiments; `encode` uses the defaults.
#[derive(Clone, Debug)]
pub struct Tuning {
@@ -30,8 +34,19 @@ pub struct Tuning {
pub round_threshold: f32,
/// Smoothing the decoder applies (0 to 3 passes of its edge-preserving filter).
pub epf_iters: u32,
+ /// The decoder's 3x3 smoothing; only worth it when the encoder sharpens before the transform, which it does not.
pub gaborish: bool,
pub epf_sharpness: u8,
+ /// Print where the bytes go (for the measuring tools).
+ pub verbose: bool,
+ /// How much coarser X and B are quantized than the weights say (1.25 per step above 2).
+ pub x_qm_scale: u32,
+ pub b_qm_scale: u32,
+ /// Adaptive quantization: how strongly a block's quant follows its activity (0 = not at all), and the ratios it
+ /// may go down to and up to.
+ pub aq_power: f32,
+ pub aq_min: f32,
+ pub aq_max: f32,
}
impl Tuning {
@@ -45,12 +60,47 @@ impl Tuning {
} 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 }
+ Tuning {
+ distance,
+ strength: 1.0,
+ dc_mult: 0.55,
+ round_threshold: 0.5,
+ epf_iters: 0,
+ gaborish: false,
+ epf_sharpness: 4,
+ verbose: false,
+ x_qm_scale: 3,
+ b_qm_scale: 2,
+ aq_power: 0.0,
+ aq_min: 0.5,
+ aq_max: 2.0,
+ }
+ }
+
+ /// For the measuring tools: one setting by its name; false when there is none of that name.
+ pub fn set(&mut self, key: &str, v: f32) -> bool {
+ match key {
+ "q" => *self = Tuning::from_quality(v),
+ "strength" => self.strength = v,
+ "dc" => self.dc_mult = v,
+ "round" => self.round_threshold = v,
+ "epf" => self.epf_iters = v as u32,
+ "gab" => self.gaborish = v > 0.0,
+ "sharp" => self.epf_sharpness = v as u8,
+ "verbose" => self.verbose = v > 0.0,
+ "xqm" => self.x_qm_scale = v as u32,
+ "bqm" => self.b_qm_scale = v as u32,
+ "aq" => self.aq_power = v,
+ "aqmin" => self.aq_min = v,
+ "aqmax" => self.aq_max = v,
+ _ => return false,
+ }
+ true
}
}
/// 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".
+/// 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> {
@@ -62,11 +112,15 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
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);
+ let planes = if has_alpha {
+ xyb::to_xyb(&fill_transparent(rgba, w, h), w, h, bw * 8, bh * 8)
+ } else {
+ 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.
+ // Quantization: blocks get a quant around 16, the global scale makes up the strength.
let strength = tuning.strength / tuning.distance.max(0.01);
- let raw_quant = 8u32;
+ let raw_quant = 16u32;
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 {
@@ -74,39 +128,41 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
raw_quant,
quant_lf,
round_offset: tuning.round_threshold,
- x_qm_scale: 3,
- b_qm_scale: 2,
+ x_qm_scale: tuning.x_qm_scale,
+ b_qm_scale: tuning.b_qm_scale,
+ aq_power: tuning.aq_power,
+ aq_min: tuning.aq_min,
+ aq_max: tuning.aq_max,
};
- let blocks = vardct::quantize(&planes, bw, bh, &q);
+ let coefs = vardct::analyze(&planes, bw, bh);
+ let quant_map = vardct::quant_map(&coefs, &q);
+ let blocks = vardct::quantize(&coefs, bw, bh, &quant_map, &q);
- // The streams of modular data share one tree.
+ // 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).
+ let grad = || Box::new(T::Leaf(modular::PRED_GRADIENT));
let tree = Tree::new(T::Split(
1,
- 2,
- // the block metadata (stream 3): channels ytox, ytob, (type, quant), epf
+ 20,
+ grad(), // alpha of a group
Box::new(T::Split(
- 0,
+ 1,
2,
- Box::new(T::Leaf(modular::PRED_GRADIENT)),
+ // the block metadata: channels ytox, ytob, (type, quant), epf
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)),
+ 2,
+ grad(),
+ Box::new(T::Split(0, 1, Box::new(T::Split(2, 0, grad(), grad())), grad())),
)),
- )),
- 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)))),
+ 0,
+ // the low-frequency image: channels Y, X, B
+ Box::new(T::Split(0, 1, grad(), Box::new(T::Split(0, 0, grad(), grad())))),
+ grad(), // alpha of the whole picture
)),
- // the global stream (stream 0): alpha
- Box::new(T::Leaf(modular::PRED_GRADIENT)),
)),
));
let mut dc_tokens = Vec::new();
@@ -117,17 +173,44 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
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: 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 leaf_codes = ans::build_codes(tree.num_leaves, &[&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 {
+ 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 {
+ 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]);
+ }
+ let (pred, id) = tree.leaf_of(21 + 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);
+ }
+ }
+ }
+ let mut leaf_streams: Vec<&[ans::Token]> = vec![&dc_tokens, &meta_tokens, &alpha_global];
+ leaf_streams.extend(alpha_groups.iter().map(|t| t.as_slice()));
+ let leaf_codes = ans::build_codes(tree.num_leaves, &leaf_streams);
// The coefficients of each group.
- let (gw, gh) = (bw.div_ceil(vardct::GROUP_BLOCKS), bh.div_ceil(vardct::GROUP_BLOCKS));
+ 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..gh {
- for gx in 0..gw {
+ 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);
@@ -150,6 +233,18 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
lf_global.put(1, 1); // a global tree
tree.write(&mut lf_global);
leaf_codes.write_header(&mut lf_global);
+ if has_alpha {
+ // the global modular stream: its header, and the alpha channel when it is small enough to be in it
+ modular::write_stream_header(&mut lf_global);
+ if gw * gh == 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
+ // an entropy decoder anyway and reads its state, so the section ends with an empty stream (the state is
+ // what a decoder ends with, 0x130000).
+ leaf_codes.write_stream(&mut lf_global, &[]);
+ }
+ }
let mut lf_group = BitWriter::new();
lf_group.put(0, 2); // extra precision
@@ -163,15 +258,34 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
hf_global.put(2, 2); // the coefficient order is the natural one
ac_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()
- .map(|t| {
+ .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();
+ if tuning.verbose {
+ eprintln!(
+ "lf_global {} B (tree+leaf hist), lf_group {} B (dc {} tokens, meta {}), hf_global {} B, ac {} B in {} tokens",
+ lf_global.bit_len() / 8,
+ lf_group.bit_len() / 8,
+ dc_tokens.len(),
+ meta_tokens.len(),
+ 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>()
+ );
+ }
+
// --- the file
let mut out = BitWriter::new();
out.put(0xff, 8);
@@ -233,11 +347,10 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
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 {
+ if gw * gh == 1 {
let mut all = lf_global;
all.append(&lf_group);
all.append(&hf_global);
@@ -266,6 +379,35 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin
bytes
}
+/// The picture with the colour of fully transparent pixels made like their neighbours' (they are never seen, and an
+/// edge between them and the visible colours would cost bits).
+fn fill_transparent(rgba: &[u8], w: usize, h: usize) -> std::borrow::Cow<'_, [u8]> {
+ if !rgba.chunks_exact(4).take(w * h).any(|p| p[3] == 0) {
+ return std::borrow::Cow::Borrowed(rgba);
+ }
+ let mut px = rgba[..w * h * 4].to_vec();
+ for y in 0..h {
+ // the colour to the left, else the one above, else the first visible one in the row
+ let first_visible = (0..w).find(|&x| px[(y * w + x) * 4 + 3] != 0);
+ for x in 0..w {
+ let i = (y * w + x) * 4;
+ if px[i + 3] == 0 {
+ let from = if x > 0 {
+ Some(i - 4)
+ } else if y > 0 {
+ Some(i - w * 4)
+ } else {
+ first_visible.map(|f| (y * w + f) * 4)
+ };
+ if let Some(f) = from {
+ px.copy_within(f..f + 3, i);
+ }
+ }
+ }
+ }
+ std::borrow::Cow::Owned(px)
+}
+
fn put_global_scale(bw: &mut BitWriter, v: u32) {
match v {
1..=2048 => {
diff --git a/crates/rf-jxl/src/modular.rs b/crates/rf-jxl/src/modular.rs
index 6998076d..3ae4f611 100644
--- a/crates/rf-jxl/src/modular.rs
+++ b/crates/rf-jxl/src/modular.rs
@@ -71,6 +71,14 @@ impl Tree {
}
}
+ /// The predictor and leaf for a channel of a stream, for the leaves that depend on nothing else.
+ pub fn leaf_of(&self, stream: u32, channel: u32) -> (u8, u32) {
+ let mut props = [0i32; 16];
+ props[0] = channel as i32;
+ props[1] = stream as i32;
+ self.walk(&props)
+ }
+
/// 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();
@@ -167,6 +175,34 @@ pub fn encode_channels(chans: &[Chan], stream: u32, tree: &Tree, out: &mut Vec<T
}
}
+/// One channel that is coded with a single leaf of the tree (the gradient predictor, one distribution), without the
+/// work of evaluating the tree for every pixel.
+pub fn encode_gradient(ch: &Chan, pred: u8, id: u32, out: &mut Vec<Token>) {
+ assert_eq!(pred, PRED_GRADIENT);
+ 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)) });
+ }
+ }
+}
+
/// 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) {
diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rs
index ba66a58a..c853a4fc 100644
--- a/crates/rf-jxl/src/vardct.rs
+++ b/crates/rf-jxl/src/vardct.rs
@@ -144,10 +144,11 @@ fn dct8x8(m: &[[f32; 8]; 8], src: &[f32], stride: usize, out: &mut [f32; 64]) {
}
}
+
/// 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`).
+ /// The frame's global scale and the quant a block gets when nothing says otherwise.
pub global_scale: u32,
pub raw_quant: u32,
/// The low-frequency image's extra divisor.
@@ -156,13 +157,11 @@ pub struct Quant {
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
- }
+ /// Adaptive quantization: exponent of the activity ratio (0 = every block the same), and how far a block's quant
+ /// may go from the base, as ratios.
+ pub aq_power: f32,
+ pub aq_min: f32,
+ pub aq_max: f32,
}
/// The quantized picture, block by block.
@@ -173,6 +172,8 @@ pub struct Blocks {
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]>,
+ /// The quant of every block (1 to 256).
+ pub quant: Vec<u16>,
}
#[inline(always)]
@@ -181,23 +182,56 @@ fn dequant_value(q: i32, c: usize) -> 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 {
+/// 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]> {
let t = tables();
let stride = bw * 8;
- let strength = q.strength();
+ let mut out = vec![[[0f32; 64]; 3]; bw * bh];
+ for by in 0..bh {
+ for bx in 0..bw {
+ for c in 0..3 {
+ dct8x8(&t.dct, &planes[c][by * 8 * stride + bx * 8..], stride, &mut out[by * bw + bx][c]);
+ }
+ }
+ }
+ out
+}
+
+/// The quant of each block: blocks with little going on (where mistakes show) get a finer one, busy blocks a coarser
+/// one, in proportion to how their activity compares with the picture's typical one.
+pub fn quant_map(co: &[[[f32; 64]; 3]], q: &Quant) -> Vec<u16> {
+ let base = q.raw_quant as f32;
+ if q.aq_power == 0.0 {
+ return vec![q.raw_quant as u16; co.len()];
+ }
+ // activity: the energy of the luma's high frequencies, as an amplitude
+ let act: Vec<f32> = co.iter().map(|b| (b[1][1..].iter().map(|v| v * v).sum::<f32>() / 63.0).sqrt()).collect();
+ let mean_log = act.iter().map(|a| (a + 1e-4).ln()).sum::<f32>() / act.len() as f32;
+ let typical = mean_log.exp();
+ act.iter()
+ .map(|a| {
+ let m = ((typical / (a + 1e-4)).powf(q.aq_power)).clamp(q.aq_min, q.aq_max);
+ (base * m).round().clamp(1.0, 256.0) as u16
+ })
+ .collect()
+}
+
+/// Quantization of all blocks, `quant` the quant of each.
+pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], q: &Quant) -> Blocks {
+ let t = tables();
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];
+ // 1 / quantization step of each coefficient for a block quant of 1
+ let unit = q.global_scale as f32 / 65536.0;
+ let mut inv_step1 = [[0f32; 64]; 3];
+ let mut step1 = [[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];
+ step1[c][k] = t.weight[c][k] * dm[c] / unit;
+ inv_step1[c][k] = 1.0 / step1[c][k];
}
}
// low-frequency steps
@@ -211,40 +245,36 @@ pub fn quantize(planes: &[Vec<f32>; 3], bw: usize, bh: usize, q: &Quant) -> Bloc
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;
- }
+ for bi in 0..bw * bh {
+ 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)
+ 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_step1[1][k] * rq);
+ ac[bi][1][k] = qq.clamp(-32000, 32000) as i16;
+ y_rec_ac[k] = dequant_value(qq, 1) * step1[1][k] / rq;
+ }
+ for k in 1..64 {
+ let qq = round(co[0][k] * inv_step1[0][k] * rq);
+ ac[bi][0][k] = qq.clamp(-32000, 32000) as i16;
+ let rb = co[2][k] - y_rec_ac[k];
+ let qq = round(rb * inv_step1[2][k] * rq);
+ ac[bi][2][k] = qq.clamp(-32000, 32000) as i16;
}
}
- Blocks { bw, bh, dc, ac }
+ 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()
diff --git a/crates/rf-jxl/tests/roundtrip.rs b/crates/rf-jxl/tests/roundtrip.rs
index d47ab977..12c9c5b3 100644
--- a/crates/rf-jxl/tests/roundtrip.rs
+++ b/crates/rf-jxl/tests/roundtrip.rs
@@ -151,6 +151,62 @@ fn stripes_keep_their_direction() {
check("horizontal stripes", w, h, &horizontal, 90.0, 60.0);
}
+/// A picture whose alpha is a soft-edged disc (and fully transparent outside, with colour under it that must not
+/// matter).
+fn with_alpha(w: u32, h: u32) -> Vec<u8> {
+ let mut px = synthetic(w, h, 5);
+ for y in 0..h {
+ for x in 0..w {
+ let (fx, fy) = (x as f32 / w as f32 - 0.5, y as f32 / h as f32 - 0.5);
+ let d = (fx * fx + fy * fy).sqrt();
+ let a = ((0.42 - d) * 40.0).clamp(0.0, 1.0);
+ px[((y * w + x) * 4 + 3) as usize] = (a * 255.0).round() as u8;
+ }
+ }
+ px
+}
+
+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 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()) });
+ // jxl-oxide: all channels, the fourth is alpha
+ 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();
+ assert_eq!(fb.channels(), 4, "colour and alpha");
+ let ox: Vec<u8> = fb.buf().iter().map(|v| (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8).collect();
+ let d = jxl_image_rs_integration::JxlDecoder::new(Cursor::new(&bytes)).expect("jxl-rs reads the file");
+ let rs = image::DynamicImage::from_decoder(d).expect("jxl-rs decodes the picture").to_rgba8().into_raw();
+ for (who, dec) in [("jxl-oxide", &ox), ("jxl-rs", &rs)] {
+ let (mut sum, mut n) = (0i64, 0i64);
+ for (a, b) in px.chunks_exact(4).zip(dec.chunks_exact(4)) {
+ assert_eq!(a[3], b[3], "{who}: alpha must be exact");
+ if a[3] == 255 {
+ for i in 0..3 {
+ sum += (a[i] as i32 - b[i] as i32).abs() as i64;
+ n += 1;
+ }
+ }
+ }
+ let mean = sum as f64 / n.max(1) as f64;
+ eprintln!("alpha {w}x{h}: {} bytes, {who}: alpha exact, mean colour error on opaque pixels {mean:.2}", bytes.len());
+ assert!(mean < 6.0, "{who}: colour error {mean}");
+ }
+}
+
+#[test]
+fn alpha_is_exact() {
+ check_alpha(100, 80);
+ check_alpha(256, 256);
+ check_alpha(257, 100);
+ check_alpha(600, 300);
+ check_alpha(1, 1);
+}
+
#[test]
fn bigger_than_a_group() {
check("synthetic", 600, 400, &synthetic(600, 400, 4), 90.0, 70.0);