Merge pull request #4545 from Bruno-Alumn/feat/ai-defringe

LR-EDIT-OPTICS-DEFRINGE: AI Defringe, running a defringe model the user installs
This commit is contained in:
FredApps authored and GitHub committed 2026-11-28 02:04:23 +01:00
commit 6f08524d58
33 files changed
+3068 -17

No files matched your search

+9 -7
View File
@@ -68,15 +68,17 @@ pub struct NetRunner {
impl NetRunner {
pub fn new(net: &Net, tile: usize) -> Result<Self> {
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<Self> {
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);
+500
View File
@@ -0,0 +1,500 @@
//! 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<Self, NetError> {
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<Vec<(u32, [f32; 3])>, Error> {
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()));
}
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<bool> = 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::<usize>().max(1);
let mut done = 0;
progress(0, total);
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];
for batch in runs(e0, e1).chunks(BATCH) {
if cancel.load(Ordering::Relaxed) {
return Err(Error::Cancelled);
}
let outs: Vec<Vec<f32>> = batch.par_iter().map(|&(y, x)| self.runner.run(&pic.tile_input(y, x))).collect::<Result<_, _>>()?;
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);
}
stop()?;
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<usize> {
let mut v: Vec<usize> = (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<f32> = (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::<Vec<_>>(), 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<f32> {
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<f32> = lab.iter().map(|p| p[0]).collect();
let chroma: Vec<f32> = 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::<Vec<_>>(), 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<f32> = ab.iter().zip(&new).map(|(a, n)| f32::from(u8::from(dist(*a, *n) > 1e-4))).collect();
let keep: Vec<f32> = max_filter(&moved, w, rows, 2).iter().map(|v| 1.0 - v).collect();
let keep_a: Vec<f32> = ab.iter().zip(&keep).map(|(a, k)| a[0] * k).collect();
let keep_b: Vec<f32> = 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<Option<(u32, [f32; 3])>> = (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 = pulled(a, [t * to[0], t * to[1]], c_hi[(y + e0 - l0) * w + x]);
}
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());
}
/// 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] {
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()
}
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 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);
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();
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<f32> {
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<f32> {
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`.
/// 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<bool> {
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<f64> {
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
/// its highlights sit near 1, as the model was trained.
pub fn top(rgb: &[[f32; 3]]) -> f32 {
let mut v: Vec<f32> = 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;
+185
View File
@@ -0,0 +1,185 @@
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<bool>) {
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<(usize, [f32; 3])>> = 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: [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
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]);
}
#[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})");
}
}
}
#[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]);
}
#[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:?}");
}
+3
View File
@@ -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` (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).
//!
@@ -21,6 +22,8 @@
#[cfg(feature = "runtime")]
pub mod cpu;
#[cfg(feature = "runtime")]
pub mod defringe;
pub mod net;
pub mod onnx;
+2 -1
View File
@@ -36,7 +36,8 @@ pub fn read(path: &Path) -> Result<Net, NetError> {
read_bytes(&bytes)
}
fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
/// Read a model from its bytes.
pub fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
let graph = onnx_proto::decode(bytes)?;
let initialisers: HashMap<&str, &TensorProto> = graph.initializer.iter().map(|t| (t.name.as_str(), t)).collect();
+20
View File
@@ -232,3 +232,23 @@ pub fn smoothing_onnx() -> Vec<u8> {
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<u8> {
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<f32> = (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
}
+1
View File
@@ -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" };
+37 -1
View File
@@ -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
}
@@ -167,6 +174,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 {
@@ -186,6 +199,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)
@@ -473,6 +487,28 @@ 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 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();
+14
View File
@@ -728,6 +728,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<bool>,
}
impl Optics {
pub fn ai_defringe_enabled(&self) -> bool {
self.ai_defringe_on.unwrap_or(self.ai_defringe > 0.0)
}
}
impl Default for Optics {
@@ -748,6 +760,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,
}
}
}
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
use super::*;
use std::path::PathBuf;
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),
}
}
/// 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 = 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, &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");
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");
// 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]
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);
}
#[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]);
}
#[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);
}
+2
View File
@@ -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;
@@ -179,6 +180,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());
+155
View File
@@ -0,0 +1,155 @@
//! 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<PhotoId> {
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")),
}
}
/// 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 {
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.
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
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"));
}
// 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 };
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<Value> {
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<Value> {
let arrived = s.aidefringe_pump();
Ok(json!({"arrived": arrived, "generation": s.aidefringe.generation}))
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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<Value> {
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`"));
}
// 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, &accepted).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<Value> {
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<Value> {
let (files, bytes) = s.aidefringe_clear();
Ok(json!({"deleted": files, "bytes": bytes}))
}
pub fn specs() -> Vec<CommandSpec> {
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, 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),
]
}
+1
View File
@@ -649,6 +649,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)),
+12
View File
@@ -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;
@@ -293,6 +294,8 @@ pub struct Session {
pub(crate) unsaved_sidecars: std::collections::BTreeSet<PhotoId>,
/// 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<std::path::PathBuf>,
/// Face model downloads started this session (the staged files wait in `<face_models_dir>/.downloads`).
@@ -510,6 +513,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(),
@@ -1170,6 +1174,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();
}
+1 -1
View File
@@ -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;
+12
View File
@@ -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<crate::aidefringe::ForRender>,
}
/// `img` shrunk to fit `max_w × max_h` with a Lanczos filter (see [`RenderJob::display_fit`]).
@@ -353,6 +356,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)
+38 -6
View File
@@ -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);
@@ -145,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 {
@@ -185,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(),
@@ -206,6 +227,7 @@ impl crate::Session {
slide: None,
preview_cut: None,
display_fit: None,
ai_defringe,
})
}
@@ -240,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(),
@@ -262,6 +290,7 @@ impl crate::Session {
slide: None,
preview_cut,
display_fit: None,
ai_defringe,
})
}
@@ -286,7 +315,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 +628,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;
// an export shrinks with a sharp filter: a preview's soft one leaves a small export blurred (#2970)
+6
View File
@@ -2,6 +2,8 @@ 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;
@@ -667,6 +669,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);
@@ -680,6 +685,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]
+317
View File
@@ -0,0 +1,317 @@
//! 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<u8> {
let data: Vec<u16> = (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
}
/// 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<Value> {
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]);
install_path(&mut x.s, &path).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(), "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!(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");
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);
}
/// 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");
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");
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<usize> = (0..plain.data.len())
// 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().filter(|&&x| x.abs_diff(edge) >= 12).take(20).collect::<Vec<_>>()
);
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);
}
#[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!(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");
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"));
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();
// 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<String> = 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);
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);
}
+45
View File
@@ -379,6 +379,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<SourceMap> {
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| {
@@ -445,6 +459,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<Warp>,
}
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<Point> {
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 {
+18
View File
@@ -678,6 +678,24 @@ 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; 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;
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` 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, plan.frame)
}
/// 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.
+1
View File
@@ -100,6 +100,7 @@ impl LightcraftApp {
panels::detail::settle_wheel_edit(self, 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
+2
View File
@@ -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),
}
}
+2
View File
@@ -666,6 +666,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`).
+1
View File
@@ -1,6 +1,7 @@
//! Window regions and panels.
pub mod activity;
pub mod aidefringe;
pub mod bottombar;
pub mod bursts;
pub mod chips;
+230
View File
@@ -0,0 +1,230 @@
//! 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<String>,
}
/// 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 {
// 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 };
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));
}
}
/// 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());
}
/// 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() });
}
}
});
// 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 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;
}
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 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…")
.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, "model": info, "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(),
}
}
+2
View File
@@ -371,6 +371,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);
+1
View File
@@ -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;
+153
View File
@@ -0,0 +1,153 @@
//! 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);
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();
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);
// 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();
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);
}
#[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);
}
+113
View File
@@ -0,0 +1,113 @@
# 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 (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
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; 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
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, 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
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
`<library>/ai-defringe/<key>.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.
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, 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.
## The model contract
`defringe-model.json` (optional; 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.
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.
## 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, 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
`<config>/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-<process id>`) and the previous one
(`installed/previous`), kept until the new one is in place.
## 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.
+2 -1
View File
@@ -221,7 +221,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 tLine truncated
)
| 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`, `crates/pipeline/src/upright.rs` | a vertical family is accepted when most of it agrees, or when the lines that disagree (people, folds, foliage) gather at no rival point half as strong, so two long posts flanking a crowd decide (`upright_corrects_converging_posts_among_people`); a mode that finds nothing to correct says why (`note`, shown over the photo: too few / too short lines, one object, lines that disagree, lines meeting inside the photo) and suggests Guided. Downgraded from ✅: a user's real pavilion shots (thick posts, thin poles) were not corrected and the tuning is so far proven on synthetic scenes only; thin poles below a pixel at the 1024 px analysis size are still lost |
| LR-EDIT-GEOM-MANUAL | Manual transform | P1 | ✅ | `ctl:geometry.*` | |
@@ -808,6 +808,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-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 |
+7
View File
@@ -9,6 +9,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).
### Space opens a photo from the grid
- In the Grid and the Square Grid, Space opens the active photo in Detail, fitted to the window, as in Lightroom
Classic (issue #4417). There, Space toggles the zoom as before.