Skip to content

Commit 0ca91a2

Browse files
AlexChambersclaude
andcommitted
LR-IMP-FORMATS: coloured highlights keep their edges, refreshes never downgrade a newer proxy (storytold#1328 review)
Review of 52f6b7e8: P2. A pixel next to a strongly coloured clipped highlight (the blue sample at an orange sun's rim, a neon tube's edge) had its interpolated channels rebuilt from its weakest, measured channel, mostly with a neutral colour where the content around was clipped: a dark checkerboard line just inside the edge (public sunset ARW (2973, 1267): linear Y 0.874 -> 0.213). The rebuild may now darken a pixel only to 0.8 of the luminance its reconstruction told by value gives (highlight::CONTINUITY), else it keeps the latter; it may brighten it by as much among strongly coloured content, and further among pale content (a white sky behind twigs, where the value keeps the demosaic's cyan and magenta). That pixel is Y 0.874 again, the neon's (1491, 1210) 0.912 (main 0.979, 52f6b7e8 0.287); no pixel of either frame goes from Y > 0.8 to below 0.4 (52f6b7e8: 132 and 495). The Canon 80D twigs stay dark. Treating only the channels with their own FROM bit as unknown was tried: the mean colour spread around clipped areas went from under 3 % to 8.5 % and X-Trans lifted dark lines, so the other interpolated channel stays unknown with them. P2. Build Smart Previews rebuilt a stale proxy from the session's source, which is the old proxy's when it was decoded while the original was offline: it kept the proxy. P2. A rebuilt proxy left the session's decoded sources and rendered previews made from the old one. On storytold#1400 both are covered by its machinery, which this commit uses instead of its own: jobs read the original afresh (origin_ref), and a replaced proxy takes storytold#1400's invalidation (a marker before the first change, the thumbnail clear at the end of the run, decoded sources following the cache generation, late results refused by generation). The tests below pass on it. P2. A refresh rewrote a proxy whose other version came from a newer build (look 5 / source 0 -> 4 / 1). Ages::stale reads both versions together and leaves any proxy with a newer one alone; the folder markers only go up. With storytold#850 on storytold#1400, a Compact proxy's encode version (`enc`) counts the same way (smart::from_newer_build), staleness for the look includes an older Compact encoding (storytold#850's is_stale), and the look marker keeps its two versions, each never going back. P2. Finite samples too large for the scaling (a float DNG of 1e37 at gains 64 : 1 : 1) overflowed. The scaling pass now also checks every sample: one that is not finite, or whose magnitude times the largest gain (or divided by the smallest) exceeds 1e30 (MAX_BALANCED), makes the mosaic, read afresh, develop unbalanced. The MAX_GAIN doc no longer claims more. P3. Docs: previews bin_factor can't bin are Bayer under about 4600 px and X-Trans under about 5760 px on the long side (the 16 MP X-E1 changes). Tests: coloured suns and tubes keep their brightness at the edges (every method, phase and X-Trans), and a decoded F32 DNG of 1e37 develops unbalanced and finite (1.5e28 at the extreme gains balanced and finite), both failing on 52f6b7e8; proxies with a newer look or source version are never rewritten and the markers stay, failing without this commit. Build Smart Previews refreshes with the old proxy still cached, and a refreshed proxy replaces the session's source, cached render and late results and the reopened library's: these pass through storytold#1400's machinery. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 744edd8 commit 0ca91a2

10 files changed

Lines changed: 527 additions & 114 deletions

File tree

‎crates/engine/src/cmd/previews.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,12 @@ impl Ages {
202202
fn of(p: &lightcraft_catalog::Photo) -> Ages {
203203
Ages { look: p.fitted_look(), source: p.develops_raw() }
204204
}
205-
/// Whether the complete proxy at `path` is out of date in a way that applies to this photo.
205+
/// Whether the complete proxy at `path` is out of date in a way that applies to this photo: for the look (an older
206+
/// fit, or a Compact proxy's older encoding, [`crate::smart::is_stale`]) or for the raw decode. Never when any of
207+
/// its versions comes from a newer build: rewriting it would take that one back (a build with all of them is the
208+
/// one to bring it up to date).
206209
fn stale(self, path: &std::path::Path) -> bool {
207-
(self.look && crate::smart::is_stale(path)) || (self.source && crate::smart::source_stale(path))
210+
!crate::smart::from_newer_build(path) && ((self.look && crate::smart::is_stale(path)) || (self.source && crate::smart::source_stale(path)))
208211
}
209212
}
210213

‎crates/engine/src/smart.rs‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ pub(crate) const ENCODE_VERSION: u64 = 2;
100100
/// reconstruction, the colour model). `RENDER_CACHE_VERSION` covers renders and in-memory sources; this covers the
101101
/// persisted ones.
102102
///
103-
/// 0: no field (before it existed); 1: sensors too small to bin at preview size (under about 4600 px on the long
104-
/// side) demosaic the white-balanced mosaic with the clip mask (#1328).
103+
/// 0: no field (before it existed); 1: raws that don't bin at preview size (`files::bin_factor` is `None`: Bayer
104+
/// sensors under about 4600 px on the long side, X-Trans under about 5760 px) demosaic the white-balanced mosaic with
105+
/// the clip mask (#1328).
105106
pub const SOURCE_VERSION: u32 = 1;
106107

107108
/// The header field that records [`SOURCE_VERSION`].
@@ -411,6 +412,24 @@ pub fn is_stale(path: &Path) -> bool {
411412
})
412413
}
413414

415+
/// The `(LOOK_VERSION, SOURCE_VERSION)` the complete proxy at `path` was written by (a missing or malformed one: 0), or
416+
/// `None` when it is incomplete or unreadable ([`is_complete`]). Read together, so a refresh can tell a proxy that is old in
417+
/// one but from a newer build in the other (which it must leave alone).
418+
pub fn versions(path: &Path) -> Option<(u64, u64)> {
419+
complete_header(path).map(|(_, h)| (header_version(&h, LOOK_FIELD), header_version(&h, SOURCE_FIELD)))
420+
}
421+
422+
/// Whether the complete proxy at `path` was written by a newer build: its camera-look fit or raw decode version, or a
423+
/// Compact proxy's encode version, is above this build's. Such a proxy is never rewritten here: this build would put
424+
/// its own older look, decode or encoding in it and take that version back.
425+
pub fn from_newer_build(path: &Path) -> bool {
426+
complete_header(path).is_some_and(|(storage, h)| {
427+
header_version(&h, LOOK_FIELD) > u64::from(crate::camera_preview::LOOK_VERSION)
428+
|| header_version(&h, SOURCE_FIELD) > u64::from(SOURCE_VERSION)
429+
|| (storage == Format::Compact && header_version(&h, ENC_FIELD) > ENCODE_VERSION)
430+
})
431+
}
432+
414433
/// Whether the complete proxy at `path` holds a source decoded by an older raw decode than this build's
415434
/// ([`SOURCE_VERSION`]); only a raw's proxy is out of date for it, which the caller knows. As [`is_stale`]: a proxy
416435
/// from a newer build, or one that is incomplete, is not.
@@ -437,6 +456,16 @@ fn marker(dir: &Path, name: &str) -> Vec<u64> {
437456
text.split_whitespace().map_while(|w| w.parse::<u64>().ok()).collect()
438457
}
439458

459+
/// Record `versions` in the marker `name` in `dir`, each kept at the one recorded there if that is newer (a newer
460+
/// build checked the folder: no version in a marker goes back); versions after them that it records stay too.
461+
fn mark(dir: &Path, name: &str, versions: &[u64]) -> Result<(), String> {
462+
let old = marker(dir, name);
463+
let kept = versions.iter().enumerate().map(|(i, &v)| old.get(i).map_or(v, |&o| o.max(v))).chain(old.iter().skip(versions.len()).copied());
464+
let text = kept.map(|v| v.to_string()).collect::<Vec<_>>().join(" ");
465+
let path = dir.join(name);
466+
lightcraft_catalog::safe_file::write_atomic(&path, format!("{text}\n").as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
467+
}
468+
440469
/// Whether the smart previews folder `dir` has been checked for out-of-date proxies at this build's
441470
/// camera-look fit version and encode version (or newer ones). A missing or unreadable marker counts
442471
/// as not, and so does one written before the encode version was recorded — it only says the look
@@ -453,17 +482,14 @@ pub fn source_checked(dir: &Path) -> bool {
453482
}
454483

455484
/// Record that the proxies in `dir` were checked at this build's camera-look fit version and encode
456-
/// version.
485+
/// version (newer ones recorded stay).
457486
pub fn mark_look_checked(dir: &Path) -> Result<(), String> {
458-
let path = dir.join(LOOK_MARKER);
459-
let text = format!("{} {}\n", crate::camera_preview::LOOK_VERSION, ENCODE_VERSION);
460-
lightcraft_catalog::safe_file::write_atomic(&path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
487+
mark(dir, LOOK_MARKER, &[u64::from(crate::camera_preview::LOOK_VERSION), ENCODE_VERSION])
461488
}
462489

463-
/// Record that the raws' proxies in `dir` were checked at this build's [`SOURCE_VERSION`].
490+
/// Record that the raws' proxies in `dir` were checked at this build's [`SOURCE_VERSION`] (a newer one recorded stays).
464491
pub fn mark_source_checked(dir: &Path) -> Result<(), String> {
465-
let path = dir.join(SOURCE_MARKER);
466-
lightcraft_catalog::safe_file::write_atomic(&path, format!("{SOURCE_VERSION}\n").as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
492+
mark(dir, SOURCE_MARKER, &[u64::from(SOURCE_VERSION)])
467493
}
468494

469495
/// Load the proxy at `path`.

‎crates/engine/src/tests_import.rs‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1670,6 +1670,199 @@ fn smart_previews_of_raws_from_an_older_decode_are_refreshed() {
16701670
let _ = std::fs::remove_dir_all(&lib);
16711671
}
16721672

1673+
/// A library with an ARW (fitted look), a DNG (none) and a PNG (the test loader decodes PNG pixels for the raws),
1674+
/// all three with current smart previews; the loader counts the originals it reads.
1675+
struct SmartFixture {
1676+
s: Session,
1677+
src: std::path::PathBuf,
1678+
lib: std::path::PathBuf,
1679+
dir: std::path::PathBuf,
1680+
ids: [lightcraft_catalog::PhotoId; 3],
1681+
files: [std::path::PathBuf; 3],
1682+
calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1683+
}
1684+
1685+
impl SmartFixture {
1686+
fn new(tag: &str) -> SmartFixture {
1687+
let src = temp_dir(&format!("{tag}-src"));
1688+
let lib = temp_dir(&format!("{tag}-lib"));
1689+
for (name, seed) in [("a.png", 3), ("b.png", 9), ("c.png", 5)] {
1690+
write_png(&src.join(name), seed);
1691+
}
1692+
let mut s = Session::new().with_fs();
1693+
s.open_library(&lib, false).unwrap();
1694+
let paths: Vec<String> = ["a.png", "b.png", "c.png"].iter().map(|n| src.join(n).to_string_lossy().to_string()).collect();
1695+
s.execute("library.import", &json!({ "paths": paths })).unwrap();
1696+
let find = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id;
1697+
let ids = [find(&s, "a.png"), find(&s, "b.png"), find(&s, "c.png")];
1698+
for (id, format) in [(ids[0], "ARW"), (ids[1], "DNG")] {
1699+
let mut raw = (**s.catalog.photo(id).unwrap()).clone();
1700+
raw.format = format.into();
1701+
raw.kind = lightcraft_catalog::MediaKind::Raw;
1702+
s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id }).unwrap();
1703+
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(raw) }).unwrap();
1704+
}
1705+
s.execute("library.select", &json!({"ids": [ids[0].0, ids[1].0, ids[2].0], "active": ids[0].0})).unwrap();
1706+
let dir = s.media.smart_dir.clone().unwrap();
1707+
let files = ids.map(|id| crate::smart::sharded_file_path(&dir, s.catalog.photo(id).unwrap()));
1708+
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1709+
let plain = s.media.file_loader.clone().unwrap();
1710+
s.media.file_loader = Some(look_loader(plain, test_tone(1.5), calls.clone()));
1711+
let r = s.execute("library.smartPreviews", &json!({})).unwrap();
1712+
assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(3), Some(0)), "{r}");
1713+
SmartFixture { s, src, lib, dir, ids, files, calls }
1714+
}
1715+
/// The originals of the raws out of reach (renamed), or back.
1716+
fn offline(&self, off: bool) {
1717+
for name in ["a", "b"] {
1718+
let (on, away) = (self.src.join(format!("{name}.png")), self.src.join(format!("{name}.offline")));
1719+
let (from, to) = if off { (on, away) } else { (away, on) };
1720+
std::fs::rename(from, to).unwrap();
1721+
}
1722+
}
1723+
fn calls(&self) -> usize {
1724+
self.calls.load(std::sync::atomic::Ordering::SeqCst)
1725+
}
1726+
}
1727+
1728+
impl Drop for SmartFixture {
1729+
fn drop(&mut self) {
1730+
let _ = std::fs::remove_dir_all(&self.src);
1731+
let _ = std::fs::remove_dir_all(&self.lib);
1732+
}
1733+
}
1734+
1735+
fn mean_of(img: &lightcraft_raster::Rgb32f) -> f32 {
1736+
img.data.iter().flatten().sum::<f32>() / (img.data.len() * 3).max(1) as f32
1737+
}
1738+
1739+
/// Round 2 review of #1328: Build Smart Previews refreshes an out-of-date proxy from its original once the original is
1740+
/// back, even when the session still holds the source it decoded from the proxy meanwhile (that source is not the
1741+
/// original, so the refresh used to give up on it and count the proxy as kept).
1742+
#[test]
1743+
fn smart_previews_refresh_from_their_returned_original_with_the_proxy_still_cached() {
1744+
let mut f = SmartFixture::new("smartreturn");
1745+
for file in &f.files[..2] {
1746+
edit_smart_header(file, |h| h["source_version"] = json!(0));
1747+
}
1748+
f.offline(true);
1749+
for id in &f.ids[..2] {
1750+
f.s.media.forget(*id);
1751+
let held = f.s.source_now(*id, crate::media::SourceLevel::Preview).unwrap();
1752+
assert!(mean_of(&held) > 0.0, "decoded from the proxy");
1753+
}
1754+
f.offline(false);
1755+
f.calls.store(0, std::sync::atomic::Ordering::SeqCst);
1756+
let r = f.s.execute("library.smartPreviews", &json!({})).unwrap();
1757+
assert_eq!((r["refreshed"].as_u64(), r["staleKept"].as_u64()), (Some(2), Some(0)), "{r}");
1758+
assert_eq!(f.calls(), 2, "both raws' originals read");
1759+
assert!(f.files[..2].iter().all(|file| !crate::smart::source_stale(file)));
1760+
}
1761+
1762+
/// Round 2 review of #1328: once a proxy is rebuilt from its original, the session stops using what it decoded from
1763+
/// the old proxy, and renders made from it are not served again (in this session, and in the library reopened).
1764+
#[test]
1765+
fn a_refreshed_smart_preview_replaces_what_the_session_made_from_the_old_one() {
1766+
let mut f = SmartFixture::new("smartswap");
1767+
let (arw, file) = (f.ids[0], f.files[0].clone());
1768+
// an old proxy, unmistakable: a tenth of the original's brightness
1769+
let mut old = (*crate::smart::load(&file).unwrap().image).clone();
1770+
old.data.iter_mut().for_each(|p| p.iter_mut().for_each(|v| *v *= 0.1));
1771+
std::fs::write(&file, crate::smart::encode(&old, None).unwrap()).unwrap();
1772+
edit_smart_header(&file, |h| h["source_version"] = json!(0));
1773+
f.offline(true);
1774+
f.s.media.forget(arw);
1775+
let cached = f.s.source_now(arw, crate::media::SourceLevel::Preview).unwrap();
1776+
let thumb = f.s.thumb_job(arw, 128).unwrap();
1777+
let old_thumb = thumb.clone().run();
1778+
f.s.accept(&old_thumb);
1779+
let (key, before) = (thumb.cache.as_ref().unwrap().1, old_thumb.rendered.unwrap().image);
1780+
assert!(f.s.media.rendered.get(key).is_some(), "rendered from the old proxy, cached");
1781+
// a render that started before the refresh and finishes after it
1782+
let late = f.s.thumb_job(arw, 256).unwrap();
1783+
f.offline(false);
1784+
crate::smart::mark_look_checked(&f.dir).unwrap();
1785+
std::fs::write(f.dir.join("source-version"), b"0\n").unwrap();
1786+
crate::cmd::previews::refresh_stale_smart_previews(&mut f.s).unwrap().join().unwrap();
1787+
assert!(!crate::smart::source_stale(&file));
1788+
let fresh = mean_of(&crate::smart::load(&file).unwrap().image);
1789+
assert!(fresh > mean_of(&cached) * 5.0, "the proxy on disk is the original's");
1790+
// the late render's source is not taken in
1791+
let late = late.run();
1792+
f.s.accept(&late);
1793+
// this session: the decoded source and the cached render are gone
1794+
assert!(f.s.media.rendered.get(key).is_none(), "the render made from the old proxy is not served");
1795+
let shown = f.s.source_now(arw, crate::media::SourceLevel::Preview).unwrap();
1796+
assert!(!std::sync::Arc::ptr_eq(&cached, &shown) && mean_of(&shown) > mean_of(&cached) * 5.0, "the session uses the new source");
1797+
let again = f.s.thumb_job(arw, 128).unwrap().run();
1798+
assert!(again.rendered.unwrap().image != before, "rendered afresh");
1799+
// the library reopened, the original offline: the refreshed proxy
1800+
let lib = f.lib.clone();
1801+
f.s.close_library().unwrap();
1802+
drop(std::mem::take(&mut f.s));
1803+
f.offline(true);
1804+
f.s = Session::new().with_fs();
1805+
f.s.open_library(&lib, false).unwrap();
1806+
let shown = f.s.source_now(arw, crate::media::SourceLevel::Preview).unwrap();
1807+
assert!((mean_of(&shown) - fresh).abs() < 0.02 * fresh, "{} vs {fresh}", mean_of(&shown));
1808+
f.offline(false);
1809+
}
1810+
1811+
/// Round 2 review of #1328: a proxy written by a newer build in either version (the camera-look fit or the raw decode)
1812+
/// is never rewritten here, even when the other version is older, by Build Smart Previews or by the opening scan;
1813+
/// and the folder's markers never go back.
1814+
#[test]
1815+
fn smart_previews_from_a_newer_build_are_never_downgraded() {
1816+
let mut f = SmartFixture::new("smartnewer");
1817+
let (look, source) = (u64::from(crate::camera_preview::LOOK_VERSION), u64::from(crate::smart::SOURCE_VERSION));
1818+
for (l, s) in [(look + 1, 0), (look.saturating_sub(1), source + 1), (look + 1, source + 1)] {
1819+
for file in &f.files[..2] {
1820+
edit_smart_header(file, |h| {
1821+
h["look_version"] = json!(l);
1822+
h["source_version"] = json!(s);
1823+
});
1824+
}
1825+
let before: Vec<Vec<u8>> = f.files[..2].iter().map(|file| std::fs::read(file).unwrap()).collect();
1826+
let r = f.s.execute("library.smartPreviews", &json!({})).unwrap();
1827+
assert_eq!(r["refreshed"], 0, "({l}, {s}): {r}");
1828+
std::fs::write(f.dir.join("look-version"), b"0\n").unwrap();
1829+
std::fs::write(f.dir.join("source-version"), b"0\n").unwrap();
1830+
crate::cmd::previews::refresh_stale_smart_previews(&mut f.s).unwrap().join().unwrap();
1831+
let after: Vec<Vec<u8>> = f.files[..2].iter().map(|file| std::fs::read(file).unwrap()).collect();
1832+
assert!(before == after, "({l}, {s}) rewritten");
1833+
}
1834+
// a Compact proxy from a newer encoding (#850's `enc`), its look and decode current, stays too
1835+
let enc = crate::smart::ENCODE_VERSION;
1836+
for file in &f.files[..2] {
1837+
edit_smart_header(file, |h| {
1838+
h["look_version"] = json!(look);
1839+
h["source_version"] = json!(source);
1840+
h["enc"] = json!(enc + 1);
1841+
});
1842+
}
1843+
let before: Vec<Vec<u8>> = f.files[..2].iter().map(|file| std::fs::read(file).unwrap()).collect();
1844+
let r = f.s.execute("library.smartPreviews", &json!({})).unwrap();
1845+
assert_eq!(r["refreshed"], 0, "enc {}: {r}", enc + 1);
1846+
std::fs::write(f.dir.join("look-version"), b"0 0\n").unwrap();
1847+
crate::cmd::previews::refresh_stale_smart_previews(&mut f.s).unwrap().join().unwrap();
1848+
let after: Vec<Vec<u8>> = f.files[..2].iter().map(|file| std::fs::read(file).unwrap()).collect();
1849+
assert!(before == after, "enc {} rewritten", enc + 1);
1850+
// markers from a newer build stay as they are, version by version
1851+
std::fs::write(f.dir.join("look-version"), b"99 97\n").unwrap();
1852+
std::fs::write(f.dir.join("source-version"), b"98\n").unwrap();
1853+
crate::smart::mark_look_checked(&f.dir).unwrap();
1854+
crate::smart::mark_source_checked(&f.dir).unwrap();
1855+
assert_eq!(std::fs::read_to_string(f.dir.join("look-version")).unwrap().trim(), "99 97");
1856+
assert_eq!(std::fs::read_to_string(f.dir.join("source-version")).unwrap().trim(), "98");
1857+
std::fs::write(f.dir.join("look-version"), b"99\n").unwrap();
1858+
crate::smart::mark_look_checked(&f.dir).unwrap();
1859+
assert_eq!(
1860+
std::fs::read_to_string(f.dir.join("look-version")).unwrap().trim(),
1861+
format!("99 {enc}"),
1862+
"a newer look kept, the encode version added"
1863+
);
1864+
}
1865+
16731866
/// The look marker: missing, damaged or older than this build's fit version counts as unchecked.
16741867
#[test]
16751868
fn smart_preview_look_marker_is_read_safely() {

0 commit comments

Comments
 (0)