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: colour from luma fitted per picture and per tile, measuring knobs
gelenmedya206fde2bfec5
diff --git a/crates/rf-jxl/src/ans.rs b/crates/rf-jxl/src/ans.rsindex bbeb308f..ebf5b052 100644--- a/crates/rf-jxl/src/ans.rs+++ b/crates/rf-jxl/src/ans.rs@@ -399,6 +399,7 @@ pub fn build_codes(num_contexts: usize, streams: &[&[Token]]) -> Codes {for &i in &order {let h = &used[i].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() {diff --git a/crates/rf-jxl/src/bits.rs b/crates/rf-jxl/src/bits.rsindex 1022f774..2058ff9a 100644--- a/crates/rf-jxl/src/bits.rs+++ b/crates/rf-jxl/src/bits.rs@@ -25,10 +25,6 @@ impl BitWriter {}}- pub fn put_bool(&mut self, b: bool) {- self.put(b as u64, 1);- }-/// Number of bits written so far.pub fn bit_len(&self) -> usize {self.buf.len() * 8 + self.nbits as usize@@ -69,7 +65,6 @@ impl BitWriter {/// One of the four forms of the headers' "u32" integers; 2 bits say which one is used.pub enum U32Form {- Val(u32),Bits(u32),BitsOffset(u32, u32),}@@ -78,10 +73,6 @@ pub enum U32Form {pub fn put_u32(bw: &mut BitWriter, v: u32, forms: [U32Form; 4]) {for (sel, f) in forms.iter().enumerate() {match *f {- U32Form::Val(x) if x == v => {- bw.put(sel as u64, 2);- return;- }U32Form::Bits(n) if n >= 32 || v >> n == 0 => {bw.put(sel as u64, 2);bw.put(v as u64, n);@@ -98,6 +89,32 @@ pub fn put_u32(bw: &mut BitWriter, v: u32, forms: [U32Form; 4]) {panic!("u32 {v} fits none of the forms");}+/// The 16-bit float (1 sign, 5 exponent, 10 mantissa bits) nearest to `v`; zero and the normal range only.+pub fn f16_bits(v: f32) -> u16 {+ if v == 0.0 {+ return 0;+ }+ let sign = if v < 0.0 { 0x8000u16 } else { 0 };+ let b = v.abs().to_bits();+ let exp = ((b >> 23) & 0xff) as i32 - 127 + 15;+ debug_assert!((1..31).contains(&exp), "{v} is out of the 16-bit float's normal range");+ let man = b & 0x7f_ffff;+ // round the 23-bit mantissa to 10 bits; a carry moves into the exponent by itself+ let rounded = ((exp as u32) << 10) + ((man + 0x1000) >> 13);+ sign | rounded as u16+}++/// What a 16-bit float stands for (zero and the normal range).+pub fn f16_value(bits: u16) -> f32 {+ let exp = ((bits >> 10) & 0x1f) as i32;+ if exp == 0 {+ return 0.0;+ }+ let man = (bits & 0x3ff) as f32;+ let v = (1.0 + man / 1024.0) * 2f32.powi(exp - 15);+ if bits & 0x8000 != 0 { -v } else { v }+}+pub fn ceil_log2(v: usize) -> u32 {if v <= 1 { 0 } else { usize::BITS - (v - 1).leading_zeros() }}diff --git a/crates/rf-jxl/src/lib.rs b/crates/rf-jxl/src/lib.rsindex 300090c1..637a8156 100644--- a/crates/rf-jxl/src/lib.rs+++ b/crates/rf-jxl/src/lib.rs@@ -42,11 +42,15 @@ pub struct Tuning {/// 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,+ /// Multipliers of the low-frequency steps of X, Y and B (1 keeps the format's defaults).+ pub dc_scale: [f32; 3],+ /// Changes to the default weights of the 8x8 DCT's frequency bands (see `vardct::DCT8_BANDS`): the first of each+ /// channel scales the weights, the others move the steps between bands.+ pub band_delta: [[f32; 6]; 3],+ /// Fit how much of Y is taken off X and B to the picture (else the format's defaults: none off X, all off B).+ pub cfl: bool,+ /// And per 64x64 pixel tile.+ pub cfl_tiles: bool,}impl Tuning {@@ -71,9 +75,10 @@ impl Tuning {verbose: false,x_qm_scale: 3,b_qm_scale: 2,- aq_power: 0.0,- aq_min: 0.5,- aq_max: 2.0,+ dc_scale: [1.0; 3],+ band_delta: [[0.0; 6]; 3],+ cfl: true,+ cfl_tiles: true,}}@@ -90,9 +95,25 @@ impl Tuning {"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,+ "cfl" => self.cfl = v > 0.0,+ "tiles" => self.cfl_tiles = v > 0.0,+ "dcx" => self.dc_scale[0] = v,+ "dcy" => self.dc_scale[1] = v,+ "dcb" => self.dc_scale[2] = v,+ k if k.len() == 3 && k.starts_with('w') => {+ // wy2 = 0.2: the band step 2 of Y moved by 0.2+ let c = match &k[1..2] {+ "x" => 0,+ "y" => 1,+ "b" => 2,+ _ => return false,+ };+ let i: usize = k[2..3].parse().unwrap_or(9);+ if i > 5 {+ return false;+ }+ self.band_delta[c][i] = v;+ }_ => return false,}true@@ -123,25 +144,58 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninlet 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);+ // the low-frequency factors, as the decoder will read them back from 16-bit floats (factor * 128)+ let custom_lf = tuning.dc_scale != [1.0; 3];+ let lf_bits: [u16; 3] = std::array::from_fn(|c| bits::f16_bits(vardct::LF_QUANT[c] * tuning.dc_scale[c] * 128.0));+ let lf_quant: [f32; 3] = if custom_lf {+ std::array::from_fn(|c| bits::f16_value(lf_bits[c]) / 128.0)+ } else {+ vardct::LF_QUANT+ };+ // the weights of the 8x8 DCT's coefficients, from parameters that go through 16-bit floats+ let custom_bands = tuning.band_delta != [[0.0; 6]; 3];+ let band_bits: [[u16; 6]; 3] = std::array::from_fn(|c| {+ std::array::from_fn(|i| {+ let d = vardct::DCT8_BANDS[c][i];+ // the first value is stored divided by 64, and scaled by the delta as a factor+ if i == 0 { bits::f16_bits(d / 64.0 * (1.0 + tuning.band_delta[c][0])) } else { bits::f16_bits(d + tuning.band_delta[c][i]) }+ })+ });+ let bands: [[f32; 6]; 3] = std::array::from_fn(|c| {+ std::array::from_fn(|i| {+ let v = bits::f16_value(band_bits[c][i]);+ if i == 0 { v * 64.0 } else { v }+ })+ });+ let weight = vardct::dct8_weights(&if custom_bands { bands } else { vardct::DCT8_BANDS });+ let coefs = vardct::analyze(&planes, bw, bh);+ // 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] };+ let small = |v: f32| if v.abs() < 1e-3 { 0.0 } else { v };+ let base_bits = [bits::f16_bits(small(fit[0])), bits::f16_bits(small(fit[1]))];+ let base = [bits::f16_value(base_bits[0]), bits::f16_value(base_bits[1])];+ let lf_off: [i32; 2] = [((fit[2] - base[0]) * 84.0).round().clamp(-128.0, 127.0) as i32, ((fit[3] - base[1]) * 84.0).round().clamp(-128.0, 127.0) as i32];+ let cfl = [base[0], base[1], base[0] + lf_off[0] as f32 / 84.0, base[1] + lf_off[1] as f32 / 84.0];let q = vardct::Quant {global_scale,- raw_quant,quant_lf,+ lf_quant,+ weight,+ cfl,round_offset: tuning.round_threshold,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 coefs = vardct::analyze(&planes, bw, bh);- let quant_map = vardct::quant_map(&coefs, &q);- let blocks = vardct::quantize(&coefs, bw, bh, &quant_map, &q);+ // every block gets the same quant (an activity-based map was tried, and cost more than it saved)+ 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);// 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,20,@@ -169,10 +223,9 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninmodular::encode_channels(&vardct::dc_channels(&blocks), 1, &tree, &mut dc_tokens);let mut meta_tokens = Vec::new();let nblocks = bw * bh;- let tiles = (bw.div_ceil(8), bh.div_ceil(8));let meta = [- Chan { w: tiles.0, h: tiles.1, data: vec![0; tiles.0 * tiles.1] },- Chan { w: tiles.0, h: tiles.1, data: vec![0; tiles.0 * tiles.1] },+ Chan { w: 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] },];@@ -220,16 +273,32 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin// --- the sectionslet mut lf_global = BitWriter::new();- lf_global.put(1, 1); // default LF quantization factors+ if custom_lf {+ lf_global.put(0, 1);+ for b in lf_bits {+ lf_global.put(b as u64, 16);+ }+ } else {+ lf_global.put(1, 1); // default LF quantization factors+ }put_global_scale(&mut lf_global, global_scale);put_quant_lf(&mut lf_global, quant_lf);// the block context map: Y has its own contexts, X and B share theirslf_global.put(0, 1);lf_global.put(0, 12); // no thresholds on the LF valueslf_global.put(0, 4); // none on the quantization- let ctx_map: Vec<u8> = (0..3 * 13).map(|i| if i < 13 { 0 } else { 1 }).collect();+ 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);- lf_global.put(1, 1); // default colour correlation+ if tuning.cfl {+ lf_global.put(0, 1);+ lf_global.put(0, 2); // colour factor 84+ lf_global.put(base_bits[0] as u64, 16);+ lf_global.put(base_bits[1] as u64, 16);+ lf_global.put((lf_off[0] + 128) as u64, 8);+ lf_global.put((lf_off[1] + 128) as u64, 8);+ } else {+ lf_global.put(1, 1); // default colour correlation+ }lf_global.put(1, 1); // a global treetree.write(&mut lf_global);leaf_codes.write_header(&mut lf_global);@@ -253,7 +322,21 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninmodular::write_stream(&mut lf_group, &leaf_codes, &meta_tokens);let mut hf_global = BitWriter::new();- hf_global.put(1, 1); // default dequantization matrices+ if custom_bands {+ hf_global.put(0, 1);+ hf_global.put(6, 3); // the 8x8 DCT: a table made from distance bands+ hf_global.put(5, 4); // six bands+ for c in 0..3 {+ for i in 0..6 {+ hf_global.put(band_bits[c][i] as u64, 16);+ }+ }+ for _ in 1..17 {+ hf_global.put(0, 3); // every other transform keeps the library's table+ }+ } else {+ hf_global.put(1, 1); // default dequantization matrices+ }hf_global.put(0, ceil_log2(gw * gh)); // one set of histogramshf_global.put(2, 2); // the coefficient order is the natural oneac_codes.write_header(&mut hf_global);@@ -274,6 +357,14 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tunin.collect();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.bit_len() / 8,@@ -379,6 +470,10 @@ pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuninbytes}+fn grad() -> Box<T> {+ Box::new(T::Leaf(modular::PRED_GRADIENT))+}+/// 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]> {diff --git a/crates/rf-jxl/src/vardct.rs b/crates/rf-jxl/src/vardct.rsindex c853a4fc..f3fcd02c 100644--- a/crates/rf-jxl/src/vardct.rs+++ b/crates/rf-jxl/src/vardct.rs@@ -8,20 +8,19 @@ use std::sync::OnceLock;use crate::ans::Token;use crate::modular::{Chan, pack_signed};-pub const BLOCK: usize = 8;/// Blocks per group side (groups are 256 pixels).pub const GROUP_BLOCKS: usize = 32;/// How the decoder weighs the coefficients of the 8x8 DCT, X, Y and B (the "distance band" parameters of the/// default library table).-const DCT8_BANDS: [[f32; 6]; 3] = [+pub const DCT8_BANDS: [[f32; 6]; 3] = [[3150.0, 0.0, -0.4, -0.4, -0.4, -2.0],[560.0, 0.0, -0.3, -0.3, -0.3, -0.3],[512.0, -2.0, -1.0, 0.0, -1.0, -2.0],];/// The low-frequency image's quantization factors, X, Y, B.-const LF_QUANT: [f32; 3] = [1.0 / 4096.0, 1.0 / 512.0, 1.0 / 256.0];+pub const LF_QUANT: [f32; 3] = [1.0 / 4096.0, 1.0 / 512.0, 1.0 / 256.0];/// Where small quantized values land again (X, Y, B), and the pull toward zero of the bigger ones.const QUANT_BIAS: [f32; 3] = [1.0 - 0.05465007330715401, 1.0 - 0.07005449891748593, 1.0 - 0.049935103337343655];const QUANT_BIAS_NUM: f32 = 0.145;@@ -47,12 +46,38 @@ pub const NUM_AC_CONTEXTS: usize = NUM_BLOCK_CONTEXTS * (NON_ZERO_BUCKETS + ZEROstruct Tables {/// The order the coefficients are coded in: position k holds the raster index (y * 8 + x).order: [u8; 64],- /// 1 / (the decoder's weight), channel by channel (X, Y, B): the unscaled dequantization step.- weight: [[f32; 64]; 3],/// The forward DCT's matrix: row k is the k-th basis function, scaled so the DC is the mean.dct: [[f32; 8]; 8],}+/// 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];+ 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);+ }+ }+ }+ weight+}+fn tables() -> &'static Tables {static T: OnceLock<Tables> = OnceLock::new();T.get_or_init(|| {@@ -84,29 +109,6 @@ fn tables() -> &'static Tables {cur += 1;}}- // The weights: bands interpolated by the distance from the DC corner.- let mut weight = [[0f32; 64]; 3];- let mult = |v: f32| if v > 0.0 { 1.0 + v } else { 1.0 / (1.0 - v) };- for c in 0..3 {- let mut bands = [0f32; 17];- bands[0] = DCT8_BANDS[c][0];- for i in 1..6 {- bands[i] = bands[i - 1] * mult(DCT8_BANDS[c][i]);- }- let scale = 5.0 / (std::f32::consts::SQRT_2 + 1e-6);- let rcp = scale / 7.0;- for y in 0..8 {- for x in 0..8 {- let (dx, dy) = (x as f32 * rcp, y as f32 * rcp);- let d = (dx * dx + dy * dy).sqrt();- let idx = d.floor();- let frac = d - idx;- let idx = idx as usize;- let (a, b) = (bands[idx], bands[idx + 1]);- weight[c][y * 8 + x] = 1.0 / ((b / a).powf(frac) * a);- }- }- }let mut dct = [[0f32; 8]; 8];for (k, row) in dct.iter_mut().enumerate() {let s = if k == 0 { 1.0 } else { std::f64::consts::SQRT_2 };@@ -114,7 +116,7 @@ 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, weight, dct }+ Tables { order, dct }})}@@ -150,18 +152,18 @@ fn dct8x8(m: &[[f32; 8]; 8], src: &[f32], stride: usize, out: &mut [f32; 64]) {pub struct 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.pub quant_lf: u32,+ /// The low-frequency image's factors for X, Y and B as the decoder will have them.+ pub lf_quant: [f32; 3],+ /// 1 / weight of every coefficient, X, Y, B (see `dct8_weights`).+ pub weight: [[f32; 64]; 3],+ /// How much of Y the decoder adds to X and B: [X high freq, B high freq, X low freq, B low freq].+ pub cfl: [f32; 4],/// Rounding: values below `round_offset` of a step become zero, the rest round to nearest.pub round_offset: f32,pub x_qm_scale: u32,pub b_qm_scale: u32,- /// 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.@@ -197,28 +199,58 @@ pub fn analyze(planes: &[Vec<f32>; 3], bw: usize, bh: usize) -> Vec<[[f32; 64];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()];+/// 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 y = b[1][0] as f64;+ dyy += y * y;+ dyx += y * b[0][0] as f64;+ dyb += y * b[2][0] as f64;+ }+ let f = |num: f64, den: f64| if den > 1e-12 { (num / den).clamp(-3.9, 3.9) as f32 } else { 0.0 };+ [f(yx, yy), f(yb, yy), f(dyx, dyy), f(dyb, dyy)]+}++/// Per 64x64 pixel tile, how far (in 84ths) the factor of Y taken off X and B should be from `base`: the least squares+/// fit of the tile's high frequencies. Returns the tiles' (x, b) offsets, row by row.+pub fn fit_cfl_tiles(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, base: [f32; 2]) -> Vec<[i32; 2]> {+ let (tw, th) = (bw.div_ceil(8), bh.div_ceil(8));+ let mut sums = vec![[0f64; 3]; tw * th];+ 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;+ }+ }}- // 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+ sums.iter()+ .map(|s| {+ if s[0] < 1e-9 {+ return [0, 0];+ }+ let f = |num: f64, base: f32| (((num / s[0]) as f32 - base) * 84.0).round().clamp(-128.0, 127.0) as i32;+ [f(s[1], base[0]), f(s[2], base[1])]}).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();+pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], tile_cfl: &[[i32; 2]], q: &Quant) -> Blocks {+ let tw = bw.div_ceil(8);let dm = [(1.0f32 / 1.25).powf(q.x_qm_scale as f32 - 2.0),1.0,@@ -230,13 +262,13 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], q: &let mut step1 = [[0f32; 64]; 3];for c in 0..3 {for k in 0..64 {- step1[c][k] = t.weight[c][k] * dm[c] / unit;+ step1[c][k] = q.weight[c][k] * dm[c] / unit;inv_step1[c][k] = 1.0 / step1[c][k];}}// low-frequency stepslet inv_quant_lf = 65536.0 / (q.global_scale as f32 * q.quant_lf as f32);- let lf_fac = [LF_QUANT[0] * inv_quant_lf, LF_QUANT[1] * inv_quant_lf, LF_QUANT[2] * inv_quant_lf];+ let 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];@@ -251,8 +283,8 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], q: &// 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;+ 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;@@ -263,10 +295,13 @@ pub fn quantize(co: &[[[f32; 64]; 3]], bw: usize, bh: usize, quant: &[u16], q: &ac[bi][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 (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 qq = round(co[0][k] * inv_step1[0][k] * rq);+ 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;- let rb = co[2][k] - y_rec_ac[k];+ 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;}