From 263d8c4fffbd6a191b7695431277f84d0fe511ce Mon Sep 17 00:00:00 2001 From: Bruno Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:01:14 +0100 Subject: [PATCH] AI Defringe: review fixes (model folder, accepted terms, memo, publishing, cancellation, Auto Sync, thumbnails, guards) --- crates/denoise/src/defringe.rs | 69 +++++++-- crates/denoise/src/defringe/tests.rs | 35 +++++ crates/denoise/src/lib.rs | 2 +- crates/develop/src/lib.rs | 13 ++ crates/engine/src/aidefringe.rs | 186 ++++++++++++++++++------ crates/engine/src/aidefringe/tests.rs | 60 +++++++- crates/engine/src/cmd/aidefringe.rs | 22 ++- crates/engine/src/lib.rs | 8 + crates/engine/src/media/session.rs | 35 ++++- crates/engine/src/tests.rs | 4 + crates/engine/src/tests/aidefringe.rs | 69 ++++++++- crates/pipeline/src/lib.rs | 4 +- crates/ui-egui/src/panels/aidefringe.rs | 36 +++-- crates/ui-egui/src/tests/aidefringe.rs | 25 +++- docs/ai-defringe.md | 17 ++- 15 files changed, 490 insertions(+), 95 deletions(-) diff --git a/crates/denoise/src/defringe.rs b/crates/denoise/src/defringe.rs index 27b28ccc46..2a495e82d3 100644 --- a/crates/denoise/src/defringe.rs +++ b/crates/denoise/src/defringe.rs @@ -80,9 +80,12 @@ impl Model { progress: &(dyn Fn(usize, usize) + Sync), cancel: &AtomicBool, ) -> Result, Error> { - if w == 0 || h == 0 || rgb.len() != w * h || clip.len() != w * h || u32::try_from(w * h).is_err() { + let n = w.checked_mul(h).filter(|&n| n > 0 && u32::try_from(n).is_ok()); + if n.is_none_or(|n| rgb.len() != n || clip.len() != n) { return Err(Error::Input("the picture and its clip mask don't match its size".into())); } + let stop = || if cancel.load(Ordering::Relaxed) { Err(Error::Cancelled) } else { Ok(()) }; + stop()?; if rgb.iter().any(|p| p.iter().any(|v| !v.is_finite())) { return Err(Error::Input("the picture has non-finite values".into())); } @@ -107,6 +110,7 @@ impl Model { let ramp = ramp(); let mut changed = Vec::new(); for &(r0, r1, e0, e1) in &bands { + stop()?; let rows = e1 - e0; let mut acc = vec![[0f32; 3]; rows * w]; let mut wsum = vec![0f32; rows * w]; @@ -139,6 +143,7 @@ impl Model { acc.iter().zip(&wsum).map(|(a, &s)| if s > 0.0 { a.map(|v| v / s.max(1e-6)) } else { [0.0, 0.0, -20.0] }).collect(); band(rgb, w, h, (r0, r1, e0, e1), &raw, &mut changed); } + stop()?; progress(total, total); Ok(changed) } @@ -263,6 +268,12 @@ fn band(rgb: &[[f32; 3]], w: usize, h: usize, (r0, r1, e0, e1): (usize, usize, u let (d, to) = ([nab[0] - a[0], nab[1] - a[1]], [bg[0] - a[0], bg[1] - a[1]]); let t = ((d[0] * to[0] + d[1] * to[1]) / (to[0] * to[0] + to[1] * to[1]).max(1e-8)).clamp(0.0, 1.0); nab = [a[0] + t * to[0], a[1] + t * to[1]]; + // the pull toward the surroundings may not make a pixel green that wasn't either + let (ca, cn) = ((a[0] * a[0] + a[1] * a[1] + 1e-12).sqrt(), (nab[0] * nab[0] + nab[1] * nab[1] + 1e-12).sqrt()); + if green(nab, cn) && !green(a, ca) { + let s = (0.01 / cn).min(1.0); + nab = [nab[0] * s, nab[1] * s]; + } } if dist(a, nab) <= MOVED { return None; @@ -409,17 +420,53 @@ fn log_luminance(p: [f32; 3]) -> f32 { /// The clip mask a defringe model reads, for a `w × h` picture: pixels whose 5 × 5 mean of the brightest channel is /// within 7 % of `top`. +/// Worked row by row with running sums, so it needs no picture-sized buffers beyond the mask. pub fn clip_mask(rgb: &[[f32; 3]], w: usize, h: usize, top: f32) -> Vec { - let m: Vec = rgb.iter().map(|p| p[0].max(p[1]).max(p[2])).collect(); - box_sum(&m, w, h, 2) - .iter() - .enumerate() - .map(|(i, s)| { - let (x, y) = (i % w, i / w); - let n = ((x + 2).min(w - 1) - x.saturating_sub(2) + 1) * ((y + 2).min(h - 1) - y.saturating_sub(2) + 1); - s / n as f32 >= 0.93 * top - }) - .collect() + if w.checked_mul(h) != Some(rgb.len()) || rgb.is_empty() { + return vec![false; rgb.len()]; + } + // a row's 5-wide sums of the brightest channel + let row = |y: usize| -> Vec { + let line = &rgb[y * w..(y + 1) * w]; + let m = |x: usize| f64::from(line[x][0].max(line[x][1]).max(line[x][2])); + let mut out = vec![0f64; w]; + let mut run: f64 = (0..3.min(w)).map(m).sum(); + for (x, o) in out.iter_mut().enumerate() { + *o = run; + if x + 3 < w { + run += m(x + 3); + } + if x >= 2 { + run -= m(x - 2); + } + } + out + }; + let mut cols = vec![0f64; w]; + for y in 0..3.min(h) { + for (c, v) in cols.iter_mut().zip(row(y)) { + *c += v; + } + } + let mut mask = Vec::with_capacity(w * h); + for y in 0..h { + let ny = (y + 2).min(h - 1) - y.saturating_sub(2) + 1; + for (x, c) in cols.iter().enumerate() { + let nx = (x + 2).min(w - 1) - x.saturating_sub(2) + 1; + mask.push(c / (nx * ny) as f64 >= 0.93 * f64::from(top)); + } + if y + 3 < h { + for (c, v) in cols.iter_mut().zip(row(y + 3)) { + *c += v; + } + } + if y >= 2 { + for (c, v) in cols.iter_mut().zip(row(y - 2)) { + *c -= v; + } + } + } + mask } /// The 99.9th percentile of the brightest channel (over every third pixel): the value a picture is divided by so diff --git a/crates/denoise/src/defringe/tests.rs b/crates/denoise/src/defringe/tests.rs index 896977ec56..583c54498e 100644 --- a/crates/denoise/src/defringe/tests.rs +++ b/crates/denoise/src/defringe/tests.rs @@ -123,3 +123,38 @@ fn the_clip_mask_marks_the_brightest_pixels() { let mask = clip_mask(&rgb, 300, 20, t); assert!(mask[10 * 300 + 50] && !mask[10 * 300 + 200] && !mask[10 * 300 + 98]); } + +#[test] +fn cancelling_is_honoured_with_no_tile_to_run() { + // flat: no tile is run, and the flag is still seen + let rgb = vec![[0.18f32; 3]; 300 * 280]; + let clip = vec![false; 300 * 280]; + let r = model([0.0, 0.0, 0.0]).correct(&rgb, &clip, 300, 280, &|_, _| {}, &AtomicBool::new(true)); + assert!(matches!(r, Err(Error::Cancelled))); +} + +#[test] +fn sizes_that_overflow_are_refused() { + let r = model([0.0, 0.0, 0.0]).correct(&[], &[], usize::MAX / 2 + 1, 2, &|_, _| {}, &AtomicBool::new(false)); + assert!(matches!(r, Err(Error::Input(_)))); +} + +#[test] +fn the_clip_mask_matches_a_plain_5_by_5_mean() { + let (w, h) = (23, 17); + let rgb: Vec<[f32; 3]> = (0..w * h).map(|i| [((i * 37) % 11) as f32 / 10.0, 0.2, ((i * 13) % 7) as f32 / 6.0]).collect(); + let mask = clip_mask(&rgb, w, h, 0.9); + for y in 0..h { + for x in 0..w { + let (mut s, mut n) = (0f64, 0); + for yy in y.saturating_sub(2)..(y + 3).min(h) { + for xx in x.saturating_sub(2)..(x + 3).min(w) { + let p = rgb[yy * w + xx]; + s += f64::from(p[0].max(p[1]).max(p[2])); + n += 1; + } + } + assert_eq!(mask[y * w + x], s / n as f64 >= 0.93 * 0.9, "({x}, {y})"); + } + } +} diff --git a/crates/denoise/src/lib.rs b/crates/denoise/src/lib.rs index bbce01961b..284400920e 100644 --- a/crates/denoise/src/lib.rs +++ b/crates/denoise/src/lib.rs @@ -11,7 +11,7 @@ //! - [`product`]: the cache file the denoised picture is kept in (half floats, compressed in strips) and the //! blend with the plain demosaic that the Amount slider controls. //! - [`cpu`] and [`runtime`]: a single-thread pure-Rust CPU runner and its installation self-test. -//! - [`defringe`]: AI Defringe, a defringe network run over a whole picture with its guards. +//! - `defringe` (with the `runtime` feature): AI Defringe, a defringe network run over a whole picture with its guards. //! - [`net`] and [`onnx`]: checked plain network data and bounded ONNX decoding, shared by CPU and GPU. //! - [`remote`]: running tiles on another computer's graphics card over TCP (a [`run::TileRunner`] and its server). //! diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 55c87056c6..66caf27c8d 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -192,6 +192,7 @@ impl DevelopSettings { self.curve = d; } Section::Color => self.wb.mode = WbMode::AsShot, + Section::Optics => self.optics.ai_defringe_on = None, Section::Detail => { self.enhance.denoise_on = None; // not a slider: reset like them, to the general default (off) @@ -479,6 +480,18 @@ mod tests { assert!(!s.profile.camera_local_tone); } + #[test] + fn resetting_optics_clears_the_ai_defringe_switch() { + // switched off by hand, then Optics reset: a later Amount turns it on, as on a fresh photo + let mut s = DevelopSettings::default(); + s.optics.ai_defringe = 60.0; + s.optics.ai_defringe_on = Some(false); + s.reset_section(Section::Optics); + assert_eq!((s.optics.ai_defringe, s.optics.ai_defringe_on), (0.0, None)); + s.optics.ai_defringe = 30.0; + assert!(s.optics.ai_defringe_enabled()); + } + #[test] fn section_toggles() { let mut s = DevelopSettings::default(); diff --git a/crates/engine/src/aidefringe.rs b/crates/engine/src/aidefringe.rs index 7e1c2c5fa8..d9ca5ce13a 100644 --- a/crates/engine/src/aidefringe.rs +++ b/crates/engine/src/aidefringe.rs @@ -116,10 +116,17 @@ pub fn models_dir() -> Option { .or_else(|| crate::config::config_dir().map(|d| d.join("defringe-models"))) } -/// The model installed in `dir`: its manifest and file, if there is one. +/// The folder inside the models folder that holds the installed model. LightCraft owns it and nothing else there: +/// the models folder may be one the user keeps other files in. +const CURRENT: &str = "installed"; +/// The previous installation while a new one replaces it, kept until the replacement is in place. +const PREVIOUS: &str = ".installed-previous"; + +/// The model installed in models folder `dir`: its manifest and file, if there is one. pub fn installed(dir: &Path) -> Option<(Manifest, PathBuf)> { - let m = Manifest::parse(&std::fs::read_to_string(dir.join(MANIFEST)).ok()?).ok()?; - let file = dir.join(&m.file); + let cur = dir.join(CURRENT); + let m = Manifest::parse(&std::fs::read_to_string(cur.join(MANIFEST)).ok()?).ok()?; + let file = cur.join(&m.file); file.is_file().then_some((m, file)) } @@ -172,26 +179,38 @@ fn bare(onnx: &Path, name: &str) -> Result { } fn read_model_file(path: &Path, m: &Manifest) -> Result, String> { - let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len(); - if len > MAX_MODEL_BYTES { + use std::io::Read; + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let mut bytes = Vec::new(); + // read at most one byte past the limit, whatever the file says its size is + file.take(MAX_MODEL_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > MAX_MODEL_BYTES { return Err("the model file is too large".into()); } - let bytes = std::fs::read(path).map_err(|e| e.to_string())?; if lightcraft_denoise_core::hash::sha256_hex(&bytes) != m.sha256 { return Err("the model file's SHA-256 is not the one its manifest gives".into()); } Ok(bytes) } -/// Install the model `onnx` (with its manifest beside it) in `dir`, after checking its hash and running it once: it -/// replaces the installed one. The caller has shown the user the manifest's licence and notice. -pub fn install(onnx: &Path, dir: &Path) -> Result { +/// Install the model `onnx` (with its manifest beside it, or without one: [`inspect`]) in models folder `dir`, after +/// checking its hash and running it once: it replaces the installed one. `accepted` is the manifest the user was shown +/// and accepted ([`inspect`]'s answer); if the file or its manifest changed since, nothing is installed. +pub fn install(onnx: &Path, dir: &Path, accepted: &Manifest) -> Result { let m = inspect(onnx)?; + if &m != accepted { + return Err("the model or its description changed after you accepted it: install it again to see its terms".into()); + } + // the bytes read here are the ones checked, run and installed let bytes = read_model_file(onnx, &m)?; self_test(&bytes)?; - let parent = dir.parent().ok_or("the defringe models folder has no parent")?; - std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let staging = parent.join(format!(".defringe-models-{}", std::process::id())); + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let (cur, prev) = (dir.join(CURRENT), dir.join(PREVIOUS)); + // a previous installation left behind by an install that could not put it back is restored first, never deleted + if !cur.exists() && prev.exists() { + std::fs::rename(&prev, &cur).map_err(|e| format!("couldn't restore the previous model from {}: {e}", prev.display()))?; + } + let staging = dir.join(format!(".installing-{}", std::process::id())); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?; let write = || -> std::io::Result<()> { @@ -202,25 +221,33 @@ pub fn install(onnx: &Path, dir: &Path) -> Result { let _ = std::fs::remove_dir_all(&staging); return Err(e.to_string()); } - let old = parent.join(format!(".defringe-models-old-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&old); - if dir.exists() { - std::fs::rename(dir, &old).map_err(|e| e.to_string())?; + if prev.exists() { + std::fs::remove_dir_all(&prev).map_err(|e| e.to_string())?; } - if let Err(e) = std::fs::rename(&staging, dir) { - let _ = std::fs::rename(&old, dir); + if cur.exists() { + std::fs::rename(&cur, &prev).map_err(|e| e.to_string())?; + } + if let Err(e) = std::fs::rename(&staging, &cur) { + let _ = std::fs::remove_dir_all(&staging); + if prev.exists() + && let Err(back) = std::fs::rename(&prev, &cur) + { + return Err(format!("couldn't install the model ({e}), nor put the previous one back ({back}); it is kept in {}", prev.display())); + } return Err(e.to_string()); } - let _ = std::fs::remove_dir_all(&old); + let _ = std::fs::remove_dir_all(&prev); Ok(m) } -/// Delete the model installed in `dir` (corrections already made stay until the cache is cleared). +/// Delete the model installed in models folder `dir` (only LightCraft's own folder in it; corrections already made +/// stay until the cache is cleared). pub fn remove(dir: &Path) -> Result { - if !dir.exists() { + let cur = dir.join(CURRENT); + if !cur.exists() { return Ok(false); } - std::fs::remove_dir_all(dir).map_err(|e| e.to_string())?; + std::fs::remove_dir_all(&cur).map_err(|e| e.to_string())?; Ok(true) } @@ -284,9 +311,16 @@ pub struct Correction { h: usize, index: Vec, gain: Vec<[u16; 3]>, - /// The last source it was applied to (address and size) at an amount (thousandths), and the result: renders of - /// one view reuse the corrected picture, so the stage cache keeps working while sliders move. - memo: Mutex)>>, + /// The last source it was applied to, at an amount (thousandths), and the result: renders of one view reuse the + /// corrected picture, so the stage cache keeps working while sliders move. Both are weak: the memo keeps no picture + /// alive (each would be a whole picture), and a source freed and replaced at the same address never matches. + memo: Mutex>, +} + +struct Memo { + source: std::sync::Weak, + thousandths: u32, + result: std::sync::Weak, } impl Correction { @@ -301,12 +335,14 @@ impl Correction { return src.clone(); } let k = amount.min(1.0); - let tag = (Arc::as_ptr(src) as usize, src.width, src.height, (k * 1000.0).round() as u32); + let thousandths = (k * 1000.0).round() as u32; let mut memo = self.memo.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((t, img)) = memo.as_ref() - && *t == tag + if let Some(m) = memo.as_ref() + && m.thousandths == thousandths + && m.source.upgrade().is_some_and(|s| Arc::ptr_eq(&s, src)) + && let Some(img) = m.result.upgrade() { - return img.clone(); + return img; } let (w, h) = (src.width, src.height); let mut out = (**src).clone(); @@ -319,8 +355,18 @@ impl Correction { } } } else { - // each source pixel covers (self.w / w) × (self.h / h) pixels of the correction - let area = (self.w as f32 / w as f32).max(1.0) * (self.h as f32 / h as f32).max(1.0); + // each pixel of the render takes the mean gain over the pixels of the correction that map to it (how many + // depends on where it is when the sizes don't divide) + let covers = |big: usize, small: usize| -> Vec { + let mut n = vec![0u32; small]; + for x in 0..big { + if let Some(c) = n.get_mut((x * small / big).min(small - 1)) { + *c += 1; + } + } + n + }; + let (nx, ny) = (covers(self.w, w), covers(self.h, h)); let mut acc: HashMap = HashMap::new(); for (&i, g) in self.index.iter().zip(&self.gain) { let (x, y) = (i as usize % self.w, i as usize / self.w); @@ -331,6 +377,7 @@ impl Correction { } } for (i, s) in acc { + let area = (nx.get(i % w).copied().unwrap_or(1) * ny.get(i / w).copied().unwrap_or(1)).max(1) as f32; if let Some(p) = out.data.get_mut(i) { for (v, d) in p.iter_mut().zip(s) { *v *= 1.0 + d / area * k; @@ -339,12 +386,15 @@ impl Correction { } } let out = Arc::new(out); - *memo = Some((tag, out.clone())); + *memo = Some(Memo { source: Arc::downgrade(src), thousandths, result: Arc::downgrade(&out) }); out } + /// Write the correction to `path` through a temporary file of this writer's own, if `publish` still allows it + /// (the cache was not cleared since the work started). Another writer that published the same correction first + /// is a success. #[cfg_attr(not(feature = "denoise"), allow(dead_code))] - fn write(&self, path: &Path) -> Result<(), String> { + fn write(&self, path: &Path, publish: &Publish) -> Result<(), String> { let mut body = Vec::with_capacity(self.index.len() * 10); for (i, g) in self.index.iter().zip(&self.gain) { body.extend_from_slice(&i.to_le_bytes()); @@ -363,9 +413,22 @@ impl Correction { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; } - let tmp = path.with_extension("tmp"); + static NEXT: AtomicUsize = AtomicUsize::new(0); + let tmp = path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); std::fs::write(&tmp, &b).map_err(|e| e.to_string())?; - std::fs::rename(&tmp, path).map_err(|e| e.to_string()) + let epoch = publish.epoch.lock().unwrap_or_else(PoisonError::into_inner); + let done = if *epoch != publish.at { + Err("the AI Defringe cache was cleared while this correction was made".into()) + } else { + match std::fs::rename(&tmp, path) { + Ok(()) => Ok(()), + Err(_) if Correction::read(path, self.key).is_some() => Ok(()), + Err(e) => Err(e.to_string()), + } + }; + drop(epoch); + let _ = std::fs::remove_file(&tmp); + done } /// The correction at `path`, if it is one, for `key`, and intact. @@ -427,6 +490,14 @@ fn f16_value(b: u16) -> f32 { if sign == 1 { -v } else { v } } +/// Whether a correction may still be published: the cache's epoch when its work started, and the cache's epoch now +/// (bumped, under the lock, when the cache is cleared). +#[derive(Clone)] +pub struct Publish { + epoch: Arc>, + at: u64, +} + /// The name of photo `p`'s correction by the model with SHA-256 `model`. pub fn key(p: &Photo, model: &str) -> u64 { let mut h = Hasher128::new(); @@ -443,6 +514,7 @@ pub struct Recipe { info: SourceInfo, model: Arc, path: Option, + publish: Publish, } impl Recipe { @@ -476,14 +548,14 @@ impl Recipe { } let c = Correction { key: self.key, w, h, index, gain, memo: Mutex::new(None) }; if let Some(path) = &self.path { - c.write(path)?; + c.write(path, &self.publish)?; } Ok(c) } #[cfg(not(feature = "denoise"))] pub fn make(&self, _: &(dyn Fn(usize, usize) + Sync), _: &AtomicBool) -> Result { - let _ = (&self.source, &self.info, &self.model, &self.path); + let _ = (&self.source, &self.info, &self.model, &self.path, &self.publish); Err("this build of LightCraft can't run AI models".into()) } } @@ -521,6 +593,8 @@ struct Job { done: Arc, total: Arc, cancel: Arc, + /// The cache's epoch when it started: a result from before a clear is dropped. + epoch: u64, _task: crate::activity::TaskGuard, } @@ -535,6 +609,10 @@ pub struct State { job: Option, /// Corrections that failed, by key, and why (not tried again until asked). failed: HashMap, + /// Corrections the user cancelled, by key (not started again until asked: Try Again, or switching it on). + cancelled: std::collections::HashSet, + /// The cache's epoch, bumped (under this lock) when it is cleared ([`Publish`]). + epoch: Arc>, /// Corrections in memory, most recently used last. ready: Vec<(PhotoId, Arc)>, /// Bumped whenever a correction arrives (renders made before it are stale). @@ -616,7 +694,12 @@ impl Session { let key = key(&p, &sha); let path = self.aidefringe_dir().map(|d| d.join(format!("{key:016x}.lcadf"))); let source = self.media.source_ref_uncached(&p, SourceLevel::Full); - Ok(Recipe { photo: id, key, source, info: self.source_info(id), model, path }) + let publish = Publish { epoch: self.aidefringe.epoch.clone(), at: self.aidefringe_epoch() }; + Ok(Recipe { photo: id, key, source, info: self.source_info(id), model, path, publish }) + } + + fn aidefringe_epoch(&self) -> u64 { + *self.aidefringe.epoch.lock().unwrap_or_else(PoisonError::into_inner) } /// The installed model's key for photo `p`, if a model is installed. @@ -703,12 +786,13 @@ impl Session { } } - /// Forget why photo `id`'s correction failed, so it is tried again. + /// Forget why photo `id`'s correction failed or that it was cancelled, so it is tried again. pub fn aidefringe_retry(&mut self, id: PhotoId) { if let Some(p) = self.catalog.photo(id).cloned() && let Some(key) = self.aidefringe_key(&p) { self.aidefringe.failed.remove(&key); + self.aidefringe.cancelled.remove(&key); } } @@ -732,7 +816,9 @@ impl Session { } r => { let Some(job) = self.aidefringe.job.take() else { return false }; + let stale = job.epoch != self.aidefringe_epoch(); match r { + _ if stale => {} Ok(Ok(c)) => { self.aidefringe_keep(job.photo, Arc::new(c)); arrived = true; @@ -740,6 +826,10 @@ impl Session { Ok(Err(e)) if !job.cancel.load(Ordering::Relaxed) => { self.aidefringe.failed.insert(job.key, e); } + // cancelled while still wanted: by the user, so not started again by itself + Ok(Err(_)) if still => { + self.aidefringe.cancelled.insert(job.key); + } Ok(Err(_)) => {} Err(_) => { self.aidefringe.failed.insert(job.key, "the defringe job stopped".into()); @@ -757,7 +847,7 @@ impl Session { return arrived; } let Some(key) = self.aidefringe_key(&p) else { return arrived }; - if self.aidefringe.failed.contains_key(&key) || self.aidefringe_get(id, key).is_some() { + if self.aidefringe.failed.contains_key(&key) || self.aidefringe.cancelled.contains(&key) || self.aidefringe_get(id, key).is_some() { return arrived; } match self.aidefringe_recipe(id) { @@ -774,7 +864,7 @@ impl Session { let task = self.activity.start("aidefringe", "AI Defringe", crate::activity::Cancel::Flag(cancel.clone())); task.detail(name); let (tx, rx) = channel(); - let (d, t, c, key, photo) = (done.clone(), total.clone(), cancel.clone(), r.key, r.photo); + let (d, t, c, key, photo, epoch) = (done.clone(), total.clone(), cancel.clone(), r.key, r.photo, r.publish.at); std::thread::Builder::new() .name("ai-defringe".into()) .spawn(move || { @@ -787,7 +877,7 @@ impl Session { let _ = tx.send(made); }) .ok(); - self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, _task: task }); + self.aidefringe.job = Some(Job { photo, key, rx, done, total, cancel, epoch, _task: task }); } /// Make photo `id`'s correction now, on this thread (for scripts and tests) → how many pixels it changes. @@ -796,14 +886,23 @@ impl Session { let c = Arc::new(r.make(&|_, _| {}, &AtomicBool::new(false))?); let n = c.changed(); self.aidefringe.failed.remove(&r.key); + self.aidefringe.cancelled.remove(&r.key); self.aidefringe_keep(id, c); Ok(n) } - /// Delete every cached correction of this library → (files, bytes). + /// Delete every cached correction of this library → (files, bytes). Work started before is not published: the + /// epoch is bumped under the lock writers publish under, so none can write after the files are deleted. pub fn aidefringe_clear(&mut self) -> (usize, u64) { + let epoch = self.aidefringe.epoch.clone(); + let mut epoch = epoch.lock().unwrap_or_else(PoisonError::into_inner); + *epoch += 1; + if let Some(j) = &self.aidefringe.job { + j.cancel.store(true, Ordering::Relaxed); + } self.aidefringe.ready.clear(); self.aidefringe.failed.clear(); + self.aidefringe.cancelled.clear(); self.aidefringe.generation += 1; let Some(dir) = self.aidefringe_dir() else { return (0, 0) }; let (mut files, mut bytes) = (0, 0); @@ -827,6 +926,7 @@ impl Session { } self.aidefringe.model = None; self.aidefringe.failed.clear(); + self.aidefringe.cancelled.clear(); self.aidefringe.generation += 1; self.aidefringe_refresh(true); } diff --git a/crates/engine/src/aidefringe/tests.rs b/crates/engine/src/aidefringe/tests.rs index 2eb7dabcd0..0311128e18 100644 --- a/crates/engine/src/aidefringe/tests.rs +++ b/crates/engine/src/aidefringe/tests.rs @@ -1,4 +1,5 @@ use super::*; +use std::path::PathBuf; fn manifest_json(sha: &str) -> String { format!( @@ -30,12 +31,33 @@ fn correction(w: usize, h: usize, at: &[(usize, [f32; 3])]) -> Correction { } } +/// A folder of this test's own, removed when it ends (also when an assertion fails). +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> TempDir { + TempDir(crate::tests_xmp::temp_dir(tag)) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn publish() -> Publish { + Publish { epoch: Arc::new(Mutex::new(0)), at: 0 } +} + #[test] fn a_correction_survives_the_disk_and_a_damaged_one_is_refused() { - let dir = std::env::temp_dir().join(format!("lc-adf-{}", std::process::id())); - let path = dir.join("c.lcadf"); + let dir = TempDir::new("adf-file"); + let path = dir.0.join("c.lcadf"); let c = correction(10, 4, &[(3, [0.5, -0.25, 0.0]), (17, [0.0, 0.125, -0.5])]); - c.write(&path).unwrap(); + c.write(&path, &publish()).unwrap(); + // a second writer of the same correction (the background job and an export) succeeds too + c.write(&path, &publish()).unwrap(); let back = Correction::read(&path, 7).unwrap(); assert_eq!((back.w, back.h, &back.index, &back.gain), (10, 4, &c.index, &c.gain)); assert!(Correction::read(&path, 8).is_none(), "another key"); @@ -44,7 +66,12 @@ fn a_correction_survives_the_disk_and_a_damaged_one_is_refused() { bytes[last] ^= 0xff; std::fs::write(&path, &bytes).unwrap(); assert!(Correction::read(&path, 7).is_none(), "damaged"); - let _ = std::fs::remove_dir_all(&dir); + // after the cache was cleared, work started before it is not published + let stale = Publish { epoch: Arc::new(Mutex::new(1)), at: 0 }; + let other = dir.0.join("d.lcadf"); + assert!(c.write(&other, &stale).is_err()); + assert!(!other.exists()); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1, "no temporary file left behind"); } #[test] @@ -71,3 +98,28 @@ fn half_floats_round_trip() { } assert_eq!(f16_value(f16_bits(1e9)), 65504.0); } + +#[test] +fn a_smaller_source_whose_size_does_not_divide_keeps_a_constant_gain() { + // 3 × 1 with the same gain everywhere, rendered 2 × 1: two pixels of it map to the first, one to the second + let c = correction(3, 1, &[(0, [0.5; 3]), (1, [0.5; 3]), (2, [0.5; 3])]); + let src = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.4; 3]; 2] }); + let out = c.apply(&src, 1.0); + for p in &out.data { + assert!(p.iter().all(|v| (v - 0.6).abs() < 1e-6), "{:?}", out.data); + } +} + +#[test] +fn the_memo_keeps_nothing_alive_and_never_mistakes_a_new_picture_for_an_old_one() { + let c = correction(2, 1, &[(0, [1.0, 0.0, 0.0])]); + let a = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.5; 3]; 2] }); + let first = c.apply(&a, 1.0); + assert!(Arc::ptr_eq(&first, &c.apply(&a, 1.0)), "the same view reuses its picture"); + assert_eq!(Arc::strong_count(&first), 1, "the memo holds no strong reference"); + drop(first); + drop(a); + // a new picture, maybe at the old one's address: corrected afresh + let b = Arc::new(Rgb32f { width: 2, height: 1, data: vec![[0.25; 3]; 2] }); + assert_eq!(c.apply(&b, 1.0).data[0], [0.5, 0.25, 0.25]); +} diff --git a/crates/engine/src/cmd/aidefringe.rs b/crates/engine/src/cmd/aidefringe.rs index 5f48684dd1..c51e67e45d 100644 --- a/crates/engine/src/cmd/aidefringe.rs +++ b/crates/engine/src/cmd/aidefringe.rs @@ -16,8 +16,9 @@ fn photo(s: &Session, p: &Value, c: &str) -> Result { } } +/// The manifest as JSON: what the user is shown, and what `aiDefringe.models.install` takes back as `model`. fn model_json(m: &aidefringe::Manifest) -> Value { - json!({"id": m.id, "name": m.name, "version": m.version, "licence": m.licence, "sha256": m.sha256, "notice": m.notice, "url": m.url}) + serde_json::to_value(m).unwrap_or(Value::Null) } /// A per-photo switch, independent of the selection and Auto Sync. Turning on starts at 100. @@ -32,6 +33,14 @@ fn toggle(s: &mut Session, p: &Value) -> Result { if on && s.aidefringe_model().is_none() { return Err(bad(C, "AI Defringe needs a model: install one in Settings > AI Defringe")); } + // switching off a photo that was never switched on changes nothing (so the first switch on still starts at 100) + if !on && d.optics.ai_defringe_on.is_none() && !d.optics.ai_defringe_enabled() { + return Ok(json!({"id": id.0, "enabled": false, "amount": d.optics.ai_defringe})); + } + if on { + // switching on asks for the correction again, even one the user cancelled + s.aidefringe_retry(id); + } // the switch is its own setting: the Amount stays where it is when it is flipped, so flipping compares with and // without; a photo that never had an Amount starts at 100 let amount = if on && d.optics.ai_defringe_on.is_none() && d.optics.ai_defringe <= 0.0 { 100.0 } else { d.optics.ai_defringe }; @@ -98,8 +107,13 @@ fn install(s: &mut Session, p: &Value) -> Result { if !bool_or(p, "acknowledged", false) { return Err(bad(C, "show the user the model's licence and notice first, then pass `acknowledged: true`")); } + // what the user accepted: the model `aiDefringe.models.inspect` gave, which must still be what the path holds + let accepted = p + .get("model") + .ok_or_else(|| bad(C, "`model` is required: the model `aiDefringe.models.inspect` gave, as the user accepted it")) + .and_then(|v| aidefringe::Manifest::parse(&v.to_string()).map_err(|e| bad(C, e)))?; let dir = s.aidefringe_models_dir().ok_or_else(|| bad(C, "no folder for defringe models (set LIGHTCRAFT_DEFRINGE_MODELS)"))?; - let m = aidefringe::install(Path::new(path), &dir).map_err(|e| bad(C, e))?; + let m = aidefringe::install(Path::new(path), &dir, &accepted).map_err(|e| bad(C, e))?; s.aidefringe_model_changed(); Ok(json!({"installed": true, "model": model_json(&m)})) } @@ -133,8 +147,8 @@ pub fn specs() -> Vec { cmd!(query "aiDefringe.pump", "AI Defringe Pump", [], None, "{} → {arrived, generation} — called every frame by the app: takes in a finished correction and starts the active photo's when AI Defringe is on and it has none", always, pump), cmd!(query "aiDefringe.make", "Make AI Defringe Correction", [], None, "{id?} → {id, changed} — make a photo's correction now and wait for it (for scripts); `changed` is how many pixels it changes", always, make), cmd!(query "aiDefringe.retry", "Retry AI Defringe", [], None, "{id?} → {id, photo} — try a photo whose correction failed again", always, retry), - cmd!(query "aiDefringe.models.inspect", "Inspect Defringe Model", [], None, "{path} → {id, name, version, licence, sha256, notice, url} — the defringe-model.json beside an .onnx file, checked; never runs the file", always, inspect), - cmd!(query "aiDefringe.models.install", "Install Defringe Model", [], None, "{path, acknowledged: true} → {installed, model} — install a defringe model from an .onnx file with a defringe-model.json beside it, after checking its SHA-256 and running it once; it replaces the installed one. `acknowledged` must be true: the user has been shown the model's licence and notice", always, install), + cmd!(query "aiDefringe.models.inspect", "Inspect Defringe Model", [], None, "{path} → {id, name, version, licence, file, sha256, contract, notice?, url?} — the defringe-model.json beside an .onnx file, checked, or one made up from the file when there is none (licence \"Not stated\"); never runs the file", always, inspect), + cmd!(query "aiDefringe.models.install", "Install Defringe Model", [], None, "{path, model, acknowledged: true} → {installed, model} — install a defringe model from an .onnx file (with a defringe-model.json beside it, or without one: `aiDefringe.models.inspect` describes it), after checking its SHA-256 and running it once; it replaces the installed one. `model` is what `aiDefringe.models.inspect` gave and `acknowledged` must be true: the user has been shown that model's licence and notice and accepted them. If the file or its description changed since, nothing is installed", always, install), cmd!(query "aiDefringe.models.remove", "Remove Defringe Model", [], None, "{} → {removed} — delete the installed defringe model (corrections already made stay until cleared)", always, remove), cmd!(query "aiDefringe.clear", "Clear AI Defringe Cache", [], None, "{} → {deleted, bytes} — delete every cached AI Defringe correction of this library (they are made again when wanted)", always, clear), ] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a5d8c2912..af2e86be5b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1038,6 +1038,14 @@ impl Session { for k in ["spots", "red_eye", "version", "process"] { o.remove(k); } + // AI Defringe is per photo, like AI Denoise's switch: its switch and Amount stay with the photo they were set on + if let Some(optics) = o.get_mut("optics").and_then(Value::as_object_mut) { + optics.remove("ai_defringe"); + optics.remove("ai_defringe_on"); + if optics.is_empty() { + o.remove("optics"); + } + } if o.is_empty() { return Vec::new(); } diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 4c9838f3a2..1c99d001f0 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -149,10 +149,24 @@ impl crate::Session { ^ (job.level as u64) << 60 ^ profile_salt.rotate_left(29) ^ lens.rotate_left(37) - ^ decoder.rotate_left(43); + ^ decoder.rotate_left(43) + ^ job.ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11)); Some(job) } + /// `ck` with AI Defringe's correction in it, when the render uses one: a thumbnail rendered before the correction + /// was there is not taken for one with it. + fn with_ai_defringe(ck: Hash128, a: Option<&crate::aidefringe::ForRender>) -> Hash128 { + match a { + Some(a) => { + let mut k = Hasher128::new(); + k.u64(ck.0 as u64).u64((ck.0 >> 64) as u64).str("aidefringe").u64(a.key()); + k.finish() + } + None => ck, + } + } + /// Cache key of a variant thumbnail ([`Self::variant_job`]). /// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile. pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 { @@ -189,7 +203,10 @@ impl crate::Session { // decoded as these settings develop it (their camera profile, or none) p.develop = Arc::new(settings.clone()); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)); + // with AI Defringe's correction when these settings use it and it is made + let ai_defringe = self.aidefringe_for_render(&p, settings, false).ok().flatten(); + let ck = + Self::with_ai_defringe(Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id)), ai_defringe.as_ref()); Some(RenderJob { request_id: 0, cache_generation: self.media.rendered.generation(), @@ -210,7 +227,7 @@ impl crate::Session { slide: None, preview_cut: None, display_fit: None, - ai_defringe: None, + ai_defringe, }) } @@ -245,8 +262,14 @@ impl crate::Session { let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64); let level = SourceLevel::for_size(needed as usize); let source = self.media.source_ref(&p, level); - let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)); - let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize); + // the photo's own look, so with its AI Defringe correction when it is on and made + let ai_defringe = self.aidefringe_for_render(&p, &settings, false).ok().flatten(); + let ck = Self::with_ai_defringe( + Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id)), + ai_defringe.as_ref(), + ); + // (a raw's embedded preview has no correction: a corrected tile is rendered) + let preview_cut = if ai_defringe.is_some() { None } else { self.face_preview_cut(&p, rect, edge, needed as usize) }; Some(RenderJob { request_id: 0, cache_generation: self.media.rendered.generation(), @@ -267,7 +290,7 @@ impl crate::Session { slide: None, preview_cut, display_fit: None, - ai_defringe: None, + ai_defringe, }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2916185704..0a2b4734aa 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -646,6 +646,9 @@ fn op_log_replay_reproduces_catalog() { #[test] fn command_sweep() { let mut s = demo(); + // `aiDefringe.models.remove` would delete the model installed in the real defringe models folder + let models = std::env::temp_dir().join(format!("lc-sweep-defringe-models-{}", std::process::id())); + s.set_aidefringe_models_dir(Some(models.clone())); let mut ids = std::collections::HashSet::new(); for c in command_specs() { assert!(ids.insert(c.id), "duplicate {}", c.id); @@ -659,6 +662,7 @@ fn command_sweep() { // empty params must never start a download from the internet assert!(!s.place_names.download_started(), "the sweep started a place names download"); assert!(s.commands().len() >= 70, "{}", s.commands().len()); + let _ = std::fs::remove_dir_all(&models); } #[test] diff --git a/crates/engine/src/tests/aidefringe.rs b/crates/engine/src/tests/aidefringe.rs index d1be34c57d..e7b990ddef 100644 --- a/crates/engine/src/tests/aidefringe.rs +++ b/crates/engine/src/tests/aidefringe.rs @@ -62,9 +62,15 @@ fn photo(s: &Session) -> lightcraft_catalog::PhotoId { s.catalog.photos().next().unwrap().id } +/// Install the model at `path` as the app does: inspect it, then install what was inspected, acknowledged. +fn install_path(s: &mut Session, path: &Path) -> crate::Result { + let model = s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()}))?; + s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": model, "acknowledged": true})) +} + fn install(x: &mut Setup) -> Value { let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); - x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap() + install_path(&mut x.s, &path).unwrap() } #[test] @@ -73,10 +79,20 @@ fn a_model_is_installed_only_when_acknowledged_and_intact() { let path = model_files(&x.dir, [-3.0, 3.0, 10.0]); let inspected = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); assert_eq!(inspected["notice"], "a test network"); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy()})).is_err(), "not acknowledged"); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": inspected})).is_err(), "not acknowledged"); + assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).is_err(), "nothing accepted"); + // the manifest changed after the user accepted it: its licence was not the one shown + let manifest = path.with_file_name(MANIFEST); + let text = std::fs::read_to_string(&manifest).unwrap(); + std::fs::write(&manifest, text.replace("\"MIT\"", "\"Non-commercial\"")).unwrap(); + let r = x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "model": inspected, "acknowledged": true})); + assert!(r.unwrap_err().to_string().contains("changed after you accepted it")); + std::fs::write(&manifest, text).unwrap(); // a file that isn't the one its manifest names + let good = std::fs::read(&path).unwrap(); std::fs::write(&path, b"something else").unwrap(); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).is_err()); + assert!(install_path(&mut x.s, &path).is_err()); + std::fs::write(&path, good).unwrap(); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); let r = install(&mut x); assert_eq!(r["model"]["id"], "push"); @@ -159,7 +175,7 @@ fn any_defringe_shaped_onnx_installs_without_a_manifest_and_anything_else_is_ref // a denoiser (the wrong shape) is refused when it is run, and nothing is installed let wrong = bare.join("smoothing.onnx"); std::fs::write(&wrong, lightcraft_denoise::synthetic::smoothing_onnx()).unwrap(); - assert!(x.s.execute("aiDefringe.models.install", &json!({"path": wrong.to_string_lossy(), "acknowledged": true})).is_err()); + assert!(install_path(&mut x.s, &wrong).is_err()); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"], Value::Null); // a defringe network on its own: named after its file, its licence unknown let path = bare.join("My Defringe v2.onnx"); @@ -167,9 +183,52 @@ fn any_defringe_shaped_onnx_installs_without_a_manifest_and_anything_else_is_ref let m = x.s.execute("aiDefringe.models.inspect", &json!({"path": path.to_string_lossy()})).unwrap(); assert_eq!((m["name"].as_str(), m["licence"].as_str()), (Some("My Defringe v2"), Some("Not stated"))); assert!(m["notice"].as_str().unwrap().contains("doesn't know who made it")); - x.s.execute("aiDefringe.models.install", &json!({"path": path.to_string_lossy(), "acknowledged": true})).unwrap(); + install_path(&mut x.s, &path).unwrap(); assert_eq!(x.s.execute("aiDefringe.status", &json!({})).unwrap()["model"]["id"], "My-Defringe-v2"); x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); assert!(x.s.execute("aiDefringe.make", &json!({})).unwrap()["changed"].as_u64().unwrap() > 0); let _ = std::fs::remove_dir_all(&x.dir); } + +#[test] +fn the_models_folder_keeps_the_users_own_files() { + let mut x = setup("adf-own-files"); + // the user pointed the models folder at one that holds their own files + let models = x.dir.join("defringe-models"); + std::fs::create_dir_all(&models).unwrap(); + std::fs::write(models.join("mine.onnx"), b"the user's").unwrap(); + install(&mut x); + install(&mut x); + assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "installing twice"); + x.s.execute("aiDefringe.models.remove", &json!({})).unwrap(); + assert_eq!(std::fs::read(models.join("mine.onnx")).unwrap(), b"the user's", "removing"); + assert_eq!(x.s.execute("aiDefringe.models.remove", &json!({})).unwrap()["removed"], false); + assert!(models.join("mine.onnx").exists()); + let _ = std::fs::remove_dir_all(&x.dir); +} + +#[test] +fn the_switch_starts_at_100_even_after_switching_off_an_untouched_photo_and_stays_out_of_auto_sync() { + let mut x = setup("adf-switch-default"); + let originals = x.dir.join("originals"); + std::fs::write(originals.join("second.dng"), stripe_dng(336, 288)).unwrap(); + x.s.execute("library.import", &json!({"paths": [originals.join("second.dng").to_string_lossy()]})).unwrap(); + install(&mut x); + let ids: Vec<_> = x.s.catalog.photos().map(|p| p.id).collect(); + let (a, b) = (ids[0], ids[1]); + x.s.execute("library.select", &json!({"ids": [a.0]})).unwrap(); + let r = x.s.execute("aiDefringe.toggle", &json!({"enabled": false})).unwrap(); + assert_eq!(r["enabled"], false); + assert_eq!(x.s.develop_of(a).unwrap().optics.ai_defringe_on, None, "nothing to switch off"); + let r = x.s.execute("aiDefringe.toggle", &json!({"enabled": true})).unwrap(); + assert_eq!(r["amount"], 100.0); + // Auto Sync with both selected: an AI Defringe change stays on the photo it was made on + x.s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap(); + x.s.auto_sync = true; + x.s.execute("develop.set", &json!({"values": {"optics.aiDefringe": 40.0, "optics.vignetting": 10.0}})).unwrap(); + let (da, db) = (x.s.develop_of(a).unwrap(), x.s.develop_of(b).unwrap()); + assert_eq!((da.optics.ai_defringe, da.optics.vignetting), (40.0, 10.0)); + assert_eq!(db.optics.vignetting, 10.0, "the rest of the edit syncs"); + assert_eq!((db.optics.ai_defringe, db.optics.ai_defringe_on), (0.0, None), "AI Defringe does not"); + let _ = std::fs::remove_dir_all(&x.dir); +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index fc377fc3c7..ce5a9f68f0 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -662,7 +662,9 @@ pub fn defringe_tap(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: & rendition.optics.remove_ca = true; let plan = plan(src, info, &rendition, req); let mut img = plan.frame.sample(src, plan.w, plan.h); - lin_cpu(&mut img, info, &plan); + // `lin_cpu` up to the Defringe stage: retouching and red-eye come after it + local_tone::apply(&mut img, info, &plan); + local::white_balance(&mut img, info, &plan.settings); img } diff --git a/crates/ui-egui/src/panels/aidefringe.rs b/crates/ui-egui/src/panels/aidefringe.rs index 56b047b2c1..230bcf4dd0 100644 --- a/crates/ui-egui/src/panels/aidefringe.rs +++ b/crates/ui-egui/src/panels/aidefringe.rs @@ -29,6 +29,8 @@ pub struct Ui { /// with it) and keeps the open photo's coming; while one is being made, asks again for its progress. pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { if now < app.caches.aidefringe.next_pump { + // come back at the deadline even if nothing else asks for a frame + ctx.request_repaint_after(std::time::Duration::from_secs_f64(app.caches.aidefringe.next_pump - now)); return; } let Ok(v) = app.session.execute("aiDefringe.pump", &json!({})) else { return }; @@ -47,6 +49,22 @@ pub fn pump_background(app: &mut LightcraftApp, ctx: &egui::Context, now: f64) { } } +/// The AI Defringe check → whether it is on now. +fn switch(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, mut on: bool) -> bool { + egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 6, bottom: 2 }).show(ui, |ui| { + let r = ui.add(egui::Checkbox::new(&mut on, tr("AI Defringe"))).on_hover_text(tr( + "Removes colour fringes of every hue (purple, blue, green) with the installed defringe model, leaving real colours alone. \ + The correction is made once in the background and kept; switching it off and on, or changing Amount, is instant.", + )); + register(ui, "aidefringe:enabled", r.rect); + if r.changed() { + let _ = app.run("aiDefringe.toggle", json!({"id": id.0, "enabled": on})); + app.caches.aidefringe.next_pump = 0.0; + } + }); + on +} + fn note(ui: &mut egui::Ui, text: &str, color: egui::Color32) { ui.add(egui::Label::new(RichText::new(text).size(11.0).color(color)).wrap()); } @@ -75,19 +93,13 @@ pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, d: &Deve } } }); + // a photo left with it on (its model since removed) can still be switched off + if d.optics.ai_defringe_enabled() { + switch(app, ui, id, true); + } return; } - let mut on = d.optics.ai_defringe_enabled(); - egui::Frame::NONE.inner_margin(pad(6, 2)).show(ui, |ui| { - let r = ui.add(egui::Checkbox::new(&mut on, tr("AI Defringe"))).on_hover_text(tr( - "Removes colour fringes of every hue (purple, blue, green) with the installed defringe model, leaving real colours alone. \ - The correction is made once in the background and kept; switching it off and on, or changing Amount, is instant.", - )); - register(ui, "aidefringe:enabled", r.rect); - if r.changed() { - let _ = app.run("aiDefringe.toggle", json!({"id": id.0, "enabled": on})); - } - }); + let on = switch(app, ui, id, d.optics.ai_defringe_enabled()); crate::panels::edit::control(app, ui, d, "optics.aiDefringe", on); if !on || status["photo"].is_null() { return; @@ -191,7 +203,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { let install = crate::button::Button::new("Accept and Install").widget("aidefringe:accept").show(ui); let cancel = crate::button::Button::new("Cancel").widget("aidefringe:cancel").show(ui); if install.clicked() { - match app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})) { + match app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": info, "acknowledged": true})) { Ok(_) => app.caches.aidefringe.rejected = None, Err(e) => app.caches.aidefringe.rejected = Some(plain(&e)), } diff --git a/crates/ui-egui/src/tests/aidefringe.rs b/crates/ui-egui/src/tests/aidefringe.rs index f5b25cd310..630fc27948 100644 --- a/crates/ui-egui/src/tests/aidefringe.rs +++ b/crates/ui-egui/src/tests/aidefringe.rs @@ -98,7 +98,8 @@ fn the_switch_turns_it_on_and_the_correction_arrives() { let dir = temp("switch"); let mut h = defringe_open(&dir); let path = model_file(&dir); - h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "acknowledged": true})).unwrap(); + let model = h.app.session.execute("aiDefringe.models.inspect", &json!({"path": path})).unwrap(); + h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": model, "acknowledged": true})).unwrap(); h.app.caches.aidefringe = Default::default(); h.step(); h.step(); @@ -127,3 +128,25 @@ fn the_switch_turns_it_on_and_the_correction_arrives() { assert_eq!(d.optics.ai_defringe, 100.0); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_photo_left_on_without_a_model_can_be_switched_off() { + let dir = temp("orphan"); + let mut h = defringe_open(&dir); + let path = model_file(&dir); + let model = h.app.session.execute("aiDefringe.models.inspect", &json!({"path": path})).unwrap(); + h.app.session.execute("aiDefringe.models.install", &json!({"path": path, "model": model, "acknowledged": true})).unwrap(); + let id = h.app.session.active().unwrap(); + h.app.session.execute("aiDefringe.toggle", &json!({"id": id.0, "enabled": true})).unwrap(); + h.app.session.execute("aiDefringe.models.remove", &json!({})).unwrap(); + h.app.caches.aidefringe = Default::default(); + h.step(); + h.step(); + assert!(on_screen(&mut h, "aidefringe:settings")); + assert!(on_screen(&mut h, "aidefringe:enabled"), "the switch stays while it is on"); + click(&mut h, "aidefringe:enabled"); + assert!(!h.app.session.develop_of(id).unwrap().optics.ai_defringe_enabled()); + h.step(); + assert!(!on_screen(&mut h, "aidefringe:enabled")); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/ai-defringe.md b/docs/ai-defringe.md index d06918c662..17253d2411 100644 --- a/docs/ai-defringe.md +++ b/docs/ai-defringe.md @@ -2,8 +2,8 @@ Optics ▸ Defringe ▸ **AI Defringe** is a per-photo switch with an **Amount** (0 to 100). It removes colour fringes of every hue (purple, blue-violet, green) with a trained network, and leaves real colours alone. Turning it on the first -time starts at 100; turning it off keeps the Amount. It acts on the requesting photo only, independently of Auto Sync, -and is undoable. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on +time starts at 100; turning it off keeps the Amount. It acts on the requesting photo only (Auto Sync never copies its switch or Amount), +and is undoable. Resetting Optics clears the switch. The manual Defringe sliders below it (Purple and Green Amount and their hue ranges) still work, on their own or together with it. AI Defringe needs a model, and **LightCraft ships none**. Settings ▸ AI Defringe ▸ **Install from file…** takes any ONNX @@ -11,8 +11,8 @@ file that has the defringe shape (see [The model contract](#the-model-contract)) its name, version and licence. Without one, LightCraft names the model after its file, gives the licence as "Not stated" with a notice saying it doesn't know who made it, and installs it only if it runs as a defringe model. Before anything is installed, Settings shows the model's name, licence and notice, and the user accepts them. Without a model the section -says where to install one. Builds without the model runtime (the web build, or a native build without the `denoise` -feature) say so and never offer the switch. +says where to install one; a photo still switched on (its model since removed) keeps the switch, so it can be switched +off. Builds without the model runtime (the web build, or a native build without the `denoise` feature) say so. ## How it works @@ -85,7 +85,8 @@ The ONNX file is read by LightCraft's own bounded reader: operators Conv, LeakyR and converted to OkLab by way of linear Rec.709 with negative values clamped. - **Output** `[1, 3, 256, 256]`: Δa and Δb before `tanh`, and the gate before its sigmoid. -Installation checks the manifest, the file's size (at most 256 MB) and SHA-256, the network's shape, and runs it twice +The install command takes back the model description `aiDefringe.models.inspect` gave, which the user accepted, and +installs nothing if the file or its description changed since. Installation checks the manifest, the file's size (at most 256 MB) and SHA-256, the network's shape, and runs it twice on a synthetic fringe: it must give finite colours, the same answer both times, and keep lightness. A model that fails is not installed and the one already there stays. @@ -94,8 +95,10 @@ is not installed and the one already there stays. `aiDefringe.toggle {id?, enabled?}`, `aiDefringe.status {id?}`, `aiDefringe.pump`, `aiDefringe.make {id?}` (makes a correction now and waits, for scripts), `aiDefringe.retry {id?}`, `aiDefringe.clear`, and `aiDefringe.models.inspect {path}`, `.install {path, acknowledged: true}`, `.remove`. The develop control is `optics.aiDefringe` (with -`optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The model folder is -`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. +`optics.ai_defringe_on` in the settings, as AI Denoise has `enhance.denoise_on`). The models folder is +`/defringe-models`, or `$LIGHTCRAFT_DEFRINGE_MODELS`. The model goes in an `installed` folder inside it, the +only thing LightCraft writes or deletes there, so the models folder can be one that holds other files. During an install +the previous model is kept as `.installed-previous` until the new one is in place. ## Limits