From 27af778cde676ca0742daf0a4d1a4304264662fa Mon Sep 17 00:00:00 2001 From: Bruno Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:39:31 +0100 Subject: [PATCH 1/9] AI Defringe: run a user-installed defringe model, cache its correction, apply it in renders and exports --- crates/denoise/src/cpu.rs | 16 +- crates/denoise/src/defringe.rs | 432 ++++++++++++++ crates/denoise/src/defringe/tests.rs | 125 ++++ crates/denoise/src/lib.rs | 3 + crates/denoise/src/onnx.rs | 3 +- crates/denoise/src/synthetic.rs | 20 + crates/develop/src/controls.rs | 1 + crates/develop/src/lib.rs | 6 + crates/develop/src/settings.rs | 14 + crates/engine/src/aidefringe.rs | 788 ++++++++++++++++++++++++++ crates/engine/src/aidefringe/tests.rs | 73 +++ crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/aidefringe.rs | 142 +++++ crates/engine/src/import/job.rs | 1 + crates/engine/src/lib.rs | 4 + crates/engine/src/media/render.rs | 12 + crates/engine/src/media/session.rs | 13 +- crates/engine/src/tests.rs | 2 + crates/engine/src/tests/aidefringe.rs | 150 +++++ crates/pipeline/src/lib.rs | 15 + 20 files changed, 1812 insertions(+), 10 deletions(-) create mode 100644 crates/denoise/src/defringe.rs create mode 100644 crates/denoise/src/defringe/tests.rs create mode 100644 crates/engine/src/aidefringe.rs create mode 100644 crates/engine/src/aidefringe/tests.rs create mode 100644 crates/engine/src/cmd/aidefringe.rs create mode 100644 crates/engine/src/tests/aidefringe.rs diff --git a/crates/denoise/src/cpu.rs b/crates/denoise/src/cpu.rs index 34e5269e42..2dad1419ec 100644 --- a/crates/denoise/src/cpu.rs +++ b/crates/denoise/src/cpu.rs @@ -67,15 +67,17 @@ pub struct NetRunner { impl NetRunner { pub fn new(net: &Net, tile: usize) -> Result { - if tile == 0 - || tile > MAX_TILE - || !net.fits_tile(tile) - || net.in_channels != 4 - || net.out_channels() != 3 - || net.shape(0).is_none_or(|s| s.channels != net.in_channels) - { + if net.in_channels != 4 || net.out_channels() != 3 { return Err(bad("the tile or Bayer-to-RGB contract does not fit the network")); } + Self::for_tiles(net, tile) + } + + /// A runner for any channel counts (the caller checks the network's contract), on `tile × tile` inputs. + pub fn for_tiles(net: &Net, tile: usize) -> Result { + if tile == 0 || tile > MAX_TILE || !net.fits_tile(tile) || net.shape(0).is_none_or(|s| s.channels != net.in_channels) { + return Err(bad("the tile does not fit the network")); + } let mut last = vec![0; net.ops().len() + 1]; for (i, op) in net.ops().iter().enumerate() { let (a, b) = sources(op); diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs new file mode 100644 index 0000000000..cc7f21d7cb --- /dev/null +++ b/crates/denoise/src/defringe.rs @@ -0,0 +1,432 @@ +//! AI Defringe inference ([`Model`]): a defringe network run over a whole picture, and the fixed guards that turn +//! its output into a corrected picture (docs/ai-defringe.md). +//! +//! The picture is linear Rec.2020 at the Defringe stage, scaled so its brightest highlights are near 1, with a mask +//! of the pixels next to clipped highlights. The network sees it as 256 px tiles of five planes (OkLab L, a, b, log +//! luminance and the clip mask) folded space-to-depth into 20 half-resolution channels, and gives back three +//! full-resolution planes: a change to OkLab a and b, and a gate. Tiles overlap by 32 px and are blended with linear +//! ramps; tiles with no edge are skipped. Lightness is never changed. The change is applied only near edges, is +//! bounded by the pixel's own chroma, stops at grey instead of crossing it, may not make a pixel green that wasn't, +//! may not leave a pixel more colourful than its neighbourhood, and keeps only the part that moves the pixel toward +//! the colour around it. Pixels the change leaves alone keep their exact values. +//! +//! The picture is worked through in bands of rows, so memory stays bounded on large photos; the result is the same +//! as working on it whole. + +use crate::cpu::NetRunner; +use crate::net::{Net, NetError}; +use crate::run::{Error, TileRunner}; +use rayon::prelude::*; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// Side of a tile, in pixels (the network takes half of it). +pub const TILE: usize = 256; +/// Pixels neighbouring tiles share. +pub const OVERLAP: usize = 32; +/// Channels the network takes: five planes folded 2 × 2. +pub const IN_CHANNELS: usize = 20; +/// The largest change of OkLab chroma the network can ask for. +const DELTA_MAX: f32 = 0.15; +/// Rows worked on at a time. +const BAND: usize = 768; +/// Rows a band reads beyond its own: the guards' neighbourhoods (3 for the edge and chroma limits, 2 + 7 for the +/// pull toward the surrounding colour), rounded up. +const HALO: usize = 12; +/// Tiles run at once (each holds about 3 MB of input and output). +const BATCH: usize = 32; +/// A tile is worth running when its lightness changes this much within 7 × 7 pixels somewhere. +const EDGE: f32 = 0.05; +/// Pixels under this much change keep their exact values. +const MOVED: f32 = 1e-5; + +/// A loaded defringe network. +#[derive(Clone)] +pub struct Model { + runner: NetRunner, +} + +impl Model { + /// Check that `net` has the defringe contract (20 channels of 128 × 128 in, 3 of 256 × 256 out) and prepare it. + pub fn new(net: &Net) -> Result { + if net.in_channels != IN_CHANNELS || net.out_channels() != 3 { + return Err(NetError::Invalid(format!( + "a defringe model takes {IN_CHANNELS} channels and gives 3; this one takes {} and gives {}", + net.in_channels, + net.out_channels() + ))); + } + let runner = NetRunner::for_tiles(net, TILE / 2)?; + let m = Self { runner }; + let out = m.runner.run(&vec![0.0; IN_CHANNELS * (TILE / 2) * (TILE / 2)]).map_err(|e| NetError::Invalid(e.to_string()))?; + if out.len() != 3 * TILE * TILE { + return Err(NetError::Invalid("a defringe model must give its planes at twice its input's size".into())); + } + Ok(m) + } + + /// Memory one running tile needs. + pub fn bytes_per_tile(&self) -> usize { + self.runner.bytes_per_tile() + } + + /// The pixels `correct` changes in a `w × h` picture `rgb` (linear Rec.2020, row by row) with clip mask `clip`, + /// as (index, corrected colour), in index order. `progress` gets (tiles done, tiles in all); `cancel` stops it. + pub fn correct( + &self, + rgb: &[[f32; 3]], + clip: &[bool], + w: usize, + h: usize, + progress: &(dyn Fn(usize, usize) + Sync), + cancel: &AtomicBool, + ) -> Result, Error> { + if w == 0 || h == 0 || rgb.len() != w * h || clip.len() != w * h || u32::try_from(w * h).is_err() { + return Err(Error::Input("the picture and its clip mask don't match its size".into())); + } + if rgb.iter().any(|p| p.iter().any(|v| !v.is_finite())) { + return Err(Error::Input("the picture has non-finite values".into())); + } + let pic = Padded::new(rgb, clip, w, h); + let ys = grid(pic.h); + let xs = grid(pic.w); + let tiles: Vec<(usize, usize)> = ys.iter().flat_map(|&y| xs.iter().map(move |&x| (y, x))).collect(); + let wanted: Vec = tiles.par_iter().map(|&(y, x)| pic.has_edge(y, x)).collect(); + let bands: Vec<(usize, usize, usize, usize)> = (0..h) + .step_by(BAND) + .map(|r0| { + let r1 = (r0 + BAND).min(h); + (r0, r1, r0.saturating_sub(HALO), (r1 + HALO).min(h)) + }) + .collect(); + let runs = |e0: usize, e1: usize| -> Vec<(usize, usize)> { + tiles.iter().zip(&wanted).filter(|(t, on)| **on && t.0 < e1 && t.0 + TILE > e0).map(|(t, _)| *t).collect() + }; + let total: usize = bands.iter().map(|b| runs(b.2, b.3).len()).sum::().max(1); + let mut done = 0; + progress(0, total); + let ramp = ramp(); + let mut changed = Vec::new(); + for &(r0, r1, e0, e1) in &bands { + let rows = e1 - e0; + let mut acc = vec![[0f32; 3]; rows * w]; + let mut wsum = vec![0f32; rows * w]; + for batch in runs(e0, e1).chunks(BATCH) { + if cancel.load(Ordering::Relaxed) { + return Err(Error::Cancelled); + } + let outs: Vec> = batch.par_iter().map(|&(y, x)| self.runner.run(&pic.tile_input(y, x))).collect::>()?; + for (&(ty, tx), out) in batch.iter().zip(&outs) { + if out.len() != 3 * TILE * TILE { + return Err(Error::Model("planes of the wrong size".into())); + } + for yy in ty.max(e0)..(ty + TILE).min(e1) { + let wy = ramp[yy - ty]; + for xx in tx..(tx + TILE).min(w) { + let wt = wy * ramp[xx - tx]; + let o = (yy - ty) * TILE + (xx - tx); + let i = (yy - e0) * w + xx; + for (c, a) in acc[i].iter_mut().enumerate() { + *a += out[c * TILE * TILE + o] * wt; + } + wsum[i] += wt; + } + } + } + done += batch.len(); + progress(done, total); + } + let raw: Vec<[f32; 3]> = acc.iter().zip(&wsum).map(|(a, &s)| if s > 0.0 { a.map(|v| v / s.max(1e-6)) } else { [0.0, 0.0, -20.0] }).collect(); + band(rgb, w, h, (r0, r1, e0, e1), &raw, &mut changed); + } + progress(total, total); + Ok(changed) + } +} + +/// Tile positions along a side of `n` (at least [`TILE`]) pixels: every `TILE − OVERLAP`, and one flush with the end. +fn grid(n: usize) -> Vec { + let mut v: Vec = (0..n - TILE).step_by(TILE - OVERLAP).collect(); + v.push(n - TILE); + v +} + +/// A tile's blend weight along one side: rising over the first [`OVERLAP`] pixels, falling over the last. +fn ramp() -> [f32; TILE] { + let mut r = [1f32; TILE]; + for k in 0..OVERLAP { + let v = (k + 1) as f32 / (OVERLAP + 1) as f32; + r[k] = v; + r[TILE - 1 - k] = v; + } + r +} + +/// The picture, extended to at least one tile each way (colours repeated from the edge, no clip mask there). +struct Padded<'a> { + rgb: std::borrow::Cow<'a, [[f32; 3]]>, + clip: std::borrow::Cow<'a, [bool]>, + w: usize, + h: usize, +} + +impl<'a> Padded<'a> { + fn new(rgb: &'a [[f32; 3]], clip: &'a [bool], w: usize, h: usize) -> Self { + if w >= TILE && h >= TILE { + return Self { rgb: rgb.into(), clip: clip.into(), w, h }; + } + let (pw, ph) = (w.max(TILE), h.max(TILE)); + let mut prgb = Vec::with_capacity(pw * ph); + let mut pclip = Vec::with_capacity(pw * ph); + for y in 0..ph { + for x in 0..pw { + prgb.push(rgb[y.min(h - 1) * w + x.min(w - 1)]); + pclip.push(x < w && y < h && clip[y * w + x]); + } + } + Self { rgb: prgb.into(), clip: pclip.into(), w: pw, h: ph } + } + + /// Whether lightness changes by [`EDGE`] within 7 × 7 pixels somewhere in the tile at (`ty`, `tx`). + fn has_edge(&self, ty: usize, tx: usize) -> bool { + let (y0, x0) = (ty.saturating_sub(3), tx.saturating_sub(3)); + let (y1, x1) = ((ty + TILE + 3).min(self.h), (tx + TILE + 3).min(self.w)); + let (ww, hh) = (x1 - x0, y1 - y0); + let l: Vec = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (y, x))).map(|(y, x)| oklab(self.rgb[y * self.w + x])[0]).collect(); + let (hi, lo) = (max_filter(&l, ww, hh, 3), max_filter(&l.iter().map(|v| -v).collect::>(), ww, hh, 3)); + (ty - y0..ty - y0 + TILE).any(|y| (tx - x0..tx - x0 + TILE).any(|x| hi[y * ww + x] + lo[y * ww + x] >= EDGE)) + } + + /// The network's input for the tile at (`ty`, `tx`): its five planes folded 2 × 2 into 20 channels. + fn tile_input(&self, ty: usize, tx: usize) -> Vec { + const S: usize = TILE / 2; + let mut input = vec![0f32; IN_CHANNELS * S * S]; + for y in 0..TILE { + for x in 0..TILE { + let i = (ty + y) * self.w + tx + x; + let p = self.rgb[i]; + let lab = oklab(p); + let planes = [lab[0], lab[1], lab[2], log_luminance(p), f32::from(u8::from(self.clip[i]))]; + let (sub, at) = ((y % 2) * 2 + x % 2, (y / 2) * S + x / 2); + for (c, v) in planes.into_iter().enumerate() { + input[(c * 4 + sub) * S * S + at] = v; + } + } + } + input + } +} + +/// Compose rows `r0..r1` of the picture from the network's `raw` planes for rows `e0..e1` (the band and its halo), +/// adding the pixels that change to `changed`. +fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, usize, usize), raw: &[[f32; 3]], changed: &mut Vec<(u32, [f32; 3])>) { + // OkLab of rows e0 − 3 .. e1 + 3: the edge and chroma limits read 7 × 7 around each pixel + let (l0, l1) = (e0.saturating_sub(3), (e1 + 3).min(h)); + let lab: Vec<[f32; 3]> = rgb[l0 * w..l1 * w].par_iter().map(|&p| oklab(p)).collect(); + let lrows = l1 - l0; + let lp: Vec = lab.iter().map(|p| p[0]).collect(); + let chroma: Vec = lab.iter().map(|p| (p[1] * p[1] + p[2] * p[2] + 1e-12).sqrt()).collect(); + let l_hi = max_filter(&lp, w, lrows, 3); + let l_lo = max_filter(&lp.iter().map(|v| -v).collect::>(), w, lrows, 3); + let c_hi = max_filter(&chroma, w, lrows, 3); + let rows = e1 - e0; + // the guarded change, for rows e0..e1 + let ab: Vec<[f32; 2]> = (0..rows * w).map(|i| { + let j = (i / w + e0 - l0) * w + i % w; + [lab[j][1], lab[j][2]] + }).collect(); + let new: Vec<[f32; 2]> = (0..rows * w) + .into_par_iter() + .map(|i| { + let j = (i / w + e0 - l0) * w + i % w; + compose(ab[i], chroma[j], l_hi[j] + l_lo[j], c_hi[j], raw[i]) + }) + .collect(); + let moved: Vec = ab.iter().zip(&new).map(|(a, n)| f32::from(u8::from(dist(*a, *n) > 1e-4))).collect(); + let keep: Vec = max_filter(&moved, w, rows, 2).iter().map(|v| 1.0 - v).collect(); + let keep_a: Vec = ab.iter().zip(&keep).map(|(a, k)| a[0] * k).collect(); + let keep_b: Vec = ab.iter().zip(&keep).map(|(a, k)| a[1] * k).collect(); + let (den, num_a, num_b) = (box_sum(&keep, w, rows, 7), box_sum(&keep_a, w, rows, 7), box_sum(&keep_b, w, rows, 7)); + let out: Vec> = (r0 * w..r1 * w) + .into_par_iter() + .map(|g| { + let i = g - e0 * w; + let (y, x) = (i / w, i % w); + let n = ((y + 7).min(rows - 1) - y.saturating_sub(7) + 1) * ((x + 7).min(w - 1) - x.saturating_sub(7) + 1); + let a = ab[i]; + let mut nab = new[i]; + if moved[i] > 0.0 { + // toward the mean colour of the untouched pixels around, at most up to it + let bg = if den[i] / n as f32 > 1e-3 { [num_a[i] / den[i], num_b[i] / den[i]] } else { [0.0, 0.0] }; + let (d, to) = ([nab[0] - a[0], nab[1] - a[1]], [bg[0] - a[0], bg[1] - a[1]]); + let t = ((d[0] * to[0] + d[1] * to[1]) / (to[0] * to[0] + to[1] * to[1]).max(1e-8)).clamp(0.0, 1.0); + nab = [a[0] + t * to[0], a[1] + t * to[1]]; + } + if dist(a, nab) <= MOVED { + return None; + } + let l = lab[(y + e0 - l0) * w + x][0]; + Some((g as u32, lab_to_rgb([l, nab[0], nab[1]]).map(|v| v.max(0.0)))) + }) + .collect(); + changed.extend(out.into_iter().flatten()); +} + +fn dist(a: [f32; 2], b: [f32; 2]) -> f32 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt() +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn green(ab: [f32; 2], c: f32) -> bool { + let hue = ab[1].atan2(ab[0]).to_degrees().rem_euclid(360.0); + c > 0.01 && (100.0..=170.0).contains(&hue) +} + +/// The new OkLab (a, b) of a pixel with colour `ab` and chroma `c`, its 7 × 7 lightness range `range` and highest +/// chroma `c_hi`, from the network's (Δa, Δb, gate) `raw`. +fn compose(ab: [f32; 2], c: f32, range: f32, c_hi: f32, raw: [f32; 3]) -> [f32; 2] { + let near_edge = smoothstep(0.05, 0.20, range); + let gate = 1.0 / (1.0 + (-raw[2]).exp()); + let k = near_edge * gate * DELTA_MAX; + let mut d = [k * raw[0].tanh(), k * raw[1].tanh()]; + // no larger than the pixel's own chroma (plus a little) + let dn = (d[0] * d[0] + d[1] * d[1] + 1e-12).sqrt(); + let s = ((c + 0.01) / dn).min(1.0); + d = [d[0] * s, d[1] * s]; + // to grey, not past it + let against = -(d[0] * ab[0] + d[1] * ab[1]); + if against > 0.0 { + let t = (c * c / against.max(1e-12)).min(1.0); + d = [d[0] * t, d[1] * t]; + } + let mut new = [ab[0] + d[0], ab[1] + d[1]]; + // not green unless it was + let cn = (new[0] * new[0] + new[1] * new[1] + 1e-12).sqrt(); + if green(new, cn) && !green(ab, c) { + let s = (0.01 / cn).min(1.0); + new = [new[0] * s, new[1] * s]; + } + // no more colourful than the neighbourhood + let cn = (new[0] * new[0] + new[1] * new[1] + 1e-12).sqrt(); + let s = (c_hi * 1.2 / cn).min(1.0); + [new[0] * s, new[1] * s] +} + +/// The largest value within `r` pixels (a (2r + 1)² square, inside the picture) of each pixel of a `w × h` plane. +fn max_filter(v: &[f32], w: usize, h: usize, r: usize) -> Vec { + let mut rows = vec![0f32; w * h]; + for y in 0..h { + let line = &v[y * w..(y + 1) * w]; + for x in 0..w { + rows[y * w + x] = line[x.saturating_sub(r)..(x + r + 1).min(w)].iter().copied().fold(f32::NEG_INFINITY, f32::max); + } + } + let mut out = vec![0f32; w * h]; + for y in 0..h { + for x in 0..w { + out[y * w + x] = (y.saturating_sub(r)..(y + r + 1).min(h)).map(|yy| rows[yy * w + x]).fold(f32::NEG_INFINITY, f32::max); + } + } + out +} + +/// The sum within `r` pixels (inside the picture) of each pixel of a `w × h` plane. +fn box_sum(v: &[f32], w: usize, h: usize, r: usize) -> Vec { + let mut rows = vec![0f32; w * h]; + for y in 0..h { + let mut run = 0f64; + let mut prefix = vec![0f64; w + 1]; + for x in 0..w { + run += f64::from(v[y * w + x]); + prefix[x + 1] = run; + } + for x in 0..w { + rows[y * w + x] = (prefix[(x + r + 1).min(w)] - prefix[x.saturating_sub(r)]) as f32; + } + } + let mut out = vec![0f32; w * h]; + let mut prefix = vec![0f64; (h + 1) * w]; + for y in 0..h { + for x in 0..w { + prefix[(y + 1) * w + x] = prefix[y * w + x] + f64::from(rows[y * w + x]); + } + } + for y in 0..h { + let (a, b) = (y.saturating_sub(r), (y + r + 1).min(h)); + for x in 0..w { + out[y * w + x] = (prefix[b * w + x] - prefix[a * w + x]) as f32; + } + } + out +} + +const REC2020_TO_709: [[f32; 3]; 3] = [[1.6605, -0.5876, -0.0728], [-0.1246, 1.1329, -0.0083], [-0.0182, -0.1006, 1.1187]]; +const M1: [[f32; 3]; 3] = [[0.412_221_47, 0.536_332_55, 0.051_445_995], [0.211_903_5, 0.680_699_5, 0.107_396_96], [0.088_302_46, 0.281_718_85, 0.629_978_7]]; +const M2: [[f32; 3]; 3] = [[0.210_454_26, 0.793_617_8, -0.004_072_047], [1.977_998_5, -2.428_592_2, 0.450_593_7], [0.025_904_037, 0.782_771_77, -0.808_675_77]]; + +fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { + [0, 1, 2].map(|r| m[r][0] * v[0] + m[r][1] * v[1] + m[r][2] * v[2]) +} + +fn inverse(m: &[[f32; 3]; 3]) -> [[f32; 3]; 3] { + let m = m.map(|r| r.map(f64::from)); + let det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); + let c = |r: usize, k: usize| { + let (r1, r2, k1, k2) = ((r + 1) % 3, (r + 2) % 3, (k + 1) % 3, (k + 2) % 3); + m[r1][k1] * m[r2][k2] - m[r1][k2] * m[r2][k1] + }; + [0, 1, 2].map(|i| [0, 1, 2].map(|j| (c(j, i) / det) as f32)) +} + +/// Linear Rec.2020 → OkLab (by way of linear Rec.709, negative values clamped first). +pub fn oklab(p: [f32; 3]) -> [f32; 3] { + let x = mul(&REC2020_TO_709, p.map(|v| v.max(0.0))).map(|v| v.max(0.0)); + mul(&M2, mul(&M1, x).map(|v| v.max(1e-9).cbrt())) +} + +/// OkLab → linear Rec.2020, the inverse of [`oklab`]. +pub fn lab_to_rgb(lab: [f32; 3]) -> [f32; 3] { + use std::sync::OnceLock; + static INV: OnceLock<[[[f32; 3]; 3]; 3]> = OnceLock::new(); + let [m2i, m1i, ri] = INV.get_or_init(|| [inverse(&M2), inverse(&M1), inverse(&REC2020_TO_709)]); + mul(ri, mul(m1i, mul(m2i, lab).map(|v| v * v * v))) +} + +/// The luminance plane the network reads: log2 of Rec.2020 luminance, over 12. +fn log_luminance(p: [f32; 3]) -> f32 { + let y = 0.2627 * p[0] + 0.6780 * p[1] + 0.0593 * p[2]; + (y.max(0.0) + 2f32.powi(-12)).log2() / 12.0 +} + +/// The clip mask a defringe model reads, for a `w × h` picture: pixels whose 5 × 5 mean of the brightest channel is +/// within 7 % of `top`. +pub fn clip_mask(rgb: &[[f32; 3]], w: usize, h: usize, top: f32) -> Vec { + let m: Vec = rgb.iter().map(|p| p[0].max(p[1]).max(p[2])).collect(); + box_sum(&m, w, h, 2) + .iter() + .enumerate() + .map(|(i, s)| { + let (x, y) = (i % w, i / w); + let n = ((x + 2).min(w - 1) - x.saturating_sub(2) + 1) * ((y + 2).min(h - 1) - y.saturating_sub(2) + 1); + s / n as f32 >= 0.93 * top + }) + .collect() +} + +/// The 99.9th percentile of the brightest channel (over every third pixel): the value a picture is divided by so +/// its highlights sit near 1, as the model was trained. +pub fn top(rgb: &[[f32; 3]]) -> f32 { + let mut v: Vec = rgb.iter().step_by(3).map(|p| p[0].max(p[1]).max(p[2])).filter(|v| v.is_finite()).collect(); + if v.is_empty() { + return 1.0; + } + let k = ((v.len() - 1) as f64 * 0.999) as usize; + v.select_nth_unstable_by(k, f32::total_cmp).1.max(1e-6) +} + +#[cfg(test)] +mod tests; diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs new file mode 100644 index 0000000000..250bb26c0c --- /dev/null +++ b/crates/denoise/src/defringe/tests.rs @@ -0,0 +1,125 @@ +use super::*; + +fn model(out: [f32; 3]) -> Model { + Model::new(&crate::onnx::read_bytes(&crate::synthetic::defringe_onnx(out)).unwrap()).unwrap() +} + +/// A grey picture with a white block on the left whose right edge has a 2 px purple fringe, the same on every row. +fn fringed(w: usize, h: usize) -> (Vec<[f32; 3]>, Vec) { + let px = |x: usize| match x { + 0..100 => [1.0, 1.0, 1.0], + 100..102 => [0.45, 0.08, 0.6], + _ => [0.18, 0.18, 0.18], + }; + let rgb: Vec<[f32; 3]> = (0..w * h).map(|i| px(i % w)).collect(); + let clip = vec![false; w * h]; + (rgb, clip) +} + +fn chroma(p: [f32; 3]) -> f32 { + let l = oklab(p); + (l[1] * l[1] + l[2] * l[2]).sqrt() +} + +fn run(m: &Model, rgb: &[[f32; 3]], clip: &[bool], w: usize, h: usize) -> Vec<(u32, [f32; 3])> { + m.correct(rgb, clip, w, h, &|_, _| {}, &AtomicBool::new(false)).unwrap() +} + +#[test] +fn a_network_that_asks_for_nothing_changes_nothing() { + let (rgb, clip) = fringed(300, 280); + assert!(run(&model([0.0, 0.0, 0.0]), &rgb, &clip, 300, 280).is_empty()); + assert!(run(&model([5.0, -5.0, -20.0]), &rgb, &clip, 300, 280).is_empty()); +} + +#[test] +fn a_purple_fringe_is_taken_toward_the_grey_around_it_and_nothing_else_moves() { + let (w, h) = (300, 280); + let (rgb, clip) = fringed(w, h); + // purple is +a −b in OkLab: push the other way, everywhere, at full gate + let changed = run(&model([-3.0, 3.0, 10.0]), &rgb, &clip, w, h); + assert!(!changed.is_empty()); + for &(i, p) in &changed { + let (x, i) = (i as usize % w, i as usize); + assert!((100..102).contains(&x), "pixel at x = {x} changed"); + assert!(chroma(p) < chroma(rgb[i]) * 0.9, "{:?} → {p:?}", rgb[i]); + assert!((oklab(p)[0] - oklab(rgb[i])[0]).abs() < 1e-4, "lightness changed"); + } + // every fringe pixel away from the picture's corners + assert_eq!(changed.len(), 2 * h); +} + +#[test] +fn bands_and_tiles_leave_no_seams() { + // taller than a band and wider than a tile: every row is the same, so every row's change must be too + let (w, h) = (300, 2 * BAND + 50); + let (rgb, clip) = fringed(w, h); + let changed = run(&model([-3.0, 3.0, 10.0]), &rgb, &clip, w, h); + let mut rows: Vec> = vec![Vec::new(); h]; + for &(i, p) in &changed { + rows[i as usize / w].push((i as usize % w, p)); + } + for (y, r) in rows.iter().enumerate() { + assert_eq!(r.len(), 2, "row {y}"); + for (a, b) in r.iter().zip(&rows[0]) { + assert_eq!(a.0, b.0); + assert!(a.1.iter().zip(&b.1).all(|(u, v)| (u - v).abs() < 1e-5), "row {y}: {a:?} against {b:?}"); + } + } +} + +#[test] +fn small_pictures_are_padded() { + let (rgb, clip) = fringed(150, 40); + let changed = run(&model([-3.0, 3.0, 10.0]), &rgb, &clip, 150, 40); + assert_eq!(changed.len(), 2 * 40); +} + +#[test] +fn a_correction_stops_at_grey_and_does_not_make_green() { + // a huge push against the pixel's own colour ends at grey, not past it + let ab = [0.05, -0.05]; + let c = (ab[0] * ab[0] + ab[1] * ab[1] as f32).sqrt(); + let new = compose(ab, c, 1.0, c, [-20.0, 20.0, 20.0]); + assert!(new[0] >= -1e-6 && new[1] <= 1e-6, "{new:?}"); + // a push across into green on a grey-ish pixel stays under 0.01 of green chroma + let ab = [0.0, 0.0]; + let new = compose(ab, 0.0, 1.0, 0.2, [-20.0, 5.0, 20.0]); + let cn = (new[0] * new[0] + new[1] * new[1]).sqrt(); + assert!(cn <= 0.0101, "{new:?}"); + // flat areas are never touched + assert_eq!(compose([0.03, 0.02], 0.036, 0.0, 0.05, [-5.0, -5.0, 20.0]), [0.03, 0.02]); +} + +#[test] +fn oklab_round_trips() { + // (colours inside Rec.709: the conversion clamps below it, as the model was trained) + for p in [[0.18, 0.18, 0.18], [0.6, 0.3, 0.4], [0.3, 0.5, 0.25], [1.0, 1.0, 1.0]] { + let back = lab_to_rgb(oklab(p)); + for (a, b) in p.iter().zip(&back) { + assert!((a - b).abs() < 1e-4, "{p:?} → {back:?}"); + } + } +} + +#[test] +fn the_wrong_shape_of_network_is_refused() { + let denoiser = crate::onnx::read_bytes(&crate::synthetic::smoothing_onnx()).unwrap(); + assert!(Model::new(&denoiser).is_err()); +} + +#[test] +fn cancelling_stops_the_run() { + let (rgb, clip) = fringed(300, 280); + let r = model([0.0, 0.0, 0.0]).correct(&rgb, &clip, 300, 280, &|_, _| {}, &AtomicBool::new(true)); + assert!(matches!(r, Err(Error::Cancelled))); +} + +#[test] +fn the_clip_mask_marks_the_brightest_pixels() { + let (rgb, _) = fringed(300, 20); + let t = top(&rgb); + assert!((t - 1.0).abs() < 1e-6); + let mask = clip_mask(&rgb, 300, 20, t); + assert!(mask[10 * 300 + 50] && !mask[10 * 300 + 200] && !mask[10 * 300 + 98]); +} diff --git a/crates/denoise/src/lib.rs b/crates/denoise/src/lib.rs index f9005c7d55..bbce01961b 100644 --- a/crates/denoise/src/lib.rs +++ b/crates/denoise/src/lib.rs @@ -11,6 +11,7 @@ //! - [`product`]: the cache file the denoised picture is kept in (half floats, compressed in strips) and the //! blend with the plain demosaic that the Amount slider controls. //! - [`cpu`] and [`runtime`]: a single-thread pure-Rust CPU runner and its installation self-test. +//! - [`defringe`]: AI Defringe, a defringe network run over a whole picture with its guards. //! - [`net`] and [`onnx`]: checked plain network data and bounded ONNX decoding, shared by CPU and GPU. //! - [`remote`]: running tiles on another computer's graphics card over TCP (a [`run::TileRunner`] and its server). //! @@ -21,6 +22,8 @@ #[cfg(feature = "runtime")] pub mod cpu; +#[cfg(feature = "runtime")] +pub mod defringe; pub mod net; pub mod onnx; diff --git a/crates/denoise/src/onnx.rs b/crates/denoise/src/onnx.rs index 074963695f..b2944b8156 100644 --- a/crates/denoise/src/onnx.rs +++ b/crates/denoise/src/onnx.rs @@ -34,7 +34,8 @@ pub fn read(path: &Path) -> Result { read_bytes(&bytes) } -fn read_bytes(bytes: &[u8]) -> Result { +/// Read a model from its bytes. +pub fn read_bytes(bytes: &[u8]) -> Result { let graph = onnx_proto::decode(bytes)?; let initialisers: HashMap<&str, &TensorProto> = graph.initializer.iter().map(|t| (t.name.as_str(), t)).collect(); diff --git a/crates/denoise/src/synthetic.rs b/crates/denoise/src/synthetic.rs index 8ceafca770..e463f4f888 100644 --- a/crates/denoise/src/synthetic.rs +++ b/crates/denoise/src/synthetic.rs @@ -232,3 +232,23 @@ pub fn smoothing_onnx() -> Vec { len_field(8, &ops, &mut model); model } + +/// A defringe-shaped network as ONNX bytes: `[1, 20, 128, 128]` → `[1, 3, 256, 256]`, giving the same `(Δa, Δb, +/// gate)` everywhere (a 1 × 1 convolution with no weights and these biases, then depth-to-space). +pub fn defringe_onnx(out: [f32; 3]) -> Vec { + let mut graph = Vec::new(); + len_field(1, &node("Conv", &["data", "weights", "bias"], "planes", &[("kernel_shape", A::Ints(&[1, 1]))]), &mut graph); + len_field(1, &node("DepthToSpace", &["planes"], "delta_gate", &[("blocksize", A::Int(2)), ("mode", A::Str("CRD"))]), &mut graph); + len_field(5, &tensor("weights", &[12, 20, 1, 1], &[0.0; 12 * 20]), &mut graph); + let bias: Vec = (0..12).map(|i| out[i / 4]).collect(); + len_field(5, &tensor("bias", &[12], &bias), &mut graph); + len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(20), Ok(128), Ok(128)]), &mut graph); + len_field(12, &value_info_bytes("delta_gate", 1, &[Ok(1), Ok(3), Ok(256), Ok(256)]), &mut graph); + let mut model = Vec::new(); + varint_field(1, 8, &mut model); + len_field(7, &graph, &mut model); + let mut ops = Vec::new(); + varint_field(2, 13, &mut ops); + len_field(8, &ops, &mut model); + model +} diff --git a/crates/develop/src/controls.rs b/crates/develop/src/controls.rs index d3447c2348..73ade3b111 100644 --- a/crates/develop/src/controls.rs +++ b/crates/develop/src/controls.rs @@ -273,6 +273,7 @@ controls! { "optics.vignettingMidpoint" => optics.vignetting_midpoint, "Midpoint", Optics, 0, 100, 50, 1, 0, Plain; "optics.profileDistortion" => optics.profile_distortion, "Profile Distortion", Optics, 0, 200, 100, 1, 0, Plain; "optics.profileVignetting" => optics.profile_vignetting, "Profile Vignetting", Optics, 0, 200, 100, 1, 0, Plain; + "optics.aiDefringe" => optics.ai_defringe, "Amount", Optics, 0, 100, 0, 1, 0, Plain; "optics.defringePurple" => optics.defringe_purple_amount, "Purple Amount", Optics, 0, 20, 0, 1, 0, Gradient { from: "#7a7a7a", to: "#a040d0" }; "optics.defringePurpleHueLo" => optics.defringe_purple_hue_lo, "Purple Hue Low", Optics, 0, 90, 30, 1, 0, Gradient { from: "#6040e0", to: "#d040b0" }; "optics.defringePurpleHueHi" => optics.defringe_purple_hue_hi, "Purple Hue High", Optics, 10, 100, 70, 1, 0, Gradient { from: "#6040e0", to: "#d040b0" }; diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 0e90df716a..55c87056c6 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -167,6 +167,12 @@ impl DevelopSettings { if a.is_finite() && self.enhance.denoise_enabled() && self.section_enabled("detail") { (a / 100.0).clamp(0.0, 1.0) as f32 } else { 0.0 } } + /// How much of AI Defringe's correction a render uses, 0..1 (0 when it is off or Optics is disabled). + pub fn ai_defringe_amount(&self) -> f32 { + let a = self.optics.ai_defringe; + if a.is_finite() && self.optics.ai_defringe_enabled() && self.section_enabled("optics") { (a / 100.0).clamp(0.0, 1.0) as f32 } else { 0.0 } + } + pub fn set_section_enabled(&mut self, section: &str, on: bool) { self.disabled_sections.retain(|s| s != section); if !on { diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index a4e6eab147..ad6607b265 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -697,6 +697,18 @@ pub struct Optics { /// automatic estimate when `remove_ca` is on. pub ca_red: f64, pub ca_blue: f64, + /// AI Defringe's Amount, 0..100 (docs/ai-defringe.md). + #[serde(skip_serializing_if = "is_zero")] + pub ai_defringe: f64, + /// Whether AI Defringe is on (`None`: on when its Amount is above 0). + #[serde(skip_serializing_if = "Option::is_none")] + pub ai_defringe_on: Option, +} + +impl Optics { + pub fn ai_defringe_enabled(&self) -> bool { + self.ai_defringe_on.unwrap_or(self.ai_defringe > 0.0) + } } impl Default for Optics { @@ -717,6 +729,8 @@ impl Default for Optics { vignetting_midpoint: 50.0, ca_red: 0.0, ca_blue: 0.0, + ai_defringe: 0.0, + ai_defringe_on: None, } } } diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs new file mode 100644 index 0000000000..db4fd979c9 --- /dev/null +++ b/crates/engine/src/aidefringe.rs @@ -0,0 +1,788 @@ +//! AI Defringe, the session's side (docs/ai-defringe.md): the model the user installed, the correction each photo +//! gets from it, and making the missing ones in the background. +//! +//! A photo's correction is *cached data*: the model reads the picture at the Defringe stage (the full-size source with +//! the default develop settings, so the edit never makes it again), and what it changes is kept as a per-pixel, +//! per-channel gain on the source picture, only for the pixels it changes. It is kept in +//! `/ai-defringe/.lcadf`, named by a hash of the photo's content, the model file and this algorithm's +//! version. A render multiplies the source picture by it, scaled by the Amount, before the develop pipeline; a +//! render smaller than the source takes the mean gain over each of its pixels. +//! +//! What runs where: the session thread decides (which photo, which model) and keeps the corrections in memory. One +//! background thread at a time decodes a photo and runs the model ([`Recipe::make`]). An export that finds its +//! photo's correction missing makes it itself, on its own thread, so it never comes out without the correction it +//! was asked for. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; +use std::sync::{Arc, Mutex, PoisonError}; + +use lightcraft_catalog::{Photo, PhotoId}; +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::SourceInfo; +use lightcraft_preview::Hasher128; +use lightcraft_raster::Rgb32f; +use serde::{Deserialize, Serialize}; + +use crate::Session; +use crate::media::{SourceLevel, SourceRef}; + +/// The composition and the correction's form; a change makes every correction again. +const VERSION: &str = "ai-defringe-1"; +/// The manifest that describes a defringe model, beside its ONNX file. +pub const MANIFEST: &str = "defringe-model.json"; +/// What a model must say it does: [`lightcraft_denoise::defringe`]'s planes in, (Δa, Δb, gate) out. +pub const CONTRACT: &str = "lightcraftDefringe1"; +/// The folder corrections are kept in, inside the library's folder. +const DIR: &str = "ai-defringe"; +/// Corrections kept in memory (each is a few megabytes: only the pixels it changes). +const IN_MEMORY: usize = 24; +/// The largest model file accepted. +const MAX_MODEL_BYTES: u64 = 256 << 20; + +/// What a defringe model is and whose it is, from the `defringe-model.json` beside its file (untrusted). +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Manifest { + pub id: String, + pub name: String, + pub version: String, + /// The licence the weights are under, as the model's author states it. + pub licence: String, + /// The ONNX file, beside the manifest. + pub file: String, + pub sha256: String, + pub contract: String, + /// Anything the user should know before using it (training data, terms). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notice: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl Manifest { + pub fn parse(text: &str) -> Result { + if text.len() > 64 * 1024 { + return Err(format!("{MANIFEST} is too large")); + } + let m: Manifest = serde_json::from_str(text).map_err(|e| format!("{MANIFEST}: {e}"))?; + let short = |name: &str, v: &str, max: usize| -> Result<(), String> { + if v.trim().is_empty() || v.len() > max || v.chars().any(char::is_control) { + return Err(format!("{MANIFEST}: `{name}` must be 1 to {max} characters of text")); + } + Ok(()) + }; + short("id", &m.id, 64)?; + if !m.id.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) { + return Err(format!("{MANIFEST}: `id` may only use letters, digits, '-', '_' and '.'")); + } + short("name", &m.name, 120)?; + short("version", &m.version, 40)?; + short("licence", &m.licence, 200)?; + short("file", &m.file, 120)?; + if m.file.contains(['/', '\\']) || m.file.starts_with('.') || !m.file.to_ascii_lowercase().ends_with(".onnx") { + return Err(format!("{MANIFEST}: `file` must be the name of an .onnx file beside it")); + } + if m.sha256.len() != 64 || !m.sha256.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(format!("{MANIFEST}: `sha256` must be 64 hexadecimal digits")); + } + if m.contract != CONTRACT { + return Err(format!("{MANIFEST}: this LightCraft runs defringe models of contract `{CONTRACT}`, not `{}`", m.contract)); + } + if let Some(n) = &m.notice + && n.len() > 4000 + { + return Err(format!("{MANIFEST}: `notice` is too long")); + } + if let Some(u) = &m.url { + short("url", u, 400)?; + } + Ok(Manifest { sha256: m.sha256.to_ascii_lowercase(), ..m }) + } +} + +/// Whether this build can run defringe models. +pub fn runtime_available() -> bool { + cfg!(feature = "denoise") +} + +/// The folder the installed model is kept in: `$LIGHTCRAFT_DEFRINGE_MODELS` if set, else `/defringe-models`. +pub fn models_dir() -> Option { + std::env::var_os("LIGHTCRAFT_DEFRINGE_MODELS") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| crate::config::config_dir().map(|d| d.join("defringe-models"))) +} + +/// The model installed in `dir`: its manifest and file, if there is one. +pub fn installed(dir: &Path) -> Option<(Manifest, PathBuf)> { + let m = Manifest::parse(&std::fs::read_to_string(dir.join(MANIFEST)).ok()?).ok()?; + let file = dir.join(&m.file); + file.is_file().then_some((m, file)) +} + +/// The manifest beside model file `onnx`, checked, without reading the model. +pub fn inspect(onnx: &Path) -> Result { + let dir = onnx.parent().ok_or("the model file has no folder")?; + let text = std::fs::read_to_string(dir.join(MANIFEST)).map_err(|e| format!("{MANIFEST} beside the model: {e}"))?; + let m = Manifest::parse(&text)?; + if onnx.file_name().and_then(|n| n.to_str()) != Some(m.file.as_str()) { + return Err(format!("{MANIFEST} describes `{}`, not this file", m.file)); + } + Ok(m) +} + +fn read_model_file(path: &Path, m: &Manifest) -> Result, String> { + let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len(); + if len > MAX_MODEL_BYTES { + return Err("the model file is too large".into()); + } + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + if lightcraft_denoise_core::hash::sha256_hex(&bytes) != m.sha256 { + return Err("the model file's SHA-256 is not the one its manifest gives".into()); + } + Ok(bytes) +} + +/// Install the model `onnx` (with its manifest beside it) in `dir`, after checking its hash and running it once: it +/// replaces the installed one. The caller has shown the user the manifest's licence and notice. +pub fn install(onnx: &Path, dir: &Path) -> Result { + let m = inspect(onnx)?; + let bytes = read_model_file(onnx, &m)?; + self_test(&bytes)?; + let parent = dir.parent().ok_or("the defringe models folder has no parent")?; + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let staging = parent.join(format!(".defringe-models-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; + let write = || -> std::io::Result<()> { + std::fs::write(staging.join(&m.file), &bytes)?; + std::fs::write(staging.join(MANIFEST), serde_json::to_vec_pretty(&m).unwrap_or_default()) + }; + if let Err(e) = write() { + let _ = std::fs::remove_dir_all(&staging); + return Err(e.to_string()); + } + let old = parent.join(format!(".defringe-models-old-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&old); + if dir.exists() { + std::fs::rename(dir, &old).map_err(|e| e.to_string())?; + } + if let Err(e) = std::fs::rename(&staging, dir) { + let _ = std::fs::rename(&old, dir); + return Err(e.to_string()); + } + let _ = std::fs::remove_dir_all(&old); + Ok(m) +} + +/// Delete the model installed in `dir` (corrections already made stay until the cache is cleared). +pub fn remove(dir: &Path) -> Result { + if !dir.exists() { + return Ok(false); + } + std::fs::remove_dir_all(dir).map_err(|e| e.to_string())?; + Ok(true) +} + +#[cfg(feature = "denoise")] +pub type Model = lightcraft_denoise::defringe::Model; + +/// A stand-in in builds without the model runtime: nothing can be loaded. +#[cfg(not(feature = "denoise"))] +pub struct Model; + +#[cfg(feature = "denoise")] +fn load_model(bytes: &[u8]) -> Result { + let net = lightcraft_denoise::onnx::read_bytes(bytes).map_err(|e| e.to_string())?; + Model::new(&net).map_err(|e| e.to_string()) +} + +#[cfg(not(feature = "denoise"))] +fn load_model(_: &[u8]) -> Result { + Err("this build of LightCraft can't run AI models".into()) +} + +/// Load the model and check it on a synthetic fringe: it runs, gives finite colours, gives the same answer twice +/// and keeps lightness. +#[cfg(feature = "denoise")] +fn self_test(bytes: &[u8]) -> Result<(), String> { + let model = load_model(bytes)?; + let (w, h) = (300, 260); + let rgb: Vec<[f32; 3]> = (0..w * h) + .map(|i| match i % w { + 0..120 => [1.0, 1.0, 1.0], + 120..122 => [0.45, 0.08, 0.6], + _ => [0.18, 0.18, 0.18], + }) + .collect(); + let clip = vec![false; w * h]; + let run = || model.correct(&rgb, &clip, w, h, &|_, _| {}, &AtomicBool::new(false)).map_err(|e| e.to_string()); + let (a, b) = (run()?, run()?); + if a != b { + return Err("the model gives different answers to the same picture".into()); + } + for (i, p) in &a { + let old = rgb.get(*i as usize).copied().unwrap_or_default(); + let (l0, l1) = (lightcraft_denoise::defringe::oklab(old)[0], lightcraft_denoise::defringe::oklab(*p)[0]); + if !p.iter().all(|v| v.is_finite()) || (l0 - l1).abs() > 1e-3 { + return Err("the model's correction changes lightness or isn't finite".into()); + } + } + Ok(()) +} + +#[cfg(not(feature = "denoise"))] +fn self_test(bytes: &[u8]) -> Result<(), String> { + load_model(bytes).map(|_| ()) +} + +/// A photo's correction: for the pixels the model changed, how much each channel of the source picture is +/// multiplied by (minus 1, as half floats). +pub struct Correction { + pub key: u64, + w: usize, + h: usize, + index: Vec, + gain: Vec<[u16; 3]>, + /// The last source it was applied to (address and size) at an amount (thousandths), and the result: renders of + /// one view reuse the corrected picture, so the stage cache keeps working while sliders move. + memo: Mutex)>>, +} + +impl Correction { + pub fn changed(&self) -> usize { + self.index.len() + } + + /// `src` with the correction applied at `amount` (0..1). A source smaller than the correction gets, for each of + /// its pixels, the mean gain over the pixels of the correction it covers. + pub fn apply(&self, src: &Arc, amount: f32) -> Arc { + if amount.is_nan() || amount <= 0.0 || self.index.is_empty() || src.width == 0 || src.height == 0 { + return src.clone(); + } + let k = amount.min(1.0); + let tag = (Arc::as_ptr(src) as usize, src.width, src.height, (k * 1000.0).round() as u32); + let mut memo = self.memo.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((t, img)) = memo.as_ref() + && *t == tag + { + return img.clone(); + } + let (w, h) = (src.width, src.height); + let mut out = (**src).clone(); + if (w, h) == (self.w, self.h) { + for (&i, g) in self.index.iter().zip(&self.gain) { + if let Some(p) = out.data.get_mut(i as usize) { + for (v, &d) in p.iter_mut().zip(g) { + *v *= 1.0 + f16_value(d) * k; + } + } + } + } else { + // each source pixel covers (self.w / w) × (self.h / h) pixels of the correction + let area = (self.w as f32 / w as f32).max(1.0) * (self.h as f32 / h as f32).max(1.0); + let mut acc: HashMap = HashMap::new(); + for (&i, g) in self.index.iter().zip(&self.gain) { + let (x, y) = (i as usize % self.w, i as usize / self.w); + let (dx, dy) = ((x * w / self.w).min(w - 1), (y * h / self.h).min(h - 1)); + let a = acc.entry(dy * w + dx).or_default(); + for (s, &d) in a.iter_mut().zip(g) { + *s += f16_value(d); + } + } + for (i, s) in acc { + if let Some(p) = out.data.get_mut(i) { + for (v, d) in p.iter_mut().zip(s) { + *v *= 1.0 + d / area * k; + } + } + } + } + let out = Arc::new(out); + *memo = Some((tag, out.clone())); + out + } + + #[cfg_attr(not(feature = "denoise"), allow(dead_code))] + fn write(&self, path: &Path) -> Result<(), String> { + let mut body = Vec::with_capacity(self.index.len() * 10); + for (i, g) in self.index.iter().zip(&self.gain) { + body.extend_from_slice(&i.to_le_bytes()); + for d in g { + body.extend_from_slice(&d.to_le_bytes()); + } + } + let packed = miniz_oxide::deflate::compress_to_vec(&body, 6); + let mut b = Vec::with_capacity(packed.len() + 48); + b.extend_from_slice(b"LCADF1\0\0"); + b.extend_from_slice(&self.key.to_le_bytes()); + for v in [self.w as u64, self.h as u64, self.index.len() as u64, body.len() as u64, fnv(&body)] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.extend_from_slice(&packed); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, &b).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, path).map_err(|e| e.to_string()) + } + + /// The correction at `path`, if it is one, for `key`, and intact. + fn read(path: &Path, key: u64) -> Option { + let b = std::fs::read(path).ok()?; + let word = |i: usize| b.get(8 + i * 8..16 + i * 8).and_then(|s| s.try_into().ok()).map(u64::from_le_bytes); + if b.get(..8)? != b"LCADF1\0\0" || word(0)? != key { + return None; + } + let (w, h, n, len, sum) = (word(1)? as usize, word(2)? as usize, word(3)? as usize, word(4)? as usize, word(5)?); + if w == 0 || h == 0 || w.checked_mul(h)? > u32::MAX as usize || n > w * h || len != n * 10 { + return None; + } + let body = miniz_oxide::inflate::decompress_to_vec_with_limit(b.get(56..)?, len).ok()?; + if body.len() != len || fnv(&body) != sum { + return None; + } + let (mut index, mut gain) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for r in body.chunks_exact(10) { + let i = u32::from_le_bytes(r.get(..4)?.try_into().ok()?); + if i as usize >= w * h || index.last().is_some_and(|&l| l >= i) { + return None; + } + index.push(i); + let d = |k: usize| r.get(4 + 2 * k..6 + 2 * k).and_then(|s| s.try_into().ok()).map(u16::from_le_bytes); + gain.push([d(0)?, d(1)?, d(2)?]); + } + Some(Correction { key, w, h, index, gain, memo: Mutex::new(None) }) + } +} + +fn fnv(b: &[u8]) -> u64 { + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| (h ^ u64::from(v)).wrapping_mul(0x0100_0000_01b3)) +} + +#[cfg_attr(not(feature = "denoise"), allow(dead_code))] +fn f16_bits(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let e = ((b >> 23) & 0xff) as i32 - 127 + 15; + let m = b & 0x7f_ffff; + if v.is_nan() || e >= 31 { + return sign | 0x7bff; // the largest finite value + } + if e <= 0 { + if e < -10 { + return sign; + } + let m = (m | 0x80_0000) >> (1 - e); + return sign | ((m + 0x1000) >> 13) as u16; + } + let r = (((e as u32) << 10) | (m >> 13)) + ((m >> 12) & 1); + sign | r.min(0x7bff) as u16 +} + +fn f16_value(b: u16) -> f32 { + let (sign, e, m) = (b >> 15, i32::from((b >> 10) & 31), f32::from(b & 1023)); + let v = if e == 0 { m / 1024.0 * 2f32.powi(-14) } else { (1.0 + m / 1024.0) * 2f32.powi(e - 15) }; + if sign == 1 { -v } else { v } +} + +/// The name of photo `p`'s correction by the model with SHA-256 `model`. +pub fn key(p: &Photo, model: &str) -> u64 { + let mut h = Hasher128::new(); + h.str(VERSION).str(model).str(&crate::media::content_key(p)); + h.finish().0 as u64 | 1 +} + +/// Everything needed to make one photo's correction, on any thread. +#[derive(Clone)] +pub struct Recipe { + pub photo: PhotoId, + pub key: u64, + source: SourceRef, + info: SourceInfo, + model: Arc, + path: Option, +} + +impl Recipe { + /// Decode the photo at full size, run the model on its Defringe-stage picture, keep the result on disk. + #[cfg(feature = "denoise")] + pub fn make(&self, progress: &(dyn Fn(usize, usize) + Sync), cancel: &AtomicBool) -> Result { + let source = self.source.load_source()?; + let src = source.image.clone(); + let info = source.info_or(self.info.clone()); + let req = lightcraft_pipeline::RenderRequest { apply_crop: false, ..lightcraft_pipeline::RenderRequest::fit(src.width, src.height) }; + let tap = lightcraft_pipeline::defringe_tap(&src, &info, &DevelopSettings::default(), &req); + if (tap.width, tap.height) != (src.width, src.height) { + return Err("the Defringe stage's picture doesn't line up with the photo".into()); + } + let (w, h) = (tap.width, tap.height); + let top = lightcraft_denoise::defringe::top(&tap.data); + let rgb: Vec<[f32; 3]> = tap.data.iter().map(|p| p.map(|v| (v / top).max(0.0))).collect(); + drop(tap); + let clip = lightcraft_denoise::defringe::clip_mask(&rgb, w, h, 1.0); + let changed = self.model.correct(&rgb, &clip, w, h, progress, cancel).map_err(|e| e.to_string())?; + // as a gain on the source picture: the Defringe stage is the source after per-channel gains (white balance, + // exposure), so the ratio the model made carries over + let (mut index, mut gain) = (Vec::with_capacity(changed.len()), Vec::with_capacity(changed.len())); + for (i, p) in changed { + let Some(old) = rgb.get(i as usize) else { continue }; + let g = [0, 1, 2].map(|c| if old[c] > 1e-4 { f16_bits((p[c] / old[c]).clamp(0.2, 5.0) - 1.0) } else { 0 }); + if g != [0; 3] { + index.push(i); + gain.push(g); + } + } + let c = Correction { key: self.key, w, h, index, gain, memo: Mutex::new(None) }; + if let Some(path) = &self.path { + c.write(path)?; + } + Ok(c) + } + + #[cfg(not(feature = "denoise"))] + pub fn make(&self, _: &(dyn Fn(usize, usize) + Sync), _: &AtomicBool) -> Result { + let _ = (&self.source, &self.info, &self.model, &self.path); + Err("this build of LightCraft can't run AI models".into()) + } +} + +/// What a render does about AI Defringe. +#[derive(Clone)] +pub enum ForRender { + /// Apply this correction at this amount. + Ready(Arc, f32), + /// Make the correction first (an export whose photo has none yet). + Make(Recipe, f32), +} + +impl ForRender { + /// `src` corrected, making the correction first if needed. + pub fn apply(&self, src: &Arc) -> Result, String> { + match self { + ForRender::Ready(c, a) => Ok(c.apply(src, *a)), + ForRender::Make(r, a) => Ok(r.make(&|_, _| {}, &AtomicBool::new(false))?.apply(src, *a)), + } + } + + pub fn key(&self) -> u64 { + match self { + ForRender::Ready(c, _) => c.key, + ForRender::Make(r, _) => r.key, + } + } +} + +struct Job { + photo: PhotoId, + key: u64, + rx: Receiver>, + done: Arc, + total: Arc, + cancel: Arc, + _task: crate::activity::TaskGuard, +} + +/// The session's AI Defringe state. +#[derive(Default)] +pub struct State { + /// The installed model, loaded: its SHA-256 and the model. + model: Option<(String, Arc)>, + /// The installed model's manifest, and when it was last read. + installed: Option<(Manifest, PathBuf)>, + seen: Option, + job: Option, + /// Corrections that failed, by key, and why (not tried again until asked). + failed: HashMap, + /// Corrections in memory, most recently used last. + ready: Vec<(PhotoId, Arc)>, + /// Bumped whenever a correction arrives (renders made before it are stale). + pub generation: u64, + /// The models folder in place of [`models_dir`] (tests, hosts with their own). + pub(crate) models_dir: Option, +} + +/// Where a photo's correction stands. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state")] +pub enum PhotoState { + /// AI Defringe is off for it. + Off, + /// No model is installed (or this build can't run one). + NoModel, + Ready { changed: usize }, + Running { done: usize, total: usize }, + Failed { error: String }, + Waiting, +} + +impl Session { + /// Where the defringe model is installed. + pub fn aidefringe_models_dir(&self) -> Option { + self.aidefringe.models_dir.clone().or_else(models_dir) + } + + /// Use `dir` for the defringe model instead of the default folder. + pub fn set_aidefringe_models_dir(&mut self, dir: Option) { + self.aidefringe.models_dir = dir; + self.aidefringe_model_changed(); + } + + fn aidefringe_dir(&self) -> Option { + self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(DIR)) + } + + /// Read which model is installed (at most every couple of seconds unless `force`). + pub fn aidefringe_refresh(&mut self, force: bool) { + let st = &mut self.aidefringe; + if !force && st.seen.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(2)) { + return; + } + st.seen = Some(web_time::Instant::now()); + st.installed = st.models_dir.clone().or_else(models_dir).and_then(|d| installed(&d)); + if st.model.as_ref().map(|m| &m.0) != st.installed.as_ref().map(|i| &i.0.sha256) { + st.model = None; + } + } + + /// The installed model's manifest. + pub fn aidefringe_model(&mut self) -> Option { + self.aidefringe_refresh(false); + self.aidefringe.installed.as_ref().map(|i| i.0.clone()) + } + + fn aidefringe_loaded(&mut self) -> Result<(String, Arc), String> { + self.aidefringe_refresh(false); + let (m, file) = self.aidefringe.installed.clone().ok_or("no defringe model is installed: install one in Settings > AI Defringe")?; + if let Some(l) = &self.aidefringe.model { + return Ok(l.clone()); + } + let model = Arc::new(load_model(&read_model_file(&file, &m)?)?); + self.aidefringe.model = Some((m.sha256.clone(), model.clone())); + Ok((m.sha256, model)) + } + + fn aidefringe_recipe(&mut self, id: PhotoId) -> Result { + let (sha, model) = self.aidefringe_loaded()?; + let p = self.catalog.photo(id).ok_or("no such photo")?.clone(); + let key = key(&p, &sha); + let path = self.aidefringe_dir().map(|d| d.join(format!("{key:016x}.lcadf"))); + let source = self.media.source_ref_uncached(&p, SourceLevel::Full); + Ok(Recipe { photo: id, key, source, info: self.source_info(id), model, path }) + } + + /// The installed model's key for photo `p`, if a model is installed. + fn aidefringe_key(&mut self, p: &Photo) -> Option { + self.aidefringe_refresh(false); + self.aidefringe.installed.as_ref().map(|i| key(p, &i.0.sha256)) + } + + /// Photo `id`'s correction, from memory or from disk. + fn aidefringe_get(&mut self, id: PhotoId, key: u64) -> Option> { + let st = &mut self.aidefringe; + if let Some(at) = st.ready.iter().position(|(p, c)| *p == id && c.key == key) { + let e = st.ready.remove(at); + let c = e.1.clone(); + st.ready.push(e); + return Some(c); + } + let path = self.aidefringe_dir()?.join(format!("{key:016x}.lcadf")); + let c = Arc::new(Correction::read(&path, key)?); + self.aidefringe_keep(id, c.clone()); + Some(c) + } + + fn aidefringe_keep(&mut self, id: PhotoId, c: Arc) { + let st = &mut self.aidefringe; + st.ready.retain(|(p, _)| *p != id); + st.ready.push((id, c)); + if st.ready.len() > IN_MEMORY { + st.ready.remove(0); + } + st.generation += 1; + } + + /// The key of photo `p`'s correction when a render of it uses one already in memory, else 0. + pub(crate) fn aidefringe_salt(&self, p: &Photo) -> u64 { + if p.develop.ai_defringe_amount() <= 0.0 { + return 0; + } + let Some((m, _)) = &self.aidefringe.installed else { return 0 }; + let k = key(p, &m.sha256); + if self.aidefringe.ready.iter().any(|(id, c)| *id == p.id && c.key == k) { k } else { 0 } + } + + /// What a render of photo `p` with settings `s` does about AI Defringe (`None`: nothing, as it is off, has no + /// model or no correction yet). With `make`, a missing correction is made by the render (an export). + pub(crate) fn aidefringe_for_render(&mut self, p: &Photo, s: &DevelopSettings, make: bool) -> Result, String> { + let amount = s.ai_defringe_amount(); + if amount <= 0.0 { + return Ok(None); + } + let Some(key) = self.aidefringe_key(p) else { + return if make { Err(format!("{}: AI Defringe is on for this photo but no defringe model is installed", p.file_name)) } else { Ok(None) }; + }; + if let Some(c) = self.aidefringe_get(p.id, key) { + return Ok(Some(ForRender::Ready(c, amount))); + } + if !make { + return Ok(None); + } + let r = self.aidefringe_recipe(p.id).map_err(|e| format!("{}: {e}", p.file_name))?; + Ok(Some(ForRender::Make(r, amount))) + } + + /// Where photo `id`'s correction stands. + pub fn aidefringe_state(&mut self, id: PhotoId) -> PhotoState { + let Some(p) = self.catalog.photo(id).cloned() else { return PhotoState::Off }; + if p.develop.ai_defringe_amount() <= 0.0 && !p.develop.optics.ai_defringe_enabled() { + return PhotoState::Off; + } + let Some(key) = self.aidefringe_key(&p).filter(|_| runtime_available()) else { return PhotoState::NoModel }; + if let Some(c) = self.aidefringe_get(id, key) { + return PhotoState::Ready { changed: c.changed() }; + } + if let Some(j) = self.aidefringe.job.as_ref().filter(|j| j.photo == id && j.key == key) { + return PhotoState::Running { done: j.done.load(Ordering::Relaxed), total: j.total.load(Ordering::Relaxed) }; + } + match self.aidefringe.failed.get(&key) { + Some(e) => PhotoState::Failed { error: e.clone() }, + None => PhotoState::Waiting, + } + } + + /// Forget why photo `id`'s correction failed, so it is tried again. + pub fn aidefringe_retry(&mut self, id: PhotoId) { + if let Some(p) = self.catalog.photo(id).cloned() + && let Some(key) = self.aidefringe_key(&p) + { + self.aidefringe.failed.remove(&key); + } + } + + /// Called often (every frame by the app): take in a finished correction, stop one no longer wanted, and start the + /// active photo's when it is on and missing. True when a correction arrived. + pub fn aidefringe_pump(&mut self) -> bool { + let mut arrived = false; + if let Some(job) = &self.aidefringe.job { + let still = self.catalog.photo(job.photo).cloned().is_some_and(|p| { + p.develop.ai_defringe_amount() > 0.0 && self.aidefringe.installed.as_ref().is_some_and(|i| key(&p, &i.0.sha256) == job.key) + }); + if !still { + job.cancel.store(true, Ordering::Relaxed); + } + match job.rx.try_recv() { + Err(TryRecvError::Empty) => { + if let Some(j) = &self.aidefringe.job { + j._task.progress(j.done.load(Ordering::Relaxed) as u64, j.total.load(Ordering::Relaxed).max(1) as u64); + } + return false; + } + r => { + let Some(job) = self.aidefringe.job.take() else { return false }; + match r { + Ok(Ok(c)) => { + self.aidefringe_keep(job.photo, Arc::new(c)); + arrived = true; + } + Ok(Err(e)) if !job.cancel.load(Ordering::Relaxed) => { + self.aidefringe.failed.insert(job.key, e); + } + Ok(Err(_)) => {} + Err(_) => { + self.aidefringe.failed.insert(job.key, "the defringe job stopped".into()); + } + } + } + } + } + if !runtime_available() { + return arrived; + } + let Some(id) = self.active() else { return arrived }; + let Some(p) = self.catalog.photo(id).cloned() else { return arrived }; + if p.develop.ai_defringe_amount() <= 0.0 { + return arrived; + } + let Some(key) = self.aidefringe_key(&p) else { return arrived }; + if self.aidefringe.failed.contains_key(&key) || self.aidefringe_get(id, key).is_some() { + return arrived; + } + match self.aidefringe_recipe(id) { + Ok(r) => self.aidefringe_start(r, &p.file_name), + Err(e) => { + self.aidefringe.failed.insert(key, e); + } + } + arrived + } + + fn aidefringe_start(&mut self, r: Recipe, name: &str) { + let (done, total, cancel) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)), Arc::new(AtomicBool::new(false))); + let task = self.activity.start("aidefringe", "AI Defringe", crate::activity::Cancel::Flag(cancel.clone())); + task.detail(name); + let (tx, rx) = channel(); + let (d, t, c, key, photo) = (done.clone(), total.clone(), cancel.clone(), r.key, r.photo); + std::thread::Builder::new() + .name("ai-defringe".into()) + .spawn(move || { + let progress = |a: usize, b: usize| { + d.store(a, Ordering::Relaxed); + t.store(b, Ordering::Relaxed); + }; + let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| r.make(&progress, &c))) + .unwrap_or_else(|_| Err("AI Defringe stopped unexpectedly".into())); + let _ = tx.send(made); + }) + .ok(); + self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, _task: task }); + } + + /// Make photo `id`'s correction now, on this thread (for scripts and tests) → how many pixels it changes. + pub fn aidefringe_make_now(&mut self, id: PhotoId) -> Result { + let r = self.aidefringe_recipe(id)?; + let c = Arc::new(r.make(&|_, _| {}, &AtomicBool::new(false))?); + let n = c.changed(); + self.aidefringe.failed.remove(&r.key); + self.aidefringe_keep(id, c); + Ok(n) + } + + /// Delete every cached correction of this library → (files, bytes). + pub fn aidefringe_clear(&mut self) -> (usize, u64) { + self.aidefringe.ready.clear(); + self.aidefringe.failed.clear(); + self.aidefringe.generation += 1; + let Some(dir) = self.aidefringe_dir() else { return (0, 0) }; + let (mut files, mut bytes) = (0, 0); + for e in std::fs::read_dir(&dir).into_iter().flatten().flatten() { + let path = e.path(); + if path.extension().is_some_and(|x| x == "lcadf") { + let len = e.metadata().map_or(0, |m| m.len()); + if std::fs::remove_file(&path).is_ok() { + files += 1; + bytes += len; + } + } + } + (files, bytes) + } + + /// The installed model changed: forget the loaded one and what failed with it. + pub(crate) fn aidefringe_model_changed(&mut self) { + if let Some(j) = &self.aidefringe.job { + j.cancel.store(true, Ordering::Relaxed); + } + self.aidefringe.model = None; + self.aidefringe.failed.clear(); + self.aidefringe.generation += 1; + self.aidefringe_refresh(true); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/aidefringe/tests.rs b/crates/engine/src/aidefringe/tests.rs new file mode 100644 index 0000000000..2eb7dabcd0 --- /dev/null +++ b/crates/engine/src/aidefringe/tests.rs @@ -0,0 +1,73 @@ +use super::*; + +fn manifest_json(sha: &str) -> String { + format!( + r#"{{"id": "test-defringe", "name": "Test defringe", "version": "1", "licence": "MIT", "file": "model.onnx", "sha256": "{sha}", "contract": "{CONTRACT}"}}"# + ) +} + +#[test] +fn a_manifest_is_checked() { + let sha = "ab".repeat(32); + let m = Manifest::parse(&manifest_json(&sha)).unwrap(); + assert_eq!((m.id.as_str(), m.file.as_str()), ("test-defringe", "model.onnx")); + assert!(Manifest::parse(&manifest_json("abc")).is_err(), "short hash"); + assert!(Manifest::parse(&manifest_json(&sha).replace(CONTRACT, "bayerToRgb")).is_err(), "a denoiser's contract"); + assert!(Manifest::parse(&manifest_json(&sha).replace("model.onnx", "../model.onnx")).is_err(), "a path"); + assert!(Manifest::parse(&manifest_json(&sha).replace("model.onnx", "model.bin")).is_err(), "not ONNX"); + assert!(Manifest::parse(&manifest_json(&sha).replace("test-defringe", "a b")).is_err(), "an id with a space"); + assert!(Manifest::parse(&manifest_json(&sha).replace("\"version\"", "\"extra\": 1, \"version\"")).is_err(), "unknown fields"); +} + +fn correction(w: usize, h: usize, at: &[(usize, [f32; 3])]) -> Correction { + Correction { + key: 7, + w, + h, + index: at.iter().map(|a| a.0 as u32).collect(), + gain: at.iter().map(|a| a.1.map(f16_bits)).collect(), + memo: Mutex::new(None), + } +} + +#[test] +fn a_correction_survives_the_disk_and_a_damaged_one_is_refused() { + let dir = std::env::temp_dir().join(format!("lc-adf-{}", std::process::id())); + let path = dir.join("c.lcadf"); + let c = correction(10, 4, &[(3, [0.5, -0.25, 0.0]), (17, [0.0, 0.125, -0.5])]); + c.write(&path).unwrap(); + let back = Correction::read(&path, 7).unwrap(); + assert_eq!((back.w, back.h, &back.index, &back.gain), (10, 4, &c.index, &c.gain)); + assert!(Correction::read(&path, 8).is_none(), "another key"); + let mut bytes = std::fs::read(&path).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0xff; + std::fs::write(&path, &bytes).unwrap(); + assert!(Correction::read(&path, 7).is_none(), "damaged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_correction_multiplies_the_source_and_a_smaller_source_gets_the_mean() { + let src = Arc::new(Rgb32f { width: 4, height: 2, data: vec![[0.5, 0.5, 0.5]; 8] }); + let c = correction(4, 2, &[(1, [0.5, -0.5, 0.0])]); + let full = c.apply(&src, 1.0); + assert_eq!(full.data[1], [0.75, 0.25, 0.5]); + assert_eq!(full.data[0], [0.5; 3]); + let half = c.apply(&src, 0.5); + assert_eq!(half.data[1], [0.625, 0.375, 0.5]); + assert!(Arc::ptr_eq(&c.apply(&src, 0.0), &src), "no amount, no copy"); + // a 2 × 1 source: its first pixel covers correction pixels 0, 1, 4 and 5, one of which has the gain + let small = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.5, 0.5, 0.5]; 2] }); + let s = c.apply(&small, 1.0); + assert_eq!(s.data[0], [0.5 * (1.0 + 0.5 / 4.0), 0.5 * (1.0 - 0.5 / 4.0), 0.5]); + assert_eq!(s.data[1], [0.5; 3]); +} + +#[test] +fn half_floats_round_trip() { + for v in [0.0f32, 0.5, -0.25, 1.0, 4.0, -0.8, 1e-3, 3.140625] { + assert!((f16_value(f16_bits(v)) - v).abs() <= v.abs() * 1e-3 + 1e-7, "{v}"); + } + assert_eq!(f16_value(f16_bits(1e9)), 65504.0); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 72b2dce09a..2e233cd37b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -5,6 +5,7 @@ //! `edit.*` (undo/redo), and queries (`catalog.query`, `photo.inspect`, `develop.get`…). mod activity; +mod aidefringe; mod before; pub(crate) mod browse; mod color; @@ -178,6 +179,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(geocode::specs()); v.extend(filters::specs()); v.extend(denoise::specs()); + v.extend(aidefringe::specs()); v.extend(face_models::specs()); v.extend(face_detect::specs()); v.extend(face_recognize::specs()); diff --git a/crates/engine/src/cmd/aidefringe.rs b/crates/engine/src/cmd/aidefringe.rs new file mode 100644 index 0000000000..c15d254df9 --- /dev/null +++ b/crates/engine/src/cmd/aidefringe.rs @@ -0,0 +1,142 @@ +//! AI Defringe commands (docs/ai-defringe.md): the per-photo switch, the installed model, and the corrections. + +use std::path::Path; + +use lightcraft_catalog::PhotoId; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, bool_or, cmd, str_param}; +use crate::aidefringe; +use crate::{Result, Session}; + +fn photo(s: &Session, p: &Value, c: &str) -> Result { + match p.get("id") { + Some(v) => Ok(PhotoId(v.as_u64().ok_or_else(|| bad(c, "`id` must be a photo id"))?)), + None => s.active().ok_or_else(|| bad(c, "select a photo")), + } +} + +fn model_json(m: &aidefringe::Manifest) -> Value { + json!({"id": m.id, "name": m.name, "version": m.version, "licence": m.licence, "sha256": m.sha256, "notice": m.notice, "url": m.url}) +} + +/// A per-photo switch, independent of the selection and Auto Sync. Turning on starts at 100. +fn toggle(s: &mut Session, p: &Value) -> Result { + const C: &str = "aiDefringe.toggle"; + let id = photo(s, p, C)?; + let mut d = (*s.develop_of(id).ok_or_else(|| bad(C, "no such photo"))?).clone(); + let on = match p.get("enabled") { + Some(v) => v.as_bool().ok_or_else(|| bad(C, "`enabled` must be true or false"))?, + None => !d.optics.ai_defringe_enabled(), + }; + if on && s.aidefringe_model().is_none() { + return Err(bad(C, "AI Defringe needs a model: install one in Settings > AI Defringe")); + } + // the switch is its own setting: the Amount stays where it is when it is flipped, so flipping compares with and + // without; a photo that never had an Amount starts at 100 + let amount = if on && d.optics.ai_defringe_on.is_none() && d.optics.ai_defringe <= 0.0 { 100.0 } else { d.optics.ai_defringe }; + if !amount.is_finite() { + return Err(bad(C, "the photo has an invalid AI Defringe amount")); + } + if d.optics.ai_defringe != amount || d.optics.ai_defringe_on != Some(on) { + s.end_interaction()?; + d.optics.ai_defringe = amount; + d.optics.ai_defringe_on = Some(on); + let op = s.develop_op(id, d, "AI Defringe").ok_or_else(|| bad(C, "no such photo"))?; + s.commit("AI Defringe", op)?; + } + Ok(json!({"id": id.0, "enabled": on, "amount": amount})) +} + +fn status(s: &mut Session, p: &Value) -> Result { + let model = s.aidefringe_model(); + let mut v = json!({ + "runtime": aidefringe::runtime_available(), + "model": model.as_ref().map(model_json), + "dir": s.aidefringe_models_dir().map(|d| d.display().to_string()), + "generation": s.aidefringe.generation, + }); + if p.get("id").is_some() || s.active().is_some() { + let id = photo(s, p, "aiDefringe.status")?; + let state = s.aidefringe_state(id); + if let Some(o) = v.as_object_mut() { + o.insert("photo".into(), serde_json::to_value(state).unwrap_or(Value::Null)); + } + } + Ok(v) +} + +/// Called every frame by the app: takes in a finished correction and keeps the active photo's coming. +fn pump(s: &mut Session, _: &Value) -> Result { + let arrived = s.aidefringe_pump(); + Ok(json!({"arrived": arrived, "generation": s.aidefringe.generation})) +} + +fn make(s: &mut Session, p: &Value) -> Result { + const C: &str = "aiDefringe.make"; + let id = photo(s, p, C)?; + let changed = s.aidefringe_make_now(id).map_err(|e| bad(C, e))?; + Ok(json!({"id": id.0, "changed": changed})) +} + +fn retry(s: &mut Session, p: &Value) -> Result { + let id = photo(s, p, "aiDefringe.retry")?; + s.aidefringe_retry(id); + Ok(json!({"id": id.0, "photo": s.aidefringe_state(id)})) +} + +fn inspect(_: &mut Session, p: &Value) -> Result { + const C: &str = "aiDefringe.models.inspect"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "`path` is required"))?; + let m = aidefringe::inspect(Path::new(path)).map_err(|e| bad(C, e))?; + Ok(model_json(&m)) +} + +fn install(s: &mut Session, p: &Value) -> Result { + const C: &str = "aiDefringe.models.install"; + let path = str_param(p, "path").ok_or_else(|| bad(C, "`path` is required"))?; + if !bool_or(p, "acknowledged", false) { + return Err(bad(C, "show the user the model's licence and notice first, then pass `acknowledged: true`")); + } + let dir = s.aidefringe_models_dir().ok_or_else(|| bad(C, "no folder for defringe models (set LIGHTCRAFT_DEFRINGE_MODELS)"))?; + let m = aidefringe::install(Path::new(path), &dir).map_err(|e| bad(C, e))?; + s.aidefringe_model_changed(); + Ok(json!({"installed": true, "model": model_json(&m)})) +} + +fn remove(s: &mut Session, _: &Value) -> Result { + let removed = match s.aidefringe_models_dir() { + Some(dir) => aidefringe::remove(&dir).map_err(|e| bad("aiDefringe.models.remove", e))?, + None => false, + }; + s.aidefringe_model_changed(); + Ok(json!({"removed": removed})) +} + +fn clear(s: &mut Session, _: &Value) -> Result { + let (files, bytes) = s.aidefringe_clear(); + Ok(json!({"deleted": files, "bytes": bytes})) +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "aiDefringe.toggle", + "AI Defringe", + [], + None, + "{id?: photoId, enabled?: bool} → {id, enabled, amount} — turn AI Defringe on (Amount 100 the first time) or off for one photo, independent of selection and Auto Sync; needs an installed defringe model", + always, + toggle + ), + cmd!(query "aiDefringe.status", "AI Defringe Status", [], None, "{id?} → {runtime, model: {id, name, version, licence, sha256, notice, url} | null, dir, generation, photo?: {state: off | noModel | ready | running | failed | waiting, changed?, done?, total?, error?}}", always, status), + cmd!(query "aiDefringe.pump", "AI Defringe Pump", [], None, "{} → {arrived, generation} — called every frame by the app: takes in a finished correction and starts the active photo's when AI Defringe is on and it has none", always, pump), + cmd!(query "aiDefringe.make", "Make AI Defringe Correction", [], None, "{id?} → {id, changed} — make a photo's correction now and wait for it (for scripts); `changed` is how many pixels it changes", always, make), + cmd!(query "aiDefringe.retry", "Retry AI Defringe", [], None, "{id?} → {id, photo} — try a photo whose correction failed again", always, retry), + cmd!(query "aiDefringe.models.inspect", "Inspect Defringe Model", [], None, "{path} → {id, name, version, licence, sha256, notice, url} — the defringe-model.json beside an .onnx file, checked; never runs the file", always, inspect), + cmd!(query "aiDefringe.models.install", "Install Defringe Model", [], None, "{path, acknowledged: true} → {installed, model} — install a defringe model from an .onnx file with a defringe-model.json beside it, after checking its SHA-256 and running it once; it replaces the installed one. `acknowledged` must be true: the user has been shown the model's licence and notice", always, install), + cmd!(query "aiDefringe.models.remove", "Remove Defringe Model", [], None, "{} → {removed} — delete the installed defringe model (corrections already made stay until cleared)", always, remove), + cmd!(query "aiDefringe.clear", "Clear AI Defringe Cache", [], None, "{} → {deleted, bytes} — delete every cached AI Defringe correction of this library (they are made again when wanted)", always, clear), + ] +} + diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index ca906c6192..701373a70e 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -518,6 +518,7 @@ impl Session { slide: None, preview_cut: None, display_fit: None, + ai_defringe: None, }; let embedded = match (&self.media.preview_loader, c.kind) { (Some(l), MediaKind::Raw) => Some((c.path.clone(), l.clone(), edge)), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd67b755f9..8a5d8c2912 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ extern crate lightcraft_denoise_core as lightcraft_denoise; pub mod activity; +pub mod aidefringe; #[cfg(not(target_arch = "wasm32"))] pub mod apple_photos; pub mod availability; @@ -287,6 +288,8 @@ pub struct Session { pub(crate) unsaved_sidecars: std::collections::BTreeSet, /// AI denoise: the model in use, the photos that have their picture and the work in progress. pub(crate) denoise: denoise::State, + /// AI Defringe: the installed model, the corrections in memory and the one being made. + pub(crate) aidefringe: aidefringe::State, /// Where the host keeps face models (one folder each); `None` where there is no file system (the web). pub face_models_dir: Option, /// Face model downloads started this session (the staged files wait in `/.downloads`). @@ -496,6 +499,7 @@ impl Session { reload_tickets: Default::default(), unsaved_sidecars: Default::default(), denoise: Default::default(), + aidefringe: Default::default(), face_models_dir: None, face_downloads: Default::default(), lensfun: Default::default(), diff --git a/crates/engine/src/media/render.rs b/crates/engine/src/media/render.rs index af7d10e268..a6b412e89f 100644 --- a/crates/engine/src/media/render.rs +++ b/crates/engine/src/media/render.rs @@ -45,6 +45,9 @@ pub struct RenderJob { /// to a 64 px step) and the window would otherwise shrink the texture with 2-tap bilinear sampling, which blurs fine detail at /// small ratios and aliases it at large ones. The caches keep the full render. pub display_fit: Option<(usize, usize)>, + /// AI Defringe's correction of the source picture ([`crate::aidefringe`]), when it is on and the photo has one + /// (or, for an export, will make one). + pub ai_defringe: Option, } /// `img` shrunk to fit `max_w × max_h` with a Lanczos filter (see [`RenderJob::display_fit`]). @@ -345,6 +348,15 @@ impl RenderJob { Ok(source) => { // the plain picture, or (Denoise amount above 0 and a denoised picture cached) the mix the amount asks for let src = &source.image_for(self.settings.denoise_amount()); + // …with AI Defringe's correction + let corrected = match &self.ai_defringe { + Some(a) => match a.apply(src) { + Ok(img) => Some(img), + Err(e) => return self.failed(e), + }, + None => None, + }; + let src = corrected.as_ref().unwrap_or(src); let info = source.info_or(self.info); // Views and exports use the GPU when there is one (waiting for the device if it is // still being created). Thumbnails (grid, filmstrip, preset and profile previews) diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 4bf40bbf57..4c9838f3a2 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -61,7 +61,9 @@ impl crate::Session { // Temporary "before" settings must not replace the photo's cached develop hash. let settings_hash = if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) }; - let salt = self.media.denoise_salt(id, &settings); + // AI Defringe's correction, when it is on and made: its key is part of the render's + let ai_defringe = if before { None } else { self.aidefringe_for_render(&p, &settings, false).ok().flatten() }; + let salt = self.media.denoise_salt(id, &settings) ^ ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11)); let profile_salt = self.media.camera_profile_salt(&settings.profile.id); let lens = super::quick::lens_key(&p); let key = settings_hash @@ -116,6 +118,7 @@ impl crate::Session { slide: None, preview_cut: None, display_fit: None, + ai_defringe, }) } @@ -131,6 +134,7 @@ impl crate::Session { job.source = self.media.source_ref(&p, job.level); } job.settings = Arc::new(settings.clone()); + job.ai_defringe = self.aidefringe_for_render(&p, settings, false).ok().flatten(); // (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the // same id is a new picture) let profile_salt = self.media.camera_profile_salt(&settings.profile.id); @@ -206,6 +210,7 @@ impl crate::Session { slide: None, preview_cut: None, display_fit: None, + ai_defringe: None, }) } @@ -262,6 +267,7 @@ impl crate::Session { slide: None, preview_cut, display_fit: None, + ai_defringe: None, }) } @@ -286,7 +292,7 @@ impl crate::Session { /// key, [`Self::variant_key`]): a view rendered before the photo's AI Denoise result was there is /// not shown as the denoised one. pub(crate) fn view_key(&self, p: &Photo, apply_crop: bool) -> Hash128 { - let salt = self.media.denoise_salt(p.id, &p.develop); + let salt = self.media.denoise_salt(p.id, &p.develop) ^ self.aidefringe_salt(p).rotate_left(11); let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id); let mut k = Hasher128::new(); k.str(&content_key(p)) @@ -599,6 +605,9 @@ impl crate::Session { *denoise = Some(wanted); } } + // …and with AI Defringe's correction, made when the job runs if it isn't yet + let p = self.catalog.photo(id).ok_or("no such photo")?.clone(); + job.ai_defringe = self.aidefringe_for_render(&p, &job.settings, true)?; job.request.space = space; job.request.depth = depth; job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 958c122871..aadeabcf79 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,6 +7,8 @@ mod album_missing; mod album_order; mod album_remove; mod albums_local; +#[cfg(feature = "denoise")] +mod aidefringe; mod autosync_wb; mod color; mod constrain_crop; diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs new file mode 100644 index 0000000000..43f1ab4cad --- /dev/null +++ b/crates/engine/src/tests/aidefringe.rs @@ -0,0 +1,150 @@ +//! AI Defringe through the session: installing a model, the switch, the background correction and exports +//! (docs/ai-defringe.md). The model is a synthetic network that asks for the same change everywhere. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::aidefringe::{CONTRACT, MANIFEST, PhotoState}; +use crate::export::{ExportOptions, export_photo}; +use crate::tests_xmp::{synthetic_dng_of, temp_dir}; + +/// A raw whose left part is bright, with a 4 px magenta stripe on its edge, then mid grey. +fn stripe_dng(w: usize, h: usize) -> Vec { + let data: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let green = (x + y) % 2 == 1; + match x { + 0..96 => 3600, + 96..100 if green => 500, + 96..100 => 3400, + _ => 1100, + } + }) + .collect(); + synthetic_dng_of(w, h, "RGGB", data, None, Default::default()) +} + +/// A synthetic defringe model and its manifest in a folder of their own → the model file. +fn model_files(dir: &Path, out: [f32; 3]) -> PathBuf { + let src = dir.join("model-src"); + std::fs::create_dir_all(&src).unwrap(); + let bytes = lightcraft_denoise::synthetic::defringe_onnx(out); + let sha = lightcraft_denoise_core::hash::sha256_hex(&bytes); + std::fs::write(src.join("defringe.onnx"), &bytes).unwrap(); + let m = json!({"id": "push", "name": "Push toward green-yellow", "version": "1", "licence": "MIT", "file": "defringe.onnx", "sha256": sha, "contract": CONTRACT, "notice": "a test network"}); + std::fs::write(src.join(MANIFEST), serde_json::to_vec(&m).unwrap()).unwrap(); + src.join("defringe.onnx") +} + +struct Setup { + dir: PathBuf, + s: Session, +} + +fn setup(tag: &str) -> Setup { + let dir = temp_dir(tag); + let originals = dir.join("originals"); + std::fs::create_dir_all(&originals).unwrap(); + std::fs::write(originals.join("stripe.dng"), stripe_dng(320, 288)).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("library"), false).unwrap(); + s.execute("library.import", &json!({"paths": [originals.join("stripe.dng").to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.set_aidefringe_models_dir(Some(dir.join("defringe-models"))); + Setup { dir, s } +} + +fn photo(s: &Session) -> lightcraft_catalog::PhotoId { + s.catalog.photos().next().unwrap().id +} + +fn install(x: &mut Setup) -> Value { + let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); + x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap() +} + +#[test] +fn a_model_is_installed_only_when_acknowledged_and_intact() { + let mut x = setup("adf-install"); + let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); + let inspected = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(inspected["notice"], "a test network"); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy()})).is_err(), "not acknowledged"); + // a file that isn't the one its manifest names + std::fs::write(&path, b"something else").unwrap(); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).is_err()); + assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); + let r = install(&mut x); + assert_eq!(r["model"]["id"], "push"); + assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"]["name"], "Push toward green-yellow"); + assert_eq!(x.s.execute("aiDefringe.models.remove", &json!({})).unwrap()["removed"], true); + assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); + let _ = std::fs::remove_dir_all(&x.dir); +} + +#[test] +fn the_switch_needs_a_model_and_the_correction_is_made_in_the_background() { + let mut x = setup("adf-switch"); + let id = photo(&x.s); + assert!(x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).is_err(), "no model yet"); + install(&mut x); + let r = x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + assert_eq!((r["enabled"].as_bool(), r["amount"].as_f64()), (Some(true), Some(100.0))); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + loop { + x.s.execute("aiDefringe.pump", &json!({})).unwrap(); + match x.s.aidefringe_state(id) { + PhotoState::Ready { changed } => { + assert!(changed > 0); + break; + } + PhotoState::Failed { error } => panic!("{error}"), + _ => {} + } + assert!(std::time::Instant::now() < deadline, "the correction never came"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert_eq!(std::fs::read_dir(x.dir.join("library").join("ai-defringe")).unwrap().flatten().count(), 1); + // switched off and on again: the Amount is kept and the correction is still there + x.s.execute("aiDefringe.toggle", &json!({"enabled": false})).unwrap(); + assert_eq!(x.s.aidefringe_state(id), PhotoState::Off); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + assert!(matches!(x.s.aidefringe_state(id), PhotoState::Ready { .. })); + // a new session finds it on disk + let Setup { dir, s } = x; + drop(s); + let mut s2 = Session::new().with_fs(); + s2.open_library(dir.join("library"), false).unwrap(); + s2.set_aidefringe_models_dir(Some(dir.join("defringe-models"))); + assert!(matches!(s2.aidefringe_state(id), PhotoState::Ready { .. })); + assert_eq!(s2.execute("aiDefringe.clear", &json!({})).unwrap()["deleted"], 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_export_makes_the_correction_when_it_is_missing_and_never_comes_out_without_it() { + let mut x = setup("adf-export"); + let id = photo(&x.s); + let o = ExportOptions::from_json(&json!({"format": "png", "width": 320, "height": 320})); + let decode = |bytes: &[u8]| lightcraft_codecs::decode(bytes, lightcraft_codecs::DecodeOptions::fit(320, 320)).unwrap().to_working(); + let plain = decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes); + install(&mut x); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + // no pump: the export makes the correction itself + let fixed = decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes); + assert_eq!((plain.width, plain.height), (fixed.width, fixed.height)); + let differs: Vec = + (0..plain.data.len()).filter(|&i| plain.data[i].iter().zip(&fixed.data[i]).any(|(a, b)| (a - b).abs() > 1e-3)).map(|i| i % plain.width).collect(); + assert!(!differs.is_empty(), "the export has no correction"); + let edge = plain.width * 96 / 320; + assert!(differs.iter().all(|&x| x.abs_diff(edge) < 12), "pixels away from the stripe changed: {:?}", differs.iter().max()); + assert_eq!(std::fs::read_dir(x.dir.join("library").join("ai-defringe")).unwrap().flatten().count(), 1); + // without a model it fails rather than export without the correction + x.s.execute("aiDefringe.models.remove", &json!({})).unwrap(); + assert!(export_photo(&mut x.s, id, &o, 1).is_err()); + let _ = std::fs::remove_dir_all(&x.dir); +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 7ca709ac3f..fc377fc3c7 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -651,6 +651,21 @@ pub fn lin_cpu(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) { redeye::apply(img, &p.eyes); } +/// The picture the AI Defringe model reads ([`lightcraft_denoise::defringe`], docs/ai-defringe.md): `s` rendered for +/// `req` up to the Defringe stage (resampled, white balance, exposure, lateral chromatic aberration corrected), with +/// the Defringe sliders left out. +pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> Rgb32f { + let effective = s.effective(); + let mut rendition = settings_for(&effective, req).into_owned(); + rendition.optics.defringe_purple_amount = 0.0; + rendition.optics.defringe_green_amount = 0.0; + rendition.optics.remove_ca = true; + let plan = plan(src, info, &rendition, req); + let mut img = plan.frame.sample(src, plan.w, plan.h); + lin_cpu(&mut img, info, &plan); + img +} + /// The settings a render of `s` for `req` uses: the HDR edit for an [`OutputDepth::F32Hdr`] /// render, otherwise its SDR rendition (see [`DevelopSettings::sdr_rendition`]). Every renderer /// (CPU and GPU) goes through this, so an SDR render of an HDR edit looks the same everywhere. From 4b4c231078e3ccfef90387b8b12bd49b47f5f711 Mon Sep 17 00:00:00 2001 From: Bruno Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:56:02 +0100 Subject: [PATCH 2/9] AI Defringe: the switch and Amount in Optics > Defringe, Settings > AI Defringe to install a model, docs --- crates/denoise/src/defringe.rs | 19 ++- crates/denoise/src/defringe/tests.rs | 4 +- crates/engine/src/aidefringe.rs | 25 ++- crates/engine/src/cmd/aidefringe.rs | 1 - crates/engine/src/tests.rs | 4 +- crates/engine/src/tests/aidefringe.rs | 6 +- crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/dialogs/settings.rs | 2 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/aidefringe.rs | 214 ++++++++++++++++++++++++ crates/ui-egui/src/panels/edit.rs | 2 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/aidefringe.rs | 129 ++++++++++++++ docs/ai-defringe.md | 104 ++++++++++++ docs/parity-checklist.md | 3 +- docs/whats-new.md | 7 + 17 files changed, 503 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/src/panels/aidefringe.rs create mode 100644 crates/ui-egui/src/tests/aidefringe.rs create mode 100644 docs/ai-defringe.md diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs index cc7f21d7cb..27b28ccc46 100644 --- a/crates/denoise/src/defringe.rs +++ b/crates/denoise/src/defringe.rs @@ -135,7 +135,8 @@ impl Model { done += batch.len(); progress(done, total); } - let raw: Vec<[f32; 3]> = acc.iter().zip(&wsum).map(|(a, &s)| if s > 0.0 { a.map(|v| v / s.max(1e-6)) } else { [0.0, 0.0, -20.0] }).collect(); + let raw: Vec<[f32; 3]> = + acc.iter().zip(&wsum).map(|(a, &s)| if s > 0.0 { a.map(|v| v / s.max(1e-6)) } else { [0.0, 0.0, -20.0] }).collect(); band(rgb, w, h, (r0, r1, e0, e1), &raw, &mut changed); } progress(total, total); @@ -230,10 +231,12 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u let c_hi = max_filter(&chroma, w, lrows, 3); let rows = e1 - e0; // the guarded change, for rows e0..e1 - let ab: Vec<[f32; 2]> = (0..rows * w).map(|i| { - let j = (i / w + e0 - l0) * w + i % w; - [lab[j][1], lab[j][2]] - }).collect(); + let ab: Vec<[f32; 2]> = (0..rows * w) + .map(|i| { + let j = (i / w + e0 - l0) * w + i % w; + [lab[j][1], lab[j][2]] + }) + .collect(); let new: Vec<[f32; 2]> = (0..rows * w) .into_par_iter() .map(|i| { @@ -364,8 +367,10 @@ fn box_sum(v: &[f32], w: usize, h: usize, r: usize) -> Vec { } const REC2020_TO_709: [[f32; 3]; 3] = [[1.6605, -0.5876, -0.0728], [-0.1246, 1.1329, -0.0083], [-0.0182, -0.1006, 1.1187]]; -const M1: [[f32; 3]; 3] = [[0.412_221_47, 0.536_332_55, 0.051_445_995], [0.211_903_5, 0.680_699_5, 0.107_396_96], [0.088_302_46, 0.281_718_85, 0.629_978_7]]; -const M2: [[f32; 3]; 3] = [[0.210_454_26, 0.793_617_8, -0.004_072_047], [1.977_998_5, -2.428_592_2, 0.450_593_7], [0.025_904_037, 0.782_771_77, -0.808_675_77]]; +const M1: [[f32; 3]; 3] = + [[0.412_221_47, 0.536_332_55, 0.051_445_995], [0.211_903_5, 0.680_699_5, 0.107_396_96], [0.088_302_46, 0.281_718_85, 0.629_978_7]]; +const M2: [[f32; 3]; 3] = + [[0.210_454_26, 0.793_617_8, -0.004_072_047], [1.977_998_5, -2.428_592_2, 0.450_593_7], [0.025_904_037, 0.782_771_77, -0.808_675_77]]; fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { [0, 1, 2].map(|r| m[r][0] * v[0] + m[r][1] * v[1] + m[r][2] * v[2]) diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs index 250bb26c0c..896977ec56 100644 --- a/crates/denoise/src/defringe/tests.rs +++ b/crates/denoise/src/defringe/tests.rs @@ -78,8 +78,8 @@ fn small_pictures_are_padded() { #[test] fn a_correction_stops_at_grey_and_does_not_make_green() { // a huge push against the pixel's own colour ends at grey, not past it - let ab = [0.05, -0.05]; - let c = (ab[0] * ab[0] + ab[1] * ab[1] as f32).sqrt(); + let ab: [f32; 2] = [0.05, -0.05]; + let c = (ab[0] * ab[0] + ab[1] * ab[1]).sqrt(); let new = compose(ab, c, 1.0, c, [-20.0, 20.0, 20.0]); assert!(new[0] >= -1e-6 && new[1] <= 1e-6, "{new:?}"); // a push across into green on a grey-ish pixel stays under 0.01 of green chroma diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index db4fd979c9..b58d927c14 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -347,7 +347,7 @@ impl Correction { return None; } let (mut index, mut gain) = (Vec::with_capacity(n), Vec::with_capacity(n)); - for r in body.chunks_exact(10) { + for r in body.as_chunks::<10>().0 { let i = u32::from_le_bytes(r.get(..4)?.try_into().ok()?); if i as usize >= w * h || index.last().is_some_and(|&l| l >= i) { return None; @@ -457,7 +457,7 @@ pub enum ForRender { /// Apply this correction at this amount. Ready(Arc, f32), /// Make the correction first (an export whose photo has none yet). - Make(Recipe, f32), + Make(Box, f32), } impl ForRender { @@ -514,9 +514,16 @@ pub enum PhotoState { Off, /// No model is installed (or this build can't run one). NoModel, - Ready { changed: usize }, - Running { done: usize, total: usize }, - Failed { error: String }, + Ready { + changed: usize, + }, + Running { + done: usize, + total: usize, + }, + Failed { + error: String, + }, Waiting, } @@ -624,7 +631,11 @@ impl Session { return Ok(None); } let Some(key) = self.aidefringe_key(p) else { - return if make { Err(format!("{}: AI Defringe is on for this photo but no defringe model is installed", p.file_name)) } else { Ok(None) }; + return if make { + Err(format!("{}: AI Defringe is on for this photo but no defringe model is installed", p.file_name)) + } else { + Ok(None) + }; }; if let Some(c) = self.aidefringe_get(p.id, key) { return Ok(Some(ForRender::Ready(c, amount))); @@ -633,7 +644,7 @@ impl Session { return Ok(None); } let r = self.aidefringe_recipe(p.id).map_err(|e| format!("{}: {e}", p.file_name))?; - Ok(Some(ForRender::Make(r, amount))) + Ok(Some(ForRender::Make(Box::new(r), amount))) } /// Where photo `id`'s correction stands. diff --git a/crates/engine/src/cmd/aidefringe.rs b/crates/engine/src/cmd/aidefringe.rs index c15d254df9..5f48684dd1 100644 --- a/crates/engine/src/cmd/aidefringe.rs +++ b/crates/engine/src/cmd/aidefringe.rs @@ -139,4 +139,3 @@ pub fn specs() -> Vec { cmd!(query "aiDefringe.clear", "Clear AI Defringe Cache", [], None, "{} → {deleted, bytes} — delete every cached AI Defringe correction of this library (they are made again when wanted)", always, clear), ] } - diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aadeabcf79..2916185704 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,13 +2,13 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; +#[cfg(feature = "denoise")] +mod aidefringe; mod album_loops; mod album_missing; mod album_order; mod album_remove; mod albums_local; -#[cfg(feature = "denoise")] -mod aidefringe; mod autosync_wb; mod color; mod constrain_crop; diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index 43f1ab4cad..5d4d376978 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -137,8 +137,10 @@ fn an_export_makes_the_correction_when_it_is_missing_and_never_comes_out_without // no pump: the export makes the correction itself let fixed = decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes); assert_eq!((plain.width, plain.height), (fixed.width, fixed.height)); - let differs: Vec = - (0..plain.data.len()).filter(|&i| plain.data[i].iter().zip(&fixed.data[i]).any(|(a, b)| (a - b).abs() > 1e-3)).map(|i| i % plain.width).collect(); + let differs: Vec = (0..plain.data.len()) + .filter(|&i| plain.data[i].iter().zip(&fixed.data[i]).any(|(a, b)| (a - b).abs() > 1e-3)) + .map(|i| i % plain.width) + .collect(); assert!(!differs.is_empty(), "the export has no correction"); let edge = plain.width * 96 / 320; assert!(differs.iter().all(|&x| x.abs_diff(edge) < 12), "pixels away from the stripe changed: {:?}", differs.iter().max()); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a913..8c5d98c2c2 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -99,6 +99,7 @@ impl LightcraftApp { self.place_names_outcome(ctx); self.slideshow_tick(ctx, now); panels::denoise::pump_background(self, ctx, now); + panels::aidefringe::pump_background(self, ctx, now); panels::faces::pump_background(self, ctx, now); focus_scan::pump(self, ctx, now); // auto import: list the watched folder every few seconds (on a worker thread: it may be on diff --git a/crates/ui-egui/src/dialogs/settings.rs b/crates/ui-egui/src/dialogs/settings.rs index 900ee796ca..055dcf76bd 100644 --- a/crates/ui-egui/src/dialogs/settings.rs +++ b/crates/ui-egui/src/dialogs/settings.rs @@ -55,6 +55,7 @@ pub const TABS: &[(&str, &str)] = &[ ("slideshow", "Slideshow"), ("faces", "Faces"), ("denoise", "AI Denoise"), + ("aidefringe", "AI Defringe"), ]; /// Preview cache sizes offered (MB; 0 = automatic: room for every photo of the library). @@ -73,6 +74,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { "slideshow" => slideshow_tab(app, ui, &t, true), "faces" => crate::panels::faces::settings_tab(app, ui, &t), "denoise" => crate::panels::denoise::settings_tab(app, ui, &t), + "aidefringe" => crate::panels::aidefringe::settings_tab(app, ui, &t), _ => general_tab(app, ui, &t), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c40d16b8e9..0e9b4748b4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -642,6 +642,8 @@ pub struct Caches { pub smart_problem_scans: usize, /// AI denoise: what the pump last saw, the model list and the downloads being watched. pub denoise: panels::denoise::Ui, + /// AI Defringe: what the pump last saw and a model file waiting to be accepted. + pub aidefringe: panels::aidefringe::Ui, /// Bumped when a face model is installed, removed or chosen, so Settings re-reads the list at once. pub faces_epoch: u64, /// Face model downloads the user started, followed until installed (see `panels::faces::pump`). diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ed9c45fb5d..f80c4afaa8 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1,6 +1,7 @@ //! Window regions and panels. pub mod activity; +pub mod aidefringe; pub mod bottombar; pub mod chips; pub mod compare; diff --git a/crates/ui-egui/src/panels/aidefringe.rs b/crates/ui-egui/src/panels/aidefringe.rs new file mode 100644 index 0000000000..d7234b9787 --- /dev/null +++ b/crates/ui-egui/src/panels/aidefringe.rs @@ -0,0 +1,214 @@ +//! AI Defringe (docs/ai-defringe.md): its switch, Amount and progress at the top of Optics ▸ Defringe, and the +//! model the user installs in Settings ▸ AI Defringe. + +use egui::RichText; +use lightcraft_catalog::PhotoId; +use lightcraft_develop::DevelopSettings; +use serde_json::{Value, json}; + +use super::settings::{heading, hint}; +use crate::LightcraftApp; +use crate::i18n::{tr, tr_format}; +use crate::theme::Tokens; +use crate::widgets::register; + +/// What the pump last saw, and a model file picked in Settings waiting to be accepted. +#[derive(Default)] +pub struct Ui { + next_pump: f64, + generation: u64, + /// The status the panel shows, re-read with each pump. + status: Value, + /// A picked model's manifest and file, shown for the user to accept before it is installed. + picked: Option<(Value, String)>, + /// Why the last pick or install was refused. + rejected: Option, +} + +/// Called every frame: takes in a finished correction (and asks for a redraw, so the loupe and the thumbnails render +/// with it) and keeps the open photo's coming; while one is being made, asks again for its progress. +pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { + if now < app.caches.aidefringe.next_pump { + return; + } + let Ok(v) = app.session.execute("aiDefringe.pump", &json!({})) else { return }; + let generation = v["generation"].as_u64().unwrap_or(0); + let status = app.session.execute("aiDefringe.status", &json!({})).unwrap_or(Value::Null); + let running = status["photo"]["state"] == "running"; + let c = &mut app.caches.aidefringe; + if generation != c.generation { + c.generation = generation; + ctx.request_repaint(); + } + c.status = status; + c.next_pump = now + if running { 0.1 } else { 0.5 }; + if running { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } +} + +fn note(ui: &mut egui::Ui, text: &str, color: egui::Color32) { + ui.add(egui::Label::new(RichText::new(text).size(11.0).color(color)).wrap()); +} + +/// Optics ▸ Defringe ▸ AI Defringe: the switch, its Amount and how the photo's correction is coming along. +pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &DevelopSettings) { + let t = Tokens::get(ui.ctx()); + crate::panels::edit::sub_title(ui, tr("AI Defringe")); + let status = app.caches.aidefringe.status.clone(); + let has_model = status["model"].is_object(); + let pad = |top, bottom| egui::Margin { left: 24, right: 22, top, bottom }; + if !has_model { + egui::Frame::NONE.inner_margin(pad(2, 6)).show(ui, |ui| { + let why = if status["runtime"] == false { + "This build of LightCraft can't run AI models." + } else { + "Removes colour fringes of every hue with a trained model. Install one first, in Settings under AI Defringe." + }; + note(ui, tr(why), t.text_dim); + if status["runtime"] != false { + ui.add_space(2.0); + let r = ui.small_button(tr("Open Settings…")); + register(ui, "aidefringe:settings", r.rect); + if r.clicked() { + app.ui.dialog = Some(crate::state::Dialog::Settings { tab: "aidefringe".into() }); + } + } + }); + return; + } + let mut on = d.optics.ai_defringe_enabled(); + egui::Frame::NONE.inner_margin(pad(6, 2)).show(ui, |ui| { + let r = ui.add(egui::Checkbox::new(&mut on, tr("AI Defringe"))).on_hover_text(tr( + "Removes colour fringes of every hue (purple, blue, green) with the installed defringe model, leaving real colours alone. \ + The correction is made once in the background and kept; switching it off and on, or changing Amount, is instant.", + )); + register(ui, "aidefringe:enabled", r.rect); + if r.changed() { + let _ = app.run("aiDefringe.toggle", json!({"id": id.0, "enabled": on})); + } + }); + crate::panels::edit::control(app, ui, d, "optics.aiDefringe", on); + if !on || status["photo"].is_null() { + return; + } + let photo = &status["photo"]; + match photo["state"].as_str() { + Some("running") | Some("waiting") => { + let (done, total) = (photo["done"].as_u64().unwrap_or(0), photo["total"].as_u64().unwrap_or(0)); + egui::Frame::NONE.inner_margin(pad(0, 6)).show(ui, |ui| { + let fraction = crate::progress::fraction_of(done, total); + let text = match fraction { + Some(f) => tr_format!("Removing fringes… {pct}%", pct = crate::progress::percent(f)), + None => tr("Starting AI Defringe…").to_string(), + }; + crate::progress::Progress::new(fraction).label(text).width(ui.available_width().min(240.0)).widget("aidefringe:progress").show(ui); + }); + } + Some("failed") => { + egui::Frame::NONE.inner_margin(pad(0, 6)).show(ui, |ui| { + note(ui, &tr_format!("AI Defringe failed: {why}", why = photo["error"].as_str().unwrap_or("")), t.caution); + ui.add_space(2.0); + let r = ui.small_button(tr("Try again")); + register(ui, "aidefringe:retry", r.rect); + if r.clicked() { + let _ = app.session.execute("aiDefringe.retry", &json!({"id": id.0})); + app.caches.aidefringe.next_pump = 0.0; + } + }); + } + _ => {} + } +} + +/// Settings ▸ AI Defringe: the installed model, and installing or removing one. +pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let status = app.session.execute("aiDefringe.status", &json!({})).unwrap_or(Value::Null); + heading(ui, t, "AI Defringe"); + hint( + ui, + t, + "Removes colour fringes (purple, blue and green edges from the lens) with a trained model: the AI Defringe switch is in the Optics panel, under Defringe. \ + Your files are never changed: each photo's correction is cached data that is made again when needed.", + ); + if status["dir"].is_null() { + hint(ui, t, "This build has nowhere to keep a defringe model, so it cannot use one. (The desktop app has.)"); + return; + } + let runtime = status["runtime"] == true; + if !runtime { + hint(ui, t, "This build cannot run AI models."); + } + let m = &status["model"]; + if m.is_object() { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label(RichText::new(m["name"].as_str().unwrap_or("")).font(t.semibold(13.5)).color(t.text)); + ui.label(RichText::new(m["version"].as_str().unwrap_or("")).color(t.text_dim)); + }); + ui.label(RichText::new(tr_format!("Licence: {licence}", licence = m["licence"].as_str().unwrap_or(""))).color(t.text_label)); + if let Some(n) = m["notice"].as_str() { + ui.add(egui::Label::new(RichText::new(n).color(t.text_dim)).wrap()); + } + let r = crate::button::Button::new("Remove").widget("aidefringe:remove").show(ui); + if r.clicked() { + let _ = app.session.execute("aiDefringe.models.remove", &json!({})); + app.caches.aidefringe.next_pump = 0.0; + } + } else { + hint(ui, t, "No defringe model is installed. LightCraft doesn't come with one: install an ONNX file with defringe-model.json beside it."); + } + ui.add_space(6.0); + let r = crate::button::Button::new("Install from file…") + .enabled(runtime && app.services.pick_denoise_model.is_some()) + .widget("aidefringe:installFile") + .show(ui); + // (the desktop app's ONNX picker, shared with AI Denoise) + if r.clicked() + && let Some(path) = app.services.pick_denoise_model.as_mut().and_then(|f| f().into_iter().next()) + { + match app.session.execute("aiDefringe.models.inspect", &json!({"path": path})) { + Ok(info) => { + app.caches.aidefringe.rejected = None; + app.caches.aidefringe.picked = Some((info, path)); + } + Err(e) => app.caches.aidefringe.rejected = Some(plain(&e)), + } + } + if let Some((info, path)) = app.caches.aidefringe.picked.clone() { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.label(RichText::new(info["name"].as_str().unwrap_or("")).font(t.semibold(13.0)).color(t.text)); + ui.label(RichText::new(tr_format!("Licence: {licence}", licence = info["licence"].as_str().unwrap_or(""))).color(t.text_label)); + if let Some(n) = info["notice"].as_str() { + ui.add(egui::Label::new(RichText::new(n).color(t.text_dim)).wrap()); + } + hint(ui, t, "Installing it means you accept its licence and its notice above."); + ui.horizontal(|ui| { + let install = crate::button::Button::new("Accept and Install").widget("aidefringe:accept").show(ui); + let cancel = crate::button::Button::new("Cancel").widget("aidefringe:cancel").show(ui); + if install.clicked() { + match app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})) { + Ok(_) => app.caches.aidefringe.rejected = None, + Err(e) => app.caches.aidefringe.rejected = Some(plain(&e)), + } + app.caches.aidefringe.picked = None; + app.caches.aidefringe.next_pump = 0.0; + } + if cancel.clicked() { + app.caches.aidefringe.picked = None; + } + }); + }); + } + if let Some(why) = app.caches.aidefringe.rejected.clone() { + hint(ui, t, &why); + } +} + +/// What an engine error says, without the command it came from. +fn plain(e: &lightcraft_engine::EngineError) -> String { + match e { + lightcraft_engine::EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + } +} diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 15f2f277f3..5872df9e53 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -362,6 +362,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { app.ui.toggle_flyout("defringe"); } if open { + crate::panels::aidefringe::section(app, ui, id, d); + sub_title(ui, crate::i18n::tr("Manual")); control(app, ui, d, "optics.defringePurple", true); let on = d.optics.defringe_purple_amount > 0.0; control(app, ui, d, "optics.defringePurpleHueLo", on); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 647b712599..c995f8102d 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -13,6 +13,7 @@ fn settle_budget_only_expands_for_llvm_coverage_runs() { } mod activity; +mod aidefringe; mod album_picker; mod album_remove; mod alt_preview; diff --git a/crates/ui-egui/src/tests/aidefringe.rs b/crates/ui-egui/src/tests/aidefringe.rs new file mode 100644 index 0000000000..f5b25cd310 --- /dev/null +++ b/crates/ui-egui/src/tests/aidefringe.rs @@ -0,0 +1,129 @@ +//! Headless tests of AI Defringe's controls: the section at the top of Optics ▸ Defringe and Settings ▸ AI Defringe +//! (docs/ai-defringe.md). The model is a synthetic network that asks for the same change everywhere. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-ui-adf-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A synthetic defringe model and its manifest → the model file. +fn model_file(dir: &Path) -> String { + let bytes = lightcraft_denoise::synthetic::defringe_onnx([-3.0, 3.0, 10.0]); + let sha = lightcraft_denoise::hash::sha256_hex(&bytes); + std::fs::write(dir.join("push.onnx"), &bytes).unwrap(); + let m = json!({"id": "push", "name": "Test push", "version": "2", "licence": "MIT", "file": "push.onnx", "sha256": sha, "contract": "lightcraftDefringe1", "notice": "Trained on nothing at all."}); + std::fs::write(dir.join("defringe-model.json"), serde_json::to_vec(&m).unwrap()).unwrap(); + dir.join("push.onnx").to_string_lossy().into_owned() +} + +/// Detail view of the demo photo with Optics ▸ Defringe open, its model folder in `dir`. +fn defringe_open(dir: &Path) -> Headless { + let services = Services { png: None, ..Default::default() }; + let mut session = lightcraft_engine::Session::with_demo(); + session.set_aidefringe_models_dir(Some(dir.join("defringe-models"))); + let app = LightcraftApp::new(session, services); + let mut h = Headless::new(app, [1200.0, 1600.0], 1.0); + let r = h.request("ui.set", json!({"view": "detail"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.right = crate::state::RightPanel::Edit; + if !h.app.ui.section_open("optics") { + h.app.ui.toggle_section("optics"); + } + if !h.app.ui.flyout_open("defringe") { + h.app.ui.toggle_flyout("defringe"); + } + h.step(); + h.step(); + h +} + +fn on_screen(h: &mut Headless, id: &str) -> bool { + let r = h.request("ui.widgets", json!({"filter": "aidefringe"}), T); + r["result"].as_array().is_some_and(|ws| ws.iter().any(|w| w["id"] == id)) +} + +fn click(h: &mut Headless, id: &str) { + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.step(); + h.step(); +} + +#[test] +fn without_a_model_the_section_points_to_settings() { + let dir = temp("none"); + let mut h = defringe_open(&dir); + assert!(!on_screen(&mut h, "aidefringe:enabled")); + assert!(on_screen(&mut h, "aidefringe:settings")); + click(&mut h, "aidefringe:settings"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Settings { tab: "aidefringe".into() })); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_model_is_installed_from_settings_after_its_terms_are_shown() { + let dir = temp("install"); + let mut h = defringe_open(&dir); + let picked = model_file(&dir); + h.app.services.pick_denoise_model = Some(Box::new(move || vec![picked.clone()])); + h.app.ui.dialog = Some(Dialog::Settings { tab: "aidefringe".into() }); + h.step(); + h.step(); + click(&mut h, "aidefringe:installFile"); + let painted = h.painted_text(); + assert!(painted.iter().any(|s| s == "Trained on nothing at all."), "the notice is shown: {painted:?}"); + assert!(h.app.session.execute("aiDefringe.status", &json!({})).unwrap()["model"].is_null(), "nothing installed before accepting"); + click(&mut h, "aidefringe:accept"); + assert_eq!(h.app.session.execute("aiDefringe.status", &json!({})).unwrap()["model"]["name"], "Test push"); + click(&mut h, "aidefringe:remove"); + assert!(h.app.session.execute("aiDefringe.status", &json!({})).unwrap()["model"].is_null()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_switch_turns_it_on_and_the_correction_arrives() { + let dir = temp("switch"); + let mut h = defringe_open(&dir); + let path = model_file(&dir); + h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})).unwrap(); + h.app.caches.aidefringe = Default::default(); + h.step(); + h.step(); + assert!(on_screen(&mut h, "aidefringe:enabled")); + click(&mut h, "aidefringe:enabled"); + let id = h.app.session.active().unwrap(); + let d = h.app.session.develop_of(id).unwrap(); + assert!(d.optics.ai_defringe_enabled()); + assert_eq!(d.optics.ai_defringe, 100.0); + let deadline = std::time::Instant::now() + Duration::from_secs(60); + loop { + h.step(); + let s = h.app.session.execute("aiDefringe.status", &json!({})).unwrap(); + match s["photo"]["state"].as_str() { + Some("ready") => break, + Some("failed") => panic!("{s}"), + _ => {} + } + assert!(std::time::Instant::now() < deadline, "the correction never arrived"); + std::thread::sleep(Duration::from_millis(20)); + } + // switched off, the Amount stays + click(&mut h, "aidefringe:enabled"); + let d = h.app.session.develop_of(id).unwrap(); + assert!(!d.optics.ai_defringe_enabled()); + assert_eq!(d.optics.ai_defringe, 100.0); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md new file mode 100644 index 0000000000..c59fdde0a4 --- /dev/null +++ b/docs/ai-defringe.md @@ -0,0 +1,104 @@ +# AI Defringe + +Optics ▸ Defringe ▸ **AI Defringe** is a per-photo switch with an **Amount** (0 to 100). It removes colour fringes of +every hue (purple, blue-violet, green) with a trained network, and leaves real colours alone. Turning it on the first +time starts at 100; turning it off keeps the Amount. It acts on the requesting photo only, independently of Auto Sync, +and is undoable. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on +their own or together with it. + +AI Defringe needs a model, and **LightCraft ships none**. Settings ▸ AI Defringe ▸ **Install from file…** takes an ONNX +file with a `defringe-model.json` beside it (see [The model contract](#the-model-contract)). Before anything is +installed, Settings shows the model's name, licence and notice, and the user accepts them. Without a model the section +says where to install one. Builds without the model runtime (the web build, or a native build without the `denoise` +feature) say so and never offer the switch. + +## How it works + +For each photo with AI Defringe on, the model reads the picture at the Defringe stage: the full-size source developed +with the default settings up to that point (white balance, exposure, lateral chromatic aberration removed; no +geometry, so it lines up with the source pixel for pixel). Its correction is kept as a gain per channel for each pixel +it changes, applied to the source picture before the develop pipeline. So: + +- The edit never makes the correction again. Moving any slider, Amount included, uses the one already made. +- A render smaller than the source (the loupe, thumbnails) takes the mean gain over each of its pixels, so thin + fringes aren't missed between samples. +- An export with AI Defringe on and no correction yet makes it before it renders, and fails with a message when no + model is installed. It never comes out without the correction it was asked for. + +The correction of the photo being edited is made in the background (Activity shows it and can cancel it) and kept in +`/ai-defringe/.lcadf`, named by a hash of the photo's content, the model file's SHA-256 and the algorithm +version (`crates/engine/src/aidefringe.rs`, `VERSION`). It is cached data: Clear (`aiDefringe.clear`) deletes it and it +is made again when wanted. A file is compressed, checksummed and read as hostile input. Up to 24 corrections stay in +memory; each holds only the pixels it changes. + +Inference runs in pure Rust on the processor, with the same ONNX reader and convolution runner as AI Denoise +(`crates/denoise/src/defringe.rs`). The network runs on 256 px tiles overlapping by 32 px, blended with linear ramps, +and tiles without an edge are skipped. The picture is worked through in bands of 768 rows, so memory stays bounded on +large photos; the result is identical to working on it whole (`bands_and_tiles_leave_no_seams`). On an Apple M-series +processor a 24 MP photo's tiles take about 1.5 s with ten threads. There is no graphics card path yet. + +### What the host does with the network's output + +The network only proposes a change; the host decides how much of it to keep. These guards are fixed, not learned: + +1. **Lightness is never changed.** Only OkLab a and b move. +2. **Only near edges.** The change is scaled by `smoothstep(0.05, 0.20, r)`, where `r` is the range of OkLab L within + 7 × 7 px, so flat areas are never touched. +3. **Bounded.** The change is at most `0.15 · tanh(Δ)` per channel, scaled by the gate's sigmoid, and no larger than + the pixel's own chroma plus 0.01. +4. **To grey, not past it.** The part of the change against the pixel's colour stops at grey. +5. **Not green unless it was.** A pixel that wasn't green (chroma above 0.01, hue 100° to 170°) keeps at most 0.01 of + green chroma. +6. **No more colourful than its neighbourhood:** at most 1.2 × the highest chroma within 7 × 7 px. +7. **Toward the surroundings.** Of each change, only the part that moves the pixel toward the mean colour of the + untouched pixels within 7 px is kept, at most up to it. Without this, a correction that stopped at grey could move + a purple fringe sideways into a brown-orange rim. +8. **Exact elsewhere.** A pixel whose colour moves by 1e-5 or less keeps its exact value. + +## The model contract + +`defringe-model.json` (checked, unknown fields refused): + +```json +{ + "id": "my-defringe", + "name": "My defringe model", + "version": "1", + "licence": "the licence the weights are under", + "file": "my-defringe.onnx", + "sha256": "64 hexadecimal digits of the ONNX file", + "contract": "lightcraftDefringe1", + "notice": "optional: anything the user should know (training data, terms)", + "url": "optional" +} +``` + +The ONNX file is read by LightCraft's own bounded reader: operators Conv, LeakyRelu, MaxPool (2 × 2), ConvTranspose +(2 × 2, stride 2), Concat and DepthToSpace (CRD), as for AI Denoise. + +- **Input** `[1, 20, 128, 128]`: a 256 px tile of five planes folded space-to-depth 2 × 2 (channel `c·4 + i·2 + j` is + plane `c` at row offset `i`, column offset `j`). The planes are OkLab L, a and b, `log2(Y + 2⁻¹²) / 12` with Y the + Rec.2020 luminance, and the clip mask (1 where the 5 × 5 mean of the brightest channel is within 7 % of the + picture's top). The picture is linear Rec.2020 divided by its top (the 99.9th percentile of the brightest channel), + and converted to OkLab by way of linear Rec.709 with negative values clamped. +- **Output** `[1, 3, 256, 256]`: Δa and Δb before `tanh`, and the gate before its sigmoid. + +Installation checks the manifest, the file's size (at most 256 MB) and SHA-256, the network's shape, and runs it twice +on a synthetic fringe: it must give finite colours, the same answer both times, and keep lightness. A model that fails +is not installed and the one already there stays. + +## Commands + +`aiDefringe.toggle {id?, enabled?}`, `aiDefringe.status {id?}`, `aiDefringe.pump`, `aiDefringe.make {id?}` (makes a +correction now and waits, for scripts), `aiDefringe.retry {id?}`, `aiDefringe.clear`, and `aiDefringe.models.inspect +{path}`, `.install {path, acknowledged: true}`, `.remove`. The develop control is `optics.aiDefringe` (with +`optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The model folder is +`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. + +## Limits + +- No model is distributed with LightCraft or offered for download. +- The correction is made from the plain picture, not the AI-denoised one. +- Processor only; a graphics card path and a background queue for photos other than the one being edited remain to + do. +- The Amount scales the gain linearly; at Amount 100 the result is the model's. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 84fe76d603..e6d4d31c56 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -216,7 +216,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | | LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `craft-raw`, `craft-raw`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `craft-raw`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `craft-raw`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`craft-raw`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) -| LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | +| LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*`, `ctl:optics.aiDefringe`, `cmd:aiDefringe.toggle`, `cmd:aiDefringe.models.install`, `crates/denoise/src/defringe.rs`, `docs/ai-defringe.md` | no fringe eyedropper. Beyond Lightroom: AI Defringe, a user-installed network (no model ships) whose correction is cached per photo and applied before develop, with fixed guards (lightness kept, toward grey and the surrounding colour only) | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | | LR-EDIT-GEOM-UPRIGHT | Upright | P1 | ✅ | `cmd:geometry.upright`, `cmd:geometry.guides` | | | LR-EDIT-GEOM-MANUAL | Manual transform | P1 | ✅ | `ctl:geometry.*` | | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | LR-EDIT-OPTICS-DEFRINGE: AI Defringe (beyond Lightroom), a user-installed defringe network with a cached per-photo correction; no model ships; status unchanged | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-05 | patch | LRC-LIB-CATALOG-LOCK: a library is written only to the folder it was opened from (on Unix, where the system gives a folder an identity, it is checked before every write of the catalog, settings, lock note and thumbnails; a share mounted over it, or a replaced folder, is refused and nothing is written; a folder that holds this session's lock note counts as the opened one, so a drive mounted again keeps saving; on Windows only that the path is still a folder is checked, so a replaced folder or a share mounted at the same path is not caught), a Move import removes its originals only once the catalog log is on disk, and dropping the lock removes only the owner note it wrote itself (#3240); status unchanged | | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | diff --git a/docs/whats-new.md b/docs/whats-new.md index 3ef7fafcdf..7c57acc6e8 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,13 @@ ## Unreleased +### AI Defringe +- Optics ▸ Defringe has an AI Defringe switch with an Amount. It removes colour fringes of every hue (purple, + blue-violet and green edges from the lens) with a trained model and leaves real colours alone. Install a model of your + own in Settings ▸ AI Defringe: LightCraft comes with none. Each photo's correction is made once in the background and + kept, so switching it off and on or moving Amount is instant, and an export makes it if it is missing. See + [AI Defringe](ai-defringe.md). + ### Flatpak updates - Help ▸ Check for Updates can now reach the release service and update standalone Flatpak bundles. This permissions repair must first arrive through your existing host-side update method. Flatpaks From 0620e00b8c170b2628fd5a52c9903115c1ec616a Mon Sep 17 00:00:00 2001 From: Bruno Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:00:00 +0100 Subject: [PATCH 3/9] AI Defringe: install any ONNX defringe model, with or without a defringe-model.json --- crates/engine/src/aidefringe.rs | 49 ++++++++++++++++++++++--- crates/engine/src/tests/aidefringe.rs | 23 ++++++++++++ crates/ui-egui/src/panels/aidefringe.rs | 6 ++- docs/ai-defringe.md | 8 ++-- 4 files changed, 76 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index b58d927c14..7e1c2c5fa8 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -123,15 +123,52 @@ pub fn installed(dir: &Path) -> Option<(Manifest, PathBuf)> { file.is_file().then_some((m, file)) } -/// The manifest beside model file `onnx`, checked, without reading the model. +/// The manifest beside model file `onnx`, checked, without running the model. A file with no `defringe-model.json` +/// describing it (any ONNX the user has) gets one made up from the file: its name, its SHA-256, and a licence that +/// says none was given. Installing it then checks that it really is a defringe model by running it. pub fn inspect(onnx: &Path) -> Result { let dir = onnx.parent().ok_or("the model file has no folder")?; - let text = std::fs::read_to_string(dir.join(MANIFEST)).map_err(|e| format!("{MANIFEST} beside the model: {e}"))?; - let m = Manifest::parse(&text)?; - if onnx.file_name().and_then(|n| n.to_str()) != Some(m.file.as_str()) { - return Err(format!("{MANIFEST} describes `{}`, not this file", m.file)); + let name = onnx.file_name().and_then(|n| n.to_str()).ok_or("the model file has no name")?; + if let Ok(text) = std::fs::read_to_string(dir.join(MANIFEST)) { + let m = Manifest::parse(&text)?; + if m.file == name { + return Ok(m); + } } - Ok(m) + bare(onnx, name) +} + +/// The manifest of an ONNX file that came without one. +fn bare(onnx: &Path, name: &str) -> Result { + let len = std::fs::metadata(onnx).map_err(|e| e.to_string())?.len(); + if len > MAX_MODEL_BYTES { + return Err("the model file is too large".into()); + } + let sha256 = lightcraft_denoise_core::hash::sha256_file(onnx).map_err(|e| e.to_string())?; + let stem = onnx.file_stem().and_then(|n| n.to_str()).unwrap_or("model"); + let id: String = stem.chars().map(|c| if c.is_ascii_alphanumeric() || "-_.".contains(c) { c } else { '-' }).take(64).collect(); + let plain = |v: &str| v.chars().filter(|c| !c.is_control()).take(120).collect::(); + let file = if name.len() <= 120 && !name.starts_with('.') && !name.contains(['/', '\\']) && name.to_ascii_lowercase().ends_with(".onnx") { + name.to_string() + } else { + "model.onnx".into() + }; + let m = Manifest { + id: if id.trim_matches(['-', '.', '_']).is_empty() { "model".into() } else { id }, + name: Some(plain(stem)).filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "Defringe model".into()), + version: sha256.get(..8).unwrap_or("1").to_string(), + licence: "Not stated".into(), + file, + sha256, + contract: CONTRACT.into(), + notice: Some(format!( + "This model came without a {MANIFEST}, so LightCraft doesn't know who made it or under which terms. \ + Use it only if you are allowed to. LightCraft checks that it runs as a defringe model before installing it." + )), + url: None, + }; + // the made-up manifest must read back as a valid one once installed + Manifest::parse(&serde_json::to_string(&m).map_err(|e| e.to_string())?) } fn read_model_file(path: &Path, m: &Manifest) -> Result, String> { diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index 5d4d376978..d1be34c57d 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -150,3 +150,26 @@ fn an_export_makes_the_correction_when_it_is_missing_and_never_comes_out_without assert!(export_photo(&mut x.s, id, &o, 1).is_err()); let _ = std::fs::remove_dir_all(&x.dir); } + +#[test] +fn any_defringe_shaped_onnx_installs_without_a_manifest_and_anything_else_is_refused() { + let mut x = setup("adf-bare"); + let bare = x.dir.join("bare"); + std::fs::create_dir_all(&bare).unwrap(); + // a denoiser (the wrong shape) is refused when it is run, and nothing is installed + let wrong = bare.join("smoothing.onnx"); + std::fs::write(&wrong, lightcraft_denoise::synthetic::smoothing_onnx()).unwrap(); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": wrong.to_string_lossy(), "acknowledged": true})).is_err()); + assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); + // a defringe network on its own: named after its file, its licence unknown + let path = bare.join("My Defringe v2.onnx"); + std::fs::write(&path, lightcraft_denoise::synthetic::defringe_onnx([-3.0, 3.0, 10.0])).unwrap(); + let m = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!((m["name"].as_str(), m["licence"].as_str()), (Some("My Defringe v2"), Some("Not stated"))); + assert!(m["notice"].as_str().unwrap().contains("doesn't know who made it")); + x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap(); + assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"]["id"], "My-Defringe-v2"); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + assert!(x.s.execute("aiDefringe.make", &json!({})).unwrap()["changed"].as_u64().unwrap() > 0); + let _ = std::fs::remove_dir_all(&x.dir); +} diff --git a/crates/ui-egui/src/panels/aidefringe.rs b/crates/ui-egui/src/panels/aidefringe.rs index d7234b9787..56b047b2c1 100644 --- a/crates/ui-egui/src/panels/aidefringe.rs +++ b/crates/ui-egui/src/panels/aidefringe.rs @@ -156,7 +156,11 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { app.caches.aidefringe.next_pump = 0.0; } } else { - hint(ui, t, "No defringe model is installed. LightCraft doesn't come with one: install an ONNX file with defringe-model.json beside it."); + hint( + ui, + t, + "No defringe model is installed. LightCraft doesn't come with one: install any ONNX defringe model. A defringe-model.json beside it gives its name and licence; without one, LightCraft names it after its file.", + ); } ui.add_space(6.0); let r = crate::button::Button::new("Install from file…") diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index c59fdde0a4..d06918c662 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -6,8 +6,10 @@ time starts at 100; turning it off keeps the Amount. It acts on the requesting p and is undoable. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on their own or together with it. -AI Defringe needs a model, and **LightCraft ships none**. Settings ▸ AI Defringe ▸ **Install from file…** takes an ONNX -file with a `defringe-model.json` beside it (see [The model contract](#the-model-contract)). Before anything is +AI Defringe needs a model, and **LightCraft ships none**. Settings ▸ AI Defringe ▸ **Install from file…** takes any ONNX +file that has the defringe shape (see [The model contract](#the-model-contract)). A `defringe-model.json` beside it gives +its name, version and licence. Without one, LightCraft names the model after its file, gives the licence as "Not +stated" with a notice saying it doesn't know who made it, and installs it only if it runs as a defringe model. Before anything is installed, Settings shows the model's name, licence and notice, and the user accepts them. Without a model the section says where to install one. Builds without the model runtime (the web build, or a native build without the `denoise` feature) say so and never offer the switch. @@ -57,7 +59,7 @@ The network only proposes a change; the host decides how much of it to keep. The ## The model contract -`defringe-model.json` (checked, unknown fields refused): +`defringe-model.json` (optional; checked, unknown fields refused): ```json { From 263d8c4fffbd6a191b7695431277f84d0fe511ce Mon Sep 17 00:00:00 2001 From: Bruno Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:01:14 +0100 Subject: [PATCH 4/9] AI Defringe: review fixes (model folder, accepted terms, memo, publishing, cancellation, Auto Sync, thumbnails, guards) --- crates/denoise/src/defringe.rs | 69 +++++++-- crates/denoise/src/defringe/tests.rs | 35 +++++ crates/denoise/src/lib.rs | 2 +- crates/develop/src/lib.rs | 13 ++ crates/engine/src/aidefringe.rs | 186 ++++++++++++++++++------ crates/engine/src/aidefringe/tests.rs | 60 +++++++- crates/engine/src/cmd/aidefringe.rs | 22 ++- crates/engine/src/lib.rs | 8 + crates/engine/src/media/session.rs | 35 ++++- crates/engine/src/tests.rs | 4 + crates/engine/src/tests/aidefringe.rs | 69 ++++++++- crates/pipeline/src/lib.rs | 4 +- crates/ui-egui/src/panels/aidefringe.rs | 36 +++-- crates/ui-egui/src/tests/aidefringe.rs | 25 +++- docs/ai-defringe.md | 17 ++- 15 files changed, 490 insertions(+), 95 deletions(-) diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs index 27b28ccc46..2a495e82d3 100644 --- a/crates/denoise/src/defringe.rs +++ b/crates/denoise/src/defringe.rs @@ -80,9 +80,12 @@ impl Model { progress: &(dyn Fn(usize, usize) + Sync), cancel: &AtomicBool, ) -> Result, Error> { - if w == 0 || h == 0 || rgb.len() != w * h || clip.len() != w * h || u32::try_from(w * h).is_err() { + let n = w.checked_mul(h).filter(|&n| n > 0 && u32::try_from(n).is_ok()); + if n.is_none_or(|n| rgb.len() != n || clip.len() != n) { return Err(Error::Input("the picture and its clip mask don't match its size".into())); } + let stop = || if cancel.load(Ordering::Relaxed) { Err(Error::Cancelled) } else { Ok(()) }; + stop()?; if rgb.iter().any(|p| p.iter().any(|v| !v.is_finite())) { return Err(Error::Input("the picture has non-finite values".into())); } @@ -107,6 +110,7 @@ impl Model { let ramp = ramp(); let mut changed = Vec::new(); for &(r0, r1, e0, e1) in &bands { + stop()?; let rows = e1 - e0; let mut acc = vec![[0f32; 3]; rows * w]; let mut wsum = vec![0f32; rows * w]; @@ -139,6 +143,7 @@ impl Model { acc.iter().zip(&wsum).map(|(a, &s)| if s > 0.0 { a.map(|v| v / s.max(1e-6)) } else { [0.0, 0.0, -20.0] }).collect(); band(rgb, w, h, (r0, r1, e0, e1), &raw, &mut changed); } + stop()?; progress(total, total); Ok(changed) } @@ -263,6 +268,12 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u let (d, to) = ([nab[0] - a[0], nab[1] - a[1]], [bg[0] - a[0], bg[1] - a[1]]); let t = ((d[0] * to[0] + d[1] * to[1]) / (to[0] * to[0] + to[1] * to[1]).max(1e-8)).clamp(0.0, 1.0); nab = [a[0] + t * to[0], a[1] + t * to[1]]; + // the pull toward the surroundings may not make a pixel green that wasn't either + let (ca, cn) = ((a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(), (nab[0] * nab[0] + nab[1] * nab[1] + 1e-12).sqrt()); + if green(nab, cn) && !green(a, ca) { + let s = (0.01 / cn).min(1.0); + nab = [nab[0] * s, nab[1] * s]; + } } if dist(a, nab) <= MOVED { return None; @@ -409,17 +420,53 @@ fn log_luminance(p: [f32; 3]) -> f32 { /// The clip mask a defringe model reads, for a `w × h` picture: pixels whose 5 × 5 mean of the brightest channel is /// within 7 % of `top`. +/// Worked row by row with running sums, so it needs no picture-sized buffers beyond the mask. pub fn clip_mask(rgb: &[[f32; 3]], w: usize, h: usize, top: f32) -> Vec { - let m: Vec = rgb.iter().map(|p| p[0].max(p[1]).max(p[2])).collect(); - box_sum(&m, w, h, 2) - .iter() - .enumerate() - .map(|(i, s)| { - let (x, y) = (i % w, i / w); - let n = ((x + 2).min(w - 1) - x.saturating_sub(2) + 1) * ((y + 2).min(h - 1) - y.saturating_sub(2) + 1); - s / n as f32 >= 0.93 * top - }) - .collect() + if w.checked_mul(h) != Some(rgb.len()) || rgb.is_empty() { + return vec![false; rgb.len()]; + } + // a row's 5-wide sums of the brightest channel + let row = |y: usize| -> Vec { + let line = &rgb[y * w..(y + 1) * w]; + let m = |x: usize| f64::from(line[x][0].max(line[x][1]).max(line[x][2])); + let mut out = vec![0f64; w]; + let mut run: f64 = (0..3.min(w)).map(m).sum(); + for (x, o) in out.iter_mut().enumerate() { + *o = run; + if x + 3 < w { + run += m(x + 3); + } + if x >= 2 { + run -= m(x - 2); + } + } + out + }; + let mut cols = vec![0f64; w]; + for y in 0..3.min(h) { + for (c, v) in cols.iter_mut().zip(row(y)) { + *c += v; + } + } + let mut mask = Vec::with_capacity(w * h); + for y in 0..h { + let ny = (y + 2).min(h - 1) - y.saturating_sub(2) + 1; + for (x, c) in cols.iter().enumerate() { + let nx = (x + 2).min(w - 1) - x.saturating_sub(2) + 1; + mask.push(c / (nx * ny) as f64 >= 0.93 * f64::from(top)); + } + if y + 3 < h { + for (c, v) in cols.iter_mut().zip(row(y + 3)) { + *c += v; + } + } + if y >= 2 { + for (c, v) in cols.iter_mut().zip(row(y - 2)) { + *c -= v; + } + } + } + mask } /// The 99.9th percentile of the brightest channel (over every third pixel): the value a picture is divided by so diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs index 896977ec56..583c54498e 100644 --- a/crates/denoise/src/defringe/tests.rs +++ b/crates/denoise/src/defringe/tests.rs @@ -123,3 +123,38 @@ fn the_clip_mask_marks_the_brightest_pixels() { let mask = clip_mask(&rgb, 300, 20, t); assert!(mask[10 * 300 + 50] && !mask[10 * 300 + 200] && !mask[10 * 300 + 98]); } + +#[test] +fn cancelling_is_honoured_with_no_tile_to_run() { + // flat: no tile is run, and the flag is still seen + let rgb = vec![[0.18f32; 3]; 300 * 280]; + let clip = vec![false; 300 * 280]; + let r = model([0.0, 0.0, 0.0]).correct(&rgb, &clip, 300, 280, &|_, _| {}, &AtomicBool::new(true)); + assert!(matches!(r, Err(Error::Cancelled))); +} + +#[test] +fn sizes_that_overflow_are_refused() { + let r = model([0.0, 0.0, 0.0]).correct(&[], &[], usize::MAX / 2 + 1, 2, &|_, _| {}, &AtomicBool::new(false)); + assert!(matches!(r, Err(Error::Input(_)))); +} + +#[test] +fn the_clip_mask_matches_a_plain_5_by_5_mean() { + let (w, h) = (23, 17); + let rgb: Vec<[f32; 3]> = (0..w * h).map(|i| [((i * 37) % 11) as f32 / 10.0, 0.2, ((i * 13) % 7) as f32 / 6.0]).collect(); + let mask = clip_mask(&rgb, w, h, 0.9); + for y in 0..h { + for x in 0..w { + let (mut s, mut n) = (0f64, 0); + for yy in y.saturating_sub(2)..(y + 3).min(h) { + for xx in x.saturating_sub(2)..(x + 3).min(w) { + let p = rgb[yy * w + xx]; + s += f64::from(p[0].max(p[1]).max(p[2])); + n += 1; + } + } + assert_eq!(mask[y * w + x], s / n as f64 >= 0.93 * 0.9, "({x}, {y})"); + } + } +} diff --git a/crates/denoise/src/lib.rs b/crates/denoise/src/lib.rs index bbce01961b..284400920e 100644 --- a/crates/denoise/src/lib.rs +++ b/crates/denoise/src/lib.rs @@ -11,7 +11,7 @@ //! - [`product`]: the cache file the denoised picture is kept in (half floats, compressed in strips) and the //! blend with the plain demosaic that the Amount slider controls. //! - [`cpu`] and [`runtime`]: a single-thread pure-Rust CPU runner and its installation self-test. -//! - [`defringe`]: AI Defringe, a defringe network run over a whole picture with its guards. +//! - `defringe` (with the `runtime` feature): AI Defringe, a defringe network run over a whole picture with its guards. //! - [`net`] and [`onnx`]: checked plain network data and bounded ONNX decoding, shared by CPU and GPU. //! - [`remote`]: running tiles on another computer's graphics card over TCP (a [`run::TileRunner`] and its server). //! diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 55c87056c6..66caf27c8d 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -192,6 +192,7 @@ impl DevelopSettings { self.curve = d; } Section::Color => self.wb.mode = WbMode::AsShot, + Section::Optics => self.optics.ai_defringe_on = None, Section::Detail => { self.enhance.denoise_on = None; // not a slider: reset like them, to the general default (off) @@ -479,6 +480,18 @@ mod tests { assert!(!s.profile.camera_local_tone); } + #[test] + fn resetting_optics_clears_the_ai_defringe_switch() { + // switched off by hand, then Optics reset: a later Amount turns it on, as on a fresh photo + let mut s = DevelopSettings::default(); + s.optics.ai_defringe = 60.0; + s.optics.ai_defringe_on = Some(false); + s.reset_section(Section::Optics); + assert_eq!((s.optics.ai_defringe, s.optics.ai_defringe_on), (0.0, None)); + s.optics.ai_defringe = 30.0; + assert!(s.optics.ai_defringe_enabled()); + } + #[test] fn section_toggles() { let mut s = DevelopSettings::default(); diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index 7e1c2c5fa8..d9ca5ce13a 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -116,10 +116,17 @@ pub fn models_dir() -> Option { .or_else(|| crate::config::config_dir().map(|d| d.join("defringe-models"))) } -/// The model installed in `dir`: its manifest and file, if there is one. +/// The folder inside the models folder that holds the installed model. LightCraft owns it and nothing else there: +/// the models folder may be one the user keeps other files in. +const CURRENT: &str = "installed"; +/// The previous installation while a new one replaces it, kept until the replacement is in place. +const PREVIOUS: &str = ".installed-previous"; + +/// The model installed in models folder `dir`: its manifest and file, if there is one. pub fn installed(dir: &Path) -> Option<(Manifest, PathBuf)> { - let m = Manifest::parse(&std::fs::read_to_string(dir.join(MANIFEST)).ok()?).ok()?; - let file = dir.join(&m.file); + let cur = dir.join(CURRENT); + let m = Manifest::parse(&std::fs::read_to_string(cur.join(MANIFEST)).ok()?).ok()?; + let file = cur.join(&m.file); file.is_file().then_some((m, file)) } @@ -172,26 +179,38 @@ fn bare(onnx: &Path, name: &str) -> Result { } fn read_model_file(path: &Path, m: &Manifest) -> Result, String> { - let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len(); - if len > MAX_MODEL_BYTES { + use std::io::Read; + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let mut bytes = Vec::new(); + // read at most one byte past the limit, whatever the file says its size is + file.take(MAX_MODEL_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > MAX_MODEL_BYTES { return Err("the model file is too large".into()); } - let bytes = std::fs::read(path).map_err(|e| e.to_string())?; if lightcraft_denoise_core::hash::sha256_hex(&bytes) != m.sha256 { return Err("the model file's SHA-256 is not the one its manifest gives".into()); } Ok(bytes) } -/// Install the model `onnx` (with its manifest beside it) in `dir`, after checking its hash and running it once: it -/// replaces the installed one. The caller has shown the user the manifest's licence and notice. -pub fn install(onnx: &Path, dir: &Path) -> Result { +/// Install the model `onnx` (with its manifest beside it, or without one: [`inspect`]) in models folder `dir`, after +/// checking its hash and running it once: it replaces the installed one. `accepted` is the manifest the user was shown +/// and accepted ([`inspect`]'s answer); if the file or its manifest changed since, nothing is installed. +pub fn install(onnx: &Path, dir: &Path, accepted: &Manifest) -> Result { let m = inspect(onnx)?; + if &m != accepted { + return Err("the model or its description changed after you accepted it: install it again to see its terms".into()); + } + // the bytes read here are the ones checked, run and installed let bytes = read_model_file(onnx, &m)?; self_test(&bytes)?; - let parent = dir.parent().ok_or("the defringe models folder has no parent")?; - std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let staging = parent.join(format!(".defringe-models-{}", std::process::id())); + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let (cur, prev) = (dir.join(CURRENT), dir.join(PREVIOUS)); + // a previous installation left behind by an install that could not put it back is restored first, never deleted + if !cur.exists() && prev.exists() { + std::fs::rename(&prev, &cur).map_err(|e| format!("couldn't restore the previous model from {}: {e}", prev.display()))?; + } + let staging = dir.join(format!(".installing-{}", std::process::id())); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; let write = || -> std::io::Result<()> { @@ -202,25 +221,33 @@ pub fn install(onnx: &Path, dir: &Path) -> Result { let _ = std::fs::remove_dir_all(&staging); return Err(e.to_string()); } - let old = parent.join(format!(".defringe-models-old-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&old); - if dir.exists() { - std::fs::rename(dir, &old).map_err(|e| e.to_string())?; + if prev.exists() { + std::fs::remove_dir_all(&prev).map_err(|e| e.to_string())?; } - if let Err(e) = std::fs::rename(&staging, dir) { - let _ = std::fs::rename(&old, dir); + if cur.exists() { + std::fs::rename(&cur, &prev).map_err(|e| e.to_string())?; + } + if let Err(e) = std::fs::rename(&staging, &cur) { + let _ = std::fs::remove_dir_all(&staging); + if prev.exists() + && let Err(back) = std::fs::rename(&prev, &cur) + { + return Err(format!("couldn't install the model ({e}), nor put the previous one back ({back}); it is kept in {}", prev.display())); + } return Err(e.to_string()); } - let _ = std::fs::remove_dir_all(&old); + let _ = std::fs::remove_dir_all(&prev); Ok(m) } -/// Delete the model installed in `dir` (corrections already made stay until the cache is cleared). +/// Delete the model installed in models folder `dir` (only LightCraft's own folder in it; corrections already made +/// stay until the cache is cleared). pub fn remove(dir: &Path) -> Result { - if !dir.exists() { + let cur = dir.join(CURRENT); + if !cur.exists() { return Ok(false); } - std::fs::remove_dir_all(dir).map_err(|e| e.to_string())?; + std::fs::remove_dir_all(&cur).map_err(|e| e.to_string())?; Ok(true) } @@ -284,9 +311,16 @@ pub struct Correction { h: usize, index: Vec, gain: Vec<[u16; 3]>, - /// The last source it was applied to (address and size) at an amount (thousandths), and the result: renders of - /// one view reuse the corrected picture, so the stage cache keeps working while sliders move. - memo: Mutex)>>, + /// The last source it was applied to, at an amount (thousandths), and the result: renders of one view reuse the + /// corrected picture, so the stage cache keeps working while sliders move. Both are weak: the memo keeps no picture + /// alive (each would be a whole picture), and a source freed and replaced at the same address never matches. + memo: Mutex>, +} + +struct Memo { + source: std::sync::Weak, + thousandths: u32, + result: std::sync::Weak, } impl Correction { @@ -301,12 +335,14 @@ impl Correction { return src.clone(); } let k = amount.min(1.0); - let tag = (Arc::as_ptr(src) as usize, src.width, src.height, (k * 1000.0).round() as u32); + let thousandths = (k * 1000.0).round() as u32; let mut memo = self.memo.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((t, img)) = memo.as_ref() - && *t == tag + if let Some(m) = memo.as_ref() + && m.thousandths == thousandths + && m.source.upgrade().is_some_and(|s| Arc::ptr_eq(&s, src)) + && let Some(img) = m.result.upgrade() { - return img.clone(); + return img; } let (w, h) = (src.width, src.height); let mut out = (**src).clone(); @@ -319,8 +355,18 @@ impl Correction { } } } else { - // each source pixel covers (self.w / w) × (self.h / h) pixels of the correction - let area = (self.w as f32 / w as f32).max(1.0) * (self.h as f32 / h as f32).max(1.0); + // each pixel of the render takes the mean gain over the pixels of the correction that map to it (how many + // depends on where it is when the sizes don't divide) + let covers = |big: usize, small: usize| -> Vec { + let mut n = vec![0u32; small]; + for x in 0..big { + if let Some(c) = n.get_mut((x * small / big).min(small - 1)) { + *c += 1; + } + } + n + }; + let (nx, ny) = (covers(self.w, w), covers(self.h, h)); let mut acc: HashMap = HashMap::new(); for (&i, g) in self.index.iter().zip(&self.gain) { let (x, y) = (i as usize % self.w, i as usize / self.w); @@ -331,6 +377,7 @@ impl Correction { } } for (i, s) in acc { + let area = (nx.get(i % w).copied().unwrap_or(1) * ny.get(i / w).copied().unwrap_or(1)).max(1) as f32; if let Some(p) = out.data.get_mut(i) { for (v, d) in p.iter_mut().zip(s) { *v *= 1.0 + d / area * k; @@ -339,12 +386,15 @@ impl Correction { } } let out = Arc::new(out); - *memo = Some((tag, out.clone())); + *memo = Some(Memo { source: Arc::downgrade(src), thousandths, result: Arc::downgrade(&out) }); out } + /// Write the correction to `path` through a temporary file of this writer's own, if `publish` still allows it + /// (the cache was not cleared since the work started). Another writer that published the same correction first + /// is a success. #[cfg_attr(not(feature = "denoise"), allow(dead_code))] - fn write(&self, path: &Path) -> Result<(), String> { + fn write(&self, path: &Path, publish: &Publish) -> Result<(), String> { let mut body = Vec::with_capacity(self.index.len() * 10); for (i, g) in self.index.iter().zip(&self.gain) { body.extend_from_slice(&i.to_le_bytes()); @@ -363,9 +413,22 @@ impl Correction { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; } - let tmp = path.with_extension("tmp"); + static NEXT: AtomicUsize = AtomicUsize::new(0); + let tmp = path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); std::fs::write(&tmp, &b).map_err(|e| e.to_string())?; - std::fs::rename(&tmp, path).map_err(|e| e.to_string()) + let epoch = publish.epoch.lock().unwrap_or_else(PoisonError::into_inner); + let done = if *epoch != publish.at { + Err("the AI Defringe cache was cleared while this correction was made".into()) + } else { + match std::fs::rename(&tmp, path) { + Ok(()) => Ok(()), + Err(_) if Correction::read(path, self.key).is_some() => Ok(()), + Err(e) => Err(e.to_string()), + } + }; + drop(epoch); + let _ = std::fs::remove_file(&tmp); + done } /// The correction at `path`, if it is one, for `key`, and intact. @@ -427,6 +490,14 @@ fn f16_value(b: u16) -> f32 { if sign == 1 { -v } else { v } } +/// Whether a correction may still be published: the cache's epoch when its work started, and the cache's epoch now +/// (bumped, under the lock, when the cache is cleared). +#[derive(Clone)] +pub struct Publish { + epoch: Arc>, + at: u64, +} + /// The name of photo `p`'s correction by the model with SHA-256 `model`. pub fn key(p: &Photo, model: &str) -> u64 { let mut h = Hasher128::new(); @@ -443,6 +514,7 @@ pub struct Recipe { info: SourceInfo, model: Arc, path: Option, + publish: Publish, } impl Recipe { @@ -476,14 +548,14 @@ impl Recipe { } let c = Correction { key: self.key, w, h, index, gain, memo: Mutex::new(None) }; if let Some(path) = &self.path { - c.write(path)?; + c.write(path, &self.publish)?; } Ok(c) } #[cfg(not(feature = "denoise"))] pub fn make(&self, _: &(dyn Fn(usize, usize) + Sync), _: &AtomicBool) -> Result { - let _ = (&self.source, &self.info, &self.model, &self.path); + let _ = (&self.source, &self.info, &self.model, &self.path, &self.publish); Err("this build of LightCraft can't run AI models".into()) } } @@ -521,6 +593,8 @@ struct Job { done: Arc, total: Arc, cancel: Arc, + /// The cache's epoch when it started: a result from before a clear is dropped. + epoch: u64, _task: crate::activity::TaskGuard, } @@ -535,6 +609,10 @@ pub struct State { job: Option, /// Corrections that failed, by key, and why (not tried again until asked). failed: HashMap, + /// Corrections the user cancelled, by key (not started again until asked: Try Again, or switching it on). + cancelled: std::collections::HashSet, + /// The cache's epoch, bumped (under this lock) when it is cleared ([`Publish`]). + epoch: Arc>, /// Corrections in memory, most recently used last. ready: Vec<(PhotoId, Arc)>, /// Bumped whenever a correction arrives (renders made before it are stale). @@ -616,7 +694,12 @@ impl Session { let key = key(&p, &sha); let path = self.aidefringe_dir().map(|d| d.join(format!("{key:016x}.lcadf"))); let source = self.media.source_ref_uncached(&p, SourceLevel::Full); - Ok(Recipe { photo: id, key, source, info: self.source_info(id), model, path }) + let publish = Publish { epoch: self.aidefringe.epoch.clone(), at: self.aidefringe_epoch() }; + Ok(Recipe { photo: id, key, source, info: self.source_info(id), model, path, publish }) + } + + fn aidefringe_epoch(&self) -> u64 { + *self.aidefringe.epoch.lock().unwrap_or_else(PoisonError::into_inner) } /// The installed model's key for photo `p`, if a model is installed. @@ -703,12 +786,13 @@ impl Session { } } - /// Forget why photo `id`'s correction failed, so it is tried again. + /// Forget why photo `id`'s correction failed or that it was cancelled, so it is tried again. pub fn aidefringe_retry(&mut self, id: PhotoId) { if let Some(p) = self.catalog.photo(id).cloned() && let Some(key) = self.aidefringe_key(&p) { self.aidefringe.failed.remove(&key); + self.aidefringe.cancelled.remove(&key); } } @@ -732,7 +816,9 @@ impl Session { } r => { let Some(job) = self.aidefringe.job.take() else { return false }; + let stale = job.epoch != self.aidefringe_epoch(); match r { + _ if stale => {} Ok(Ok(c)) => { self.aidefringe_keep(job.photo, Arc::new(c)); arrived = true; @@ -740,6 +826,10 @@ impl Session { Ok(Err(e)) if !job.cancel.load(Ordering::Relaxed) => { self.aidefringe.failed.insert(job.key, e); } + // cancelled while still wanted: by the user, so not started again by itself + Ok(Err(_)) if still => { + self.aidefringe.cancelled.insert(job.key); + } Ok(Err(_)) => {} Err(_) => { self.aidefringe.failed.insert(job.key, "the defringe job stopped".into()); @@ -757,7 +847,7 @@ impl Session { return arrived; } let Some(key) = self.aidefringe_key(&p) else { return arrived }; - if self.aidefringe.failed.contains_key(&key) || self.aidefringe_get(id, key).is_some() { + if self.aidefringe.failed.contains_key(&key) || self.aidefringe.cancelled.contains(&key) || self.aidefringe_get(id, key).is_some() { return arrived; } match self.aidefringe_recipe(id) { @@ -774,7 +864,7 @@ impl Session { let task = self.activity.start("aidefringe", "AI Defringe", crate::activity::Cancel::Flag(cancel.clone())); task.detail(name); let (tx, rx) = channel(); - let (d, t, c, key, photo) = (done.clone(), total.clone(), cancel.clone(), r.key, r.photo); + let (d, t, c, key, photo, epoch) = (done.clone(), total.clone(), cancel.clone(), r.key, r.photo, r.publish.at); std::thread::Builder::new() .name("ai-defringe".into()) .spawn(move || { @@ -787,7 +877,7 @@ impl Session { let _ = tx.send(made); }) .ok(); - self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, _task: task }); + self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, epoch, _task: task }); } /// Make photo `id`'s correction now, on this thread (for scripts and tests) → how many pixels it changes. @@ -796,14 +886,23 @@ impl Session { let c = Arc::new(r.make(&|_, _| {}, &AtomicBool::new(false))?); let n = c.changed(); self.aidefringe.failed.remove(&r.key); + self.aidefringe.cancelled.remove(&r.key); self.aidefringe_keep(id, c); Ok(n) } - /// Delete every cached correction of this library → (files, bytes). + /// Delete every cached correction of this library → (files, bytes). Work started before is not published: the + /// epoch is bumped under the lock writers publish under, so none can write after the files are deleted. pub fn aidefringe_clear(&mut self) -> (usize, u64) { + let epoch = self.aidefringe.epoch.clone(); + let mut epoch = epoch.lock().unwrap_or_else(PoisonError::into_inner); + *epoch += 1; + if let Some(j) = &self.aidefringe.job { + j.cancel.store(true, Ordering::Relaxed); + } self.aidefringe.ready.clear(); self.aidefringe.failed.clear(); + self.aidefringe.cancelled.clear(); self.aidefringe.generation += 1; let Some(dir) = self.aidefringe_dir() else { return (0, 0) }; let (mut files, mut bytes) = (0, 0); @@ -827,6 +926,7 @@ impl Session { } self.aidefringe.model = None; self.aidefringe.failed.clear(); + self.aidefringe.cancelled.clear(); self.aidefringe.generation += 1; self.aidefringe_refresh(true); } diff --git a/crates/engine/src/aidefringe/tests.rs b/crates/engine/src/aidefringe/tests.rs index 2eb7dabcd0..0311128e18 100644 --- a/crates/engine/src/aidefringe/tests.rs +++ b/crates/engine/src/aidefringe/tests.rs @@ -1,4 +1,5 @@ use super::*; +use std::path::PathBuf; fn manifest_json(sha: &str) -> String { format!( @@ -30,12 +31,33 @@ fn correction(w: usize, h: usize, at: &[(usize, [f32; 3])]) -> Correction { } } +/// A folder of this test's own, removed when it ends (also when an assertion fails). +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> TempDir { + TempDir(crate::tests_xmp::temp_dir(tag)) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn publish() -> Publish { + Publish { epoch: Arc::new(Mutex::new(0)), at: 0 } +} + #[test] fn a_correction_survives_the_disk_and_a_damaged_one_is_refused() { - let dir = std::env::temp_dir().join(format!("lc-adf-{}", std::process::id())); - let path = dir.join("c.lcadf"); + let dir = TempDir::new("adf-file"); + let path = dir.0.join("c.lcadf"); let c = correction(10, 4, &[(3, [0.5, -0.25, 0.0]), (17, [0.0, 0.125, -0.5])]); - c.write(&path).unwrap(); + c.write(&path, &publish()).unwrap(); + // a second writer of the same correction (the background job and an export) succeeds too + c.write(&path, &publish()).unwrap(); let back = Correction::read(&path, 7).unwrap(); assert_eq!((back.w, back.h, &back.index, &back.gain), (10, 4, &c.index, &c.gain)); assert!(Correction::read(&path, 8).is_none(), "another key"); @@ -44,7 +66,12 @@ fn a_correction_survives_the_disk_and_a_damaged_one_is_refused() { bytes[last] ^= 0xff; std::fs::write(&path, &bytes).unwrap(); assert!(Correction::read(&path, 7).is_none(), "damaged"); - let _ = std::fs::remove_dir_all(&dir); + // after the cache was cleared, work started before it is not published + let stale = Publish { epoch: Arc::new(Mutex::new(1)), at: 0 }; + let other = dir.0.join("d.lcadf"); + assert!(c.write(&other, &stale).is_err()); + assert!(!other.exists()); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1, "no temporary file left behind"); } #[test] @@ -71,3 +98,28 @@ fn half_floats_round_trip() { } assert_eq!(f16_value(f16_bits(1e9)), 65504.0); } + +#[test] +fn a_smaller_source_whose_size_does_not_divide_keeps_a_constant_gain() { + // 3 × 1 with the same gain everywhere, rendered 2 × 1: two pixels of it map to the first, one to the second + let c = correction(3, 1, &[(0, [0.5; 3]), (1, [0.5; 3]), (2, [0.5; 3])]); + let src = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.4; 3]; 2] }); + let out = c.apply(&src, 1.0); + for p in &out.data { + assert!(p.iter().all(|v| (v - 0.6).abs() < 1e-6), "{:?}", out.data); + } +} + +#[test] +fn the_memo_keeps_nothing_alive_and_never_mistakes_a_new_picture_for_an_old_one() { + let c = correction(2, 1, &[(0, [1.0, 0.0, 0.0])]); + let a = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.5; 3]; 2] }); + let first = c.apply(&a, 1.0); + assert!(Arc::ptr_eq(&first, &c.apply(&a, 1.0)), "the same view reuses its picture"); + assert_eq!(Arc::strong_count(&first), 1, "the memo holds no strong reference"); + drop(first); + drop(a); + // a new picture, maybe at the old one's address: corrected afresh + let b = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.25; 3]; 2] }); + assert_eq!(c.apply(&b, 1.0).data[0], [0.5, 0.25, 0.25]); +} diff --git a/crates/engine/src/cmd/aidefringe.rs b/crates/engine/src/cmd/aidefringe.rs index 5f48684dd1..c51e67e45d 100644 --- a/crates/engine/src/cmd/aidefringe.rs +++ b/crates/engine/src/cmd/aidefringe.rs @@ -16,8 +16,9 @@ fn photo(s: &Session, p: &Value, c: &str) -> Result { } } +/// The manifest as JSON: what the user is shown, and what `aiDefringe.models.install` takes back as `model`. fn model_json(m: &aidefringe::Manifest) -> Value { - json!({"id": m.id, "name": m.name, "version": m.version, "licence": m.licence, "sha256": m.sha256, "notice": m.notice, "url": m.url}) + serde_json::to_value(m).unwrap_or(Value::Null) } /// A per-photo switch, independent of the selection and Auto Sync. Turning on starts at 100. @@ -32,6 +33,14 @@ fn toggle(s: &mut Session, p: &Value) -> Result { if on && s.aidefringe_model().is_none() { return Err(bad(C, "AI Defringe needs a model: install one in Settings > AI Defringe")); } + // switching off a photo that was never switched on changes nothing (so the first switch on still starts at 100) + if !on && d.optics.ai_defringe_on.is_none() && !d.optics.ai_defringe_enabled() { + return Ok(json!({"id": id.0, "enabled": false, "amount": d.optics.ai_defringe})); + } + if on { + // switching on asks for the correction again, even one the user cancelled + s.aidefringe_retry(id); + } // the switch is its own setting: the Amount stays where it is when it is flipped, so flipping compares with and // without; a photo that never had an Amount starts at 100 let amount = if on && d.optics.ai_defringe_on.is_none() && d.optics.ai_defringe <= 0.0 { 100.0 } else { d.optics.ai_defringe }; @@ -98,8 +107,13 @@ fn install(s: &mut Session, p: &Value) -> Result { if !bool_or(p, "acknowledged", false) { return Err(bad(C, "show the user the model's licence and notice first, then pass `acknowledged: true`")); } + // what the user accepted: the model `aiDefringe.models.inspect` gave, which must still be what the path holds + let accepted = p + .get("model") + .ok_or_else(|| bad(C, "`model` is required: the model `aiDefringe.models.inspect` gave, as the user accepted it")) + .and_then(|v| aidefringe::Manifest::parse(&v.to_string()).map_err(|e| bad(C, e)))?; let dir = s.aidefringe_models_dir().ok_or_else(|| bad(C, "no folder for defringe models (set LIGHTCRAFT_DEFRINGE_MODELS)"))?; - let m = aidefringe::install(Path::new(path), &dir).map_err(|e| bad(C, e))?; + let m = aidefringe::install(Path::new(path), &dir, &accepted).map_err(|e| bad(C, e))?; s.aidefringe_model_changed(); Ok(json!({"installed": true, "model": model_json(&m)})) } @@ -133,8 +147,8 @@ pub fn specs() -> Vec { cmd!(query "aiDefringe.pump", "AI Defringe Pump", [], None, "{} → {arrived, generation} — called every frame by the app: takes in a finished correction and starts the active photo's when AI Defringe is on and it has none", always, pump), cmd!(query "aiDefringe.make", "Make AI Defringe Correction", [], None, "{id?} → {id, changed} — make a photo's correction now and wait for it (for scripts); `changed` is how many pixels it changes", always, make), cmd!(query "aiDefringe.retry", "Retry AI Defringe", [], None, "{id?} → {id, photo} — try a photo whose correction failed again", always, retry), - cmd!(query "aiDefringe.models.inspect", "Inspect Defringe Model", [], None, "{path} → {id, name, version, licence, sha256, notice, url} — the defringe-model.json beside an .onnx file, checked; never runs the file", always, inspect), - cmd!(query "aiDefringe.models.install", "Install Defringe Model", [], None, "{path, acknowledged: true} → {installed, model} — install a defringe model from an .onnx file with a defringe-model.json beside it, after checking its SHA-256 and running it once; it replaces the installed one. `acknowledged` must be true: the user has been shown the model's licence and notice", always, install), + cmd!(query "aiDefringe.models.inspect", "Inspect Defringe Model", [], None, "{path} → {id, name, version, licence, file, sha256, contract, notice?, url?} — the defringe-model.json beside an .onnx file, checked, or one made up from the file when there is none (licence \"Not stated\"); never runs the file", always, inspect), + cmd!(query "aiDefringe.models.install", "Install Defringe Model", [], None, "{path, model, acknowledged: true} → {installed, model} — install a defringe model from an .onnx file (with a defringe-model.json beside it, or without one: `aiDefringe.models.inspect` describes it), after checking its SHA-256 and running it once; it replaces the installed one. `model` is what `aiDefringe.models.inspect` gave and `acknowledged` must be true: the user has been shown that model's licence and notice and accepted them. If the file or its description changed since, nothing is installed", always, install), cmd!(query "aiDefringe.models.remove", "Remove Defringe Model", [], None, "{} → {removed} — delete the installed defringe model (corrections already made stay until cleared)", always, remove), cmd!(query "aiDefringe.clear", "Clear AI Defringe Cache", [], None, "{} → {deleted, bytes} — delete every cached AI Defringe correction of this library (they are made again when wanted)", always, clear), ] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a5d8c2912..af2e86be5b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1038,6 +1038,14 @@ impl Session { for k in ["spots", "red_eye", "version", "process"] { o.remove(k); } + // AI Defringe is per photo, like AI Denoise's switch: its switch and Amount stay with the photo they were set on + if let Some(optics) = o.get_mut("optics").and_then(Value::as_object_mut) { + optics.remove("ai_defringe"); + optics.remove("ai_defringe_on"); + if optics.is_empty() { + o.remove("optics"); + } + } if o.is_empty() { return Vec::new(); } diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 4c9838f3a2..1c99d001f0 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -149,10 +149,24 @@ impl crate::Session { ^ (job.level as u64) << 60 ^ profile_salt.rotate_left(29) ^ lens.rotate_left(37) - ^ decoder.rotate_left(43); + ^ decoder.rotate_left(43) + ^ job.ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11)); Some(job) } + /// `ck` with AI Defringe's correction in it, when the render uses one: a thumbnail rendered before the correction + /// was there is not taken for one with it. + fn with_ai_defringe(ck: Hash128, a: Option<&crate::aidefringe::ForRender>) -> Hash128 { + match a { + Some(a) => { + let mut k = Hasher128::new(); + k.u64(ck.0 as u64).u64((ck.0 >> 64) as u64).str("aidefringe").u64(a.key()); + k.finish() + } + None => ck, + } + } + /// Cache key of a variant thumbnail ([`Self::variant_job`]). /// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile. pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 { @@ -189,7 +203,10 @@ impl crate::Session { // decoded as these settings develop it (their camera profile, or none) p.develop = Arc::new(settings.clone()); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)); + // with AI Defringe's correction when these settings use it and it is made + let ai_defringe = self.aidefringe_for_render(&p, settings, false).ok().flatten(); + let ck = + Self::with_ai_defringe(Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)), ai_defringe.as_ref()); Some(RenderJob { request_id: 0, cache_generation: self.media.rendered.generation(), @@ -210,7 +227,7 @@ impl crate::Session { slide: None, preview_cut: None, display_fit: None, - ai_defringe: None, + ai_defringe, }) } @@ -245,8 +262,14 @@ impl crate::Session { let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64); let level = SourceLevel::for_size(needed as usize); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)); - let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize); + // the photo's own look, so with its AI Defringe correction when it is on and made + let ai_defringe = self.aidefringe_for_render(&p, &settings, false).ok().flatten(); + let ck = Self::with_ai_defringe( + Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)), + ai_defringe.as_ref(), + ); + // (a raw's embedded preview has no correction: a corrected tile is rendered) + let preview_cut = if ai_defringe.is_some() { None } else { self.face_preview_cut(&p, rect, edge, needed as usize) }; Some(RenderJob { request_id: 0, cache_generation: self.media.rendered.generation(), @@ -267,7 +290,7 @@ impl crate::Session { slide: None, preview_cut, display_fit: None, - ai_defringe: None, + ai_defringe, }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2916185704..0a2b4734aa 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -646,6 +646,9 @@ fn op_log_replay_reproduces_catalog() { #[test] fn command_sweep() { let mut s = demo(); + // `aiDefringe.models.remove` would delete the model installed in the real defringe models folder + let models = std::env::temp_dir().join(format!("lc-sweep-defringe-models-{}", std::process::id())); + s.set_aidefringe_models_dir(Some(models.clone())); let mut ids = std::collections::HashSet::new(); for c in command_specs() { assert!(ids.insert(c.id), "duplicate {}", c.id); @@ -659,6 +662,7 @@ fn command_sweep() { // empty params must never start a download from the internet assert!(!s.place_names.download_started(), "the sweep started a place names download"); assert!(s.commands().len() >= 70, "{}", s.commands().len()); + let _ = std::fs::remove_dir_all(&models); } #[test] diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index d1be34c57d..e7b990ddef 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -62,9 +62,15 @@ fn photo(s: &Session) -> lightcraft_catalog::PhotoId { s.catalog.photos().next().unwrap().id } +/// Install the model at `path` as the app does: inspect it, then install what was inspected, acknowledged. +fn install_path(s: &mut Session, path: &Path) -> crate::Result { + let model = s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()}))?; + s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": model, "acknowledged": true})) +} + fn install(x: &mut Setup) -> Value { let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); - x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap() + install_path(&mut x.s, &path).unwrap() } #[test] @@ -73,10 +79,20 @@ fn a_model_is_installed_only_when_acknowledged_and_intact() { let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); let inspected = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); assert_eq!(inspected["notice"], "a test network"); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy()})).is_err(), "not acknowledged"); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": inspected})).is_err(), "not acknowledged"); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).is_err(), "nothing accepted"); + // the manifest changed after the user accepted it: its licence was not the one shown + let manifest = path.with_file_name(MANIFEST); + let text = std::fs::read_to_string(&manifest).unwrap(); + std::fs::write(&manifest, text.replace("\"MIT\"", "\"Non-commercial\"")).unwrap(); + let r = x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": inspected, "acknowledged": true})); + assert!(r.unwrap_err().to_string().contains("changed after you accepted it")); + std::fs::write(&manifest, text).unwrap(); // a file that isn't the one its manifest names + let good = std::fs::read(&path).unwrap(); std::fs::write(&path, b"something else").unwrap(); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).is_err()); + assert!(install_path(&mut x.s, &path).is_err()); + std::fs::write(&path, good).unwrap(); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); let r = install(&mut x); assert_eq!(r["model"]["id"], "push"); @@ -159,7 +175,7 @@ fn any_defringe_shaped_onnx_installs_without_a_manifest_and_anything_else_is_ref // a denoiser (the wrong shape) is refused when it is run, and nothing is installed let wrong = bare.join("smoothing.onnx"); std::fs::write(&wrong, lightcraft_denoise::synthetic::smoothing_onnx()).unwrap(); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": wrong.to_string_lossy(), "acknowledged": true})).is_err()); + assert!(install_path(&mut x.s, &wrong).is_err()); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); // a defringe network on its own: named after its file, its licence unknown let path = bare.join("My Defringe v2.onnx"); @@ -167,9 +183,52 @@ fn any_defringe_shaped_onnx_installs_without_a_manifest_and_anything_else_is_ref let m = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); assert_eq!((m["name"].as_str(), m["licence"].as_str()), (Some("My Defringe v2"), Some("Not stated"))); assert!(m["notice"].as_str().unwrap().contains("doesn't know who made it")); - x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap(); + install_path(&mut x.s, &path).unwrap(); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"]["id"], "My-Defringe-v2"); x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); assert!(x.s.execute("aiDefringe.make", &json!({})).unwrap()["changed"].as_u64().unwrap() > 0); let _ = std::fs::remove_dir_all(&x.dir); } + +#[test] +fn the_models_folder_keeps_the_users_own_files() { + let mut x = setup("adf-own-files"); + // the user pointed the models folder at one that holds their own files + let models = x.dir.join("defringe-models"); + std::fs::create_dir_all(&models).unwrap(); + std::fs::write(models.join("mine.onnx"), b"the user's").unwrap(); + install(&mut x); + install(&mut x); + assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "installing twice"); + x.s.execute("aiDefringe.models.remove", &json!({})).unwrap(); + assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "removing"); + assert_eq!(x.s.execute("aiDefringe.models.remove", &json!({})).unwrap()["removed"], false); + assert!(models.join("mine.onnx").exists()); + let _ = std::fs::remove_dir_all(&x.dir); +} + +#[test] +fn the_switch_starts_at_100_even_after_switching_off_an_untouched_photo_and_stays_out_of_auto_sync() { + let mut x = setup("adf-switch-default"); + let originals = x.dir.join("originals"); + std::fs::write(originals.join("second.dng"), stripe_dng(336, 288)).unwrap(); + x.s.execute("library.import", &json!({"paths": [originals.join("second.dng").to_string_lossy()]})).unwrap(); + install(&mut x); + let ids: Vec<_> = x.s.catalog.photos().map(|p| p.id).collect(); + let (a, b) = (ids[0], ids[1]); + x.s.execute("library.select", &json!({"ids": [a.0]})).unwrap(); + let r = x.s.execute("aiDefringe.toggle", &json!({"enabled": false})).unwrap(); + assert_eq!(r["enabled"], false); + assert_eq!(x.s.develop_of(a).unwrap().optics.ai_defringe_on, None, "nothing to switch off"); + let r = x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + assert_eq!(r["amount"], 100.0); + // Auto Sync with both selected: an AI Defringe change stays on the photo it was made on + x.s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + x.s.auto_sync = true; + x.s.execute("develop.set", &json!({"values": {"optics.aiDefringe": 40.0, "optics.vignetting": 10.0}})).unwrap(); + let (da, db) = (x.s.develop_of(a).unwrap(), x.s.develop_of(b).unwrap()); + assert_eq!((da.optics.ai_defringe, da.optics.vignetting), (40.0, 10.0)); + assert_eq!(db.optics.vignetting, 10.0, "the rest of the edit syncs"); + assert_eq!((db.optics.ai_defringe, db.optics.ai_defringe_on), (0.0, None), "AI Defringe does not"); + let _ = std::fs::remove_dir_all(&x.dir); +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index fc377fc3c7..ce5a9f68f0 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -662,7 +662,9 @@ pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: & rendition.optics.remove_ca = true; let plan = plan(src, info, &rendition, req); let mut img = plan.frame.sample(src, plan.w, plan.h); - lin_cpu(&mut img, info, &plan); + // `lin_cpu` up to the Defringe stage: retouching and red-eye come after it + local_tone::apply(&mut img, info, &plan); + local::white_balance(&mut img, info, &plan.settings); img } diff --git a/crates/ui-egui/src/panels/aidefringe.rs b/crates/ui-egui/src/panels/aidefringe.rs index 56b047b2c1..230bcf4dd0 100644 --- a/crates/ui-egui/src/panels/aidefringe.rs +++ b/crates/ui-egui/src/panels/aidefringe.rs @@ -29,6 +29,8 @@ pub struct Ui { /// with it) and keeps the open photo's coming; while one is being made, asks again for its progress. pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { if now < app.caches.aidefringe.next_pump { + // come back at the deadline even if nothing else asks for a frame + ctx.request_repaint_after(std::time::Duration::from_secs_f64(app.caches.aidefringe.next_pump - now)); return; } let Ok(v) = app.session.execute("aiDefringe.pump", &json!({})) else { return }; @@ -47,6 +49,22 @@ pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { } } +/// The AI Defringe check → whether it is on now. +fn switch(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, mut on: bool) -> bool { + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }).show(ui, |ui| { + let r = ui.add(egui::Checkbox::new(&mut on, tr("AI Defringe"))).on_hover_text(tr( + "Removes colour fringes of every hue (purple, blue, green) with the installed defringe model, leaving real colours alone. \ + The correction is made once in the background and kept; switching it off and on, or changing Amount, is instant.", + )); + register(ui, "aidefringe:enabled", r.rect); + if r.changed() { + let _ = app.run("aiDefringe.toggle", json!({"id": id.0, "enabled": on})); + app.caches.aidefringe.next_pump = 0.0; + } + }); + on +} + fn note(ui: &mut egui::Ui, text: &str, color: egui::Color32) { ui.add(egui::Label::new(RichText::new(text).size(11.0).color(color)).wrap()); } @@ -75,19 +93,13 @@ pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Deve } } }); + // a photo left with it on (its model since removed) can still be switched off + if d.optics.ai_defringe_enabled() { + switch(app, ui, id, true); + } return; } - let mut on = d.optics.ai_defringe_enabled(); - egui::Frame::NONE.inner_margin(pad(6, 2)).show(ui, |ui| { - let r = ui.add(egui::Checkbox::new(&mut on, tr("AI Defringe"))).on_hover_text(tr( - "Removes colour fringes of every hue (purple, blue, green) with the installed defringe model, leaving real colours alone. \ - The correction is made once in the background and kept; switching it off and on, or changing Amount, is instant.", - )); - register(ui, "aidefringe:enabled", r.rect); - if r.changed() { - let _ = app.run("aiDefringe.toggle", json!({"id": id.0, "enabled": on})); - } - }); + let on = switch(app, ui, id, d.optics.ai_defringe_enabled()); crate::panels::edit::control(app, ui, d, "optics.aiDefringe", on); if !on || status["photo"].is_null() { return; @@ -191,7 +203,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let install = crate::button::Button::new("Accept and Install").widget("aidefringe:accept").show(ui); let cancel = crate::button::Button::new("Cancel").widget("aidefringe:cancel").show(ui); if install.clicked() { - match app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})) { + match app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": info, "acknowledged": true})) { Ok(_) => app.caches.aidefringe.rejected = None, Err(e) => app.caches.aidefringe.rejected = Some(plain(&e)), } diff --git a/crates/ui-egui/src/tests/aidefringe.rs b/crates/ui-egui/src/tests/aidefringe.rs index f5b25cd310..630fc27948 100644 --- a/crates/ui-egui/src/tests/aidefringe.rs +++ b/crates/ui-egui/src/tests/aidefringe.rs @@ -98,7 +98,8 @@ fn the_switch_turns_it_on_and_the_correction_arrives() { let dir = temp("switch"); let mut h = defringe_open(&dir); let path = model_file(&dir); - h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})).unwrap(); + let model = h.app.session.execute("aiDefringe.models.inspect", &json!({"path": path})).unwrap(); + h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": model, "acknowledged": true})).unwrap(); h.app.caches.aidefringe = Default::default(); h.step(); h.step(); @@ -127,3 +128,25 @@ fn the_switch_turns_it_on_and_the_correction_arrives() { assert_eq!(d.optics.ai_defringe, 100.0); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_photo_left_on_without_a_model_can_be_switched_off() { + let dir = temp("orphan"); + let mut h = defringe_open(&dir); + let path = model_file(&dir); + let model = h.app.session.execute("aiDefringe.models.inspect", &json!({"path": path})).unwrap(); + h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": model, "acknowledged": true})).unwrap(); + let id = h.app.session.active().unwrap(); + h.app.session.execute("aiDefringe.toggle", &json!({"id": id.0, "enabled": true})).unwrap(); + h.app.session.execute("aiDefringe.models.remove", &json!({})).unwrap(); + h.app.caches.aidefringe = Default::default(); + h.step(); + h.step(); + assert!(on_screen(&mut h, "aidefringe:settings")); + assert!(on_screen(&mut h, "aidefringe:enabled"), "the switch stays while it is on"); + click(&mut h, "aidefringe:enabled"); + assert!(!h.app.session.develop_of(id).unwrap().optics.ai_defringe_enabled()); + h.step(); + assert!(!on_screen(&mut h, "aidefringe:enabled")); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index d06918c662..17253d2411 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -2,8 +2,8 @@ Optics ▸ Defringe ▸ **AI Defringe** is a per-photo switch with an **Amount** (0 to 100). It removes colour fringes of every hue (purple, blue-violet, green) with a trained network, and leaves real colours alone. Turning it on the first -time starts at 100; turning it off keeps the Amount. It acts on the requesting photo only, independently of Auto Sync, -and is undoable. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on +time starts at 100; turning it off keeps the Amount. It acts on the requesting photo only (Auto Sync never copies its switch or Amount), +and is undoable. Resetting Optics clears the switch. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on their own or together with it. AI Defringe needs a model, and **LightCraft ships none**. Settings ▸ AI Defringe ▸ **Install from file…** takes any ONNX @@ -11,8 +11,8 @@ file that has the defringe shape (see [The model contract](#the-model-contract)) its name, version and licence. Without one, LightCraft names the model after its file, gives the licence as "Not stated" with a notice saying it doesn't know who made it, and installs it only if it runs as a defringe model. Before anything is installed, Settings shows the model's name, licence and notice, and the user accepts them. Without a model the section -says where to install one. Builds without the model runtime (the web build, or a native build without the `denoise` -feature) say so and never offer the switch. +says where to install one; a photo still switched on (its model since removed) keeps the switch, so it can be switched +off. Builds without the model runtime (the web build, or a native build without the `denoise` feature) say so. ## How it works @@ -85,7 +85,8 @@ The ONNX file is read by LightCraft's own bounded reader: operators Conv, LeakyR and converted to OkLab by way of linear Rec.709 with negative values clamped. - **Output** `[1, 3, 256, 256]`: Δa and Δb before `tanh`, and the gate before its sigmoid. -Installation checks the manifest, the file's size (at most 256 MB) and SHA-256, the network's shape, and runs it twice +The install command takes back the model description `aiDefringe.models.inspect` gave, which the user accepted, and +installs nothing if the file or its description changed since. Installation checks the manifest, the file's size (at most 256 MB) and SHA-256, the network's shape, and runs it twice on a synthetic fringe: it must give finite colours, the same answer both times, and keep lightness. A model that fails is not installed and the one already there stays. @@ -94,8 +95,10 @@ is not installed and the one already there stays. `aiDefringe.toggle {id?, enabled?}`, `aiDefringe.status {id?}`, `aiDefringe.pump`, `aiDefringe.make {id?}` (makes a correction now and waits, for scripts), `aiDefringe.retry {id?}`, `aiDefringe.clear`, and `aiDefringe.models.inspect {path}`, `.install {path, acknowledged: true}`, `.remove`. The develop control is `optics.aiDefringe` (with -`optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The model folder is -`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. +`optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The models folder is +`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. The model goes in an `installed` folder inside it, the +only thing LightCraft writes or deletes there, so the models folder can be one that holds other files. During an install +the previous model is kept as `.installed-previous` until the new one is in place. ## Limits From 872ee55c736e7a1e2cc5479447c37e33d8b24b44 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:00:04 +0100 Subject: [PATCH 5/9] AI Defringe: second review round (gains follow lateral CA, paste switches it off, grey guard after the pull, quick off/on restarts, install stays inside its own folder) --- crates/denoise/src/defringe.rs | 30 ++++--- crates/denoise/src/defringe/tests.rs | 11 +++ crates/develop/src/lib.rs | 19 +++- crates/engine/src/aidefringe.rs | 123 +++++++++++++++++++------- crates/engine/src/aidefringe/tests.rs | 49 ++++++++++ crates/engine/src/tests/aidefringe.rs | 46 +++++++++- crates/pipeline/src/geometry.rs | 45 ++++++++++ crates/pipeline/src/lib.rs | 7 +- docs/ai-defringe.md | 20 +++-- 9 files changed, 295 insertions(+), 55 deletions(-) diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs index 2a495e82d3..fd6fe43369 100644 --- a/crates/denoise/src/defringe.rs +++ b/crates/denoise/src/defringe.rs @@ -267,9 +267,11 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u let bg = if den[i] / n as f32 > 1e-3 { [num_a[i] / den[i], num_b[i] / den[i]] } else { [0.0, 0.0] }; let (d, to) = ([nab[0] - a[0], nab[1] - a[1]], [bg[0] - a[0], bg[1] - a[1]]); let t = ((d[0] * to[0] + d[1] * to[1]) / (to[0] * to[0] + to[1] * to[1]).max(1e-8)).clamp(0.0, 1.0); - nab = [a[0] + t * to[0], a[1] + t * to[1]]; - // the pull toward the surroundings may not make a pixel green that wasn't either - let (ca, cn) = ((a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(), (nab[0] * nab[0] + nab[1] * nab[1] + 1e-12).sqrt()); + // nor take it past grey, or make it green when it wasn't + let ca = (a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(); + let d = not_past_grey(a, ca, [t * to[0], t * to[1]]); + nab = [a[0] + d[0], a[1] + d[1]]; + let cn = (nab[0] * nab[0] + nab[1] * nab[1] + 1e-12).sqrt(); if green(nab, cn) && !green(a, ca) { let s = (0.01 / cn).min(1.0); nab = [nab[0] * s, nab[1] * s]; @@ -285,6 +287,17 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u changed.extend(out.into_iter().flatten()); } +/// Change `d` of colour `ab` (chroma `c`), shortened so that it goes to grey but not past it: the colour may +/// lose all of its chroma, but not come out on the other side of grey. +fn not_past_grey(ab: [f32; 2], c: f32, d: [f32; 2]) -> [f32; 2] { + let against = -(d[0] * ab[0] + d[1] * ab[1]); + if against <= 0.0 { + return d; + } + let t = (c * c / against.max(1e-12)).min(1.0); + [d[0] * t, d[1] * t] +} + fn dist(a: [f32; 2], b: [f32; 2]) -> f32 { ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt() } @@ -305,17 +318,12 @@ fn compose(ab: [f32; 2], c: f32, range: f32, c_hi: f32, raw: [f32; 3]) -> [f32; let near_edge = smoothstep(0.05, 0.20, range); let gate = 1.0 / (1.0 + (-raw[2]).exp()); let k = near_edge * gate * DELTA_MAX; - let mut d = [k * raw[0].tanh(), k * raw[1].tanh()]; + let d = [k * raw[0].tanh(), k * raw[1].tanh()]; // no larger than the pixel's own chroma (plus a little) let dn = (d[0] * d[0] + d[1] * d[1] + 1e-12).sqrt(); let s = ((c + 0.01) / dn).min(1.0); - d = [d[0] * s, d[1] * s]; - // to grey, not past it - let against = -(d[0] * ab[0] + d[1] * ab[1]); - if against > 0.0 { - let t = (c * c / against.max(1e-12)).min(1.0); - d = [d[0] * t, d[1] * t]; - } + let d = [d[0] * s, d[1] * s]; + let d = not_past_grey(ab, c, d); let mut new = [ab[0] + d[0], ab[1] + d[1]]; // not green unless it was let cn = (new[0] * new[0] + new[1] * new[1] + 1e-12).sqrt(); diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs index 583c54498e..3bde68fab5 100644 --- a/crates/denoise/src/defringe/tests.rs +++ b/crates/denoise/src/defringe/tests.rs @@ -158,3 +158,14 @@ fn the_clip_mask_matches_a_plain_5_by_5_mean() { } } } + +#[test] +fn a_change_toward_the_surroundings_stops_at_grey_too() { + // a red pixel pulled toward a blue-green surround: the step would end past grey + let a = [0.1f32, 0.0]; + let d = not_past_grey(a, 0.1, [-0.00483 - 0.1, -0.02192]); + let new = [a[0] + d[0], a[1] + d[1]]; + assert!(new[0] * a[0] + new[1] * a[1] >= -1e-7, "{new:?}"); + // a change that doesn't reach grey is kept as it is + assert_eq!(not_past_grey(a, 0.1, [-0.05, 0.01]), [-0.05, 0.01]); +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 66caf27c8d..1bd8e686de 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -39,7 +39,8 @@ impl DevelopSettings { serde_json::from_value(v.clone()) } - /// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) stated even when off, for JSON that is copied, + /// [`Self::to_json`] with Remove Hot Pixels (`detail.nr_outliers`) and AI Defringe (`optics.ai_defringe`, + /// `optics.ai_defringe_on`) stated even at their defaults, for JSON that is copied, /// merged, scaled or compared key by key (copy / paste, presets, Auto Sync). The stored JSON leaves it out when /// off, so settings saved before it keep their hash; a merge needs the `false`, or copying Detail would not turn /// the box off and a preset applied at an amount would not find its base value. @@ -48,6 +49,12 @@ impl DevelopSettings { if let Some(detail) = v.get_mut("detail").and_then(Value::as_object_mut) { detail.insert("nr_outliers".into(), Value::Bool(self.detail.nr_outliers)); } + // AI Defringe's Amount and switch are left out at their defaults too: a paste from a photo without it must + // switch it off + if let Some(optics) = v.get_mut("optics").and_then(Value::as_object_mut) { + optics.insert("ai_defringe".into(), Value::from(self.optics.ai_defringe)); + optics.insert("ai_defringe_on".into(), serde_json::json!(self.optics.ai_defringe_on)); + } v } @@ -492,6 +499,16 @@ mod tests { assert!(s.optics.ai_defringe_enabled()); } + #[test] + fn pasting_from_a_photo_without_ai_defringe_switches_it_off() { + let mut target = DevelopSettings::default(); + target.optics.ai_defringe = 60.0; + target.optics.ai_defringe_on = Some(true); + let pasted = target.merged(&DevelopSettings::default().to_json_for_merge()).unwrap(); + assert_eq!((pasted.optics.ai_defringe, pasted.optics.ai_defringe_on), (0.0, None)); + assert!(!pasted.optics.ai_defringe_enabled()); + } + #[test] fn section_toggles() { let mut s = DevelopSettings::default(); diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index d9ca5ce13a..e4fc685009 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -30,7 +30,7 @@ use crate::Session; use crate::media::{SourceLevel, SourceRef}; /// The composition and the correction's form; a change makes every correction again. -const VERSION: &str = "ai-defringe-1"; +const VERSION: &str = "ai-defringe-2"; /// The manifest that describes a defringe model, beside its ONNX file. pub const MANIFEST: &str = "defringe-model.json"; /// What a model must say it does: [`lightcraft_denoise::defringe`]'s planes in, (Δa, Δb, gate) out. @@ -116,15 +116,18 @@ pub fn models_dir() -> Option { .or_else(|| crate::config::config_dir().map(|d| d.join("defringe-models"))) } -/// The folder inside the models folder that holds the installed model. LightCraft owns it and nothing else there: -/// the models folder may be one the user keeps other files in. -const CURRENT: &str = "installed"; -/// The previous installation while a new one replaces it, kept until the replacement is in place. -const PREVIOUS: &str = ".installed-previous"; +/// The folder inside the models folder that LightCraft owns, and the only thing there it writes or deletes: the +/// models folder may be one the user keeps other files in. It holds the installed model, and during an install the +/// new one being written and the previous one, kept until the new one is in place. +const OWN: &str = "installed"; +/// The installed model, inside [`OWN`]. +const CURRENT: &str = "model"; +/// The previous model while a new one replaces it, inside [`OWN`]. +const PREVIOUS: &str = "previous"; /// The model installed in models folder `dir`: its manifest and file, if there is one. pub fn installed(dir: &Path) -> Option<(Manifest, PathBuf)> { - let cur = dir.join(CURRENT); + let cur = dir.join(OWN).join(CURRENT); let m = Manifest::parse(&std::fs::read_to_string(cur.join(MANIFEST)).ok()?).ok()?; let file = cur.join(&m.file); file.is_file().then_some((m, file)) @@ -204,13 +207,14 @@ pub fn install(onnx: &Path, dir: &Path, accepted: &Manifest) -> Result std::io::Result<()> { @@ -243,12 +247,12 @@ pub fn install(onnx: &Path, dir: &Path, accepted: &Manifest) -> Result Result { - let cur = dir.join(CURRENT); - if !cur.exists() { - return Ok(false); + let own = dir.join(OWN); + let had = own.join(CURRENT).exists(); + if own.exists() { + std::fs::remove_dir_all(&own).map_err(|e| e.to_string())?; } - std::fs::remove_dir_all(&cur).map_err(|e| e.to_string())?; - Ok(true) + Ok(had) } #[cfg(feature = "denoise")] @@ -525,10 +529,11 @@ impl Recipe { let src = source.image.clone(); let info = source.info_or(self.info.clone()); let req = lightcraft_pipeline::RenderRequest { apply_crop: false, ..lightcraft_pipeline::RenderRequest::fit(src.width, src.height) }; - let tap = lightcraft_pipeline::defringe_tap(&src, &info, &DevelopSettings::default(), &req); - if (tap.width, tap.height) != (src.width, src.height) { + let (tap, frame) = lightcraft_pipeline::defringe_tap(&src, &info, &DevelopSettings::default(), &req); + let map = frame.source_map(src.width, src.height, tap.width, tap.height); + let Some(map) = map.filter(|_| (tap.width, tap.height) == (src.width, src.height)) else { return Err("the Defringe stage's picture doesn't line up with the photo".into()); - } + }; let (w, h) = (tap.width, tap.height); let top = lightcraft_denoise::defringe::top(&tap.data); let rgb: Vec<[f32; 3]> = tap.data.iter().map(|p| p.map(|v| (v / top).max(0.0))).collect(); @@ -537,15 +542,11 @@ impl Recipe { let changed = self.model.correct(&rgb, &clip, w, h, progress, cancel).map_err(|e| e.to_string())?; // as a gain on the source picture: the Defringe stage is the source after per-channel gains (white balance, // exposure), so the ratio the model made carries over - let (mut index, mut gain) = (Vec::with_capacity(changed.len()), Vec::with_capacity(changed.len())); - for (i, p) in changed { - let Some(old) = rgb.get(i as usize) else { continue }; - let g = [0, 1, 2].map(|c| if old[c] > 1e-4 { f16_bits((p[c] / old[c]).clamp(0.2, 5.0) - 1.0) } else { 0 }); - if g != [0; 3] { - index.push(i); - gain.push(g); - } - } + let ratios = changed.into_iter().filter_map(|(i, p)| { + let old = rgb.get(i as usize)?; + Some((i, [0, 1, 2].map(|c| if old[c] > 1e-4 { (p[c] / old[c]).clamp(0.2, 5.0) - 1.0 } else { 0.0 }))) + }); + let (index, gain) = to_source(ratios, &map, w, h); let c = Correction { key: self.key, w, h, index, gain, memo: Mutex::new(None) }; if let Some(path) = &self.path { c.write(path, &self.publish)?; @@ -560,6 +561,63 @@ impl Recipe { } } +/// The gains (minus 1) the model made at Defringe-stage pixels, moved to the source pixels each plane of those +/// pixels was read from (`map`): lateral chromatic aberration correction and lens corrections read the planes of +/// a pixel from slightly different places, and the correction is applied to the source. Each plane's gain is +/// spread over the four source pixels around where it was read, with bilinear weights, and each source pixel gets +/// the weighted mean of what reached it. The unchanged pixels around the changed ones count too, with no gain, so +/// a gain that is the same over an area stays the same and the edge of a corrected area doesn't jump to full gain. +#[cfg_attr(not(feature = "denoise"), allow(dead_code))] +fn to_source( + changed: impl Iterator, + map: &lightcraft_pipeline::geometry::SourceMap, + w: usize, + h: usize, +) -> (Vec, Vec<[u16; 3]>) { + let changed: HashMap = changed.filter(|e| e.1 != [0.0; 3]).collect(); + let mut out: Vec<(u32, [u16; 3])> = if map.is_identity() { + changed.into_iter().map(|(i, g)| (i, g.map(f16_bits))).collect() + } else { + // the changed pixels and the unchanged ones within 2 px of them + let mut around: Vec = Vec::with_capacity(changed.len() * 4); + for &i in changed.keys() { + let (x, y) = (i as usize % w, i as usize / w); + for ny in y.saturating_sub(2)..(y + 3).min(h) { + for nx in x.saturating_sub(2)..(x + 3).min(w) { + around.push((ny * w + nx) as u32); + } + } + } + around.sort_unstable(); + around.dedup(); + // per source pixel and plane: the sum of weight × gain, and of weight + let mut sums: HashMap = HashMap::new(); + for i in around { + let g = changed.get(&i).copied().unwrap_or([0.0; 3]); + let (x, y) = (i as usize % w, i as usize / w); + for (c, &gc) in g.iter().enumerate() { + let Some(p) = map.at(x, y, c) else { continue }; + let (fx, fy) = (p.x - 0.5, p.y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + for (dx, dy, wgt) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { + let (sx, sy) = (x0 as i64 + dx, y0 as i64 + dy); + if wgt <= 0.0 || sx < 0 || sy < 0 || sx >= w as i64 || sy >= h as i64 { + continue; + } + let e = sums.entry((sy as usize * w + sx as usize) as u32).or_insert([[0.0; 2]; 3]); + e[c][0] += gc * wgt; + e[c][1] += wgt; + } + } + } + sums.into_iter().map(|(i, s)| (i, s.map(|[gw, wt]| f16_bits(if wt > 1e-6 { gw / wt } else { 0.0 })))).collect() + }; + out.retain(|e| e.1 != [0; 3]); + out.sort_unstable_by_key(|e| e.0); + out.into_iter().unzip() +} + /// What a render does about AI Defringe. #[derive(Clone)] pub enum ForRender { @@ -593,6 +651,8 @@ struct Job { done: Arc, total: Arc, cancel: Arc, + /// Set when the pump cancelled it because it was no longer wanted (not the user, from Activity). + unwanted: AtomicBool, /// The cache's epoch when it started: a result from before a clear is dropped. epoch: u64, _task: crate::activity::TaskGuard, @@ -805,6 +865,7 @@ impl Session { p.develop.ai_defringe_amount() > 0.0 && self.aidefringe.installed.as_ref().is_some_and(|i| key(&p, &i.0.sha256) == job.key) }); if !still { + job.unwanted.store(true, Ordering::Relaxed); job.cancel.store(true, Ordering::Relaxed); } match job.rx.try_recv() { @@ -826,8 +887,10 @@ impl Session { Ok(Err(e)) if !job.cancel.load(Ordering::Relaxed) => { self.aidefringe.failed.insert(job.key, e); } - // cancelled while still wanted: by the user, so not started again by itself - Ok(Err(_)) if still => { + // cancelled by the user (not by the pump because it was no longer wanted): not started again + // by itself. One the pump stopped that is wanted again (switched off and on quickly) starts + // again below. + Ok(Err(_)) if still && !job.unwanted.load(Ordering::Relaxed) => { self.aidefringe.cancelled.insert(job.key); } Ok(Err(_)) => {} @@ -877,7 +940,7 @@ impl Session { let _ = tx.send(made); }) .ok(); - self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, epoch, _task: task }); + self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, unwanted: AtomicBool::new(false), epoch, _task: task }); } /// Make photo `id`'s correction now, on this thread (for scripts and tests) → how many pixels it changes. diff --git a/crates/engine/src/aidefringe/tests.rs b/crates/engine/src/aidefringe/tests.rs index 0311128e18..157ed2c168 100644 --- a/crates/engine/src/aidefringe/tests.rs +++ b/crates/engine/src/aidefringe/tests.rs @@ -123,3 +123,52 @@ fn the_memo_keeps_nothing_alive_and_never_mistakes_a_new_picture_for_an_old_one( let b = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.25; 3]; 2] }); assert_eq!(c.apply(&b, 1.0).data[0], [0.5, 0.25, 0.25]); } + +#[test] +fn gains_go_back_to_where_lateral_ca_correction_read_each_plane_from() { + let (w, h) = (101, 101); + let mut frame = lightcraft_pipeline::geometry::Frame::new(w, h, &DevelopSettings::default(), false); + // red read 1 % further out from the centre (50.5, 50.5), blue 1 % further in + frame.add_lateral_ca([0.01, -0.01]); + let map = frame.source_map(w, h, w, h).unwrap(); + assert!(!map.is_identity()); + let (index, gain) = to_source([((50 * w + 90) as u32, [0.5f32, 0.25, 0.5])].into_iter(), &map, w, h); + let at = |x: usize, c: usize| index.iter().position(|&i| i as usize == 50 * w + x).map_or(0.0, |k| f16_value(gain[k][c])); + // red was read at x 90.9: 60 % from pixel 90, 40 % from 91; blue at 90.1: 40 % from 89, 60 % from 90 + let near = |a: f32, b: f32| (a - b).abs() < 1e-2; + assert!(near(at(90, 0), 0.3) && near(at(91, 0), 0.2), "red {} {}", at(90, 0), at(91, 0)); + assert!(near(at(89, 2), 0.2) && near(at(90, 2), 0.3), "blue {} {}", at(89, 2), at(90, 2)); + assert!(near(at(90, 1), 0.25) && at(89, 1) == 0.0 && at(91, 1) == 0.0, "green stays put"); + assert_eq!(at(92, 0) + at(88, 2), 0.0, "nothing further away"); + // the same gain over an area stays the same inside it + let all = (20..80).flat_map(|y| (20..80).map(move |x| ((y * w + x) as u32, [0.5f32; 3]))); + let (index, gain) = to_source(all, &map, w, h); + let k = index.iter().position(|&i| i as usize == 50 * w + 60).unwrap(); + assert!(gain[k].iter().all(|&g| near(f16_value(g), 0.5)), "{:?}", gain[k].map(f16_value)); +} + +#[test] +fn without_lens_corrections_the_gains_stay_where_they_were_made() { + let frame = lightcraft_pipeline::geometry::Frame::new(8, 4, &DevelopSettings::default(), false); + let map = frame.source_map(8, 4, 8, 4).unwrap(); + assert!(map.is_identity()); + let (index, gain) = to_source([(5u32, [0.5f32, 0.0, -0.25])].into_iter(), &map, 8, 4); + assert_eq!((index, gain), (vec![5], vec![[f16_bits(0.5), 0, f16_bits(-0.25)]])); +} + +#[test] +fn a_gain_goes_back_to_the_source_pixel_its_plane_was_read_from() { + // one bright red source pixel; sampled with lateral CA correction, it shows up elsewhere in the red plane + let (w, h) = (101, 101); + let mut src = Rgb32f { width: w, height: h, data: vec![[0.1; 3]; w * h] }; + src.data[30 * w + 95][0] = 1.0; + let mut frame = lightcraft_pipeline::geometry::Frame::new(w, h, &DevelopSettings::default(), false); + frame.add_lateral_ca([0.03, 0.0]); + let tap = frame.sample(&src, w, h); + let shown = (0..w * h).max_by(|&a, &b| tap.data[a][0].total_cmp(&tap.data[b][0])).unwrap(); + assert_ne!(shown, 30 * w + 95, "the test needs the red plane to move"); + let map = frame.source_map(w, h, w, h).unwrap(); + let (index, gain) = to_source([(shown as u32, [0.5, 0.0, 0.0])].into_iter(), &map, w, h); + let top = (0..index.len()).max_by(|&a, &b| f16_value(gain[a][0]).total_cmp(&f16_value(gain[b][0]))).unwrap(); + assert_eq!(index[top] as usize, 30 * w + 95); +} diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index e7b990ddef..9d45f62de0 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -141,6 +141,32 @@ fn the_switch_needs_a_model_and_the_correction_is_made_in_the_background() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn switching_off_and_quickly_on_again_does_not_count_as_cancelling() { + let mut x = setup("adf-offon"); + let id = photo(&x.s); + install(&mut x); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + x.s.execute("aiDefringe.pump", &json!({})).unwrap(); + // off: the pump stops the job; on again before it has returned + x.s.execute("aiDefringe.toggle", &json!({"enabled": false})).unwrap(); + x.s.execute("aiDefringe.pump", &json!({})).unwrap(); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + loop { + x.s.execute("aiDefringe.pump", &json!({})).unwrap(); + match x.s.aidefringe_state(id) { + PhotoState::Ready { .. } => break, + PhotoState::Failed { error } => panic!("{error}"), + _ => {} + } + // taken for the user's cancel, it would wait for ever + assert!(std::time::Instant::now() < deadline, "the correction never came"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let _ = std::fs::remove_dir_all(&x.dir); +} + #[test] fn an_export_makes_the_correction_when_it_is_missing_and_never_comes_out_without_it() { let mut x = setup("adf-export"); @@ -154,12 +180,17 @@ fn an_export_makes_the_correction_when_it_is_missing_and_never_comes_out_without let fixed = decode(&export_photo(&mut x.s, id, &o, 1).unwrap().bytes); assert_eq!((plain.width, plain.height), (fixed.width, fixed.height)); let differs: Vec = (0..plain.data.len()) - .filter(|&i| plain.data[i].iter().zip(&fixed.data[i]).any(|(a, b)| (a - b).abs() > 1e-3)) + // more than one 8-bit step: a step of rounding may flip anywhere + .filter(|&i| plain.data[i].iter().zip(&fixed.data[i]).any(|(a, b)| (a - b).abs() > 1.5 / 255.0)) .map(|i| i % plain.width) .collect(); assert!(!differs.is_empty(), "the export has no correction"); let edge = plain.width * 96 / 320; - assert!(differs.iter().all(|&x| x.abs_diff(edge) < 12), "pixels away from the stripe changed: {:?}", differs.iter().max()); + assert!( + differs.iter().all(|&x| x.abs_diff(edge) < 12), + "pixels away from the stripe changed: {:?}", + differs.iter().filter(|&&x| x.abs_diff(edge) >= 12).take(20).collect::>() + ); assert_eq!(std::fs::read_dir(x.dir.join("library").join("ai-defringe")).unwrap().flatten().count(), 1); // without a model it fails rather than export without the correction x.s.execute("aiDefringe.models.remove", &json!({})).unwrap(); @@ -197,9 +228,20 @@ fn the_models_folder_keeps_the_users_own_files() { let models = x.dir.join("defringe-models"); std::fs::create_dir_all(&models).unwrap(); std::fs::write(models.join("mine.onnx"), b"the user's").unwrap(); + // with the names an install used to use for its work beside its own folder + for name in [".installed-previous", &format!(".installing-{}", std::process::id())] { + std::fs::create_dir_all(models.join(name)).unwrap(); + std::fs::write(models.join(name).join("keep"), b"the user's").unwrap(); + } install(&mut x); install(&mut x); assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "installing twice"); + for name in [".installed-previous", &format!(".installing-{}", std::process::id())] { + assert_eq!(std::fs::read(models.join(name).join("keep")).unwrap(), b"the user's", "{name}"); + } + let mut names: Vec = std::fs::read_dir(&models).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, [".installed-previous".to_string(), format!(".installing-{}", std::process::id()), "installed".into(), "mine.onnx".into()]); x.s.execute("aiDefringe.models.remove", &json!({})).unwrap(); assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "removing"); assert_eq!(x.s.execute("aiDefringe.models.remove", &json!({})).unwrap()["removed"], false); diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 5d8a07489a..dddc92b9d2 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -371,6 +371,20 @@ impl Frame { .collect() } + /// Where [`Frame::sample`] into a `w × h` output reads each plane of an output pixel from, in pixels of + /// the `src_w × src_h` source. `None` when its reads are not single source points: a turned source, or + /// a prefiltered (downscaled) one. + pub fn source_map(&self, src_w: usize, src_h: usize, w: usize, h: usize) -> Option { + if self.orient != Orientation::Normal { + return None; + } + let plan = self.sample_plan(src_w, src_h, w, h); + if plan.prefilter.is_some() { + return None; + } + Some(SourceMap { plan, warp: self.warp.clone() }) + } + /// The sampling of [`Frame::sample`] from the oriented, prefiltered source `base`. fn sample_base(&self, base: std::borrow::Cow<'_, Rgb32f>, plan: SamplePlan, w: usize, h: usize) -> Rgb32f { let affine = |xf: Affine| { @@ -437,6 +451,37 @@ impl MaskMap { } } +/// Output pixel → the source position each plane is read from ([`Frame::source_map`]). +#[derive(Clone, Debug)] +pub struct SourceMap { + plan: SamplePlan, + warp: Option, +} + +impl SourceMap { + /// Where plane `ch` of output pixel `(x, y)` is read from, in source pixels (pixel centres at `.5`); + /// `None` where the output shows no photo. + pub fn at(&self, x: usize, y: usize, ch: usize) -> Option { + let centre = Point::new(x as f64 + 0.5, y as f64 + 0.5); + let (sx, sy) = (self.plan.sx, self.plan.sy); + match (&self.plan.mode, self.warp.as_ref()) { + (SampleMode::Copy, _) => Some(centre), + (SampleMode::Warp(o2t), Some(wp)) => { + let (c, g) = wp.frame(o2t, x, y)?; + let q = if ch != 1 && wp.per_channel() { wp.corrected_to_source(c, ch) } else { g }; + Some(Point::new(q.x * sx, q.y * sy)) + } + (SampleMode::Warp(o2t), None) => Some((Affine::scale(sx, sy) * *o2t).apply(centre)), + (SampleMode::Affine(xf), _) => Some(xf.apply(centre)), + } + } + + /// Whether every plane of every pixel is read from the same pixel of the source. + pub fn is_identity(&self) -> bool { + matches!(self.plan.mode, SampleMode::Copy) + } +} + /// How a render resamples its source (see [`Frame::sample_plan`]). #[derive(Clone, Debug)] pub struct SamplePlan { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index ce5a9f68f0..b3547d392d 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -653,8 +653,9 @@ pub fn lin_cpu(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) { /// The picture the AI Defringe model reads ([`lightcraft_denoise::defringe`], docs/ai-defringe.md): `s` rendered for /// `req` up to the Defringe stage (resampled, white balance, exposure, lateral chromatic aberration corrected), with -/// the Defringe sliders left out. -pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> Rgb32f { +/// the Defringe sliders left out; and the frame it was sampled through, whose [`geometry::Frame::source_map`] says which +/// source pixel each plane of each of its pixels came from. +pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> (Rgb32f, geometry::Frame) { let effective = s.effective(); let mut rendition = settings_for(&effective, req).into_owned(); rendition.optics.defringe_purple_amount = 0.0; @@ -665,7 +666,7 @@ pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: & // `lin_cpu` up to the Defringe stage: retouching and red-eye come after it local_tone::apply(&mut img, info, &plan); local::white_balance(&mut img, info, &plan.settings); - img + (img, plan.frame) } /// The settings a render of `s` for `req` uses: the HDR edit for an [`OutputDepth::F32Hdr`] diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index 17253d2411..471c5f217e 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -17,9 +17,11 @@ off. Builds without the model runtime (the web build, or a native build without ## How it works For each photo with AI Defringe on, the model reads the picture at the Defringe stage: the full-size source developed -with the default settings up to that point (white balance, exposure, lateral chromatic aberration removed; no -geometry, so it lines up with the source pixel for pixel). Its correction is kept as a gain per channel for each pixel -it changes, applied to the source picture before the develop pipeline. So: +with the default settings up to that point (white balance, exposure, lateral chromatic aberration removed, and the +camera's own lens corrections; no crop or rotation). Its correction is kept as a gain per channel for each pixel it +changes, applied to the source picture before the develop pipeline. Lateral chromatic aberration correction reads each +colour plane of a pixel from a slightly different place in the source, so each plane's gain is moved back to where it +was read from (spread over the four source pixels around it). So: - The edit never makes the correction again. Moving any slider, Amount included, uses the one already made. - A render smaller than the source (the loupe, thumbnails) takes the mean gain over each of its pixels, so thin @@ -53,7 +55,7 @@ The network only proposes a change; the host decides how much of it to keep. The green chroma. 6. **No more colourful than its neighbourhood:** at most 1.2 × the highest chroma within 7 × 7 px. 7. **Toward the surroundings.** Of each change, only the part that moves the pixel toward the mean colour of the - untouched pixels within 7 px is kept, at most up to it. Without this, a correction that stopped at grey could move + untouched pixels within 7 px is kept, at most up to it, and rules 4 and 5 are applied to it again. Without this, a correction that stopped at grey could move a purple fringe sideways into a brown-orange rim. 8. **Exact elsewhere.** A pixel whose colour moves by 1e-5 or less keeps its exact value. @@ -94,11 +96,13 @@ is not installed and the one already there stays. `aiDefringe.toggle {id?, enabled?}`, `aiDefringe.status {id?}`, `aiDefringe.pump`, `aiDefringe.make {id?}` (makes a correction now and waits, for scripts), `aiDefringe.retry {id?}`, `aiDefringe.clear`, and `aiDefringe.models.inspect -{path}`, `.install {path, acknowledged: true}`, `.remove`. The develop control is `optics.aiDefringe` (with +{path}`, `.install {path, model, acknowledged: true}` (`model` is the description `.inspect` gave, which the user +accepted), `.remove`. The develop control is `optics.aiDefringe` (with `optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The models folder is -`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. The model goes in an `installed` folder inside it, the -only thing LightCraft writes or deletes there, so the models folder can be one that holds other files. During an install -the previous model is kept as `.installed-previous` until the new one is in place. +`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. LightCraft writes and deletes only an `installed` folder +inside it, so the models folder can be one that holds other files. That folder holds the model (`installed/model`) and, +during an install, the new model being written (`installed/installing-`) and the previous one +(`installed/previous`), kept until the new one is in place. ## Limits From 9ddb7ac9077a530e7687831a63c8f812c40dc30b Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:44:47 +0100 Subject: [PATCH 6/9] AI Defringe: visit each pixel once when mapping gains back, cap chroma after the pull --- crates/denoise/src/defringe.rs | 26 +++++++++++++++++--------- crates/denoise/src/defringe/tests.rs | 14 ++++++++++++++ crates/engine/src/aidefringe.rs | 26 +++++++++++++------------- docs/ai-defringe.md | 2 +- 4 files changed, 45 insertions(+), 23 deletions(-) diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs index fd6fe43369..1ea375d271 100644 --- a/crates/denoise/src/defringe.rs +++ b/crates/denoise/src/defringe.rs @@ -267,15 +267,7 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u let bg = if den[i] / n as f32 > 1e-3 { [num_a[i] / den[i], num_b[i] / den[i]] } else { [0.0, 0.0] }; let (d, to) = ([nab[0] - a[0], nab[1] - a[1]], [bg[0] - a[0], bg[1] - a[1]]); let t = ((d[0] * to[0] + d[1] * to[1]) / (to[0] * to[0] + to[1] * to[1]).max(1e-8)).clamp(0.0, 1.0); - // nor take it past grey, or make it green when it wasn't - let ca = (a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(); - let d = not_past_grey(a, ca, [t * to[0], t * to[1]]); - nab = [a[0] + d[0], a[1] + d[1]]; - let cn = (nab[0] * nab[0] + nab[1] * nab[1] + 1e-12).sqrt(); - if green(nab, cn) && !green(a, ca) { - let s = (0.01 / cn).min(1.0); - nab = [nab[0] * s, nab[1] * s]; - } + nab = pulled(a, [t * to[0], t * to[1]], c_hi[(y + e0 - l0) * w + x]); } if dist(a, nab) <= MOVED { return None; @@ -287,6 +279,22 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u changed.extend(out.into_iter().flatten()); } +/// Colour `a` moved by `d` toward the surroundings, with rules 4 to 6 applied again: not past grey, not green unless +/// it was, and no more colourful than 1.2 × `c_hi`, the highest chroma within 7 × 7 px. +fn pulled(a: [f32; 2], d: [f32; 2], c_hi: f32) -> [f32; 2] { + let ca = (a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(); + let d = not_past_grey(a, ca, d); + let mut n = [a[0] + d[0], a[1] + d[1]]; + let cn = (n[0] * n[0] + n[1] * n[1] + 1e-12).sqrt(); + if green(n, cn) && !green(a, ca) { + let s = (0.01 / cn).min(1.0); + n = [n[0] * s, n[1] * s]; + } + let cn = (n[0] * n[0] + n[1] * n[1] + 1e-12).sqrt(); + let s = (c_hi * 1.2 / cn).min(1.0); + [n[0] * s, n[1] * s] +} + /// Change `d` of colour `ab` (chroma `c`), shortened so that it goes to grey but not past it: the colour may /// lose all of its chroma, but not come out on the other side of grey. fn not_past_grey(ab: [f32; 2], c: f32, d: [f32; 2]) -> [f32; 2] { diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs index 3bde68fab5..563b92cc21 100644 --- a/crates/denoise/src/defringe/tests.rs +++ b/crates/denoise/src/defringe/tests.rs @@ -169,3 +169,17 @@ fn a_change_toward_the_surroundings_stops_at_grey_too() { // a change that doesn't reach grey is kept as it is assert_eq!(not_past_grey(a, 0.1, [-0.05, 0.01]), [-0.05, 0.01]); } + +#[test] +fn a_change_toward_the_surroundings_is_no_more_colourful_than_the_neighbourhood() { + // a faint orange pixel pulled toward a strongly orange mean from beyond its own 7 × 7 neighbourhood + let a = [0.02f32, 0.02]; + let n = pulled(a, [0.18, 0.18], 0.05); + let c = (n[0] * n[0] + n[1] * n[1]).sqrt(); + assert!(c <= 0.05 * 1.2 + 1e-6, "{n:?} has chroma {c}"); + // the direction is kept + assert!((n[0] - n[1]).abs() < 1e-6, "{n:?}"); + // a pull that stays within the limit is kept as it is + let n = pulled(a, [0.01, 0.01], 0.05); + assert!((n[0] - 0.03).abs() < 1e-6 && (n[1] - 0.03).abs() < 1e-6, "{n:?}"); +} diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index e4fc685009..fa1d15d3f0 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -13,7 +13,7 @@ //! photo's correction missing makes it itself, on its own thread, so it never comes out without the correction it //! was asked for. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError, channel}; @@ -578,21 +578,21 @@ fn to_source( let mut out: Vec<(u32, [u16; 3])> = if map.is_identity() { changed.into_iter().map(|(i, g)| (i, g.map(f16_bits))).collect() } else { - // the changed pixels and the unchanged ones within 2 px of them - let mut around: Vec = Vec::with_capacity(changed.len() * 4); - for &i in changed.keys() { + // the changed pixels and the unchanged ones within 2 px of them, each visited once, in a fixed order so + // the sums come out the same every time + let mut keys: Vec = changed.keys().copied().collect(); + keys.sort_unstable(); + let mut seen: HashSet = HashSet::with_capacity(changed.len()); + let around = keys.into_iter().flat_map(|i| { let (x, y) = (i as usize % w, i as usize / w); - for ny in y.saturating_sub(2)..(y + 3).min(h) { - for nx in x.saturating_sub(2)..(x + 3).min(w) { - around.push((ny * w + nx) as u32); - } - } - } - around.sort_unstable(); - around.dedup(); + (y.saturating_sub(2)..(y + 3).min(h)).flat_map(move |ny| (x.saturating_sub(2)..(x + 3).min(w)).map(move |nx| (ny * w + nx) as u32)) + }); // per source pixel and plane: the sum of weight × gain, and of weight let mut sums: HashMap = HashMap::new(); for i in around { + if !seen.insert(i) { + continue; + } let g = changed.get(&i).copied().unwrap_or([0.0; 3]); let (x, y) = (i as usize % w, i as usize / w); for (c, &gc) in g.iter().enumerate() { @@ -670,7 +670,7 @@ pub struct State { /// Corrections that failed, by key, and why (not tried again until asked). failed: HashMap, /// Corrections the user cancelled, by key (not started again until asked: Try Again, or switching it on). - cancelled: std::collections::HashSet, + cancelled: HashSet, /// The cache's epoch, bumped (under this lock) when it is cleared ([`Publish`]). epoch: Arc>, /// Corrections in memory, most recently used last. diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index 471c5f217e..212aa1e2c1 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -55,7 +55,7 @@ The network only proposes a change; the host decides how much of it to keep. The green chroma. 6. **No more colourful than its neighbourhood:** at most 1.2 × the highest chroma within 7 × 7 px. 7. **Toward the surroundings.** Of each change, only the part that moves the pixel toward the mean colour of the - untouched pixels within 7 px is kept, at most up to it, and rules 4 and 5 are applied to it again. Without this, a correction that stopped at grey could move + untouched pixels within 7 px is kept, at most up to it, and rules 4 to 6 are applied to it again. Without this, a correction that stopped at grey could move a purple fringe sideways into a brown-orange rim. 8. **Exact elsewhere.** A pixel whose colour moves by 1e-5 or less keeps its exact value. From f87ad33595bb872a788f49ba6e0e6491d23d11ff Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:56:56 +0100 Subject: [PATCH 7/9] AI Defringe: give the UI switch test five minutes for the correction on a loaded CI runner --- crates/ui-egui/src/tests/aidefringe.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/aidefringe.rs b/crates/ui-egui/src/tests/aidefringe.rs index 630fc27948..e2bf6c5349 100644 --- a/crates/ui-egui/src/tests/aidefringe.rs +++ b/crates/ui-egui/src/tests/aidefringe.rs @@ -109,7 +109,8 @@ fn the_switch_turns_it_on_and_the_correction_arrives() { let d = h.app.session.develop_of(id).unwrap(); assert!(d.optics.ai_defringe_enabled()); assert_eq!(d.optics.ai_defringe, 100.0); - let deadline = std::time::Instant::now() + Duration::from_secs(60); + // generous: on a loaded CI runner the whole suite shares a few cores + let deadline = std::time::Instant::now() + Duration::from_secs(300); loop { h.step(); let s = h.app.session.execute("aiDefringe.status", &json!({})).unwrap(); From 0b11feed415de1edeb0cc42d9dd31dd52a512efc Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:25:44 +0100 Subject: [PATCH 8/9] AI Defringe: the correction's key includes the photo's lens database profile --- crates/engine/src/aidefringe.rs | 7 +++-- crates/engine/src/media.rs | 2 +- crates/engine/src/tests/aidefringe.rs | 41 +++++++++++++++++++++++++++ docs/ai-defringe.md | 4 +-- 4 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index fa1d15d3f0..1eaa3fe8ac 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -502,10 +502,13 @@ pub struct Publish { at: u64, } -/// The name of photo `p`'s correction by the model with SHA-256 `model`. +/// The name of photo `p`'s correction by the model with SHA-256 `model`, for its content and its lens profile. pub fn key(p: &Photo, model: &str) -> u64 { let mut h = Hasher128::new(); - h.str(VERSION).str(model).str(&crate::media::content_key(p)); + // the lens database's profile pinned to the photo too: the correction is made on the picture that profile + // corrects, and its gains are mapped back through that frame; a refreshed profile changes neither the file nor + // the model (review of #4545) + h.str(VERSION).str(model).str(&crate::media::content_key(p)).u64(crate::media::lens_key(p)); h.finish().0 as u64 | 1 } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index dcba02494d..b267d0cb18 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -37,7 +37,7 @@ mod source; pub use cache::DenoiseIndex; #[cfg(test)] pub(crate) use cache::rendered_budget; -pub use quick::{QuickJob, QuickSource, content_key, source_info}; +pub use quick::{QuickJob, QuickSource, content_key, lens_key, source_info}; pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index 9d45f62de0..5b621c642b 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -141,6 +141,47 @@ fn the_switch_needs_a_model_and_the_correction_is_made_in_the_background() { let _ = std::fs::remove_dir_all(&dir); } +/// Review of #4545: a correction is made for the lens database's profile pinned to the photo. When that profile is +/// refreshed (same file, same model), the correction made before is not used again; switching back to the old +/// profile finds it again. +#[test] +fn a_refreshed_lens_profile_does_not_reuse_the_old_correction() { + use lightcraft_develop::{EmbeddedLens, EmbeddedWarp, LensSource}; + let mut x = setup("adf-lens"); + let id = photo(&x.s); + install(&mut x); + let lens = |k: f64| EmbeddedLens { + warp: Some(EmbeddedWarp { planes: [[1.0, k, 0.0, 0.0, 0.0, 0.0]; 3], radius: 0.6, ..Default::default() }), + source: LensSource::Database, + ..Default::default() + }; + x.s.catalog.apply(lightcraft_catalog::Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.02))) }).unwrap(); + x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + let ready = |s: &mut Session| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + loop { + s.execute("aiDefringe.pump", &json!({})).unwrap(); + match s.aidefringe_state(id) { + PhotoState::Ready { .. } => break, + PhotoState::Failed { error } => panic!("{error}"), + _ => {} + } + assert!(std::time::Instant::now() < deadline, "the correction never came"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + }; + ready(&mut x.s); + // the database refreshes the profile: same bytes, same model, but the old correction no longer fits + x.s.catalog.apply(lightcraft_catalog::Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(0.03))) }).unwrap(); + assert!(!matches!(x.s.aidefringe_state(id), PhotoState::Ready { .. }), "the correction for the old profile isn't reused"); + ready(&mut x.s); + assert_eq!(std::fs::read_dir(x.dir.join("library").join("ai-defringe")).unwrap().flatten().count(), 2, "one per profile"); + // the old profile back: its correction is found again + x.s.catalog.apply(lightcraft_catalog::Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.02))) }).unwrap(); + assert!(matches!(x.s.aidefringe_state(id), PhotoState::Ready { .. })); + let _ = std::fs::remove_dir_all(&x.dir); +} + #[test] fn switching_off_and_quickly_on_again_does_not_count_as_cancelling() { let mut x = setup("adf-offon"); diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index 212aa1e2c1..acd5ded1aa 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -30,8 +30,8 @@ was read from (spread over the four source pixels around it). So: model is installed. It never comes out without the correction it was asked for. The correction of the photo being edited is made in the background (Activity shows it and can cancel it) and kept in -`/ai-defringe/.lcadf`, named by a hash of the photo's content, the model file's SHA-256 and the algorithm -version (`crates/engine/src/aidefringe.rs`, `VERSION`). It is cached data: Clear (`aiDefringe.clear`) deletes it and it +`/ai-defringe/.lcadf`, named by a hash of the photo's content, the lens database profile pinned to it, the model file's +SHA-256 and the algorithm version (`crates/engine/src/aidefringe.rs`, `VERSION`). It is cached data: Clear (`aiDefringe.clear`) deletes it and it is made again when wanted. A file is compressed, checksummed and read as hostile input. Up to 24 corrections stay in memory; each holds only the pixels it changes. From c72d640fe85d5fe9201228c06d165ee406dacd96 Mon Sep 17 00:00:00 2001 From: FredApps Date: Sat, 28 Nov 2026 05:42:18 +0700 Subject: [PATCH 9/9] docs: keep the revision-history table as one table after merging main --- docs/parity-checklist.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index b572e4fa64..6790f65712 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -809,7 +809,6 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| | 2026-11-19 | minor | LR-EDIT-OPTICS-DEFRINGE: AI Defringe (beyond Lightroom), a user-installed defringe network with a cached per-photo correction; no model ships; status unchanged | - | 2026-10-29 | minor | MENU-EDIT-SELECTBY: Edit → Select by lists each rating on its own (★ only … ★★★★★ only, `library.selectBy` with `ratingOp: eq`) after the "and higher" rows, beside Unrated (#3311); status unchanged (✅) | | 2026-11-15 | patch | LR-PRE-AMOUNT: Amount blends tone curves, fades in the strength of a profile/LUT or switched-on group a preset changes, and takes white balance on another scale whole (#2669); the step at half amount for switches and choices stays (#2207); status unchanged (✅) | | 2026-11-09 | minor | LR-PREF-LOCALSTORAGE: the low-disk notice warns under 20 GB free, no longer under 10 % of the drive (76 GB free of a 926 GB drive warned, #4013); status unchanged |