From 7c3d7901321a9bb4862aa48f055a0c41d83af063 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:26:41 +0100 Subject: [PATCH 01/30] Assisted Culling: test two bursts and a deleted photo with stackGroups Two bursts make two stacks in one undo step; a deleted photo is measured but left out of its burst's stack. The blur and PNG helpers of the stacking test move to module level so both tests share them. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests/import.rs | 116 +++++++++++++++++++++--------- 1 file changed, 82 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index d97b00a9c6..d2d44e722a 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -1120,6 +1120,44 @@ fn assisted_culling_burst_limits_are_adjustable() { let _ = std::fs::remove_dir_all(&dir); } +/// A box blur of radius `r`: the larger `r`, the lower the focus score. +fn soften(img: &lightcraft_raster::Rgb32f, r: usize) -> lightcraft_raster::Rgb32f { + let (w, h) = (img.width, img.height); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + let (mut acc, mut n) = ([0f32; 3], 0.0); + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + let c = img.data[yy * w + xx]; + acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; + n += 1.0; + } + } + out.data[y * w + x] = acc.map(|v| v / n); + } + } + out +} + +/// Write a linear image as an sRGB PNG. +fn save_png(img: &lightcraft_raster::Rgb32f, path: &std::path::Path) { + let data: Vec<[u8; 4]> = img + .data + .iter() + .map(|c| { + let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; + [e(c[0]), e(c[1]), e(c[2]), 255] + }) + .collect(); + let png = lightcraft_codecs::encode_png( + &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), + &Default::default(), + ) + .unwrap(); + std::fs::write(path, png).unwrap(); +} + /// Assisted culling with `stackGroups` (#2277): each burst becomes one collapsed stack with its /// sharpest photo on top, an unrelated photo stays loose, analysis and stack are one undo step, /// and a second run neither makes another stack nor splits the existing one. @@ -1127,40 +1165,7 @@ fn assisted_culling_burst_limits_are_adjustable() { fn assisted_culling_stacks_each_burst_best_on_top() { let dir = temp_dir("cull-stack"); let scene = lightcraft_scenes::demo_library()[0].render(480, 320); - let soften = |img: &lightcraft_raster::Rgb32f, r: usize| { - let (w, h) = (img.width, img.height); - let mut out = img.clone(); - for y in 0..h { - for x in 0..w { - let (mut acc, mut n) = ([0f32; 3], 0.0); - for yy in y.saturating_sub(r)..(y + r + 1).min(h) { - for xx in x.saturating_sub(r)..(x + r + 1).min(w) { - let c = img.data[yy * w + xx]; - acc = [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2]]; - n += 1.0; - } - } - out.data[y * w + x] = acc.map(|v| v / n); - } - } - out - }; - let save = |img: &lightcraft_raster::Rgb32f, name: &str| { - let data: Vec<[u8; 4]> = img - .data - .iter() - .map(|c| { - let e = |v: f32| (lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8; - [e(c[0]), e(c[1]), e(c[2]), 255] - }) - .collect(); - let png = lightcraft_codecs::encode_png( - &lightcraft_codecs::EncodeImage::rgba8(&lightcraft_raster::Rgba8 { width: img.width, height: img.height, data }), - &Default::default(), - ) - .unwrap(); - std::fs::write(dir.join(name), png).unwrap(); - }; + let save = |img: &lightcraft_raster::Rgb32f, name: &str| save_png(img, &dir.join(name)); save(&soften(&scene, 3), "a_soft.png"); save(&scene, "b_sharp.png"); save(&soften(&scene, 6), "c_softer.png"); @@ -1234,6 +1239,49 @@ fn assisted_culling_stacks_each_burst_best_on_top() { let _ = std::fs::remove_dir_all(&dir); } +/// Assisted culling with `stackGroups` (#2277): two bursts make two stacks in one undo step, and a +/// deleted photo is measured but left out of its burst's stack, even when it is the sharpest. +#[test] +fn assisted_culling_stacks_two_bursts_and_leaves_deleted_photos_out() { + let dir = temp_dir("cull-stack-two"); + let (one, two) = (lightcraft_scenes::demo_library()[0].render(480, 320), lightcraft_scenes::demo_library()[7].render(480, 320)); + let files = [ + ("a_soft.png", soften(&one, 3), "10:00:00"), + ("b_sharp.png", one.clone(), "10:00:01"), + ("c_softer.png", soften(&one, 6), "10:00:02"), + ("d_sharp.png", two.clone(), "10:05:00"), + ("e_soft.png", soften(&two, 4), "10:05:01"), + ]; + for (name, img, _) in &files { + save_png(img, &dir.join(name)); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.to_string_lossy()]})).unwrap(); + let by_name = |s: &Session, n: &str| s.catalog.photos().find(|p| p.file_name == n).unwrap().id; + for (name, _, at) in &files { + let id = by_name(&s, name); + s.commit("t", lightcraft_catalog::Op::SetCaptured { id, captured: Some(format!("2026-05-01T{at}")) }).unwrap(); + } + let [soft, sharp, softer, d, e] = files.map(|f| by_name(&s, f.0)); + let ids: Vec = [soft, sharp, softer, d, e].iter().map(|p| p.0).collect(); + s.commit("t", lightcraft_catalog::Op::SetDeleted { id: sharp, deleted: true }).unwrap(); + let n = s.commits(); + let r = s.execute("photo.analyze", &json!({"ids": ids, "stackGroups": true})).unwrap(); + assert_eq!((r["groups"].clone(), r["stacks"].clone()), (json!(2), json!(2)), "{r}"); + assert_eq!(s.commits(), n + 1, "analysis and both stacks are one undo step"); + // the deleted photo is measured, but its burst is stacked from the other two + assert!(s.catalog.photo(sharp).unwrap().analysis.is_some()); + assert!(s.catalog.stack_of(sharp).is_none(), "a deleted photo is never stacked"); + let st = s.catalog.stack_of(soft).unwrap(); + assert!(st.collapsed && st.top() == soft && st.photos.len() == 2 && st.photos.contains(&softer), "{st:?}"); + let st = s.catalog.stack_of(d).unwrap(); + assert!(st.collapsed && st.top() == d && st.photos.len() == 2 && st.photos.contains(&e), "{st:?}"); + // one undo removes both stacks + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.stacks().next().is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Find Dust Spots: soft dark spots on a smooth sky are found and healed (one undo step). #[test] fn dust_spots_are_found_and_healed() { From ed7dbd8082a5b8c88a313923ad9367c06bc89800 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:30:19 +0100 Subject: [PATCH 02/30] Assisted Culling: a cull dialog without stack_groups reads it as false Like reset_bursts, the field takes its default when the JSON leaves it out, so main's dialog-copy test builds the dialog unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state/dialog.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/state/dialog.rs b/crates/ui-egui/src/state/dialog.rs index 4c0549e926..092da21881 100644 --- a/crates/ui-egui/src/state/dialog.rs +++ b/crates/ui-egui/src/state/dialog.rs @@ -171,6 +171,7 @@ pub enum Dialog { Cull { reject_below: f32, pick_best: bool, + #[serde(default)] stack_groups: bool, burst_gap: f32, similarity: f32, From 16f8f7e8a0b89e7f00dc94ce2274845fd70078f9 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Fri, 6 Nov 2026 01:34:21 +0600 Subject: [PATCH 03/30] Grid: one selected photo shows "1 selected" in the header (#3776) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Library grid's header added the selection count only from two selected photos up, so selecting one showed nothing, while the reference app shows "1 selected". It now shows from one. The Spanish, Brazilian Portuguese and Swedish strings were plural-only ("1 seleccionadas"); they now read "Seleccionadas: 1 · ...", the noun-first form Italian and Polish already use. --- crates/ui-egui/locales/es-formats.json | 2 +- crates/ui-egui/locales/pt-br-formats.json | 2 +- crates/ui-egui/locales/sv-formats.json | 2 +- crates/ui-egui/src/panels/grid.rs | 2 +- .../ui-egui/src/panels/grid/header_tests.rs | 35 +++++++++++++++++++ 5 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 7b697e946b..32547eebe8 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -169,7 +169,7 @@ "{n} photo{} now · updates automatically as photos change": "{n} foto{} ahora · se actualiza automáticamente cuando cambian las fotos", "{n} selected photo{} · {pages} page{}": "{n} foto{0} seleccionada{0} · {pages} página{1}", "{pid} (missing)": "{pid} (falta)", - "{sel_n} selected · {counted}": "{sel_n} seleccionadas · {counted}", + "{sel_n} selected · {counted}": "Seleccionadas: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} {n} foto{}", "{weekday}, {day}": "{weekday}, {day}", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 83d5a37518..e547bee56a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -128,7 +128,7 @@ "{n} photo{} match · updates automatically as photos change": "{n} foto{0} correspondente{0} · atualiza automaticamente conforme as fotos mudam", "{n} photo{} now · updates automatically as photos change": "{n} foto{} agora · atualiza automaticamente conforme as fotos mudam", "{n} selected photo{} · {pages} page{}": "{n} foto{0} selecionada{0} · {pages} página{1}", - "{sel_n} selected · {counted}": "{sel_n} selecionadas · {counted}", + "{sel_n} selected · {counted}": "Selecionadas: {sel_n} · {counted}", "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb} {n} foto{}", "{weekday}, {day}": "{weekday}, {day}", diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 7d40388d1b..68995acf5c 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -253,7 +253,7 @@ "{pct} %": "{pct} %", "{photos} catalog records processed; {collections} collections.": "{photos} katalogposter bearbetade; {collections} samlingar.", "{pid} (missing)": "{pid} (saknas)", - "{sel_n} selected · {counted}": "{sel_n} markerade · {counted}", + "{sel_n} selected · {counted}": "Markerade: {sel_n} · {counted}", "{size} GB": "{size} GB", "{stage}… {:.0}%": "{stage}… {:.0} %", "{s} s of AV1 video": "{s} s AV1-video", diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index db4dfa1b83..2c16c38047 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -298,7 +298,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let chips = lightcraft_engine::filter_chips(&app.session.filter, &app.session.catalog); let total = app.session.source_total(); let counted = super::chips::count_text(ids.len(), total, !chips.is_empty()); - let cnt = if sel_n > 1 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted }; + let cnt = if sel_n > 0 { crate::i18n::tr_format!("{sel_n} selected · {counted}", counted = counted, sel_n = sel_n) } else { counted }; match app.session.browse.clone().filter(|_| app.session.source == lightcraft_engine::LibrarySource::Folder) { Some(b) => { let local = app.caches.grid.local(&app.session.catalog, &ids, generation); diff --git a/crates/ui-egui/src/panels/grid/header_tests.rs b/crates/ui-egui/src/panels/grid/header_tests.rs index 463991625e..88b992d3b4 100644 --- a/crates/ui-egui/src/panels/grid/header_tests.rs +++ b/crates/ui-egui/src/panels/grid/header_tests.rs @@ -17,6 +17,41 @@ fn breadcrumbs_open_their_folder_as_spelled() { assert!(to("").is_empty() && to("/").is_empty() && to(r"\\").is_empty()); } +/// Issue #3776: one selected photo is counted in the header as two or more are ("1 selected · 3 +/// photos"); with nothing selected the header shows the photo count alone. +#[test] +fn the_header_counts_a_single_selected_photo() { + use lightcraft_catalog::{Op, Photo, Source}; + for selected in [0, 1, 2] { + let mut session = lightcraft_engine::Session::new(); + for i in 0..3 { + let id = session.catalog.alloc_photo_id(); + let p = Photo::new(id, Source::File { path: format!("/pics/{i}.jpg") }, "x.jpg", "JPEG", 60, 40, "2026-01-01T10:00:00"); + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + session.selection.ids = session.catalog.photos().take(selected).map(|p| p.id).collect(); + let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + app.ui.view = crate::state::ViewMode::PhotoGrid; + let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); + h.step(); + h.step(); + assert_eq!(h.app.session.selection.ids.len(), selected, "the selection is kept"); + let painted = h.painted_text(); + let expected = if selected == 0 { "3 photos".to_string() } else { format!("{selected} selected · 3 photos") }; + assert!(painted.contains(&expected), "{selected} selected: the header shows {expected:?}: {painted:?}"); + if selected == 0 { + assert!(!painted.iter().any(|s| s.contains("selected ·")), "nothing selected, no count: {painted:?}"); + } + } + // a language whose word for "selected" agrees with the number reads "noun: number", right for one as for many + for (locale, expected) in [(Locale::Es, "Seleccionadas: 1 · x"), (Locale::PtBr, "Selecionadas: 1 · x"), (Locale::Sv, "Markerade: 1 · x")] { + crate::i18n::set_language(locale); + let one = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 1, counted = "x"); + crate::i18n::set_language(Locale::En); + assert_eq!(one, expected, "{locale:?}"); + } +} + fn text_bounds(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(text) => out.push(text.visual_bounding_rect()), From c97fee7b2f79d1b473e8c446d2cd3121ad8a6bc7 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Fri, 6 Nov 2026 04:09:48 +0600 Subject: [PATCH 04/30] Grid: the library header's selection count is cut, not clipped, when it is wider than the header (#3776) In the library view the count was painted right-aligned at any width, so at the narrowest pane a long count started outside the header and lost its beginning. It now truncates with "..." and shows the full text on hover, as the folder header's count already did; the title still gives way first. The header moved into its own function so a test can render it at a set width, and the folder view's one-photo count is tested too. --- crates/ui-egui/src/panels/grid.rs | 46 ++++++---- .../ui-egui/src/panels/grid/header_tests.rs | 87 ++++++++++++++++++- 2 files changed, 114 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 2c16c38047..556f809d27 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -291,7 +291,6 @@ pub fn rows_between(rows: &[GridRow], top: f32, bottom: f32) -> &[GridRow] { } fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); let (generation, ids) = app.session.visible_shared(); // header: source title + count let sel_n = app.session.selection.ids.len(); @@ -305,21 +304,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { folder_header(app, ui, &b, &ids, local, &cnt); } None => { - let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); - ui.painter().rect_filled(hr, 0.0, t.canvas); - let full = crate::i18n::source_title(&app.session); - let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.font(12.5), t.text_dim).size().x; - // the title gives way to the count: a long album or folder name is trimmed, in full on hover - let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); - let font = t.semibold(17.0); - let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); - let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); - let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim); - crate::widgets::register(ui, "grid:title", title_rect); - crate::widgets::register(ui, "grid:count", count_rect); - if title != full { - ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full); - } + library_header(app, ui, &cnt); } } super::chips::show(app, ui, &chips); @@ -1016,6 +1001,35 @@ struct BadgeFlags { hovered: bool, } +/// The header of a library view (All Photos, an album, a library folder…): the source's title and +/// the photo count. +fn library_header(app: &LightcraftApp, ui: &mut egui::Ui, cnt: &str) -> Rect { + let t = Tokens::get(ui.ctx()); + let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); + ui.painter().rect_filled(hr, 0.0, t.canvas); + let full = crate::i18n::source_title(&app.session); + // the title gives way to the count: a long album or folder name is trimmed, in full on hover; + // a count wider than all but the title's ellipsis (a narrow centre pane) is cut, as a Local + // folder's is, and reads in full on hover + let count_w = ui.painter().layout_no_wrap(cnt.to_owned(), t.font(12.5), t.text_dim).size().x.ceil().min((hr.width() - 96.0).max(0.0).floor()); + let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); + let font = t.semibold(17.0); + let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); + let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); + let count_box = Rect::from_min_max(pos2(hr.right() - 20.0 - count_w, hr.top()), pos2(hr.right() - 20.0, hr.bottom())); + let label = egui::Label::new(egui::RichText::new(cnt).font(t.font(12.5)).color(t.text_dim)).truncate().show_tooltip_when_elided(false); + let count = ui + .scope_builder(egui::UiBuilder::new().max_rect(count_box).layout(egui::Layout::right_to_left(egui::Align::Center)), |ui| ui.add(label)) + .inner; + crate::widgets::register(ui, "grid:title", title_rect); + crate::widgets::register(ui, "grid:count", count.rect); + count.on_hover_text(cnt); + if title != full { + ui.interact(title_rect, ui.scope_id().with("grid-title"), Sense::hover()).on_hover_text(full); + } + hr +} + /// The header of a Local folder view: the path as a breadcrumb (each part opens that folder), /// Include subfolders, Add to My Photos. fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engine::Browse, ids: &[PhotoId], local_n: usize, cnt: &str) -> Rect { diff --git a/crates/ui-egui/src/panels/grid/header_tests.rs b/crates/ui-egui/src/panels/grid/header_tests.rs index 88b992d3b4..db5cd37ffe 100644 --- a/crates/ui-egui/src/panels/grid/header_tests.rs +++ b/crates/ui-egui/src/panels/grid/header_tests.rs @@ -22,7 +22,7 @@ fn breadcrumbs_open_their_folder_as_spelled() { #[test] fn the_header_counts_a_single_selected_photo() { use lightcraft_catalog::{Op, Photo, Source}; - for selected in [0, 1, 2] { + for (selected, folder) in [(0, false), (1, false), (2, false), (0, true), (1, true)] { let mut session = lightcraft_engine::Session::new(); for i in 0..3 { let id = session.catalog.alloc_photo_id(); @@ -30,15 +30,24 @@ fn the_header_counts_a_single_selected_photo() { session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); } session.selection.ids = session.catalog.photos().take(selected).map(|p| p.id).collect(); + if folder { + // a Local folder view: the same count, in the breadcrumb header + session.source = lightcraft_engine::LibrarySource::Folder; + session.browse = Some(lightcraft_engine::Browse { path: "/pics".into(), subfolders: false }); + } let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); app.ui.view = crate::state::ViewMode::PhotoGrid; let mut h = crate::headless::Headless::new(app, [1400.0, 900.0], 1.0); h.step(); h.step(); assert_eq!(h.app.session.selection.ids.len(), selected, "the selection is kept"); + let has = |id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + assert!(has("grid:count") && has("grid:folderHeader") == folder, "folder {folder}: {:?}", h.app.widgets); let painted = h.painted_text(); - let expected = if selected == 0 { "3 photos".to_string() } else { format!("{selected} selected · 3 photos") }; - assert!(painted.contains(&expected), "{selected} selected: the header shows {expected:?}: {painted:?}"); + let photos = crate::panels::chips::count_text(h.app.session.visible_cloned().len(), h.app.session.source_total(), false); + assert!(folder || photos == "3 photos", "{photos}"); + let expected = if selected == 0 { photos } else { format!("{selected} selected · {photos}") }; + assert!(painted.contains(&expected), "folder {folder}, {selected} selected: the header shows {expected:?}: {painted:?}"); if selected == 0 { assert!(!painted.iter().any(|s| s.contains("selected ·")), "nothing selected, no count: {painted:?}"); } @@ -52,6 +61,78 @@ fn the_header_counts_a_single_selected_photo() { } } +/// Every text the frame painted as it reads on screen (a cut one with its "…"), with where it was painted. +fn texts_painted(shape: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match shape { + egui::Shape::Text(text) => { + let shown = text.galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| g.chr)).collect(); + out.push((shown, text.visual_bounding_rect())); + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts_painted(s, out)), + _ => {} + } +} + +/// A library view's count too long for a narrow centre pane (German, at the narrowest the photo +/// area gets) is cut to stay inside the header, beside the title, and reads in full on hover. +#[test] +fn a_long_library_count_stays_inside_a_narrow_header() { + for width in [crate::state::MIN_PHOTO_WIDTH, 590.0] { + for scale in [1.0, 2.0] { + let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + let ctx = egui::Context::default(); + crate::i18n::set_language(Locale::De); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx); + let counted = crate::i18n::tr_format!("{matching} of {t} photos", matching = 123_456_789, t = 987_654_321); + let cnt = crate::i18n::tr_format!("{sel_n} selected · {counted}", sel_n = 123_456_789, counted = counted); + let frame = |time: f64, events: Vec| { + let mut header = Rect::NOTHING; + let raw = HeadlessView::raw_input(vec2(width, 300.0), scale, time, events); + let mut out = ctx.run_ui(raw, |ui| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + header = super::library_header(&app, ui, &cnt); + }); + }); + out.textures_delta.clear(); + let mut texts = Vec::new(); + for shape in &out.shapes { + texts_painted(&shape.shape, &mut texts); + } + (texts, crate::widgets::take_registry(&ctx), header) + }; + let (mut texts, mut widgets, mut header) = (Vec::new(), Vec::new(), Rect::NOTHING); + for f in 0..3 { + (texts, widgets, header) = frame(f as f64 / 60.0, vec![]); + } + let widget = |id: &str| widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r); + let (Some(count), Some(title)) = (widget("grid:count"), widget("grid:title")) else { panic!("no count or title: {widgets:?}") }; + let at = format!("{width} {scale}"); + assert!(header.left() >= 0.0 && header.right() <= width, "{at}: header must not expand past the centre pane: {header:?}"); + assert!(header.contains_rect(count), "{at}: the count stays inside the header: {count:?} in {header:?}"); + assert!(title.right() <= count.left(), "{at}: the title stays left of the count: {title:?} {count:?}"); + for (i, (text, a)) in texts.iter().enumerate() { + assert!(header.expand(1.0).contains_rect(*a), "{at}: {text:?} painted outside the header: {a:?}"); + for (other, b) in texts.iter().skip(i + 1) { + assert!(!a.intersects(*b), "{at}: {text:?} overlaps {other:?}"); + } + } + // cut where it doesn't fit, and in full on hover + let fits = width > 500.0; + assert_eq!(texts.iter().any(|(t, _)| *t == cnt), fits, "{at}: {texts:?}"); + let cut = cnt.split(" von ").next().unwrap_or_default(); + assert!(fits || texts.iter().any(|(t, _)| t.ends_with('…') && t.starts_with(cut)), "{at}: the count is cut at its end: {texts:?}"); + let mut shown = Vec::new(); + for f in 3..120 { + let events = if f == 3 { vec![egui::Event::PointerMoved(count.center())] } else { vec![] }; + (shown, _, _) = frame(f as f64 / 60.0, events); + } + assert!(shown.iter().any(|(t, _)| *t == cnt), "{at}: the full count shows on hover: {shown:?}"); + crate::i18n::set_language(Locale::En); + } + } +} + fn text_bounds(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(text) => out.push(text.visual_bounding_rect()), From 96f3fd2d6120c9e0730cf6f768a0491645ea540d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:45:53 +0100 Subject: [PATCH 05/30] Tests: the next folder drop gets 20 seconds to land (#3834) It checked the file on the frame after the drop, which failed on busy Windows runners. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/tests/folder_drop.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/folder_drop.rs b/crates/ui-egui/src/tests/folder_drop.rs index 11b5ae2f7f..ba1dc5c501 100644 --- a/crates/ui-egui/src/tests/folder_drop.rs +++ b/crates/ui-egui/src/tests/folder_drop.rs @@ -339,7 +339,9 @@ fn dont_ask_again_moves_the_next_drop_at_once() { let target = folder_row(&h, &home).unwrap(); drop_beach(&mut h, dunes, target); assert!(h.app.ui.dialog.is_none(), "not asked"); - assert!(home.join("dunes.png").is_file(), "moved at once"); + // no question comes first, but the file itself can take a moment on a busy machine + let moved = home.join("dunes.png"); + assert!(h.step_until(std::time::Duration::from_secs(20), |_| moved.is_file()), "moved without a question"); let _ = std::fs::remove_dir_all(&root); } From 0429844cd9dbdf320d78262b0a4ad64ee21f3447 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 01:29:41 +0200 Subject: [PATCH 06/30] never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137) (#2170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * never-crash: deny the panic lints in every crate root; GPU asserts become fail paths (#2137) The never-crash policy was documented but not machine-checked for the two largest crates: engine and meta carried only #![forbid(unsafe_code)], so a future unwrap/expect/panic would pass cargo xtask ci. Both crate roots now also carry as does xtask (previously un-annotated); the guarded expects in meta/src/xmp.rs and xtask's parity.rs / root() now use the documented #[allow(clippy::expect_used)] + invariant form. crates/gpu: the three production asserts become fail(FailKind::Fatal, ..) + return, so a binding-count mismatch, an over-long readback, or a wrong-length curve fails the render over to the CPU instead of crashing (finish_and_read also early-returns on len == 0, which would have issued a zero-size copy_buffer_to_buffer that wgpu rejects). xtask: new roots check (in ci) verifies every workspace lib root and every binary main.rs carries both attributes; crates/sysmem is the documented exception for forbid(unsafe_code) only. A panic in placement or readback is a fail, not a crash. * audit fixes: roots covers binary and cdylib/rlib roots; render gates on failed() after finish_block (#2137) Two reviewers audited the first commit; both highs it found are fixed here: - roots scanner: the by_ref().any()/any() pair consumed the kind iterator hunting for "lib", so every bin-only root (both app mains, the sam3-worker bin, xtask itself) and the cdylib/rlib web root was silently unchecked — the check covered 29 of the 33 real roots. Kind detection now collects the kinds once and matches lib/rlib/dylib/cdylib/staticlib, with a root_paths regression test over bin, lib and cdylib/rlib targets; unreadable root files now fail with the I/O error instead of a fake policy violation. - render.rs: the caller gates on failed() right after finish_block, so the malformed-curve fail path can no longer reach the band loop's p[y0_at] index on the empty block. - finish_and_read: the len == 0 path now submits the encoder before returning zeros, so a failure staged in the same render stays detectable (the old zero-size copy failed loudly via the error scopes; a bare return would have hidden it). - docs: finish_block and finish_and_read state their failure contracts; USAGE and AGENTS.md name the new roots step in the ci enumeration. * xtask: check a library root at the source path that cargo metadata reports The roots check read src/lib.rs for every library target, so a package that sets its library path was checked on the wrong file. Libraries now use the reported source path, with the same default as binaries when none is given. * xtask: match the crate-root deny lints by whole name, ignoring a trailing comment A lint named only in a trailing comment, or a lint whose name contains another (clippy::panic inside clippy::panic_in_result_fn), satisfied the deny check. Lint names are now compared whole and a trailing comment is ignored. * xtask: read the crate-root attributes from the header, not a fixed 30 lines The roots check read only the first 30 lines of each crate root, so a root whose attributes came after a longer doc header was reported as missing them. The check now reads the inner attributes at the top of the file: it skips blank lines and comments, reads each attribute whole, and stops at the first item. A multi-line list is read in full and a commented-out attribute does not count. * xtask: reword two comments in the roots check Comments only: the lint-name match and the source-path default are described without naming a lint or a build tool. No code changes. * xtask: report a root attribute that overrides the required denies * xtask: accept a runtime manifest dir only when it has a parent * xtask: render the overridden deny attribute without literal braces The write! escaped the braces around the substituted attribute and lint, so the violation printed `#![{allow}({clippy::panic})]`; assert the rendered message in the allow-override test. * Tests: new test helpers meet the crate-root panic lints Main added test helpers after this branch; the deny at the crate root now applies to them. Co-Authored-By: Claude Opus 5.5 * roots: crates/wincolor is the second crate allowed unsafe Main added it for the Windows colour APIs after this branch; its module docs already say so. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 15 +- CLAUDE.md | 6 +- crates/engine/src/denoise.rs | 5 +- crates/engine/src/denoise/builtin/tests.rs | 1 + crates/engine/src/export/tests.rs | 2 +- crates/engine/src/face_download.rs | 5 +- crates/engine/src/lensfun_download.rs | 2 + crates/engine/src/lib.rs | 1 + crates/engine/src/lightroom_catalog/tests.rs | 2 +- crates/engine/src/model_download.rs | 5 +- crates/engine/src/tests/import.rs | 2 +- crates/gpu/src/ctx.rs | 58 ++- crates/gpu/src/params.rs | 17 +- crates/gpu/src/render.rs | 3 + crates/meta/src/lib.rs | 1 + crates/meta/src/xmp.rs | 9 +- xtask/src/ci.rs | 3 +- xtask/src/ci_quick.rs | 2 +- xtask/src/main.rs | 50 ++- xtask/src/parity.rs | 1 + xtask/src/roots.rs | 432 +++++++++++++++++++ 21 files changed, 592 insertions(+), 30 deletions(-) create mode 100644 xtask/src/roots.rs diff --git a/AGENTS.md b/AGENTS.md index 72858c816d..f179510775 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,10 +50,15 @@ of it. - **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native. - **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. -- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate - root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, - clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit - integration tests, examples and benches. New crates start with the attribute. +- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace + denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with + `[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root + (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, + clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include + `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include + the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` + (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` + web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). ## Non-negotiables - **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). @@ -62,7 +67,7 @@ of it. - **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) diff --git a/CLAUDE.md b/CLAUDE.md index 5aac6471de..6ef579697e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,9 @@ of it. (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include - the attribute before modules or other crate items; crate-level `//!` documentation may precede it. + the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` + (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` + web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). ## Non-negotiables - **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). @@ -71,7 +73,7 @@ of it. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' - tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR + tests, layers, assets, roots, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. diff --git a/crates/engine/src/denoise.rs b/crates/engine/src/denoise.rs index d12c97f6ff..1eb2544d4b 100644 --- a/crates/engine/src/denoise.rs +++ b/crates/engine/src/denoise.rs @@ -64,5 +64,8 @@ pub(crate) use settings::{Settings, forget_gpu_set_ups, installed_models, read_c pub(crate) use state::State; pub use state::{Pace, PhotoState}; -#[cfg(all(test, feature = "denoise"))] +// Two stacked cfgs (not `all(test, feature = …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(feature = "denoise")] mod gpu_tests; diff --git a/crates/engine/src/denoise/builtin/tests.rs b/crates/engine/src/denoise/builtin/tests.rs index ef85e8559f..e5416bfd00 100644 --- a/crates/engine/src/denoise/builtin/tests.rs +++ b/crates/engine/src/denoise/builtin/tests.rs @@ -2,6 +2,7 @@ use super::*; use crate::denoise::forget_gpu_set_ups; /// A folder of the test's own: the card's set-up leaves its marker in it. +#[allow(clippy::unwrap_used)] fn folder(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("lc-engine-builtin-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index 86600ddb57..d1d387b26f 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -225,7 +225,7 @@ fn sharpened_pixels_are_pinned() { let samples = src.data.iter().flat_map(|p| [p[0], p[1], p[2]].map(|v| u16::from(v) * 257)).collect(); let mut deep = DeepImage { width: src.width, height: src.height, samples: DeepSamples::U16(samples), space: OutputSpace::Srgb }; output_sharpen_deep(&mut deep, target, SharpenAmount::Standard); - let DeepSamples::U16(v) = &deep.samples else { unreachable!() }; + let DeepSamples::U16(v) = &deep.samples else { panic!("expected U16 samples") }; got.push(fnv(&v.iter().flat_map(|s| s.to_le_bytes()).collect::>())); } assert_eq!(got, SHARPENED, "{got:#x?}"); diff --git a/crates/engine/src/face_download.rs b/crates/engine/src/face_download.rs index f5d0dd5fcb..46d3a845ca 100644 --- a/crates/engine/src/face_download.rs +++ b/crates/engine/src/face_download.rs @@ -246,7 +246,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) { } } -#[cfg(all(test, not(target_arch = "wasm32")))] +// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; use lightcraft_faces::hash::sha256_hex; diff --git a/crates/engine/src/lensfun_download.rs b/crates/engine/src/lensfun_download.rs index c24b07f7a9..9eb382526f 100644 --- a/crates/engine/src/lensfun_download.rs +++ b/crates/engine/src/lensfun_download.rs @@ -608,6 +608,7 @@ mod tests { let _ = std::fs::remove_file(beside(&dir, LOCK)); } + #[allow(clippy::unwrap_used)] fn scratch(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("lc-lensfun-{name}-{}", std::process::id())); for leftover in [d.clone(), beside(&d, STAGING), beside(&d, PREVIOUS)] { @@ -618,6 +619,7 @@ mod tests { } /// A local server answering `GET /db/` with that file's body (404 otherwise). + #[allow(clippy::unwrap_used)] fn serve(files: Vec<(&'static str, Vec)>) -> String { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}/db", l.local_addr().unwrap()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b0e3d2b9e5..53077f95c6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,7 @@ //! of decoded source proxies. Rendering is done by [`RenderJob`]s that are `Send` so frontends can //! run them off the UI thread. #![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // Model/cache types remain available without linking the optional inference crate. #[cfg(not(feature = "denoise"))] diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index 06739138c1..e2952fd000 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -1122,7 +1122,7 @@ fn record(values: &[SqlValue]) -> Vec { body.extend(s.as_bytes()); 13 + 2 * s.len() as u64 } - _ => unreachable!(), + _ => panic!("unexpected SqlValue in a test record: {value:?}"), }; header.extend(varint(serial)); } diff --git a/crates/engine/src/model_download.rs b/crates/engine/src/model_download.rs index 96f5eb1c74..9dcf025a3d 100644 --- a/crates/engine/src/model_download.rs +++ b/crates/engine/src/model_download.rs @@ -226,7 +226,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) { } } -#[cfg(all(test, not(target_arch = "wasm32")))] +// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)` +// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] mod tests { use super::*; use lightcraft_denoise::hash::sha256_hex; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 49176077fb..5df2ac680d 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -853,7 +853,7 @@ fn import_rename_sequence_keeps_flushed_copy_and_move_results() { assert!(paths[3].is_file(), "the failed source remains in place"); assert_eq!(r["moved"].as_array().map(Vec::len), Some(3), "{r}"); } - _ => unreachable!(), + other => panic!("no such mode: {other}"), } let _ = std::fs::remove_dir_all(base); } diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 2735116e39..290b95ac99 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -556,8 +556,12 @@ impl Gpu { } /// Submit command buffers, then make the buffers this thread dropped before reusable. + /// Nothing is submitted once this render has failed: the render is discarded and recomputed + /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure. pub fn submit(&self, cmds: impl IntoIterator) { - self.queue.submit(cmds); + if !failed() { + self.queue.submit(cmds); + } let retired = take_retired(); self.pool(retired); } @@ -610,6 +614,12 @@ impl Gpu { pub fn upload(&self, data: &[T]) -> Buf { let bytes: &[u8] = bytemuck::cast_slice(data); let len = bytes.len() / 4; + // A failed render runs no further GPU work (`Gpu::submit` skips the submission and the + // render is redone on the CPU): staging the bytes would still queue a copy for the next + // submission, so the caller gets the placeholder with the requested length instead. + if failed() { + return Buf { buf: Some(Tracked::new(self.placeholder())), len }; + } if bytes.is_empty() { return self.buffer(1); } @@ -715,7 +725,12 @@ impl Gpu { fail(FailKind::Fatal, format!("unknown kernel {name}")); return; }; - assert_eq!(bufs.len(), k.nbuf, "{name}: binding count"); + if bufs.len() != k.nbuf { + // a caller/kernel mismatch would bind the wrong buffers: fail this render over to the + // CPU instead of crashing + fail(FailKind::Fatal, format!("{name}: binding count {} != {}", bufs.len(), k.nbuf)); + return; + } let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE); let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }]; for (i, b) in bufs.iter().enumerate() { @@ -731,15 +746,27 @@ impl Gpu { /// Submit `enc`, then read back the first `len` 32-bit values of `src`. /// - /// A failed readback (device lost, map error, timeout) fails the render ([`FailKind::Fatal`]) - /// and returns zeros, which the caller discards; after an earlier failure in the same render - /// nothing more is submitted. + /// A failed readback (device lost, map error, timeout) or a `len` past the buffer's end fails + /// the render ([`FailKind::Fatal`]) and returns zeros, which the caller discards; after an + /// earlier failure in the same render nothing more is submitted. `T` is always a 32-bit type + /// at the call sites (the copy and the readback tail are defined in 32-bit words). pub fn finish_and_read(&self, mut enc: wgpu::CommandEncoder, src: &Buf, len: usize) -> Vec { - assert!(len <= src.len, "readback of {len} values from a buffer of {}", src.len); let zeros = || vec![::zeroed(); len]; if failed() { return zeros(); } + // a zero-length readback would issue a `copy_buffer_to_buffer` of size 0, which wgpu + // rejects as an invalid copy: submit the (possibly staged) work untouched and return + // zeros instead + if len == 0 { + self.submit([enc.finish()]); + return zeros(); + } + if len > src.len { + // a caller bug would read past the buffer: fail this render over to the CPU + fail(FailKind::Fatal, format!("readback of {len} values from a buffer of {}", src.len)); + return zeros(); + } let size = (len * 4) as u64; let staging = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), @@ -1193,6 +1220,25 @@ mod tests { let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len()); assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice()); } + /// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the + /// submission, so nothing further runs on the GPU): the caller gets the placeholder with the + /// requested length instead of a staging buffer holding a copy of the data for a submission + /// that will never happen. + #[test] + fn an_upload_after_a_failure_returns_the_placeholder() { + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + super::fail(super::FailKind::Fatal, "simulated failure before an upload".into()); + assert!(super::failed()); + let b = g.upload(&[7u32; 1024]); + assert_eq!(b.buf.as_ref().map(|t| t.0.size()), Some(16), "the placeholder, not a staged 4 KiB buffer"); + assert_eq!(b.len, 1024, "the requested length is preserved"); + // leave this thread's failure for nobody: later tests on the thread start unfailed + assert_eq!(super::take_failure().map(|f| f.kind), Some(super::FailKind::Fatal)); + } + /// Issue #1858: once a Vulkan or DX12 device is lost, wgpu 30 panics in `Device::poll` instead of /// returning an error. A render's readback panicked; while it unwound, a buffer's way back to /// the pool polls again from a destructor, and that second panic aborted the app. diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 8c8624a23c..97244b6a04 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -5,6 +5,8 @@ use lightcraft_develop::VignetteStyle; use lightcraft_pipeline::colorops::POINT_WORDS; use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut}; +use crate::ctx::{FailKind, fail}; + /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; @@ -168,6 +170,9 @@ pub struct Present { /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | /// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). +/// +/// A curve whose length is not [`CURVE_N`] fails the render ([`FailKind::Fatal`]) and returns an +/// empty parameter block with a truncated aux table, which the caller discards (CPU fallback). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -176,7 +181,17 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let curve_off = aux.len(); if let Some(c) = &fp.curves { for l in c { - assert_eq!(l.v.len(), CURVE_N as usize); + if l.v.len() != CURVE_N as usize { + // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and + // the mask terms that follow) and make the kernel read the wrong data. `fail()` + // records the failure on this thread so the render falls back to the CPU; the + // partial `(p, aux)` returned here is never bound to a pipeline. + fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); + // `p` is only assembled below the curve loop, so an empty block is as good as any: + // the caller (render.rs) gates on `failed()` right after this returns and bails to + // the CPU fallback before indexing `p` or uploading `aux`. + return (Vec::new(), aux); + } aux.extend_from_slice(&l.v); } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 701cc3c5de..5a60e547ea 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -764,6 +764,9 @@ pub fn render( (None, None) => None, }; let (p, aux) = finish_block(&fp, &terms, &present); + if crate::ctx::failed() { + return None; // a malformed parameter block failed the render: the CPU fallback redoes it + } let aux = gpu.upload(&aux); // cleared, so that work which never ran cannot pass for an image (see the check below) let out = cx.zeroed(n); diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index ffa0d2f83b..91186e3d8c 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -12,6 +12,7 @@ //! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks). //! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed). #![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod container; pub mod cr3; diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index bb23bfd1ff..958abed653 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -305,7 +305,7 @@ fn parse_tree(s: &str) -> Result { } } Event::End(_) if stack.len() > 1 => { - let n = stack.pop().expect("len > 1"); + let Some(n) = stack.pop() else { return Err(XmpError::Xml("end tag without an open element".into())) }; scopes.pop(); if let Some(parent) = stack.last_mut() { parent.children.push(n); @@ -340,10 +340,11 @@ fn parse_tree(s: &str) -> Result { } // close unterminated elements leniently while stack.len() > 1 { - let n = stack.pop().expect("len > 1"); - stack.last_mut().expect("root").children.push(n); + let Some(n) = stack.pop() else { return Err(XmpError::Xml("unterminated element without a node".into())) }; + let Some(parent) = stack.last_mut() else { return Err(XmpError::Xml("unterminated element without a parent".into())) }; + parent.children.push(n); } - Ok(stack.pop().expect("root")) + stack.pop().ok_or_else(|| XmpError::Xml("xmp packet without a root element".into())) } fn is_rdf_meta_attr(k: &str) -> bool { diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 6b55595706..556ea01b12 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -1,7 +1,7 @@ use super::layers::cmd_layers; use super::raw_samples::RAW_SAMPLES; use super::wasm::{cmd_wasm, cmd_wasm_for}; -use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, run}; +use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run}; /// CI build jobs: one per 1.5 GB of RAM available when CI starts, at most one per CPU, 4 when it /// is unknown. With line-table debuginfo, 4 jobs measured about 3 GB of RAM in use and 2 jobs @@ -339,6 +339,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { } steps.push(("layers", Box::new(cmd_layers))); steps.push(("assets", Box::new(|| assets::run(&root)))); + steps.push(("roots", Box::new(roots::run))); if wants("wasm") { match plan.as_ref().filter(|p| !p.workspace_wide) { Some(p) => steps.push(("wasm", Box::new(|| cmd_wasm_for(Some(&p.packages))))), diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index be3e5777df..2143d09bbb 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -4,7 +4,7 @@ //! parity check, ~23 minutes cold. `--quick` looks at what changed since the merge base with //! `origin/main` (or `--base REF`), committed or not, and runs: //! -//! - fmt, layers, assets: always (seconds); +//! - fmt, layers, assets, roots: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); //! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 153498a009..33b236b56d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -2,6 +2,8 @@ //! //! Pure Rust (std + serde_json; flate2/brotli for the web bundle). External tools (`cargo`, `curl`, `tar`) are //! invoked through `std::process::Command`. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod assets; mod bench; @@ -11,6 +13,7 @@ mod ci_report; mod ico; mod layers; mod parity; +mod roots; mod stats; mod version; mod web; @@ -39,6 +42,8 @@ commands: ico ... pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh) layers enforce the crate dependency layering (plan/architecture.md §3) + roots every production crate root carries #![forbid(unsafe_code)] and the six-lint + deny list (AGENTS.md; crates/sysmem is exempt from the forbid only) parity [--write] check docs/parity-checklist.md (every cmd:/ctl: id and path it cites exists) and print the Lightroom parity summary; --write refreshes the summary table in the document @@ -47,7 +52,7 @@ commands: build the browser app (apps/lightcraft-web) into /web-site/; --serve serves it on http://127.0.0.1: (default 8080) ci [--hardware] [--summary-md] [--quick [--base REF]] - fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, wasm + fmt --check, clippy -D warnings, heif, test, GPU probe, parity refs, layers, assets, roots, wasm (stops at first failure). Tests run under cargo test (cargo nextest with LIGHTCRAFT_NEXTEST=1), without examples, then doctests with cargo test --doc; after them it prints the translation gaps report (never a failure). Writes @@ -75,6 +80,7 @@ fn main() -> ExitCode { Some("ico") => ico::run(&rest), Some("version") => version::run(&root(), &rest), Some("layers") => cmd_layers(), + Some("roots") => roots::run(), Some("assets") => assets::run(&root()), Some("bench") => bench::run(&root(), &rest), Some("parity") => parity::run(&root(), rest.contains(&"--write")), @@ -117,9 +123,17 @@ fn cmd_raw_frame(files: &[&str]) -> Result<(), String> { pub fn root() -> PathBuf { // `cargo run` sets it at run time; prefer that over the compile-time value, which goes stale // when the checkout moves and the cached xtask binary isn't rebuilt - let dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from).filter(|d| d.join("Cargo.toml").is_file()); - let dir = dir.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR"))); - dir.parent().expect("xtask has a parent dir").to_path_buf() + workspace_root(std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from).filter(|d| d.join("Cargo.toml").is_file()), env!("CARGO_MANIFEST_DIR")) +} + +/// The workspace root for an xtask-crate directory. A runtime manifest dir (already checked to +/// carry Cargo.toml) wins only when it has a parent: a filesystem root or an empty path names no +/// crate below a workspace, and there is no directory above it. The compile-time fallback +/// (`/xtask`) always has a parent; without one the crate dir itself is the best +/// remaining answer. +fn workspace_root(runtime_manifest_dir: Option, compile_time_manifest_dir: &str) -> PathBuf { + let dir = runtime_manifest_dir.filter(|d| d.parent().is_some()).unwrap_or_else(|| PathBuf::from(compile_time_manifest_dir)); + dir.parent().map_or_else(|| dir.clone(), Path::to_path_buf) } pub fn cargo() -> Command { @@ -164,3 +178,31 @@ pub fn metadata() -> Result { } serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: bad JSON: {e}")) } + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + /// A runtime `CARGO_MANIFEST_DIR` without a parent (`/`, or an empty path) cannot name the + /// xtask crate: the parent lookup used to crash on it, and the workspace root falls back to + /// the compile-time value instead. + #[test] + fn a_runtime_manifest_dir_without_a_parent_is_not_the_workspace_root() { + let root = super::workspace_root(Some(PathBuf::from("/")), "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + let root = super::workspace_root(Some(PathBuf::from("")), "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + } + + #[test] + fn a_runtime_manifest_dir_names_its_own_workspace() { + let root = super::workspace_root(Some(PathBuf::from("/checkout/xtask")), "/elsewhere/xtask"); + assert_eq!(root, Path::new("/checkout")); + } + + #[test] + fn without_a_runtime_value_the_compile_time_manifest_dir_decides() { + let root = super::workspace_root(None, "/checkout/xtask"); + assert_eq!(root, Path::new("/checkout")); + } +} diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs index 7adcfc6c02..4c85c0acaa 100644 --- a/xtask/src/parity.rs +++ b/xtask/src/parity.rs @@ -237,6 +237,7 @@ pub fn summarize(doc: &Doc) -> (Vec<(String, Counts)>, Counts) { if sections.last().is_none_or(|(s, _)| *s != r.section) { sections.push((r.section.clone(), Counts::default())); } + #[allow(clippy::expect_used)] // either non-empty above or a section was just pushed sections.last_mut().expect("pushed").1.add(r); total.add(r); } diff --git a/xtask/src/roots.rs b/xtask/src/roots.rs new file mode 100644 index 0000000000..440229bd16 --- /dev/null +++ b/xtask/src/roots.rs @@ -0,0 +1,432 @@ +//! Crate-root lint attributes: every production crate root carries both `#![forbid(unsafe_code)]` +//! and the deny list (`clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, +//! `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`). +//! +//! Machine-enforced so a future crate can't silently drop the never-crash policy (AGENTS.md). +//! `check` works on already-read file contents so it is unit-testable without the real tree. +//! +//! Exception: `crates/wincolor` calls Windows' colour APIs, so it is exempt too (see its module docs). +//! Exception (documented in AGENTS.md): `crates/sysmem` holds LightCraft's other allowed `unsafe` +//! (one FFI call), so it is exempt from `forbid(unsafe_code)` — it still needs the deny list, and +//! carries it. + +use std::path::PathBuf; + +const DENY_LINTS: &[&str] = + &["clippy::unwrap_used", "clippy::expect_used", "clippy::panic", "clippy::unimplemented", "clippy::todo", "clippy::unreachable"]; + +/// Crate roots exempt from `forbid(unsafe_code)` (they still need the deny list). +const UNSAFE_EXCEPTION: &[&str] = &["lightcraft-sysmem", "lightcraft-wincolor"]; + +#[derive(Debug, Clone)] +pub struct CrateRoot { + pub name: String, + /// The root source file (`src/lib.rs` for libs, `src/main.rs` for binaries). + pub root: PathBuf, + /// Its contents, already read (kept separate so `check` needs no filesystem). + pub src: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Violation { + MissingForbid { + name: String, + path: PathBuf, + }, + MissingDeny { + name: String, + path: PathBuf, + }, + /// A crate-root `allow`/`expect`/`warn` names a required lint: rustc applies the later + /// attribute over the deny list, so the lint is not denied after all. + OverriddenDeny { + name: String, + path: PathBuf, + attribute: String, + lint: String, + }, +} + +impl std::fmt::Display for Violation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Violation::MissingForbid { name, path } => { + write!(f, "{name}: missing `#![forbid(unsafe_code)]` in {}", path.display()) + } + Violation::MissingDeny { name, path } => { + write!(f, "{name}: missing `#![deny(...)]` with all six clippy lints in {}", path.display()) + } + Violation::OverriddenDeny { name, path, attribute, lint } => { + write!(f, "{name}: the crate-root `#![{attribute}({lint})]` overrides the required deny list in {}", path.display()) + } + } + } +} + +/// Check every crate root carries both attributes; violations sorted for stable output. +pub fn check(roots: &[CrateRoot]) -> Vec { + let mut out = Vec::new(); + for r in roots { + let is_unsafe_exception = UNSAFE_EXCEPTION.contains(&r.name.as_str()); + // the inner attributes before the first item, however long the doc header above them is + let attrs = inner_attrs(&r.src); + let has_forbid = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); + let has_deny = + attrs.iter().any(|a| lint_list(a).is_some_and(|(verb, names)| verb == "deny" && DENY_LINTS.iter().all(|lint| names.contains(lint)))); + // a later crate-root `allow`/`expect`/`warn` naming a required lint applies over the deny + // list (rustc takes the later attribute), so the policy silently stops holding + let mut overridden: Option<(&str, &str)> = None; + for a in &attrs { + let Some((verb, names)) = lint_list(a) else { continue }; + if !matches!(verb, "allow" | "expect" | "warn") { + continue; + } + if let Some(lint) = names.iter().find(|n| DENY_LINTS.contains(n)) { + overridden = Some((verb, lint)); + break; + } + } + if !has_forbid && !is_unsafe_exception { + out.push(Violation::MissingForbid { name: r.name.clone(), path: r.root.clone() }); + } + if !has_deny { + out.push(Violation::MissingDeny { name: r.name.clone(), path: r.root.clone() }); + } + if let Some((attribute, lint)) = overridden { + out.push(Violation::OverriddenDeny { + name: r.name.clone(), + path: r.root.clone(), + attribute: attribute.to_string(), + lint: lint.to_string(), + }); + } + } + out.sort_by_key(|v| v.to_string()); + out.dedup(); + out +} + +/// The verb and the lint names of a root `#![verb(...)]` attribute, or `None` for anything else. +/// Names are compared whole, so a longer name that starts with a listed name does not count. +fn lint_list(attr: &str) -> Option<(&str, Vec<&str>)> { + let body = attr.strip_prefix("#![")?.strip_suffix(")]")?; + let (verb, names) = body.split_once('(')?; + Some((verb, names.split(',').map(str::trim).filter(|n| !n.is_empty()).collect())) +} + +/// The inner attributes (`#![...]`) at the top of a crate root, each with its whitespace removed. +/// Blank lines and comments before them are skipped, and the scan stops at the first item, so the +/// length of the doc header does not matter and an attribute inside a nested module is never read. +fn inner_attrs(src: &str) -> Vec { + let b = src.as_bytes(); + let mut out = Vec::new(); + let mut i = skip_trivia(b, 0); + while b.get(i..).is_some_and(|rest| rest.starts_with(b"#![")) { + let start = i; + let mut depth = 0usize; + let mut in_str = false; + while let Some(&c) = b.get(i) { + i += 1; + if in_str { + match c { + b'\\' => i += 1, + b'"' => in_str = false, + _ => {} + } + } else { + match c { + b'"' => in_str = true, + b'[' => depth += 1, + b']' => { + depth = depth.saturating_sub(1); + if depth == 0 { + break; + } + } + _ => {} + } + } + } + let Some(text) = src.get(start..i) else { break }; + out.push(text.split_whitespace().collect()); + i = skip_trivia(b, i); + } + out +} + +/// The first index at or after `i` that is neither whitespace nor part of a comment. +fn skip_trivia(b: &[u8], mut i: usize) -> usize { + loop { + while b.get(i).is_some_and(u8::is_ascii_whitespace) { + i += 1; + } + let rest = b.get(i..).unwrap_or_default(); + if rest.starts_with(b"//") { + while b.get(i).is_some_and(|&c| c != b'\n') { + i += 1; + } + } else if rest.starts_with(b"/*") { + i = skip_block_comment(b, i); + } else { + return i; + } + } +} + +/// The index just past the block comment that starts at `i` (block comments nest, as in Rust). +fn skip_block_comment(b: &[u8], mut i: usize) -> usize { + let mut depth = 0usize; + loop { + match b.get(i..) { + Some(rest) if rest.starts_with(b"/*") => { + depth += 1; + i += 2; + } + Some(rest) if rest.starts_with(b"*/") => { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + return i; + } + } + Some(_) => i += 1, + None => return i, + } + } +} + +/// Collect the (package name, root source path) pairs for every workspace lib/bin target. +/// `src_path` from the package metadata is absolute and is used as it is; without it, libs default to the +/// manifest's `src/lib.rs` and binaries to `src/main.rs`. +/// Library kinds include `rlib`/`cdylib` so roots like the web build's `crate-type = +/// ["cdylib", "rlib"]` are covered, and `proc-macro`, which cargo reports as a kind of its own. +pub fn root_paths(meta: &serde_json::Value) -> Result, String> { + let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?; + let mut out: Vec<(String, PathBuf)> = Vec::new(); + for p in pkgs { + let name = p["name"].as_str().ok_or("package without name")?.to_owned(); + let manifest_dir = std::path::Path::new(p["manifest_path"].as_str().ok_or("package without manifest_path")?) + .parent() + .ok_or("manifest without parent")? + .to_path_buf(); + for t in p["targets"].as_array().into_iter().flatten() { + let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(|k| k.as_str()).collect(); + let is_lib = kinds.iter().any(|&k| matches!(k, "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro")); + let is_bin = kinds.contains(&"bin"); + if is_lib || is_bin { + let fallback = if is_lib { "src/lib.rs" } else { "src/main.rs" }; + let root = match t["src_path"].as_str() { + Some(s) => PathBuf::from(s), + None => manifest_dir.join(fallback), + }; + out.push((name.clone(), root)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out) +} + +/// Read each root's contents (separate from [`root_paths`] so the path-collection logic is +/// unit-testable without the real tree). +pub fn from_metadata(meta: &serde_json::Value) -> Result, String> { + let mut out = Vec::new(); + for (name, root) in root_paths(meta)? { + let src = std::fs::read_to_string(&root).map_err(|e| format!("roots: {}: {e}", root.display()))?; + out.push(CrateRoot { name, root, src }); + } + Ok(out) +} + +/// Run the roots check against the real workspace tree. +pub fn run() -> Result<(), String> { + let roots = from_metadata(&super::metadata()?)?; + let violations = check(&roots); + if violations.is_empty() { + println!("OK: {} crate roots carry both `#![forbid(unsafe_code)]` and the deny list.", roots.len()); + Ok(()) + } else { + Err(violations.iter().map(|v| format!(" {v}")).collect::>().join("\n")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn root(name: &str, src: &str) -> CrateRoot { + CrateRoot { name: name.into(), root: PathBuf::from(format!("src/{name}.rs")), src: src.into() } + } + + const DENY: &str = "clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable"; + + #[test] + fn both_attributes_pass() { + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn missing_forbid_reported() { + let src = format!("#![deny({DENY})]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingForbid { .. }]), "{v:?}"); + } + + #[test] + fn missing_deny_reported() { + let v = check(&[root("lightcraft-foo", "#![forbid(unsafe_code)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn sysmem_exempt_from_forbid_but_not_deny() { + let good = format!("#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-sysmem", &good)]).is_empty()); + let v = check(&[root("lightcraft-sysmem", "#![forbid(unsafe_code)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn root_paths_collects_bin_cdylib_and_lib_targets() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-bin-only", "manifest_path": "/ws/bin-only/Cargo.toml", + "targets": [ { "kind": ["bin"], "src_path": "/ws/bin-only/src/main.rs" } ] }, + { "name": "lightcraft-meta", "manifest_path": "/ws/meta/Cargo.toml", + "targets": [ { "kind": ["lib"], "src_path": "/ws/meta/src/lib.rs" } ] }, + { "name": "lightcraft-web", "manifest_path": "/ws/web/Cargo.toml", + "targets": [ { "kind": ["cdylib", "rlib"], "src_path": "/ws/web/src/lib.rs" } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + let names: Vec<_> = paths.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, vec!["lightcraft-bin-only", "lightcraft-meta", "lightcraft-web"]); + assert_eq!(paths[0].1, std::path::Path::new("/ws/bin-only/src/main.rs")); + assert_eq!(paths[1].1, std::path::Path::new("/ws/meta/src/lib.rs")); + assert_eq!(paths[2].1, std::path::Path::new("/ws/web/src/lib.rs")); + } + + #[test] + fn root_paths_collects_proc_macro_targets() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-macros", "manifest_path": "/ws/macros/Cargo.toml", + "targets": [ { "kind": ["proc-macro"], "src_path": "/ws/macros/src/derive.rs" } ] }, + { "name": "lightcraft-plain-macros", "manifest_path": "/ws/plain-macros/Cargo.toml", + "targets": [ { "kind": ["proc-macro"] } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!( + paths, + vec![ + ("lightcraft-macros".to_owned(), PathBuf::from("/ws/macros/src/derive.rs")), + ("lightcraft-plain-macros".to_owned(), PathBuf::from("/ws/plain-macros/src/lib.rs")), + ] + ); + } + + #[test] + fn deny_must_contain_all_six_lints() { + let v = check(&[root("lightcraft-foo", "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used)]\nfn f() {}\n")]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn a_root_allow_overriding_a_required_lint_is_reported() { + // rustc applies the later attribute, so the deny list above it no longer denies + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\n#![allow(clippy::panic)]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::OverriddenDeny { lint, .. }] if lint == "clippy::panic"), "{v:?}"); + assert_eq!( + v.first().map(|v| v.to_string()).as_deref(), + Some("lightcraft-foo: the crate-root `#![allow(clippy::panic)]` overrides the required deny list in src/lightcraft-foo.rs"), + "the rendered message shows the attribute, not literal braces", + ); + } + + #[test] + fn a_root_expect_overriding_a_required_lint_is_reported() { + let src = format!("#![forbid(unsafe_code)]\n#![deny({DENY})]\n#![expect(clippy::unwrap_used)]\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::OverriddenDeny { lint, .. }] if lint == "clippy::unwrap_used"), "{v:?}"); + } + + #[test] + fn an_item_level_allow_inside_a_function_is_not_an_override() { + // the documented guarded-expect form: the crate-level deny list stays intact + let src = format!( + "#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{\n #[allow(clippy::expect_used)] // invariant\n let x: u8 = None.expect(\"checked above\");\n}}\n" + ); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn library_root_follows_the_declared_lib_path() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-custom", "manifest_path": "/ws/custom/Cargo.toml", + "targets": [ { "kind": ["lib"], "src_path": "/ws/custom/src/core.rs" } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!(paths, vec![("lightcraft-custom".to_owned(), PathBuf::from("/ws/custom/src/core.rs"))]); + } + + #[test] + fn a_lint_named_only_in_a_trailing_comment_does_not_count() { + let src = "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo)] // clippy::unreachable\nfn f() {}\n"; + let v = check(&[root("lightcraft-foo", src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn lint_names_must_match_whole() { + let src = "#![forbid(unsafe_code)]\n#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn, clippy::unimplemented, clippy::todo, clippy::unreachable)]\nfn f() {}\n"; + let v = check(&[root("lightcraft-foo", src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn attributes_after_a_long_header_are_found() { + let header: String = (0..40).map(|n| format!("//! header line {n}\n")).collect(); + let src = format!("{header}\n#![forbid(unsafe_code)]\n#![deny({DENY})]\nfn f() {{}}\n"); + assert!(check(&[root("lightcraft-foo", &src)]).is_empty()); + } + + #[test] + fn multi_line_deny_attribute_is_read() { + let src = "#![forbid(unsafe_code)]\n#![deny(\n clippy::unwrap_used,\n clippy::expect_used,\n clippy::panic,\n clippy::unimplemented,\n clippy::todo,\n clippy::unreachable,\n)]\nfn f() {}\n"; + assert!(check(&[root("lightcraft-foo", src)]).is_empty()); + } + + #[test] + fn attributes_of_a_nested_module_do_not_count() { + let src = format!("#![forbid(unsafe_code)]\nfn f() {{}}\nmod inner {{\n #![deny({DENY})]\n}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn a_commented_out_attribute_does_not_count() { + let src = format!("#![forbid(unsafe_code)]\n/*\n#![deny({DENY})]\n*/\nfn f() {{}}\n"); + let v = check(&[root("lightcraft-foo", &src)]); + assert!(matches!(&v[..], [Violation::MissingDeny { .. }]), "{v:?}"); + } + + #[test] + fn targets_without_src_path_fall_back_to_the_default_files() { + let meta = serde_json::json!({ + "packages": [ + { "name": "lightcraft-plain", "manifest_path": "/ws/plain/Cargo.toml", + "targets": [ { "kind": ["lib"] } ] }, + { "name": "lightcraft-tool", "manifest_path": "/ws/tool/Cargo.toml", + "targets": [ { "kind": ["bin"] } ] }, + ] + }); + let paths = root_paths(&meta).expect("metadata should parse"); + assert_eq!(paths[0].1, PathBuf::from("/ws/plain/src/lib.rs")); + assert_eq!(paths[1].1, PathBuf::from("/ws/tool/src/main.rs")); + } +} From 826875470a94e5e1b1bf43c9e604497f01413c08 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:35:26 +0100 Subject: [PATCH 07/30] Paint clipped pixels red/blue when clipping warnings (J) are on (#3638) Fixes #3620 Co-authored-by: Claude Opus 5.5 --- crates/pipeline/src/visualize.rs | 51 +++++++++++++++++++++++-- crates/ui-egui/src/panels/detail.rs | 28 ++++---------- crates/ui-egui/src/tests/alt_preview.rs | 31 +++++++++++++++ 3 files changed, 86 insertions(+), 24 deletions(-) diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index 63bd7dc858..86d6ade16c 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -57,8 +57,16 @@ pub enum Overlay { SharpenDetail, /// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking). SharpenMask, + /// Clipping warnings (J): the photo with every pixel that has a channel at 255 painted + /// [`CLIP_HIGH`] and every other pixel with a channel at 0 painted [`CLIP_LOW`]. + ClipWarnings, } +/// [`Overlay::ClipWarnings`] colour of clipped highlights. +pub const CLIP_HIGH: [u8; 3] = [255, 0, 0]; +/// [`Overlay::ClipWarnings`] colour of clipped shadows. +pub const CLIP_LOW: [u8; 3] = [0, 0, 255]; + /// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white. pub const HDR_BANDS: [[u8; 3]; 4] = [[255, 214, 92], [255, 150, 40], [235, 64, 52], [214, 60, 210]]; @@ -148,6 +156,7 @@ impl Overlay { Overlay::Grayscale => (8, 0.0), Overlay::SharpenDetail => (9, 0.0), Overlay::SharpenMask => (10, 0.0), + Overlay::ClipWarnings => (11, 0.0), } } @@ -171,6 +180,7 @@ impl Overlay { 8 => Overlay::Grayscale, 9 => Overlay::SharpenDetail, 10 => Overlay::SharpenMask, + 11 => Overlay::ClipWarnings, _ => Overlay::None, } } @@ -189,6 +199,7 @@ impl Overlay { Overlay::Grayscale => 0x5002, Overlay::SharpenDetail => 0x5003, Overlay::SharpenMask => 0x5004, + Overlay::ClipWarnings => 0x5005, } } @@ -208,7 +219,7 @@ impl Overlay { /// The clipping previews, which test the sRGB values the histogram counts (a render for a /// display profile draws them in sRGB, then converts). pub fn is_clipping(self) -> bool { - matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights) + matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings) } /// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]). @@ -219,7 +230,10 @@ impl Overlay { /// Whether the overlay works pixel by pixel on the finished image, so a window render shows /// the same as the whole frame would. pub fn per_pixel(self) -> bool { - matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale) + matches!( + self, + Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings | Overlay::Grayscale + ) } /// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components). @@ -310,6 +324,7 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane> } Overlay::ClipShadows => clipping(img, false), Overlay::ClipHighlights => clipping(img, true), + Overlay::ClipWarnings => clip_warnings(img), Overlay::Grayscale => grayscale(img), Overlay::SharpenDetail | Overlay::SharpenMask => { if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) { @@ -362,6 +377,25 @@ pub fn clipping(img: &mut Rgba8, high: bool) { }); } +/// [`Overlay::ClipWarnings`]: pixels with a channel at 255 in [`CLIP_HIGH`], the rest with a +/// channel at 0 in [`CLIP_LOW`], everything else unchanged. +pub fn clip_warnings(img: &mut Rgba8) { + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for px in row.iter_mut() { + let c = &px[..3]; + let paint = if c.contains(&255) { + CLIP_HIGH + } else if c.contains(&0) { + CLIP_LOW + } else { + continue; + }; + *px = [paint[0], paint[1], paint[2], 255]; + } + }); +} + fn grayscale(img: &mut Rgba8) { let w = img.width; for_rows(&mut img.data, w, |_, row| { @@ -713,7 +747,8 @@ mod tests { assert!(Overlay::for_control(c).is_some(), "{c}"); } assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping()); - let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask]; + let all = + [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask, Overlay::ClipWarnings]; for o in all { let (k, v) = o.to_parts(); assert_eq!(Overlay::from_parts(k, v), o); @@ -721,6 +756,16 @@ mod tests { assert_ne!(o.key(), Overlay::HdrRange.key()); } assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel()); + assert!(Overlay::ClipWarnings.is_clipping() && Overlay::ClipWarnings.per_pixel()); + } + + #[test] + fn clip_warnings_paint_clipped_pixels_only() { + let data = vec![[255, 255, 255, 255], [0, 0, 0, 255], [128, 128, 128, 255], [255, 40, 0, 255], [10, 0, 30, 255]]; + let mut img = Rgba8 { width: 5, height: 1, data }; + super::clip_warnings(&mut img); + let rgb: Vec<[u8; 3]> = img.data.iter().map(|p| [p[0], p[1], p[2]]).collect(); + assert_eq!(rgb, [super::CLIP_HIGH, super::CLIP_LOW, [128, 128, 128], super::CLIP_HIGH, super::CLIP_LOW]); } #[test] diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 534949ab00..b827d14306 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -344,7 +344,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // the line of a wipe over both draw_wipe_line(app.ui.before_after, &p, img_rect, line); let map = CanvasMap::new(&frame, img_rect); - let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool, clipping: !show_before }; + let over = OverPhoto { photo: &photo, d: &d, map: &map, canvas, img_rect, fullscreen, crop_tool }; photo_overlays(app, ui, &p, &over); // Cursor selection must also run on gesture frames, when tool input is suppressed. if !matches!(right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye) { @@ -1064,17 +1064,12 @@ struct OverPhoto<'a> { img_rect: Rect, fullscreen: bool, crop_tool: bool, - /// the clipping overlay may show (not in the Before view) - clipping: bool, } -/// The overlays over the photo: clipping, layout image, info, filter pill, faces, focus point and +/// The overlays over the photo: layout image, info, filter pill, faces, focus point and /// the transform grid. fn photo_overlays(app: &mut LightcraftApp, ui: &mut egui::Ui, p: &egui::Painter, o: &OverPhoto) { let (canvas, img_rect) = (o.canvas, o.img_rect); - if app.ui.show_clipping && o.clipping && !o.fullscreen { - clipping_overlay(app, p, img_rect); - } // View ▸ Loupe Overlay ▸ Layout Image, over the photo (the After view in a before/after) super::layout_overlay::draw(app, p, img_rect); register(ui, "canvas:image", img_rect); @@ -1154,7 +1149,7 @@ fn targeted_drag(app: &mut LightcraftApp, resp: &egui::Response, map: &CanvasMap } /// The diagnostic overlay the loupe shows (an Alt-drag preview, the selected mask, Point Color's -/// visualized range, Visualize Spots). +/// visualized range, Visualize Spots, the clipping warnings). pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay { use lightcraft_pipeline::{MaskView, Overlay}; if app.ui.fullscreen { @@ -1198,20 +1193,11 @@ pub(crate) fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcra if edit && app.ui.hdr_visualize && d.hdr.enabled { return Overlay::HdrRange; } - Overlay::None -} - -fn clipping_overlay(app: &LightcraftApp, p: &egui::Painter, r: Rect) { - // Highlight clipped regions using the histogram's extremes isn't spatial; show a subtle frame hint. - if let Some(h) = app.renderer.textures.get(&Slot::Main).and_then(|t| t.histogram.as_ref()) { - let (lo, hi) = h.clipping(); - if hi > 0.003 { - p.rect_stroke(r, 0.0, Stroke::new(2.0, Color32::from_rgb(255, 60, 60)), StrokeKind::Outside); - } - if lo > 0.003 { - p.rect_stroke(r.expand(3.0), 0.0, Stroke::new(2.0, Color32::from_rgb(60, 120, 255)), StrokeKind::Outside); - } + // Clipping warnings (J): clipped highlights red, clipped shadows blue, on the photo itself + if app.ui.show_clipping { + return Overlay::ClipWarnings; } + Overlay::None } fn general_cursor(app: &LightcraftApp, ui: &egui::Ui, resp: &egui::Response, img: Rect, canvas: Rect) { diff --git a/crates/ui-egui/src/tests/alt_preview.rs b/crates/ui-egui/src/tests/alt_preview.rs index 7a212869fc..5997b41b43 100644 --- a/crates/ui-egui/src/tests/alt_preview.rs +++ b/crates/ui-egui/src/tests/alt_preview.rs @@ -69,3 +69,34 @@ fn alt_during_a_blacks_drag_shows_shadow_clipping_until_released() { let after = h.app.session.develop_of(h.app.session.active().expect("photo")).expect("develop").light.blacks; assert!(after < before, "the drag itself still moved Blacks: {before} → {after}"); } + +/// Share of the loupe render's pixels painted exactly `c`. +fn share_of(h: &Headless, c: [u8; 3]) -> f64 { + let t = h.app.renderer.textures.get(&crate::render::Slot::Main).expect("loupe render"); + let px = &t.pixels.as_ref().expect("pixels kept").pixels; + let n = px.iter().filter(|p| [p.r(), p.g(), p.b()] == c).count(); + n as f64 / px.len().max(1) as f64 +} + +/// Issue #3620: J (clipping warnings) paints the clipped pixels themselves, red where a channel +/// is blown to white and blue where one is crushed to black, not just a frame around the photo. +#[test] +fn j_paints_clipped_highlights_red_and_clipped_shadows_blue() { + let mut h = detail(); + let set = |h: &mut Headless, ev: f64| { + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.exposure", "value": ev}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + }; + set(&mut h, 5.0); + let (red, blue) = ([255, 0, 0], [0, 0, 255]); + assert!(share_of(&h, red) < 0.1, "without J the blown photo is not painted red: {}", share_of(&h, red)); + let r = h.request("ui.key", json!({"key": "J"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.show_clipping); + assert!(share_of(&h, red) > 0.5, "blown highlights shown in red: {}", share_of(&h, red)); + set(&mut h, -5.0); + assert!(share_of(&h, blue) > 0.01, "crushed shadows shown in blue: {}", share_of(&h, blue)); + assert!(share_of(&h, red) < 0.01, "nothing blown at -5 EV: {}", share_of(&h, red)); +} From 68b464011ff128442ee572d2424f700cf69fefe2 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 02:23:04 +0200 Subject: [PATCH 08/30] Import review: an optional batch-edit recipe for newly imported photos (#2940) * Import: an optional batch-edit recipe for newly imported photos library.import takes a recipe, a list of develop control ids and values. Each control is set, clamped to its range like a slider's, on every photo the import actually adds, after the XMP sidecar, the camera default and the chosen preset, as one more History step named Import adjustments. Photos that are skipped as duplicates, restored from Recently Deleted or joined from a browsed folder are not touched, as the preset and keywords never touch them. A recipe names plain adjustments only. White balance is refused, because a temperature means Kelvin on a raw with colour matrices and a shift from the as-shot white on a rendered photo, so one number cannot name the same look for a whole batch, and the as-shot white balance of a raw is never touched. Geometry and crop controls are refused, because the slider refits the crop around a new angle and a batch write cannot. Per-photo controls such as pointColor.0.hueShift are refused, because a write to a photo without that instance is dropped. The rule is on the control's spec (a control of the shared list, outside the Geometry section, not white balance, and one that set accepts), so new controls follow it. An id named twice counts once, the last value winning, and a list longer than the control list is refused. ImportJob::new checks a recipe built in code the same way, before any file is read or placed. preset.saveRecipe saves a recipe as a user preset that stores only the settings the recipe names, including a control the recipe sets to its default, and refuses a recipe that stores nothing. The preset gets its id the way imported presets do (user.-, then -2, -3 ...), so no two presets share one: an id from the list length repeats once a preset is deleted, and the first preset with an id is the one that gets applied. A name or group over 100 characters is refused, and saving the same recipe under the same name and group again returns the preset that exists. * Import recipe: tests Cover a recipe on import (the values, the Import adjustments step, a render, one undo step), the refusals (unknown ids, malformed items, per-photo controls, geometry and crop, white balance, too many entries, by the command and by ImportJob::new), clamping and a repeated id, a raw's as-shot white balance staying as imported, a saved recipe preset giving the same settings as the recipe (including a reset to a default), the photos the recipe leaves alone (duplicates by path and by content, a restored photo, a browsed photo that joins; a photo imported afresh gets it), preset ids staying distinct after a delete and surviving a reopened library, and both commands being listed with their parameters. * Import review: a Batch edits section The import review gets a collapsible Batch edits section: sliders for the everyday adjustments (exposure, contrast, highlights, shadows, whites, blacks, vibrance, saturation, clarity, texture, dehaze, sharpening, grain, vignette). The controls moved off their default go to library.import as its recipe, only when there are any, and a summary beside the section counts them. The recipe stays in the dialog until the import runs, so cancelling changes neither the catalog nor the presets. Save as Preset, which needs a name and a recipe, saves the recipe with preset.saveRecipe. It leaves the review's own preset choice as it is, so a preset picked for the import is never replaced by the saved one. The name goes in a TextField, as new text boxes do. The summary line is a new tr_format message, added with a translation to every formats catalog; the other new messages are plain and show in English until a catalog translates them. * Import review recipe: tests Unit tests hold the dialog to the engine: every control it offers is one a recipe may name, a slider moved back to its default leaves the recipe, and start passes a recipe to library.import only when the dialog has one. Driving the real review, Save as Preset saves nothing without a name or without a recipe and with both saves exactly the recipe (leaving the review's preset choice and the catalog alone), cancelling the review discards the recipe, and confirming imports the photos with it as one undo step, or without an Import adjustments step when there is none. * Import recipe: tests for the disabled Save button and MCP reachability The disabled state of Save as Preset was not pinned: the engine refuses a nameless or empty recipe anyway, so the preset count stayed the same even with the button always on. The test now also expects no error toast, which only an enabled button that asked the engine would raise. A new MCP end-to-end test drives both commands through the public tools: list_commands documents them, run_command takes library.import with a recipe (a recipe naming white balance is a tool error that imports nothing), get_develop shows the values on the imported photo, and the generated cmd_preset_saveRecipe tool saves a recipe. * Import recipe: follow main's register(ui) and Id::unique after the rebase Upstream main changed widgets::register to take &egui::Ui (every other call site passes ui) and deprecated egui::Id::new in favour of Id::unique (same hash, so the stored open/closed state is unchanged). Adapt the batch-edit recipe section so lightcraft-ui-egui compiles again. * docs: parity row LR-IMP-RECIPE for batch edits during import * Keep HDR resets when a recipe is saved as a preset A recipe that resets an HDR control to its default was dropped when it was saved as a preset, because the HDR subtree is left out of the settings JSON while it is the default. The recipe's settings are now compared with the HDR subtree always present, so the reset is stored alone and next to other adjustments. Round-trip tests apply the saved preset to settings with a non-default headroom. * Address review findings * Address review findings * Import review: the imports the merge left in body.rs Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 60 ++++ crates/engine/src/cmd/develop.rs | 130 ++++++++ crates/engine/src/cmd/library/import.rs | 1 + crates/engine/src/cmd/library/specs.rs | 2 +- crates/engine/src/import.rs | 3 +- crates/engine/src/import/commit.rs | 13 + crates/engine/src/import/job.rs | 2 + crates/engine/src/import/types.rs | 10 + crates/engine/src/tests/import.rs | 313 ++++++++++++++++++++ crates/mcp/tests/it/e2e.rs | 45 +++ crates/ui-egui/locales/de-formats.json | 1 + crates/ui-egui/locales/es-formats.json | 1 + crates/ui-egui/locales/fr-formats.json | 1 + crates/ui-egui/locales/ja-formats.json | 1 + crates/ui-egui/locales/pt-br-formats.json | 1 + crates/ui-egui/locales/ru-formats.json | 1 + crates/ui-egui/locales/uk-formats.json | 1 + crates/ui-egui/locales/zh-hans-formats.json | 1 + crates/ui-egui/locales/zh-hant-formats.json | 1 + crates/ui-egui/src/dialogs/import.rs | 58 +++- crates/ui-egui/src/dialogs/import/body.rs | 92 +++++- crates/ui-egui/src/dialogs/import/task.rs | 7 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/import_recipe.rs | 182 ++++++++++++ docs/gaps.md | 1 + docs/parity-checklist.md | 4 +- 26 files changed, 926 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tests/import_recipe.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0c93a56a65..d9e3466611 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -271,6 +271,66 @@ pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool { pub(crate) fn ok() -> Result { Ok(Value::Null) } + +/// A batch-edit recipe from a command's params: `[{id, value}, …]`, each `id` a develop control a +/// recipe may name ([`check_recipe`]). Empty when absent or null. A malformed item, a control a +/// recipe may not name, or more entries than there are controls is an error, so a typo is refused +/// rather than silently ignored. An id named twice counts once, the last value winning; the list +/// comes back in id order. +pub(crate) fn recipe_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("recipe").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let Some(items) = v.as_array() else { + return Err(bad(cmd, "`recipe` must be a list of {id, value}")); + }; + let most = lightcraft_develop::controls::CONTROLS.len(); + if items.len() > most { + return Err(bad(cmd, format!("a recipe has one entry per control, at most {most} (it has {})", items.len()))); + } + let mut by_id = std::collections::BTreeMap::new(); + for it in items { + let id = it.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "each recipe item needs an `id`"))?; + let value = it.get("value").and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("recipe `{id}` needs a numeric `value`")))?; + by_id.insert(id.to_string(), value); + } + let recipe: Vec<(String, f64)> = by_id.into_iter().collect(); + check_recipe(&recipe).map_err(|e| bad(cmd, e))?; + Ok(recipe) +} + +/// Whether every control of `recipe` is one a batch-edit recipe may name, else why not. The rule is +/// on the control's spec: a plain control of the shared list, writable on any photo's settings +/// (`set` takes it), outside the Geometry section and not white balance. +/// +/// - Per-photo instances (`pointColor.0.hueShift`, `redEye.0.pupilSize`) are not in the list; on a +/// photo without that instance a write is dropped. +/// - Geometry controls (`crop.angle`, `geometry.*`) need the photo's own size: the slider refits the +/// crop around a new angle, which a batch write cannot do. +/// - White balance means something else on each kind of file (Kelvin on a raw with matrices, +/// relative to the as-shot white on a rendered photo or a raw without them), so one temperature +/// cannot name the same look for every photo of a batch. +pub(crate) fn check_recipe(recipe: &[(String, f64)]) -> std::result::Result<(), String> { + use lightcraft_develop::{Section, controls}; + let mut scratch = lightcraft_develop::DevelopSettings::default(); + for (id, value) in recipe { + let Some(spec) = controls::CONTROLS.iter().find(|c| c.id == id.as_str()) else { + return Err(format!( + "unknown recipe control `{id}` (see develop.controls; a control that belongs to one photo, such as pointColor.0.hueShift, is not one)" + )); + }; + if spec.section == Section::Geometry { + return Err(format!("`{id}` is a geometry control: a recipe does not crop, straighten or transform photos")); + } + if id.starts_with("wb.") { + return Err(format!( + "`{id}` is white balance: a recipe does not set it, because a temperature means something else on a raw than on a rendered photo" + )); + } + if !controls::set(&mut scratch, id, *value) { + return Err(format!("recipe control `{id}` cannot be set")); + } + } + Ok(()) +} pub(crate) fn point(p: &Value, key: &str) -> Option { let a = p.get(key)?.as_array()?; Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?)) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 5399aee9b8..5403ad6eb2 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -33,6 +33,58 @@ fn groups_param(p: &Value, c: &str) -> Result>> { } } +/// The leaves of `a` that differ from `b` (same shape), as a partial JSON object: `None` when they +/// are equal. Used to store only what a batch-edit recipe names, so applying the saved preset +/// later never overrides the settings the recipe doesn't name. +fn partial_diff(a: &Value, b: &Value) -> Option { + match (a, b) { + (Value::Object(x), Value::Object(y)) => { + let mut out = serde_json::Map::new(); + for (k, v) in x { + if let Some(d) = partial_diff(v, y.get(k).unwrap_or(&Value::Null)) { + out.insert(k.clone(), d); + } + } + (!out.is_empty()).then_some(Value::Object(out)) + } + (x, y) => (x != y).then(|| x.clone()), + } +} + +/// The settings as JSON with the HDR subtree always present: [`Hdr`] is left out while it is the default +/// (its JSON stays as it was), so a reset to a default HDR value would have nothing to compare with and +/// would be dropped from a saved preset. +fn full_json(s: &DevelopSettings) -> Value { + let mut v = s.to_json(); + if let Some(obj) = v.as_object_mut() { + obj.entry("hdr").or_insert_with(|| serde_json::to_value(s.hdr).unwrap_or(Value::Null)); + } + v +} + +/// The partial settings a batch-edit recipe names, with the values the import would give (clamped +/// by the control specs). Each named control is compared with the same control at a value it is not +/// set to, so a control the recipe sets to its default (a reset) is stored too, and nothing else is. +/// `None` when the recipe names nothing that is stored, or a control that cannot be written. +fn recipe_partial(recipe: &[(String, f64)]) -> Option { + let (mut named, mut other) = (DevelopSettings::default(), DevelopSettings::default()); + for (id, v) in recipe { + if !controls::set(&mut named, id, *v) { + return None; + } + } + for (id, _) in recipe { + let (spec, now) = (controls::find(id)?, controls::get(&named, id)?); + if !controls::set(&mut other, id, if now > spec.min { spec.min } else { spec.max }) { + return None; + } + } + partial_diff(&full_json(&named), &full_json(&other)) +} + +/// The longest name or group a saved recipe preset may have (characters). +const MAX_PRESET_TEXT: usize = 100; + fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) { let p = s.catalog.photo(id); let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0)); @@ -1162,6 +1214,41 @@ pub fn specs() -> Vec { s.presets.push(Preset::from_settings(&pid, name, group, &d, &groups)); Ok(json!({"id": pid})) }), + cmd!( + "preset.saveRecipe", + "Save Import Recipe as Preset", + [], + None, + "{name (up to 100 characters), group?: default Import Recipes, recipe: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}]} → {id, name} — save a batch-edit recipe (as library.import takes it) as a user preset, so it can be reused from the Preset list; only the settings the recipe names are stored, so applying it later never overrides the rest. The preset gets an id no other preset has; saving the same recipe under the same name and group again returns the preset that already is", + always, + |s, p| { + const C: &str = "preset.saveRecipe"; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing name"))?.to_string(); + let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).unwrap_or("Import Recipes").to_string(); + if name.chars().count() > MAX_PRESET_TEXT || group.chars().count() > MAX_PRESET_TEXT { + return Err(bad(C, format!("a name or group is at most {MAX_PRESET_TEXT} characters"))); + } + let recipe = super::recipe_param(p, C)?; + if recipe.is_empty() { + return Err(bad(C, "the recipe is empty")); + } + let settings = recipe_partial(&recipe).ok_or_else(|| bad(C, "the recipe sets nothing a preset can store"))?; + // presets get their ids as imported ones do (`user.-`, then -2, -3…): an id from the list's + // length repeats once a preset is deleted, and the first preset with an id is the one that gets applied + let preset = Preset { id: String::new(), name, group, settings, favorite: false, builtin: false }; + let id = match s.add_presets(vec![preset.clone()]).into_iter().next() { + Some(id) => id, + // the same recipe under the same name and group is already a preset + None => s + .presets + .iter() + .find(|q| !q.builtin && q.name == preset.name && q.group == preset.group && q.settings == preset.settings) + .map(|q| q.id.clone()) + .ok_or_else(|| bad(C, "the preset could not be saved"))?, + }; + Ok(json!({"id": id, "name": preset.name})) + } + ), cmd!("preset.delete", "Delete Preset", [], None, "{id}", always, |s, p| { let pid = str_param(p, "id").ok_or_else(|| bad("preset.delete", "missing id"))?; let i = s.presets.iter().position(|x| x.id == pid).ok_or_else(|| bad("preset.delete", "unknown preset"))?; @@ -1336,3 +1423,46 @@ fn has_history_after(s: &Session) -> std::result::Result<(), String> { Err("at the latest History step".into()) } } + +#[cfg(test)] +mod recipe_tests { + use super::*; + + /// Equal settings differ nowhere, so there is nothing to store; a difference comes back with + /// its path only. + #[test] + fn partial_diff_is_the_changed_leaves_only() { + let a = json!({"light": {"exposure": 1.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &a), None); + let b = json!({"light": {"exposure": 0.0, "contrast": 0.0}, "color": {"vibrance": 5.0}}); + assert_eq!(partial_diff(&a, &b), Some(json!({"light": {"exposure": 1.0}}))); + assert_eq!(partial_diff(&a, &json!({})), Some(a.clone()), "a leaf the other side lacks is a difference"); + } + + fn recipe(items: &[(&str, f64)]) -> Vec<(String, f64)> { + items.iter().map(|(id, v)| (id.to_string(), *v)).collect() + } + + /// A recipe that names nothing, or a control `set` would drop (a per-photo instance on fresh + /// settings), stores nothing: the command answers with an error, not an empty preset. + #[test] + fn a_recipe_that_stores_nothing_is_none() { + assert_eq!(recipe_partial(&[]), None); + assert_eq!(recipe_partial(&recipe(&[("pointColor.0.hueShift", 5.0)])), None, "set returns false for it"); + assert_eq!(recipe_partial(&recipe(&[("nope.nope", 5.0)])), None); + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.5)])), Some(json!({"light": {"exposure": 0.5}}))); + // a reset to the control's default is stored + assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.0)])), Some(json!({"light": {"exposure": 0.0}}))); + } + + /// The HDR subtree is left out of the JSON while it is the default, so a reset of a headroom to its + /// default is stored in the preset by itself and next to another adjustment. + #[test] + fn an_hdr_reset_is_stored_alone_and_next_to_another_adjustment() { + let reset = recipe_partial(&recipe(&[("hdr.maxEv", 3.0)])).expect("a reset is stored"); + assert_eq!(reset.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{reset}"); + let both = recipe_partial(&recipe(&[("hdr.maxEv", 3.0), ("light.exposure", 0.5)])).expect("both are stored"); + assert_eq!(both.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{both}"); + assert_eq!(both.pointer("/light/exposure"), Some(&json!(0.5)), "{both}"); + } +} diff --git a/crates/engine/src/cmd/library/import.rs b/crates/engine/src/cmd/library/import.rs index 2a663b79de..188dc6ae99 100644 --- a/crates/engine/src/cmd/library/import.rs +++ b/crates/engine/src/cmd/library/import.rs @@ -82,6 +82,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result { metadata_preset, convert_dng: bool_or(p, "dng", false), local: bool_or(p, "local", false), + recipe: crate::cmd::recipe_param(p, "library.import")?, }; let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); Ok(ImportRequest { paths, opts, album, album_name }) diff --git a/crates/engine/src/cmd/library/specs.rs b/crates/engine/src/cmd/library/specs.rs index 7732b855ba..c725ac216b 100644 --- a/crates/engine/src/cmd/library/specs.rs +++ b/crates/engine/src/cmd/library/specs.rs @@ -1348,7 +1348,7 @@ pub fn specs() -> Vec { "Import Photos", ["File"], Some("Cmd+Shift+I"), - "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}", + "{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}", always, |s, p| { let req = import_params(s, p)?; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index cd3123e522..96ce93d0c1 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -15,7 +15,8 @@ //! 6. Apply each photo's XMP sidecar (or a raw/DNG file's embedded XMP): the sidecar wins for //! metadata and develop settings are restored (see [`crate::sidecar`]). Its capture time fills //! in when the file has none (read before step 5, so it also files and names the copy). -//! 7. Optionally apply a preset and add keywords (the import dialog's options). +//! 7. Optionally apply a preset, then a batch-edit recipe (one more History step), and add +//! keywords (the import dialog's options). //! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records; //! the files stay at the destination — undo never moves files back over a card.) //! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index d283bb0ac4..104d1f63b9 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -291,6 +291,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare p.edited = Some(now.clone()); p.history.push(lightcraft_catalog::HistoryStep { label, settings: d }); } + // the batch-edit recipe goes on top of everything above (sidecar, camera default, + // preset): only the controls it names change, through the same specs the sliders use + if !opts.recipe.is_empty() { + let mut d = (*p.develop).clone(); + for (id, v) in &opts.recipe { + // (`ImportJob::new` refused any id `set` would not write, and `set` clamps to the range) + lightcraft_develop::controls::set(&mut d, id, *v); + } + let d = std::sync::Arc::new(d); + p.develop = d.clone(); + p.edited = Some(now.clone()); + p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d }); + } report.imported.push(id.0); p.local = opts.local; if opts.local { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index e8ed759dd2..ca906c6192 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -163,6 +163,8 @@ impl ImportJob { /// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes /// the probes a preceding scan left ([`Session::import_probes`]). pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result { + // a recipe is checked before any file is read or placed, not when the photos are committed + crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?; let mode = opts.mode; // Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of // every added file in its own storage already, so "copy" there means "add". diff --git a/crates/engine/src/import/types.rs b/crates/engine/src/import/types.rs index f342bf4c92..aab839931b 100644 --- a/crates/engine/src/import/types.rs +++ b/crates/engine/src/import/types.rs @@ -67,6 +67,16 @@ pub struct ImportOptions { pub metadata_preset: Option, /// Copy: raws are copied as DNG (Copy as DNG). pub convert_dng: bool, + /// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5), + /// applied to every imported photo *after* its XMP sidecar, camera default and import preset, + /// as one more History step (`Import adjustments`). Only the named controls change; the recipe + /// is a snapshot taken when the import starts, so editing a preset afterwards cannot change it. + /// It names plain adjustments only (no white balance, geometry or crop: `cmd::check_recipe`), + /// and [`ImportJob::new`] refuses anything else. + /// Empty (the default) = no recipe. A photo the library already has keeps its own settings: + /// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed + /// folder (Local) is never touched, as the preset and keywords never are. + pub recipe: Vec<(String, f64)>, } /// How copies are filed in the destination. The date is the capture time, else the time of the diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 5df2ac680d..34e301a6fd 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3139,6 +3139,319 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() { let _ = std::fs::remove_dir_all(&src); } +/// A batch-edit recipe changes the imported photos' actual develop settings (not just an option +/// label), renders, is one undo step, and can be saved as a preset that stores only what it names. +#[test] +fn a_batch_edit_recipe_changes_imported_photos() { + let src = temp_dir("recipe"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = Session::new().with_fs(); + let r = s + .execute( + "library.import", + &json!({ + "paths": [src.to_string_lossy()], + "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}], + }), + ) + .unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); + for p in s.catalog.photos() { + assert_eq!(p.develop.light.exposure, 0.5, "{}", p.file_name); + assert_eq!(p.develop.color.vibrance, 20.0, "{}", p.file_name); + assert!(p.history.iter().any(|h| h.label == "Import adjustments"), "{}", p.file_name); + } + // the edit really renders (the recipe is applied to the settings, not only recorded) + let id = s.catalog.photos().next().unwrap().id; + assert!(s.render_now(id, 32, 32).is_ok()); + // saving the recipe as a preset keeps only the settings it names + let p = s.execute("preset.saveRecipe", &json!({"name": "Warm Trip", "recipe": [{"id": "light.exposure", "value": 0.5}]})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(0.5)), "{}", saved.settings); + assert!(saved.settings.get("color").is_none(), "an unnamed group is not stored: {}", saved.settings); + // one undo step for the whole import + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 0); + let _ = std::fs::remove_dir_all(&src); +} + +/// A malformed recipe, or one naming a control a recipe may not name, is refused before anything +/// is imported, and by the command that saves one: unknown ids, controls that belong to one photo, +/// geometry and crop controls (the slider refits the crop around them), white balance (a +/// temperature means something else on each kind of file), and lists longer than the control list. +#[test] +fn a_bad_recipe_is_refused() { + let mut s = Session::new().with_fs(); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": [{"id": "nope.nope", "value": 1}]})).unwrap_err(); + assert!(format!("{err}").contains("unknown recipe control"), "{err}"); + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": "x"})).unwrap_err(); + assert!(format!("{err}").contains("recipe"), "{err}"); + assert_eq!(s.catalog.len(), 0); + let too_many: Vec = (0..lightcraft_develop::controls::CONTROLS.len() + 1).map(|_| json!({"id": "light.exposure", "value": 1})).collect(); + for (bad, why) in [ + (json!([{"value": 1}]), "needs an `id`"), + (json!([{"id": "light.exposure"}]), "numeric"), + (json!([{"id": "light.exposure", "value": "high"}]), "numeric"), + (json!([7]), "needs an `id`"), + (json!([{"id": "pointColor.0.hueShift", "value": 5}]), "unknown recipe control"), + (json!([{"id": "redEye.0.pupilSize", "value": 5}]), "unknown recipe control"), + (json!([{"id": "crop.angle", "value": 5}]), "geometry"), + (json!([{"id": "geometry.rotate", "value": 5}]), "geometry"), + (json!([{"id": "wb.temp", "value": 5200}]), "white balance"), + (json!([{"id": "wb.tint", "value": 5}]), "white balance"), + (json!([{"id": "light.exposure", "value": 1}, {"id": "crop.angle", "value": 5}]), "geometry"), + (json!(too_many), "at most"), + ] { + let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + let before = s.presets.len(); + let err = s.execute("preset.saveRecipe", &json!({"name": "Bad", "recipe": bad})).unwrap_err().to_string(); + assert!(err.contains(why), "{why}: {err}"); + assert_eq!(s.presets.len(), before, "nothing saved for {why}"); + } + // the job itself refuses what the command would (a recipe built in code, not from JSON) + let opts = crate::import::ImportOptions { recipe: vec![("crop.angle".into(), 5.0)], ..Default::default() }; + assert!(crate::import::ImportJob::new(&mut s, opts).is_err()); + // no name, a name that is too long, or nothing in the recipe: no preset + let one = json!([{"id": "light.exposure", "value": 1}]); + for params in [json!({"recipe": one}), json!({"name": " ", "recipe": one}), json!({"name": "x".repeat(101), "recipe": one})] { + assert!(s.execute("preset.saveRecipe", ¶ms).is_err(), "{params}"); + } + assert!(s.execute("preset.saveRecipe", &json!({"name": "x".repeat(100), "recipe": one})).is_ok(), "a name of 100 characters is fine"); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty", "recipe": []})).is_err()); + assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty"})).is_err()); + assert!(!s.presets.iter().any(|p| p.name == "Empty")); +} + +/// The recipe's values go through the control specs like a slider's: past the range they stop at +/// it, for the photo and for the preset. A control named twice counts once, the last value wins. +#[test] +fn recipe_values_are_clamped_like_a_slider() { + let src = temp_dir("recipe-clamp"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + let recipe = json!([{"id": "light.exposure", "value": 1}, {"id": "light.exposure", "value": 99}, {"id": "light.contrast", "value": -1000}]); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + let p = s.catalog.photos().next().unwrap(); + assert_eq!((p.develop.light.exposure, p.develop.light.contrast), (5.0, -100.0)); + let saved = s.execute("preset.saveRecipe", &json!({"name": "Clamped", "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == saved["id"].as_str().unwrap()).unwrap(); + assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(5.0)), "{}", saved.settings); + assert_eq!(saved.settings.pointer("/light/contrast"), Some(&json!(-100.0)), "{}", saved.settings); + let _ = std::fs::remove_dir_all(&src); +} + +/// A session whose files probe as DNG raws shot at 4800 K, tint +12 (the pixels stay the PNG's; +/// nothing here renders them), to see what an import does to a raw's as-shot white balance. +fn session_with_raw_probe() -> Session { + let mut s = Session::new().with_fs(); + let real = s.media.file_probe.clone().unwrap(); + s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| { + let mut info = real(path)?; + info.kind = lightcraft_catalog::MediaKind::Raw; + info.format = "DNG".into(); + info.as_shot_wb = Some((4800.0, 12.0)); + Ok(info) + })); + s +} + +fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId { + let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap(); + lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}"))) +} + +fn white_balance(s: &Session, id: lightcraft_catalog::PhotoId) -> lightcraft_develop::WhiteBalance { + s.catalog.photo(id).unwrap().develop.wb +} + +/// A recipe never touches white balance: a raw keeps the as-shot temperature, tint and scale it was +/// imported with, whatever else the recipe sets, and a recipe cannot name a temperature or tint. +#[test] +fn a_recipe_leaves_a_raws_as_shot_white_balance_alone() { + use lightcraft_develop::{WbMode, WbScale}; + let src = temp_dir("recipe-wb"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + let mut s = session_with_raw_probe(); + let plain = import_one(&mut s, &src.join("a.png"), json!([])); + let w = white_balance(&s, plain); + assert_eq!((w.mode, w.temp, w.tint, w.scale), (WbMode::AsShot, 4800.0, 12.0, WbScale::Kelvin), "{w:?}"); + let with = import_one(&mut s, &src.join("b.png"), json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 30}])); + assert_eq!(white_balance(&s, with), w, "the as-shot white balance is as the import left it"); + assert_eq!(s.catalog.photo(with).unwrap().develop.light.exposure, 0.5); + for id in ["wb.temp", "wb.tint"] { + let err = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": [{"id": id, "value": 5200}]})).unwrap_err(); + assert!(err.to_string().contains("white balance"), "{err}"); + } + let _ = std::fs::remove_dir_all(&src); +} + +/// Saved as a preset and applied to a photo as it was imported, a recipe gives the settings +/// importing with it gives (for a raw too), and the preset holds a control the recipe sets to its +/// default: that is a reset, not "nothing named". +#[test] +fn a_recipe_saved_as_a_preset_gives_what_the_recipe_gives() { + let src = temp_dir("recipe-preset"); + let recipes = [ + json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]), + json!([{"id": "light.exposure", "value": 99}]), + json!([{"id": "detail.sharpenAmount", "value": 0}, {"id": "grain.amount", "value": 30}]), + json!([{"id": "vignette.amount", "value": -25}, {"id": "effects.clarity", "value": 15}, {"id": "mixer.red.hue", "value": 10}]), + ]; + let mut s = session_with_raw_probe(); + for (i, recipe) in recipes.iter().enumerate() { + write_png(&src.join(format!("with{i}.png")), 2 * i as u8); + write_png(&src.join(format!("plain{i}.png")), 2 * i as u8 + 1); + let with = import_one(&mut s, &src.join(format!("with{i}.png")), recipe.clone()); + let plain = import_one(&mut s, &src.join(format!("plain{i}.png")), json!([])); + let saved = s.execute("preset.saveRecipe", &json!({"name": format!("Recipe {i}"), "recipe": recipe})).unwrap(); + s.selection = crate::Selection::single(plain); + s.execute("preset.apply", &json!({"id": saved["id"], "ids": [plain.0]})).unwrap(); + let (with, plain) = (s.catalog.photo(with).unwrap(), s.catalog.photo(plain).unwrap()); + assert_eq!(with.develop, plain.develop, "recipe {recipe}"); + } + // the sharpening reset (a raw's default is 40) is in the preset although 0 is the control's default + let reset = s.presets.iter().find(|p| p.name == "Recipe 2").unwrap(); + assert_eq!(reset.settings.pointer("/detail/sharpen_amount"), Some(&json!(0.0)), "{}", reset.settings); + assert_eq!(s.catalog.photos().find(|p| p.file_name == "with2.png").unwrap().develop.detail.sharpen_amount, 0.0); + let _ = std::fs::remove_dir_all(&src); +} + +/// The recipe applies to the photos an import adds. A file the library has (by path or by +/// content), a trashed one that comes back, and a browsed one that joins keep their own +/// settings; a trashed one imported afresh is a new photo and gets the recipe. +#[test] +fn a_recipe_only_touches_the_photos_an_import_adds() { + let src = temp_dir("recipe-skipped"); + write_png(&src.join("a.png"), 1); + write_png(&src.join("b.png"), 2); + write_png(&src.join("c.png"), 3); + std::fs::copy(src.join("a.png"), src.join("a-copy.png")).unwrap(); // same bytes as a + let recipe = json!([{"id": "color.vibrance", "value": 20}]); + let adjusted = |s: &Session, name: &str| { + let p = s.catalog.photos().find(|p| p.file_name == name && !p.deleted).unwrap_or_else(|| panic!("no {name}")); + (p.develop.color.vibrance, p.history.iter().any(|h| h.label == "Import adjustments")) + }; + + let mut s = Session::new().with_fs(); + let first = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(first); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap(); + let a_before = s.catalog.photo(first).unwrap().develop.clone(); + + let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 2, "{r}"); // b and c + assert_eq!(ids(&r, "duplicates"), 2, "{r}"); // a (same path) and a-copy (same content) + assert_eq!(adjusted(&s, "b.png"), (20.0, true)); + assert_eq!(adjusted(&s, "c.png"), (20.0, true)); + assert_eq!(adjusted(&s, "a.png"), (0.0, false), "a duplicate is not edited"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "nor is the photo it duplicates"); + assert_eq!(s.catalog.len(), 3); + + // in Recently Deleted: restored with its own settings, no recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!((ids(&r, "imported"), ids(&r, "restored")), (0, 1), "{r}"); + assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "a restored photo keeps its edits"); + assert!(!s.catalog.photo(first).unwrap().history.iter().any(|h| h.label == "Import adjustments")); + + // …imported afresh, it is a new photo and gets the recipe + s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe, "onDeleted": "fresh"})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "a.png"), (20.0, true)); + + // browsed first (Local), then imported: the record joins the library as it is, as it does for + // a preset or keywords + let other = temp_dir("recipe-browsed"); + write_png(&other.join("d.png"), 4); + s.execute("library.browse", &json!({"path": other.to_string_lossy()})).unwrap(); + let r = s.execute("library.import", &json!({"paths": [other.join("d.png").to_string_lossy()], "recipe": recipe})).unwrap(); + assert_eq!(ids(&r, "imported"), 1, "{r}"); + assert_eq!(adjusted(&s, "d.png"), (0.0, false), "a browsed photo that joins keeps its own settings"); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&other); +} + +/// A saved recipe never takes another preset's id: with presets A and B, A deleted, a recipe saved +/// as "B" is its own preset and applying it applies the recipe, not the older B. Saving the same +/// recipe under the same name again is that preset, and the presets are in presets.json. +#[test] +fn saved_recipe_presets_get_distinct_ids_and_survive_reopening() { + let lib = temp_dir("recipe-presets-lib"); + let src = temp_dir("recipe-presets-src"); + write_png(&src.join("a.png"), 1); + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let photo = import_one(&mut s, &src.join("a.png"), json!([])); + s.selection = crate::Selection::single(photo); + let create = |s: &mut Session, name: &str| s.execute("preset.create", &json!({"name": name})).unwrap()["id"].as_str().unwrap().to_string(); + let (a, old_b) = (create(&mut s, "A"), create(&mut s, "B")); + s.execute("preset.delete", &json!({"id": a})).unwrap(); + let recipe = json!([{"id": "light.exposure", "value": 0.7}]); + let saved = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + let new_b = saved["id"].as_str().unwrap().to_string(); + assert_ne!(new_b, old_b); + let mut all: Vec<&str> = s.presets.iter().map(|p| p.id.as_str()).collect(); + let n = all.len(); + all.sort(); + all.dedup(); + assert_eq!(all.len(), n, "every preset has its own id"); + s.execute("preset.apply", &json!({"id": new_b})).unwrap(); + assert_eq!(s.catalog.photo(photo).unwrap().develop.light.exposure, 0.7, "the saved recipe is what gets applied"); + // the same recipe, name and group: the preset it already is + let again = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap(); + assert_eq!(again["id"], saved["id"]); + assert_eq!(s.presets.iter().filter(|p| p.name == "B").count(), 2); + drop(s); + + let mut t = Session::new().with_fs(); + t.open_library(&lib, false).unwrap(); + let mut bs: Vec<&str> = t.presets.iter().filter(|p| p.name == "B").map(|p| p.id.as_str()).collect(); + bs.sort(); + let mut expected = [old_b.as_str(), new_b.as_str()]; + expected.sort(); + assert_eq!(bs, expected, "both are still there after reopening"); + assert!(!t.presets.iter().any(|p| p.name == "A"), "the deleted one stays deleted"); + drop(t); + let _ = std::fs::remove_dir_all(&lib); + let _ = std::fs::remove_dir_all(&src); +} + +/// Both commands are in the command list with their parameters documented, which is where the +/// control channel, the CLI and MCP's `list_commands` read them. +#[test] +fn the_recipe_commands_are_listed_with_their_parameters() { + let s = Session::new(); + let commands = s.commands(); + let import = commands.iter().find(|c| c.id == "library.import").unwrap(); + assert!(import.params.contains("recipe?: [{id:") && import.params.contains("Import adjustments"), "{}", import.params); + assert!(import.params.contains("no white balance, geometry or crop") && import.params.contains("is not changed"), "{}", import.params); + let save = commands.iter().find(|c| c.id == "preset.saveRecipe").expect("preset.saveRecipe is a command"); + assert!(save.enabled && save.params.contains("recipe: [{id:") && save.params.contains("name"), "{}", save.params); +} + +/// A saved recipe that resets an HDR control to its default is applied as the recipe would apply it: +/// alone, and next to another adjustment, on a photo whose HDR settings are not the default. +#[test] +fn a_saved_hdr_reset_applies_to_existing_hdr_settings() { + let mut s = Session::new(); + for recipe in [json!([{"id": "hdr.maxEv", "value": 3}]), json!([{"id": "hdr.maxEv", "value": 3}, {"id": "light.exposure", "value": 0.5}])] { + let p = s.execute("preset.saveRecipe", &json!({"name": format!("Reset {recipe}"), "recipe": recipe})).unwrap(); + let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap().settings.clone(); + let mut base = lightcraft_develop::DevelopSettings::default(); + base.hdr.enabled = true; + base.hdr.max_ev = 1.5; + let out = lightcraft_develop::apply_partial(&base, &saved, 1.0); + assert_eq!(out.hdr.max_ev, 3.0, "{saved}"); + assert!(out.hdr.enabled, "the reset leaves the other HDR settings alone: {saved}"); + let want_exposure = if recipe.as_array().unwrap().len() > 1 { 0.5 } else { base.light.exposure }; + assert_eq!(out.light.exposure, want_exposure, "{saved}"); + } +} + /// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the /// root (CodeRabbit on #3055 / #3080). #[test] diff --git a/crates/mcp/tests/it/e2e.rs b/crates/mcp/tests/it/e2e.rs index 2a8db44c7d..0e0bd98e5e 100644 --- a/crates/mcp/tests/it/e2e.rs +++ b/crates/mcp/tests/it/e2e.rs @@ -412,3 +412,48 @@ fn export_without_token_finishes_after_eof() { assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2); std::fs::remove_dir_all(dir).unwrap(); } + +/// A batch-edit recipe is reachable over MCP without a tool of its own: `run_command` takes +/// `library.import` with a `recipe`, the generated `cmd_preset_saveRecipe` tool saves one as a +/// preset, `list_commands` documents both, and a recipe naming white balance is a tool error that +/// imports nothing. +#[test] +fn a_batch_edit_recipe_is_reachable_over_mcp() { + let dir = std::env::temp_dir().join(format!("lightcraft-mcp-recipe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [(x * 2) as u8, (y * 3) as u8, 128, 255]); + lightcraft_mcp::write_image(&dir.join("gradient.png"), &img, 90).unwrap(); + let paths = json!([dir.to_string_lossy()]); + let mut server = Server::new(Box::new(Headless::default())); + let replies = session( + &mut server, + &[ + call(1, "list_commands", json!({"filter": "recipe"})), + call(2, "run_command", json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "wb.temp", "value": 5000}]}})), + call(3, "query_photos", json!({"limit": 5})), + call( + 4, + "run_command", + json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]}}), + ), + call(5, "get_develop", json!({})), + call(6, "cmd_preset_saveRecipe", json!({"name": "Warm", "recipe": [{"id": "light.exposure", "value": 0.5}]})), + call(7, "list_commands", json!({"filter": "library.import"})), + ], + ); + let listed = |r: &Value| -> Vec { serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap() }; + let save = listed(&replies[0]).into_iter().find(|c| c["id"] == "preset.saveRecipe").expect("preset.saveRecipe is listed"); + assert!(save["params"].as_str().unwrap().contains("recipe: [{id:"), "{save}"); + assert_eq!(replies[1]["result"]["isError"], true, "{}", replies[1]); + assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("white balance"), "{}", replies[1]); + assert!(replies[2]["result"]["structuredContent"]["photos"].as_array().unwrap().is_empty(), "the refused import added nothing"); + assert_eq!(replies[3]["result"]["isError"], false, "{}", replies[3]); + assert_eq!(replies[3]["result"]["structuredContent"]["imported"].as_array().unwrap().len(), 1); + assert_eq!(replies[4]["result"]["structuredContent"]["light"]["exposure"], 0.5, "{}", replies[4]); + assert_eq!(replies[4]["result"]["structuredContent"]["color"]["vibrance"], 20.0, "{}", replies[4]); + assert_eq!(replies[5]["result"]["isError"], false, "{}", replies[5]); + assert_eq!(replies[5]["result"]["structuredContent"]["name"], "Warm"); + let import = listed(&replies[6]).into_iter().find(|c| c["id"] == "library.import").expect("library.import is listed"); + assert!(import["params"].as_str().unwrap().contains("recipe?: [{id:"), "{import}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 43d8da59b4..7e78396a1c 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} Foto{} zu „Meine Fotos“ hinzugefügt", "Added {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzugefügt", "Added {what} to {name}": "{what} zu {name} hinzugefügt", + "Adjustments: {n}": "Anpassungen: {n}", "Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}", "All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index bdfd440f1f..77d40f0ec0 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} foto{0} añadida{0} a Mis fotos", "Added {n} photo{} to “{}”": "{n} foto{0} añadida{0} a “{1}”", "Added {what} to {name}": "{what} añadido a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Adding photos… {} of {}": "Añadiendo fotos… {} de {}", "All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 16782e3499..ba6bcc7b0f 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "{n} photo{} ajoutée(s) à Mes photos", "Added {n} photo{} to “{}”": "{n} photo{} ajoutée(s) à « {} »", "Added {what} to {name}": "{what} ajouté à {name}", + "Adjustments: {n}": "Réglages : {n}", "Adding photos… {} of {}": "Ajout des photos… {} sur {}", "All {n} selected photos move by the same amount.": "Les {n} photos sélectionnées se déplacent de la même valeur.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Déjà dans la bibliothèque, dans « Supprimés récemment » : {} photo{} sélectionnée(s) · clic droit → Restaurer, ou Supprimer définitivement pour importer à nouveau", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index bc6ce0e60a..9f7dd3fe7c 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "。{outside}枚は記録時間の範囲外", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:PR {}件、コミット {}件、+{} / −{} 行(Δ {})、バイナリアセット +{} / −{}、{} – {}", "Added {what} to {name}": "{what}を{name}に追加しました", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動読み込み:{}枚の写真を追加しました{:.0}", "Building previews for {} photos…": "{}枚のプレビューを作成中…", "Couldn't open the editor: {e}": "エディターを開けませんでした:{e}", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index cecd8149c0..4227fe328a 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": "; {outside} fora do intervalo de tempo", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}: {} PRs, {} commits, +{} / −{} linhas (Δ {}), +{} / −{} arquivos binários, {} – {}", "Added {what} to {name}": "{what} adicionado a {name}", + "Adjustments: {n}": "Ajustes: {n}", "Auto Import: added {} photo{}": "Importação automática: {} foto{1} adicionada{1}", "Building previews for {} photos…": "Gerando prévias de {} fotos…", "Couldn't open the editor: {e}": "Não foi possível abrir o editor: {e}", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index d6156cc1fa..24134de944 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -25,6 +25,7 @@ "Added {n} photo{} to My Photos": "В «Мои фото» добавлено фото: {n}{:.0}", "Added {n} photo{} to “{}”": "В «{1}» добавлено фото: {n}{0:.0}", "Added {what} to {name}": "{what}: добавлено в {name}", + "Adjustments: {n}": "Корректировки: {n}", "Adding photos… {} of {}": "Добавление фото… {} из {}", "All {n} selected photos move by the same amount.": "Все выбранные фото ({n}) сдвигаются на одно и то же значение.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в библиотеке, в «Недавно удалённых»: выбрано фото: {}{:.0} · щёлкните правой кнопкой → Восстановить или Удалить навсегда, чтобы импортировать заново", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index ed5e041f82..d30091f2d2 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -23,6 +23,7 @@ "Added {n} photo{} to My Photos": "До моїх фото додано: {n}{:.0}", "Added {n} photo{} to “{}”": "До «{1}» додано фото: {n}{0:.0}", "Added {what} to {name}": "{what}: додано до {name}", + "Adjustments: {n}": "Коригування: {n}", "Adding photos… {} of {}": "Додавання фото… {} з {}", "All {n} selected photos move by the same amount.": "Усі вибрані фото ({n}) зміщуються на однакове значення.", "Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Уже в бібліотеці, у нещодавно видалених: вибрано фото: {}{:.0} · права кнопка → Відновити або Видалити назавжди, щоб імпортувати заново", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 2996e1a217..1d5f27c576 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 张不在其时间范围内", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 个 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 个二进制资源,{} – {}", "Added {what} to {name}": "已将{what}添加到 {name}", + "Adjustments: {n}": "调整:{n}", "Auto Import: added {} photo{}": "自动导入:已添加 {0} 张照片{1:.0}", "Building previews for {} photos…": "正在为 {0} 张照片生成预览…", "Couldn't open the editor: {e}": "无法打开编辑器:{e}", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 93f6d6fa00..51fb1109ae 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -159,6 +159,7 @@ "; {outside} outside its time range": ";{outside} 張不在其時間範圍內", "@{}: {} PRs, {} commits, +{} / −{} lines (Δ {}), +{} / −{} binary assets, {} – {}": "@{}:{} 個 PR,{} 次提交,+{} / −{} 行(Δ {}),+{} / −{} 個二進位資產,{} – {}", "Added {what} to {name}": "已將{what}加入 {name}", + "Adjustments: {n}": "調整:{n}", "Auto Import: added {} photo{}": "自動匯入:已新增 {} 張照片{:.0}", "Building previews for {} photos…": "正在為 {} 張照片建立預覽…", "Couldn't open the editor: {e}": "無法開啟編輯器:{e}", diff --git a/crates/ui-egui/src/dialogs/import.rs b/crates/ui-egui/src/dialogs/import.rs index 4336e5e82f..5ce31dacce 100644 --- a/crates/ui-egui/src/dialogs/import.rs +++ b/crates/ui-egui/src/dialogs/import.rs @@ -3,7 +3,8 @@ //! a grid of thumbnails with checkboxes (duplicates marked and unchecked; Shift-click sets a //! range), the destination (add in place / copy or move into the library's `Originals/` or a //! chosen folder, filed by day, by month, into one folder or by a custom folder template, -//! optionally renamed), an album (existing or new), a preset and keywords to apply. When the scan +//! optionally renamed), an album (existing or new), a preset, an optional batch-edit recipe +//! ("Batch edits": develop controls set on every new photo) and keywords to apply. When the scan //! left something out (a walk cut at its limit, folders it couldn't read, files that are not //! photos) one line under the count says so ([`scan_note`]). Importing runs on a worker thread //! (files are probed, copied or moved there) and its batches join the catalog between frames, with @@ -29,6 +30,7 @@ mod task; #[cfg(test)] pub(crate) use body::grid_height; +use body::recipe_items; pub(crate) use body::scan_note; #[cfg(test)] pub(crate) use body::thumb_edge; @@ -36,6 +38,8 @@ pub(crate) use body::thumb_edge; use body::{DEFAULT_BELOW_GRID, badge_rect, dup_counts}; pub use body::{DEFAULT_FOLDER_TEMPLATE, body, example_destination, source_summary}; pub(crate) use body::{DIALOG_SIZE, THUMB_SIZE_DEFAULT, note_dialog_bottom, thumb_size}; +#[cfg(test)] +use body::{RECIPE_CONTROLS, note_recipe_value}; pub(crate) use scan::StoppingScans; #[cfg(not(target_arch = "wasm32"))] pub(crate) use scan::cards_seen; @@ -63,6 +67,12 @@ pub struct ImportDialog { pub new_album: String, /// Preset id ("" = none). pub preset: String, + /// An optional batch-edit recipe: develop control id → value (only controls moved off their + /// default are kept), set on every photo this import adds, on top of its sidecar, camera + /// default and preset (the `recipe` param of `library.import`). + pub recipe: std::collections::BTreeMap, + /// Name typed for "Save as Preset" (the recipe saved for reuse). + pub recipe_name: String, /// Comma-separated keywords. pub keywords: String, /// Copy: destination folder ("" = the library's Originals/). @@ -384,4 +394,50 @@ mod tests { d.click(2, true); assert_eq!(d.checked, [true, true, false, false, true, true]); } + + /// The dialog offers only controls a recipe may name: `library.import` refuses the others + /// (white balance, geometry and crop, per-photo controls), so one offered here would make every + /// import with it fail. Each is moved off its default, as a slider drag does. + #[test] + fn every_offered_recipe_control_is_accepted_by_the_import() { + let session = lightcraft_engine::Session::new(); + let mut d = dialog(); + for id in RECIPE_CONTROLS { + let spec = lightcraft_develop::controls::find(id).unwrap_or_else(|| panic!("{id} is not a develop control")); + let moved = if spec.default < spec.max { spec.max } else { spec.min }; + note_recipe_value(&mut d.recipe, spec, moved); + } + assert_eq!(d.recipe.len(), RECIPE_CONTROLS.len(), "all named, none repeated"); + let params = json!({"paths": ["img0.jpg"], "recipe": recipe_items(&d.recipe)}); + let request = lightcraft_engine::cmd::library::import_params(&session, ¶ms).unwrap_or_else(|e| panic!("refused: {e}")); + assert_eq!(request.opts.recipe.len(), RECIPE_CONTROLS.len()); + } + + /// A slider moved off its default names its control in the recipe; moved back, it no longer does. + #[test] + fn a_slider_back_at_its_default_leaves_the_recipe() { + let spec = lightcraft_develop::controls::find("light.exposure").unwrap(); + let mut recipe = std::collections::BTreeMap::new(); + note_recipe_value(&mut recipe, spec, 0.5); + assert_eq!(recipe.get("light.exposure"), Some(&0.5)); + note_recipe_value(&mut recipe, spec, 1.25); + assert_eq!(recipe.get("light.exposure"), Some(&1.25), "a new value replaces the old"); + note_recipe_value(&mut recipe, spec, spec.default); + assert!(recipe.is_empty(), "{recipe:?}"); + } + + /// `start` hands `library.import` a `recipe` only when the dialog has one. + #[test] + fn start_passes_the_recipe_only_when_the_dialog_has_one() { + let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services { png: None, ..Default::default() }); + let mut d = dialog(); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert!(params.get("recipe").is_none(), "{params}"); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), -20.0); + start(&mut app, &d).unwrap(); + let params = app.import.take().map(|t| t.params).unwrap(); + assert_eq!(params["recipe"], json!([{"id": "color.vibrance", "value": -20.0}, {"id": "light.exposure", "value": 0.5}]), "{params}"); + } } diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index d461d690ab..5228f7b95b 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -1,7 +1,7 @@ use serde_json::json; use super::tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning}; -use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Vec2, pos2, register, vec2}; +use super::{Color32, ImportDialog, LightcraftApp, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, Value, Vec2, pos2, register, vec2}; /// The review dialog's first size (points). It can be resized; the photo grid takes the height. pub(crate) const DIALOG_SIZE: [f32; 2] = [960.0, 720.0]; @@ -447,6 +447,96 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let r = ui.add(egui::TextEdit::singleline(&mut d.keywords).hint_text(crate::i18n::tr("comma, separated")).desired_width(f32::INFINITY)); register(ui, "field:importKeywords", r.rect); }); + recipe_section(app, ui, d); +} + +/// The develop controls offered in the import review's optional batch-edit recipe: the everyday +/// adjustments, not a second editor. Each must be one a recipe may name (`library.import` refuses +/// the others: no white balance, geometry or crop); a test holds the list to that. Anything else is +/// reached by choosing or saving a preset. +pub(super) const RECIPE_CONTROLS: &[&str] = &[ + "light.exposure", + "light.contrast", + "light.highlights", + "light.shadows", + "light.whites", + "light.blacks", + "color.vibrance", + "color.saturation", + "effects.clarity", + "effects.texture", + "effects.dehaze", + "detail.sharpenAmount", + "grain.amount", + "vignette.amount", +]; + +/// A recipe as the `recipe` param of `library.import` and `preset.saveRecipe`. +pub(super) fn recipe_items(recipe: &std::collections::BTreeMap) -> Value { + Value::Array(recipe.iter().map(|(id, v)| json!({"id": id, "value": v})).collect()) +} + +/// Record a slider's new value in the recipe: a control back at its default is no longer named. +pub(super) fn note_recipe_value(recipe: &mut std::collections::BTreeMap, spec: &lightcraft_develop::controls::ControlSpec, value: f64) { + if (value - spec.default).abs() < 1e-9 { + recipe.remove(spec.id); + } else { + recipe.insert(spec.id.to_string(), value); + } +} + +/// The optional "Batch edits" section of the import review: a small recipe of develop controls set +/// on every photo this import adds, on top of its XMP sidecar, camera default and the chosen preset. +/// The recipe lives only in the dialog until the import runs, so cancelling changes neither the +/// catalog nor the preset collections; "Save as Preset" is the explicit way to keep one for reuse. +fn recipe_section(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { + let t = Tokens::get(ui.ctx()); + let open_id = egui::Id::unique("import-recipe-open"); + let mut open = ui.ctx().data(|m| m.get_temp::(open_id)).unwrap_or(false); + field(ui, "Batch edits", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if crate::widgets::text_button(ui, "importRecipeToggle", if open { "Hide adjustments" } else { "Adjust…" }, open).clicked() { + open = !open; + } + let n = d.recipe.len(); + let summary = if n == 0 { crate::i18n::tr("None").to_string() } else { crate::i18n::tr_format!("Adjustments: {n}", n = n) }; + ui.label(egui::RichText::new(summary).color(if n == 0 { t.text_dim } else { t.text_label })); + }); + ui.ctx().data_mut(|m| m.insert_temp(open_id, open)); + if !open { + return; + } + ui.label( + egui::RichText::new(crate::i18n::tr( + "Set on every photo this import adds, after its XMP sidecar and the preset above; photos the library already has are left alone. A slider left at its default changes nothing. Nothing is saved unless you save it as a preset.", + )) + .color(t.text_dim) + .small(), + ); + for &id in RECIPE_CONTROLS { + let Some(spec) = lightcraft_develop::controls::find(id) else { continue }; + let v = d.recipe.get(id).copied().unwrap_or(spec.default); + if let Some(nv) = crate::widgets::slider(ui, spec, v, true, None).value { + note_recipe_value(&mut d.recipe, spec, nv); + } + } + field(ui, "Recipe", |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + crate::text_field::TextField::singleline("field:importRecipeName", &mut d.recipe_name) + .hint(crate::i18n::tr("name for a saved preset")) + .width(160.0) + .show(ui); + let can = !d.recipe.is_empty() && !d.recipe_name.trim().is_empty(); + let b = ui.add_enabled(can, egui::Button::new(crate::i18n::tr("Save as Preset"))); + register(ui, "button:importRecipeSave", b.rect); + if b.clicked() { + let params = json!({"name": d.recipe_name.trim(), "recipe": recipe_items(&d.recipe)}); + match app.run("preset.saveRecipe", params) { + Ok(_) => app.toast(ui.ctx(), crate::i18n::tr("Saved as a preset")), + Err(e) => app.toast_error(ui.ctx(), e), + } + } + }); } /// Draw one import-dialog candidate cell: register `import:{i}`, request the cell's thumbnail, diff --git a/crates/ui-egui/src/dialogs/import/task.rs b/crates/ui-egui/src/dialogs/import/task.rs index 5c27983400..71ac358f9a 100644 --- a/crates/ui-egui/src/dialogs/import/task.rs +++ b/crates/ui-egui/src/dialogs/import/task.rs @@ -1,5 +1,5 @@ use super::scan::{busy_synchronizing, running}; -use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json}; +use super::{ImportDialog, ImportUprightMode, ImportWarning, ImportWarningCode, LightcraftApp, Ordering, Value, json, recipe_items}; /// Files per batch in the browser build (each batch joins the catalog as it is ready, so the /// progress window updates); the desktop's worker uses [`lightcraft_engine::import::batch_size`]. @@ -16,7 +16,7 @@ pub struct ImportTask { queue: Vec, pub total: usize, pub done: usize, - params: Value, + pub(super) params: Value, pub imported: usize, /// Brought back from Recently Deleted (`onDeleted: restore`). pub restored: usize, @@ -225,6 +225,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result (true, true) => "move", }; let mut params = json!({"mode": mode, "keywords": d.keywords()}); + if !d.recipe.is_empty() { + params["recipe"] = recipe_items(&d.recipe); + } if !d.on_deleted.is_empty() { params["onDeleted"] = json!(d.on_deleted); } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e71ef8164a..f801ee843f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -40,6 +40,7 @@ mod grid; mod grid_drag; mod guided_guides; mod histogram_drag; +mod import_recipe; mod import_scan_note; mod import_thumbnails; mod info_dialogs; diff --git a/crates/ui-egui/src/tests/import_recipe.rs b/crates/ui-egui/src/tests/import_recipe.rs new file mode 100644 index 0000000000..7a46603dfe --- /dev/null +++ b/crates/ui-egui/src/tests/import_recipe.rs @@ -0,0 +1,182 @@ +//! The import review's "Batch edits" section: the recipe in the dialog is what the import sets on +//! the photos it adds, "Save as Preset" needs a name and a recipe, and cancelling the review +//! changes neither the catalog nor the presets. + +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use crate::dialogs::import::ImportDialog; +use crate::headless::Headless; +use crate::state::{Dialog, ViewMode}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); +const SETTLE: Duration = Duration::from_secs(120); + +/// A folder of two small PNGs. +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-ui-import-recipe-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..2u8 { + let data: Vec<[u8; 4]> = (0..40 * 30).map(|k| [(k % 40 * 6) as u8, i * 90, 7, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: 40, height: 30, data }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join(format!("img{i}.png")), png).unwrap(); + } + dir +} + +/// The app with an empty library and the import review open on a folder of two photos. +fn review(tag: &str) -> (Headless, PathBuf) { + let dir = folder(tag); + let app = LightcraftApp::new(lightcraft_engine::Session::new().with_fs(), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1300.0, 1400.0], 1.0); + h.app.ui.view = ViewMode::PhotoGrid; + let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), T); + assert_eq!(r["result"]["scanning"], true, "{r}"); + assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens"); + h.settle(SETTLE); + (h, dir) +} + +fn dialog(h: &mut Headless) -> &mut ImportDialog { + match &mut h.app.ui.dialog { + Some(Dialog::Import { opts }) => opts, + other => panic!("no import review: {other:?}"), + } +} + +/// Where a widget is and where the review's window is: `[x, y, w, h]` each. +fn rects(h: &mut Headless, id: &str) -> ([f64; 4], [f64; 4]) { + let r = h.request("ui.widgets", json!({}), T); + let all = r["result"].as_array().expect("widgets"); + let find = |name: &str| -> [f64; 4] { + let w = all.iter().find(|w| w["id"] == name).unwrap_or_else(|| panic!("no widget {name}")); + [0usize, 1, 2, 3].map(|i| w["rect"][i].as_f64().unwrap()) + }; + (find(id), find("dialog:window")) +} + +/// Click a widget of the review, scrolling the review first when the widget is below its window +/// (the review's content scrolls; the Batch edits section is at the bottom of it). +fn click(h: &mut Headless, id: &str) { + for _ in 0..40 { + let (w, win) = rects(h, id); + if w[1] + w[3] <= win[1] + win[3] - 30.0 { + break; + } + h.request("ui.move", json!({"x": win[0] + win[2] / 2.0, "y": win[1] + win[3] / 2.0}), T); + h.request("ui.scroll", json!({"dy": -400.0}), T); + h.settle(SETTLE); + } + let (w, win) = rects(h, id); + assert!(w[1] >= win[1] && w[1] + w[3] <= win[1] + win[3], "{id} {w:?} is inside the window {win:?}"); + let r = h.request("ui.clickWidget", json!({"id": id}), T); + assert_eq!(r["ok"], true, "{id}: {r}"); + h.settle(SETTLE); +} + +fn toast(h: &Headless) -> String { + h.app.ui.toast.clone().map(|t| t.0).unwrap_or_default() +} + +/// Wait for the import the review started to finish. +fn finish_import(h: &mut Headless) { + let t0 = std::time::Instant::now(); + while h.app.import.is_some() && t0.elapsed() < Duration::from_secs(60) { + h.step(); + } + assert!(h.app.import.is_none(), "the import finished"); + h.settle(SETTLE); +} + +/// "Save as Preset" saves nothing without a name or without a recipe, and with both saves exactly +/// the recipe as a preset, leaving the review's own choices (its preset, the photos) as they were. +#[test] +fn save_as_preset_needs_a_name_and_a_recipe() { + let (mut h, dir) = review("save"); + let presets0 = h.app.session.presets.len(); + click(&mut h, "button:importRecipeToggle"); + assert!( + h.request("ui.widgets", json!({"filter": "importRecipeSave"}), T)["result"].as_array().is_some_and(|w| !w.is_empty()), + "the section is open" + ); + + dialog(&mut h).recipe_name = "Warm trip".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a name alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off: pressing it does not even ask the engine (which would refuse with a message)"); + + let d = dialog(&mut h); + d.recipe_name = " ".into(); + d.recipe.insert("light.exposure".into(), 0.5); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0, "a recipe alone saves nothing"); + assert_eq!(toast(&h), "", "the button is off without a name too"); + + dialog(&mut h).recipe_name = " Warm trip ".into(); + click(&mut h, "button:importRecipeSave"); + assert_eq!(h.app.session.presets.len(), presets0 + 1, "{}", toast(&h)); + let saved = h.app.session.presets.iter().find(|p| p.name == "Warm trip").expect("the preset is named as typed, trimmed"); + assert_eq!(saved.settings, json!({"light": {"exposure": 0.5}}), "only what the recipe names"); + assert_eq!(toast(&h), "Saved as a preset"); + assert_eq!(dialog(&mut h).preset, "", "the review's own preset choice is not replaced"); + assert_eq!(h.app.session.catalog.len(), 0, "nothing was imported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Cancelling the review with a recipe in it adds no photo and saves no preset. +#[test] +fn cancelling_the_review_discards_the_recipe() { + let (mut h, dir) = review("cancel"); + let presets0 = h.app.session.presets.len(); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe_name = "Never saved".into(); + h.settle(SETTLE); + let r = h.request("ui.dialog.cancel", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); + assert!(h.app.ui.dialog.is_none() && h.app.import.is_none()); + assert_eq!((h.app.session.catalog.len(), h.app.session.presets.len(), h.app.session.undo.len()), (0, presets0, undo0)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming the review with a recipe imports the photos with it: each has the values and the +/// Import adjustments step, and the import is still one undo step. +#[test] +fn confirming_with_a_recipe_sets_it_on_the_new_photos() { + let (mut h, dir) = review("confirm"); + let undo0 = h.app.session.undo.len(); + let d = dialog(&mut h); + d.recipe.insert("light.exposure".into(), 0.5); + d.recipe.insert("color.vibrance".into(), 20.0); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + for p in h.app.session.catalog.photos() { + assert_eq!((p.develop.light.exposure, p.develop.color.vibrance), (0.5, 20.0), "{}", p.file_name); + assert!(p.history.iter().any(|s| s.label == "Import adjustments"), "{}", p.file_name); + } + assert_eq!(h.app.session.undo.len(), undo0 + 1, "one undo step"); + h.request("engine.execute", json!({"command": "edit.undo"}), T); + assert_eq!(h.app.session.catalog.len(), 0); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Confirming without a recipe adds no Import adjustments step. +#[test] +fn confirming_without_a_recipe_adds_no_adjustment_step() { + let (mut h, dir) = review("plain"); + let r = h.request("ui.dialog.confirm", json!({}), T); + assert_eq!(r["ok"], true, "{r}"); + finish_import(&mut h); + assert_eq!(h.app.session.catalog.len(), 2); + assert!(h.app.session.catalog.photos().all(|p| !p.history.iter().any(|s| s.label == "Import adjustments"))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/gaps.md b/docs/gaps.md index 5d01ebf9a2..08cebce09d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -153,6 +153,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-12 | minor | Gap 20 shrinks: Mamiya MEF decodes (`vendor/mef.rs`) and is imported; gap 10 count 240 → 241 | | 2026-10-12 | minor | Gap 20 shrinks: Epson ERF decodes (`vendor/erf.rs`), 3 bodies verified; gap 10 count 237 → 240 | | 2026-10-13 | minor | Gap 28: F6 (filmstrip) and F7 (left panel) are bound, so the entry no longer lists them as missing; hours unchanged | +| 2026-10-13 | minor | Import gains an optional batch-edit recipe (LR-IMP-RECIPE); it is additive and no ranked gap lists it, so no gap closes and the numbers do not move | | 2026-10-20 | patch | Gap 24: extreme brush segments skip the intermediate dabs; the gap stays open | | 2026-10-11 | minor | Gap 10 shrinks: Leica Q3 verified by a recorded check of 38 private DNGs (236 models verified; Leica 14); gap not closed | | 2026-10-12 | minor | Camera-look deep shadows follow the JPEG toe (#1307); camera calibration remains partial | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index bcdaada1cf..99381ec5f5 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -26,7 +26,7 @@ cited here still exists. Formerly docs/parity.md. | Section | ✅ | 🟡 | ⬜ | 🚫 | P0 done | P1 done | |---|---:|---:|---:|---:|---:|---:| -| A. Import (IMP) | 12 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | +| A. Import (IMP) | 13 | 3 | 1 | 1 | 4/6 (67%) | 5/5 (100%) | | B. Library management (LIB) | 22 | 2 | 1 | 2 | 9/9 (100%) | 9/9 (100%) | | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | @@ -75,6 +75,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-DEVICE | Import from camera/card | P1 | ✅ | `cmd:library.devices`, `cmd:file.addFromDevice`, `crates/engine/src/devices.rs` | mounted volumes with a DCIM folder (macOS /Volumes, Linux /media and /run/media, Windows drive letters); File → Import from Device → the import review, copying into the library by default; menus serve the last scan and rescan in the background (never blocking a frame; hot-plugs repaint); copies are verified (a new file, synced, checked against the content hash the scan computed — byte compare with the source when there is none, issue #134; a bad copy is removed and reported as failed, never counted as imported; taken names get -1, -2…, never replaced — issue #96, `crates/engine/src/import_move.rs`); no PTP/MTP (cameras that don't mount as a disk); Settings → Import → Cameras and Cards can open the import review when a camera or card is connected (off by default; a card that was already in doesn't ask, and an open dialog or running import is finished first; `crates/ui-egui/src/dialogs/import.rs`) | | LR-IMP-AUTO | Watched-folder auto import | P2 | ✅ | `cmd:library.autoImport`, `cmd:library.autoImportScan`, `crates/ui-egui/src/dialogs/settings.rs` | Settings ▸ Import ▸ Auto Import: a watched folder whose new photos are added (in place or copied) once complete, into an optional album; scanned every 3 s | | LR-IMP-PRESET | Preset on import | P2 | ✅ | `cmd:library.import` (`preset`) | chosen in the import review; one History entry | +| LR-IMP-RECIPE | Batch edits during import | P2 | ✅ | `cmd:library.import` (`recipe`), `cmd:preset.saveRecipe` (registered; `crates/engine/src/tests/import.rs` asserts it), `crates/ui-egui/src/dialogs/import.rs` | an optional Batch edits section in the import review: sliders for everyday adjustments (Light, Vibrance and Saturation, Clarity, Texture and Dehaze, Sharpening, Grain, Vignette) whose values are set on every photo the import adds, after its XMP sidecar, camera default and the chosen preset, as one extra History step (`Import adjustments`) after the preset's own; a photo the library already has (a duplicate, one restored from Recently Deleted, one joined from a browsed folder) is not changed; a summary beside the section counts the adjustments, it does not list them; Save as Preset stores only the settings the recipe names (`cmd:preset.saveRecipe`) so it can be reused from the Preset list; the recipe lives only in the dialog until the import runs, so Cancel changes neither the catalog nor the preset collections. The command takes any plain develop control, not only the ones the dialog offers, and refuses white balance, geometry and crop controls, per-photo controls and unknown ids before anything is imported. Not a second editor: white balance is not offered (a temperature means something else on a raw than on a rendered photo, so the command refuses it too), and neither are crop, masks, curve or point colour; a slider left at its default names nothing, so setting a control to its default for the whole batch is only possible through the command | | LR-IMP-RAWDEFAULT | Raw defaults | P1 | ✅ | `cmd:library.preferences`, `crates/engine/src/import.rs`, `crates/ui-egui/src/dialogs/settings.rs` | LightCraft default / a preset / per camera (make + model); non-raw default too; the preset look counts as unedited and Reset returns to it | | LR-IMP-MIGRATE | Migrate other catalogs | OOS | 🚫 | | | | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | @@ -924,6 +925,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-13 | minor | KEY-SLIDER-RESET: hovering a slider's name or thumb says a double-click resets it; a double-click on the thumb is one undo step, not two; a disabled slider's name doesn't reset it (issue #1436); status unchanged (✅) | | 2026-10-20 | patch | LR-MASK-BRUSH: extreme segments skip intermediate dabs; ordinary spacing and endpoints preserved; status unchanged (🟡) | | 2026-10-12 | minor | LR-META-XMP: bounded complete-APP1 manual JPEG reread, fail-closed sidecar precedence and scoped regression coverage; LR-META-EXIF-FULL: reuse loaded bytes; statuses unchanged | +| 2026-10-13 | minor | LR-IMP-RECIPE added (✅): an optional batch-edit recipe for newly imported photos (`library.import` `recipe`, `preset.saveRecipe`, the Batch edits section of the import review); no existing row changes | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type; no walk behaviour changes; status unchanged (✅) | | 2026-10-13 | minor | LR-IMP-ADD-DIALOG: the import review (and `library.importPreview`) says when its folder scan stopped at the walk limit, could not read folders or skipped files that are not a supported photo type (XMP sidecars are not counted); no walk behaviour changes; status unchanged (✅) | | 2026-10-11 | minor | LR-MERGE-HDR: HDR and panorama merges of raws without colour matrices (CR2, NEF, ARW…) write the colour they open with as DNG tags (issue #965); status unchanged | From 472560b30936259fe50f8df67b9ad57ea8ef7a6d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:36:08 +0100 Subject: [PATCH 09/30] Tests: clipping warnings crush the shadows with Blacks (#3839) Main fails this test: Exposure -5 alone no longer leaves a channel at 0 in the demo photo. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/tests/alt_preview.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/tests/alt_preview.rs b/crates/ui-egui/src/tests/alt_preview.rs index 5997b41b43..96a9d60e6d 100644 --- a/crates/ui-egui/src/tests/alt_preview.rs +++ b/crates/ui-egui/src/tests/alt_preview.rs @@ -97,6 +97,10 @@ fn j_paints_clipped_highlights_red_and_clipped_shadows_blue() { assert!(h.app.ui.show_clipping); assert!(share_of(&h, red) > 0.5, "blown highlights shown in red: {}", share_of(&h, red)); set(&mut h, -5.0); + // the demo photo's shadows don't reach black on Exposure alone: Blacks crushes them + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"control": "light.blacks", "value": -100.0}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(SETTLE); assert!(share_of(&h, blue) > 0.01, "crushed shadows shown in blue: {}", share_of(&h, blue)); assert!(share_of(&h, red) < 0.01, "nothing blown at -5 EV: {}", share_of(&h, red)); } From 394327910507d73bb56b74835bda785c6bc297b9 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:44:58 +0100 Subject: [PATCH 10/30] Colour noise reduction: joint linear chroma filter with speck brake, CPU and GPU (#815) (#1348) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * WIP: colour NR v2 prototype (env LIGHTCRAFT_NR_V2, CPU only) Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 on by default (LIGHTCRAFT_NR_V2=0 turns it off), GPU renders read back for it Co-Authored-By: Claude Opus 5.5 * WIP: cache renders with the new colour NR apart from older ones Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 on the GPU (fused down / apply kernels), coefficient grid sigma / 2 Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 on the CPU without full-size intermediates (row-streamed passes) Co-Authored-By: Claude Opus 5.5 * WIP: report peak device-buffer use per GPU stage with LIGHTCRAFT_PROFILE * WIP: colour NR v2 linear mode (NRV2_LINEAR=1: c - Y, additive, noise model), Jensen term, mean-drift probe Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 noise model with equal-count luminance bands and a non-negative fit; probe asserts the mean over 3 noise realisations Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 linear mode by default (per channel, K 64, coarse pass smooths only the coarse part); CPU on GPU renders; real-colour probe Known: tests_window::noise_reduction_does_not_depend_on_the_window fails (the noise is measured in the rendered window; the square-root mode failed it too). Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 joint guide (NRV2_JOINT=1, opt-in), luminance guide knobs, leaf-next-to-black probe, camera-look guard from 858 Co-Authored-By: Claude Opus 5.5 * WIP: colour NR v2 reads its env knobs once (per-pixel env reads made the linear mode 11x slower); joint stage timings with LIGHTCRAFT_PROFILE Co-Authored-By: Claude Opus 5.5 * WIP: joint colour NR without redundant passes (fused paths + next weights, none after the last scale, delta-1 weights from the path), two-component buffers, parallel reconstruction Bit-identical to 8b89526d (test joint_matches_the_reference_bit_for_bit against a test-only copy). Cat 32.7 MP, CPU: 6.2 -> 5.0 s at Color 25, 7.0 -> 5.6 s at 100; working buffers 2.36 -> 1.44 GB. Co-Authored-By: Claude Opus 5.5 * WIP: joint colour NR with separate H/V slice loops and zero-difference shortcuts (no division, weight 1 without exp) Still bit-identical to 8b89526d. Interleaved 24 MP bench: 2.72 s vs 4.52 s for the reference. Co-Authored-By: Claude Opus 5.5 * WIP: joint colour NR on the GPU (nrcj.wgsl), default on; whole-image noise model from samples, halo bands above 2 GB Kernels mirror nrc_joint step for step (same scale plan, noise model fitted on the CPU from GPU samples). Cat 32.7 MP on a Quadro M2200: wb/nr 1.2-1.3 s vs 4-5 s CPU; against the CPU max 1 LSB; bands = single. Waits after dropping large buffers (freed memory otherwise piled up to the whole 4 GB). Cache key includes joint. Co-Authored-By: Claude Opus 5.5 * WIP: GPU joint NR plans its bands from a budget that includes the output buffer and the device buffer limit; halo 2*sum(delta) + max delta + 8; a band that cannot fit runs only this stage on the CPU Bands vs one piece: at most 1 LSB in a few dozen pixels (running-sum boxes round differently per band start). Co-Authored-By: Claude Opus 5.5 * WIP: GPU joint NR budgets its bands from the free device memory where it can be asked without unsafe (nvidia-smi, amdgpu sysfs), cached 3 s; fixed 2 GB otherwise Co-Authored-By: Claude Opus 5.5 * WIP: docs/nr-color-v2-history.md: every approach tried, measured and dropped, speed numbers, known limits (no outlier brake yet) Co-Authored-By: Claude Opus 5.5 * WIP: history doc: speck behaviour stated qualitatively until measured on full-size renders Co-Authored-By: Claude Opus 5.5 * WIP: joint colour NR speck brake: compact colour specks (chroma far past the noise, small luminance step, shift not reaching the 5x5 border) lose their colour before the guide is built; weak at Color 25, full at 100; CPU and GPU Co-Authored-By: Claude Opus 5.5 * WIP: joint NR CPU 5.2 -> 3.5 s (33 MP), bit for bit: guide as planes with branch-free distance rows, exponentiated paths, pilot straight into planes, speck brake in place with a min/max pre-test Co-Authored-By: Claude Opus 5.5 * WIP: joint NR GPU: path and weight pairs instead of quads (48 instead of 60 bytes per pixel, 33 MP in one piece), speck and pilot kernels without loop-indexed private arrays, noise fit cached for identical samples; Quadro M2200 2.15 -> 1.47 s, HD 630 5.66 -> 4.26 s Co-Authored-By: Claude Opus 5.5 * WIP: speck brake: compactness from the second largest border share (a line or edge crosses the 5x5 border twice; one noisy border pixel no longer protects a speck) Co-Authored-By: Claude Opus 5.5 * #815: colour noise reduction as process V3 The joint method (linear R−Y / B−Y, edge-aware guide, speck brake) is process V3 and the latest; edits on V1 and V2 keep main's blurred chromaticity. The prototype switches (LIGHTCRAFT_NR_V2, NRV2_*) and the square-root and per-channel variants they selected are gone, with their GPU kernels; nrc_params uses the former defaults as constants, so V3 renders as the prototype did. The GPU falls back to the CPU joint filter when no band fits. vram is native only (wasm build). Docs: process-versions, nr-color-joint, parity checklist, what's new. Co-Authored-By: Claude Opus 5.5 * #815: process routing test initialises its settings in place (clippy field_reassign_with_default) Co-Authored-By: Claude Opus 5.5 * #815: one GPU band plan at a time, with a reserve for every render on the device An export batch renders two photos side by side (`export_parallelism`). Each joint colour NR planned its bands from the device memory free at that moment and counted the shared buffer pool as its own, so two plans made at once could together ask for more than there is. Measured on a Quadro M2200 (4 GB): two 33 MP exports side by side peaked at 3761 of 4096 MiB. The plan and its bands now run under one lock (`BANDS`), and the budget leaves `VRAM_RESERVE` for each render on the device (`RENDERS`), not just for this one. Co-Authored-By: Claude Opus 5.5 * #815: the joint colour NR's noise fit and pilot no longer switch at a hard bound With main's preview-scaled luminance NR (#960) the CPU and GPU renders of a 640-px preview differed by up to 10 levels (gpu equivalence `output_spaces_match`). Their images after luminance NR differ by 9e-7 rms, but one luminance band of the noise fit sat at exactly 4 times the first fit: the CPU's samples dropped it, the GPU's kept it, and the fitted noise came out 2.6 % apart. The pilot's axis choice then switched at a few pixels, and the edge-aware weights carried that on. - robust_line: a band's weight fades to 0 between 4 and 5 times the fit instead of dropping at 4 (identical below 4). - pilot_pick: the smoother-axis mean fades in between 0.8 and 1.25 times its bound instead of switching at it (identical outside), on the CPU, in nrcj.wgsl and in the test reference. All 19 CPU/GPU comparisons of the equivalence suite are within 1 level again. The new test noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound uses the bands of that preview and fails on the old fit (5.6 % jump). Co-Authored-By: Claude Opus 5.5 * #815: the joint colour NR measures the whole frame's noise and is keyed by process A window measured the noise model on the pixels it held, so a loupe window could smooth differently from the same pixels of the full render or the export. The model now comes from fixed tiles of the whole frame (`lightcraft_pipeline::colour_noise`, `nrc_joint::tiles`), the same for every window, for the CPU and the GPU, and is kept in the stage cache. The linear stage's cache key now includes the colour filter in use, so a process change (Update to Current Process, undo) no longer reuses the other filter's denoised image. Co-Authored-By: Claude Opus 5.5 * M-NR: deep windows match the whole render; the VRAM query no longer stalls renders - A U16 / F32 window with the joint colour NR is grown by the filter's reach and cut back, like an 8-bit one (DeepImage::crop). - The free device memory is refreshed in the background once the cached answer is stale; only the first question for an adapter waits. The joint NR asks before it takes the BANDS lock. - nvidia-smi starts without a console window on Windows (CREATE_NO_WINDOW). Co-Authored-By: Claude Opus 5.5 * M-NR: the VRAM query finds the right card and keeps one answer per adapter - A card is found by its PCI address (wgpu device_pci_bus_id, nvidia-smi pci.bus_id, the amdgpu sysfs directory) where both sides report one; else by a device id that only one card has. Two cards of one model without an address give no answer, and the fixed band budget applies. - Each adapter keeps its own cached answer, so a late background refresh cannot replace another adapter's answer. A refresh not done after 10 s is retried. - The cache tests wait on signals instead of fixed sleeps. Co-Authored-By: Claude Opus 5.5 * M-NR: the VRAM cache tests no longer depend on timing The two cache tests used a 20 ms TTL: on a slow machine a refreshed answer could go stale again between assertions and start an extra query. They now use a 30 s TTL and age an answer explicitly (Cache::expire, test only). Co-Authored-By: Claude Opus 5.5 * GPU: allow joint_band's eight arguments, as color_nr_joint does Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/develop/src/settings.rs | 8 +- crates/gpu/src/ctx.rs | 29 +- crates/gpu/src/lib.rs | 2 + crates/gpu/src/render.rs | 282 ++++- crates/gpu/src/vram.rs | 373 +++++++ crates/gpu/src/wgsl/nrcj.wgsl | 489 ++++++++ crates/pipeline/src/finish.rs | 2 +- crates/pipeline/src/geometry.rs | 37 + crates/pipeline/src/lib.rs | 101 +- crates/pipeline/src/light_v3.rs | 2 +- crates/pipeline/src/local.rs | 341 +++++- crates/pipeline/src/nrc_joint.rs | 1175 ++++++++++++++++++++ crates/pipeline/src/nrc_joint_reference.rs | 352 ++++++ crates/pipeline/src/output.rs | 21 + crates/pipeline/src/tests.rs | 42 + crates/pipeline/src/tests_nr_scale.rs | 4 +- crates/pipeline/src/tests_window.rs | 40 + docs/nr-color-joint.md | 64 ++ docs/nr-color-v2-history.md | 183 +++ docs/parity-checklist.md | 3 +- docs/process-versions.md | 3 +- docs/whats-new.md | 7 + tools/nrc-metrics.py | 90 ++ 23 files changed, 3621 insertions(+), 29 deletions(-) create mode 100644 crates/gpu/src/vram.rs create mode 100644 crates/gpu/src/wgsl/nrcj.wgsl create mode 100644 crates/pipeline/src/nrc_joint.rs create mode 100644 crates/pipeline/src/nrc_joint_reference.rs create mode 100644 docs/nr-color-joint.md create mode 100644 docs/nr-color-v2-history.md create mode 100644 tools/nrc-metrics.py diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 9c2af1740c..c4197c2911 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -93,12 +93,15 @@ pub enum Process { /// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so /// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632). V5, + /// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with + /// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815). + V6, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 5] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5]; - pub const LATEST: Process = Process::V5; + pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6]; + pub const LATEST: Process = Process::V6; pub const fn version(self) -> ProcessVersion { match self { @@ -107,6 +110,7 @@ impl Process { Process::V3 => ProcessVersion(3), Process::V4 => ProcessVersion(4), Process::V5 => ProcessVersion(5), + Process::V6 => ProcessVersion(6), } } } diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 290b95ac99..dee6205a36 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -64,6 +64,23 @@ const MODULES: &[Module] = &[ "fringe_apply", ], }, + Module { + src: include_str!("wgsl/nrcj.wgsl"), + bindings: &[("a", false, "f32"), ("b", false, "f32"), ("dst", true, "f32")], + entries: &[ + "nrcj_yuv", + "nrcj_uv", + "nrcj_samples", + "nrcj_speck", + "nrcj_pilot", + "nrcj_links1", + "nrcj_paths", + "nrcj_links", + "nrcj_dh", + "nrcj_dv", + "nrcj_recon", + ], + }, Module { src: include_str!("wgsl/spot.wgsl"), bindings: &[("img", true, "f32"), ("pts", false, "f32"), ("al", true, "f32"), ("sp", true, "f32"), ("df", true, "f32"), ("wt", true, "f32")], @@ -294,7 +311,8 @@ pub(crate) struct Tracked(wgpu::Buffer); impl Tracked { fn new(b: wgpu::Buffer) -> Tracked { - ALLOCATED.fetch_add(b.size(), Ordering::Relaxed); + let now = ALLOCATED.fetch_add(b.size(), Ordering::Relaxed) + b.size(); + PEAK.fetch_max(now, Ordering::Relaxed); Tracked(b) } } @@ -317,6 +335,15 @@ thread_local! { /// Bytes of device buffers that exist (in use, retired or pooled). static ALLOCATED: AtomicU64 = AtomicU64::new(0); +/// Most bytes allocated since [`take_peak`] (profiling). +static PEAK: AtomicU64 = AtomicU64::new(0); + +/// The most bytes allocated since the last call; starts over from what is allocated now. +pub(crate) fn take_peak() -> (u64, u64) { + let now = ALLOCATED.load(Ordering::Relaxed); + (PEAK.swap(now, Ordering::Relaxed), now) +} + /// Bytes waiting in per-thread retired lists. static RETIRED_BYTES: AtomicU64 = AtomicU64::new(0); /// The render device is lost: wgpu's `poll` panics from then on, so [`Gpu::poll`] stops calling it. diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 342fe039d0..faac8634d7 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -45,6 +45,8 @@ pub mod nn; mod params; #[cfg(not(target_arch = "wasm32"))] mod render; +#[cfg(not(target_arch = "wasm32"))] +mod vram; #[cfg(not(target_arch = "wasm32"))] pub use render::{DisplayFrame, GpuStages, Output}; diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 5a60e547ea..8e6afa3700 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -9,6 +9,7 @@ use lightcraft_geom::Orientation; use lightcraft_pipeline::finish::{FinishParams, FinishParamsInput, MASK_TERMS, mask_terms}; use lightcraft_pipeline::geometry::SampleMode; use lightcraft_pipeline::local::plane_at; +use lightcraft_pipeline::nrc_joint::JointNoise; use lightcraft_pipeline::{Plan, RenderRequest, Rendered, SourceInfo, local}; use lightcraft_raster::resample::Filter; use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8}; @@ -33,6 +34,8 @@ struct Entry { geo: u64, sampled: Arc, lin: Option<(u64, Arc)>, + /// The joint colour NR's noise model of the whole frame, keyed by `Plan::noise_key`. + colour_noise: Option<(u64, JointNoise)>, planes: Planes, } @@ -645,13 +648,15 @@ pub fn render( fault: Option, display: bool, ) -> Option { + let _in_flight = InFlight::new(); let mut t = profiling().then(std::time::Instant::now); // Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the // timings are real. let lap = |what: &str, t: &mut Option, cx: &mut Cx<'_>| match t { Some(t) => { cx.sync(); - eprintln!(" gpu {what}: {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + let (peak, now) = crate::ctx::take_peak(); + eprintln!(" gpu {what}: {:.1} ms (device buffers: peak {} MB, now {} MB)", t.elapsed().as_secs_f64() * 1e3, peak >> 20, now >> 20); *t = std::time::Instant::now(); } None => cx.flush(), @@ -704,9 +709,15 @@ pub fn render( lap("sample", &mut t, &mut cx); // 2. white balance, defringe, spots, noise reduction + let mut colour_noise = cached.as_ref().and_then(|e| e.colour_noise).filter(|(k, _)| *k == plan.noise_key); let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == plan.lin_key) { Some((_, b)) => b, - None => Arc::new(linear(&mut cx, &sampled, info, &plan, &mut host)), + None => { + if colour_noise.is_none() { + colour_noise = lightcraft_pipeline::colour_noise(src, info, &plan).map(|n| (plan.noise_key, n)); + } + Arc::new(linear(&mut cx, &sampled, info, &plan, &mut host, colour_noise.as_ref().map(|c| &c.1))) + } }; lap("wb/nr", &mut t, &mut cx); @@ -722,7 +733,7 @@ pub fn render( } lap("planes", &mut t, &mut cx); if let Some(c) = stages { - c.put(Entry { src: src.clone(), geo: plan.geo, sampled, lin: Some((plan.lin_key, lin.clone())), planes }); + c.put(Entry { src: src.clone(), geo: plan.geo, sampled, lin: Some((plan.lin_key, lin.clone())), colour_noise, planes }); } // 4. masks @@ -930,8 +941,8 @@ fn unwritten(data: &[[u8; 4]]) -> usize { data.chunks(4096).filter(|c| c.iter().fold(255u8, |a, p| a & p[3]) != 255).map(|c| c.iter().filter(|p| p[3] != 255).count()).sum() } -/// The white-balanced, retouched, denoised image. -fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, host: &mut Host) -> Buf { +/// The white-balanced, retouched, denoised image (`colour_noise`: see `denoise`). +fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, host: &mut Host, colour_noise: Option<&JointNoise>) -> Buf { let (w, h) = (plan.w, plan.h); let n = w * h; let s = &*plan.settings; @@ -963,7 +974,7 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho eyed } }; - denoise(cx, img, plan) + denoise(cx, img, plan, colour_noise) } /// Defringe (`optics::defringe`) of the white-balanced image. @@ -1056,8 +1067,9 @@ fn histogram(cx: &mut Cx<'_>, out: &Buf, w: usize, region: (usize, usize, usize, Histogram { r: part(0), g: part(1), b: part(2), luma: part(3), total: v.get(4 * Histogram::BINS).copied().unwrap_or(0), hdr: None } } -/// Noise reduction (`local::denoise`). -fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { +/// Noise reduction (`local::denoise`). `colour_noise`: the whole frame's noise model for the joint colour +/// NR (`lightcraft_pipeline::colour_noise`); `None`: measured on `img`. +fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>, colour_noise: Option<&JointNoise>) -> Buf { let (w, h) = (plan.w, plan.h); let n = w * h; let (lum, col) = local::nr_params(&plan.settings, plan.detail_scale); @@ -1070,6 +1082,20 @@ fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { map(cx, "nr_lum", n, &[nr.k.to_bits()], [Some(&img), Some(&l), Some(&f)], &out); img = out; } + if col.is_some() && local::joint_colour_nr(&plan.settings) { + let Some(p) = local::nrc_params(&plan.settings, plan.detail_scale) else { return img }; + let s = &plan.settings.detail; + let (detail, amount) = ((s.nr_color_detail / 100.0) as f32, (s.nr_color / 100.0) as f32); + if let Some(out) = color_nr_joint(cx, &img, w, h, &p, detail, amount, colour_noise) { + return out; + } + // too small for the noise samples, or not even one band fits the device: this step on the CPU + let mut host = cx.read_rgb(&img, w, h); + let mut d = (*plan.settings).clone(); + d.detail.nr_luminance = 0.0; + local::denoise(&mut host, &d, plan.detail_scale, colour_noise); + return cx.gpu.upload(rgb_words(&host)); + } if let Some(nr) = col { let chroma = cx.gpu.buffer(n * 3); map(cx, "chroma_k", n, &[], [Some(&img), None, None], &chroma); @@ -1081,6 +1107,226 @@ fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf { img } +/// Run a `nrcj.wgsl` kernel on `n` items with inputs `a`, `b` and output `out`. +fn nrcj(cx: &mut Cx<'_>, k: &str, n: usize, p: &[u32], a: &Buf, b: Option<&Buf>, out: &Buf) { + cx.run(k, p, &[Some(a), b, Some(out)], groups1(n)); +} + +/// Device memory left aside when the joint NR plans its bands from the free memory (the rest of the +/// render, the display, other programs). +const VRAM_RESERVE: u64 = 384 << 20; + +/// Renders on the device right now ([`render`]). An export batch renders photos side by side: while one +/// plans its noise reduction bands, each of the others may still allocate the buffers of its other stages. +static RENDERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Held while a noise reduction plans its bands and runs them: two plans made at once from the same free +/// memory would together ask for more than there is. +static BANDS: Mutex<()> = Mutex::new(()); + +/// Counts a render in [`RENDERS`] while it lives. +struct InFlight; + +impl InFlight { + fn new() -> Self { + RENDERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + InFlight + } +} + +impl Drop for InFlight { + fn drop(&mut self) { + RENDERS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// The band budget from the device memory free right now and our own pooled buffers (which we reuse), less +/// [`VRAM_RESERVE`] for each render on the device (this one's other stages and every other render's). +fn band_budget_from(free: u64, pooled: u64, renders: usize) -> usize { + let reserve = VRAM_RESERVE.saturating_mul(renders.max(1) as u64); + free.saturating_add(pooled).saturating_sub(reserve) as usize +} + +/// The joint colour noise reduction (`lightcraft_pipeline::nrc_joint`) on the GPU, the same steps as the +/// CPU: only the noise samples are read back (the noise model is fitted on the CPU, by the same code). +/// Large images are filtered in horizontal bands whose halo covers every step's reach, so each kept pixel +/// gets the whole-image result; the noise model is the whole image's, or `frame_noise` (the whole frame's, +/// for a window). `None` when the image is too small for the noise samples (the caller falls back to the CPU). +#[allow(clippy::too_many_arguments)] +fn color_nr_joint( + cx: &mut Cx<'_>, + img: &Buf, + w: usize, + h: usize, + p: &local::NrcParams, + detail: f32, + amount: f32, + frame_noise: Option<&JointNoise>, +) -> Option { + use lightcraft_pipeline::nrc_joint; + let strength = nrc_joint::strength(amount); + let brake = nrc_joint::speck_brake(amount); + if w < 3 || h < 3 { + return None; + } + if strength <= 0.0 { + return Some(cx.copy(img)); + } + let n = w * h; + let started = profiling().then(std::time::Instant::now); + let mut noise = match frame_noise { + Some(noise) => *noise, + None => { + // noise samples of the whole image: same pixels as the CPU, fitted by the same code + let stride = nrc_joint::noise_sample_stride(n); + let count = n.div_ceil(stride); + let smp = cx.gpu.buffer(11 * count); + nrcj(cx, "nrcj_samples", count, &[count as u32, w as u32, h as u32, stride as u32], img, None, &smp); + let raw: Vec = cx.read(&smp, 11 * count); + drop(smp); + if let Some(t) = started { + eprintln!(" gpu joint samples + read: {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + } + let samples: Vec = raw + .as_chunks::<11>() + .0 + .iter() + .filter(|s| s[0] == 1.0 && s.iter().all(|v| v.is_finite())) + .map(|s| (s[1], [[s[2], s[3], s[4]], [s[5], s[6], s[7]], [s[8], s[9], s[10]]])) + .collect(); + nrc_joint::noise_from_samples(samples) + } + }; + noise.tolerance = nrc_joint::tolerance(detail); + if let Some(t) = started { + eprintln!(" gpu joint noise model: {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + } + let sigma = p.passes.last().map_or(0.0, |q| q.sigma); + let plan = nrc_joint::scale_plan(sigma, w, h); + // Rows a kept pixel depends on: a wrong value at a band edge (treated as an image border) moves + // inwards by delta per vertical sweep, two sweeps per scale; at the farthest row it reaches, a + // scale's weight and path still read up to delta rows further (at most the largest delta); the + // guide's blur and pilot reach a few rows, the speck brake two more. Hence 2·Σdelta + max delta + 10. + let halo = plan.iter().map(|d| 2 * d.0).sum::() + plan.last().map_or(0, |d| d.0) + 10; + // Memory: the whole output (3 values per pixel) is held besides the input; a band then holds about + // 12 values per pixel (guide 3, two chroma buffers 2 + 2, paths 2, weights 2; up to 12 while the + // speck brake and the guide run). The budget for both together is `band_budget_from` the device memory + // free right now (where the driver can be asked, `crate::vram`); else a fixed 2 GB. One band plan at a + // time (`BANDS`), held until the bands are done. PROTOTYPE: `NRV2_GPU_BAND_MB` overrides it. + // (free memory asked before the lock: the first question for a device waits for the driver) + let free = crate::vram::free_bytes(&cx.gpu.info); + let _bands = BANDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let fixed = std::env::var("NRV2_GPU_BAND_MB").ok().and_then(|v| v.parse::().ok()).map(|mb| mb << 20); + let renders = RENDERS.load(std::sync::atomic::Ordering::Relaxed); + let measured = free.map(|free| band_budget_from(free, crate::ctx::memory().pooled, renders)); + let budget = fixed.or(measured).unwrap_or(2048 << 20); + if profiling() { + eprintln!( + " gpu joint budget: {} MB ({}, {renders} render(s) on the device)", + budget >> 20, + if fixed.is_some() { + "NRV2_GPU_BAND_MB" + } else if measured.is_some() { + "free device memory" + } else { + "fixed default" + } + ); + } + let out_bytes = 12 * n; + let per_row = 48 * w; + // no band may exceed the device's largest buffer either (3 values per pixel are the largest) + let limit_rows = (cx.gpu.limit() as usize / (12 * w)).max(1); + let rows = (budget.saturating_sub(out_bytes) / per_row).min(limit_rows); + let core = if rows >= h { + h + } else if rows > 2 * halo { + rows - 2 * halo + } else { + // not even one band with its halo fits: this stage runs on the CPU (the rest of the render stays here) + return None; + }; + let out = cx.gpu.buffer(3 * n); + let mut y0 = 0; + while y0 < h { + let y1 = (y0 + core).min(h); + let (b0, b1) = if core >= h { (0, h) } else { (y0.saturating_sub(halo), (y1 + halo).min(h)) }; + let filtered = joint_band(cx, img, w, b0, b1 - b0, &noise, brake, &plan); + let kept = (y1 - y0) * w; + nrcj(cx, "nrcj_recon", kept, &[kept as u32, strength.to_bits(), (y0 * w) as u32, (b0 * w) as u32], img, Some(&filtered), &out); + drop(filtered); + // wait: the driver frees a dropped buffer only once the GPU is done with it, and a band's + // buffers are large (without waiting, freed memory piled up to the whole 4 GB of a Quadro M2200) + cx.sync(); + y0 = y1; + } + Some(out) +} + +/// The filtered chroma pairs of rows `b0 .. b0 + bh` of the image, treated as an image of their own. +#[allow(clippy::too_many_arguments)] +fn joint_band( + cx: &mut Cx<'_>, + img: &Buf, + w: usize, + b0: usize, + bh: usize, + noise: &lightcraft_pipeline::nrc_joint::JointNoise, + brake: lightcraft_pipeline::nrc_joint::SpeckBrake, + plan: &[(usize, f32)], +) -> Buf { + let n = w * bh; + let mut np = vec![n as u32, w as u32, bh as u32]; + np.extend(noise.model.alpha.iter().chain(&noise.model.beta).chain(&noise.ymax).map(|v| v.to_bits())); + np.push(noise.tolerance.to_bits()); + let mut yuv = cx.gpu.buffer(3 * n); + nrcj(cx, "nrcj_yuv", n, &[n as u32, (b0 * w) as u32], img, None, &yuv); + if brake.share > 0.0 { + let mut sp = np.clone(); + sp.extend([brake.threshold.to_bits(), brake.share.to_bits()]); + let despecked = cx.gpu.buffer(3 * n); + nrcj(cx, "nrcj_speck", n, &sp, &yuv, None, &despecked); + yuv = despecked; + } + let blurred = gaussian(cx, &yuv, w, bh, 3, 0.8); + let guide = cx.gpu.buffer(3 * n); + nrcj(cx, "nrcj_pilot", n, &np, &yuv, Some(&blurred), &guide); + drop(blurred); + let mut filtered = cx.gpu.buffer(2 * n); + nrcj(cx, "nrcj_uv", n, &[n as u32], &yuv, None, &filtered); + drop(yuv); + // dropped buffers only become reusable (and their memory free) once the GPU is done with them + cx.sync(); + // paths (exp(−path), as on the CPU) and pair weights; the next scale's paths go to the scratch buffer, + // free after the diffusion steps, as on the CPU + let mut paths = cx.gpu.buffer(2 * n); + nrcj(cx, "nrcj_links1", n, &np, &guide, None, &paths); + let links = cx.gpu.buffer(2 * n); + let mut lp = np.clone(); + lp.push(1); + nrcj(cx, "nrcj_links", n, &lp, &guide, Some(&paths), &links); + let mut scratch = cx.gpu.buffer(2 * n); + for (k, &(delta, rate)) in plan.iter().enumerate() { + let dp = [n as u32, w as u32, bh as u32, delta as u32, rate.to_bits()]; + for _ in 0..2 { + nrcj(cx, "nrcj_dh", n, &dp, &filtered, Some(&links), &scratch); + std::mem::swap(&mut filtered, &mut scratch); + nrcj(cx, "nrcj_dv", n, &dp, &filtered, Some(&links), &scratch); + std::mem::swap(&mut filtered, &mut scratch); + } + if let Some(&(next, _)) = plan.get(k + 1) { + nrcj(cx, "nrcj_paths", n, &[n as u32, w as u32, bh as u32, delta as u32], &paths, None, &scratch); + std::mem::swap(&mut paths, &mut scratch); + let mut lp = np.clone(); + lp.push(next as u32); + nrcj(cx, "nrcj_links", n, &lp, &guide, Some(&paths), &links); + } + } + drop((scratch, paths, links, guide)); + cx.sync(); + filtered +} + /// The planes the per-pixel stage reads. struct Prep { log_l: Arc, @@ -1374,6 +1620,26 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho mod tests { use super::*; + /// Two exports side by side: each band plan leaves room for the other render, so the two together + /// stay within the free memory they both measured. + #[test] + fn band_budget_leaves_room_for_every_render_on_the_device() { + let (free, pooled) = (3000u64 << 20, 200u64 << 20); + let alone = band_budget_from(free, pooled, 1); + assert_eq!(alone, (3200usize << 20) - VRAM_RESERVE as usize); + assert_eq!(band_budget_from(free, pooled, 0), alone, "the render itself is always counted"); + let two = band_budget_from(free, pooled, 2); + assert_eq!(two, alone - VRAM_RESERVE as usize); + assert_eq!(band_budget_from(100 << 20, 0, 3), 0, "nothing left: no band fits, the CPU runs the step"); + let before = RENDERS.load(std::sync::atomic::Ordering::Relaxed); + { + let _a = InFlight::new(); + let _b = InFlight::new(); + assert!(RENDERS.load(std::sync::atomic::Ordering::Relaxed) >= before + 2); + } + assert!(RENDERS.load(std::sync::atomic::Ordering::Relaxed) < before + 2, "a finished render no longer counts"); + } + #[test] fn coverage_mask_matches_per_pixel_decision() { use lightcraft_develop::{EmbeddedLens, EmbeddedWarp}; diff --git a/crates/gpu/src/vram.rs b/crates/gpu/src/vram.rs new file mode 100644 index 0000000000..ae79478d22 --- /dev/null +++ b/crates/gpu/src/vram.rs @@ -0,0 +1,373 @@ +//! How much device memory is free right now, where that can be asked without `unsafe`: the NVIDIA +//! driver's `nvidia-smi` (Linux and Windows) and the amdgpu driver's sysfs counters (Linux). Other +//! devices (AMD/Intel on Windows needs DXGI; integrated GPUs share system memory) report `None`, and the +//! caller keeps its fixed budget. The answer is cached for a few seconds: renders ask often, and the +//! query starts a process on NVIDIA. Only the first question for an adapter waits for the query; later +//! ones get the last answer while a background thread asks again, so no render (and no lock it holds) +//! waits for `nvidia-smi`. A card is found by its PCI address where the backend reports it, else by its +//! device id; when that matches several cards (two of the same model), the answer is `None`. + +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +/// How long an answer is fresh; an older one is still returned while a newer one is asked for. +const TTL: Duration = Duration::from_secs(3); +/// How long `nvidia-smi` may take before it is given up on. +const QUERY_TIMEOUT: Duration = Duration::from_secs(2); + +const NVIDIA: u32 = 0x10de; +const AMD: u32 = 0x1002; + +static CACHE: Cache = Cache::new(TTL); + +/// Free device memory of the adapter `info` describes, in bytes, or `None` when it cannot be asked. +pub fn free_bytes(info: &wgpu::AdapterInfo) -> Option { + let adapter = Adapter { vendor: info.vendor, device: info.device, bus: pci_address(&info.device_pci_bus_id) }; + CACHE.get(&adapter, query) +} + +/// Which card: vendor and device id, and the PCI address where the backend reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Adapter { + vendor: u32, + device: u32, + bus: Option, +} + +/// A PCI address: domain, bus, device, function. +type Pci = [u32; 4]; + +/// `0000:01:00.0` (Vulkan, sysfs) or `00000000:01:00.0` (`nvidia-smi`). +fn pci_address(s: &str) -> Option { + let mut parts = s.trim().split(':'); + let (domain, bus, rest) = (parts.next()?, parts.next()?, parts.next()?); + let (device, function) = rest.split_once('.')?; + if parts.next().is_some() { + return None; + } + let hex = |x: &str| u32::from_str_radix(x.trim(), 16).ok(); + Some([hex(domain)?, hex(bus)?, hex(device)?, hex(function)?]) +} + +/// One card a driver lists, with its free memory in bytes. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Card { + bus: Option, + device: u32, + free: u64, +} + +/// The free memory of `want` among the listed `cards`: the card at its PCI address when both sides +/// report one, else the only card with its device id, else the only card listed. `None` when that is +/// ambiguous or the address is listed by no card. +fn pick(cards: &[Card], want: &Adapter) -> Option { + if let Some(bus) = want.bus + && cards.iter().any(|c| c.bus.is_some()) + { + return cards.iter().find(|c| c.bus == Some(bus)).map(|c| c.free); + } + let mut same = cards.iter().filter(|c| c.device == want.device); + match (same.next(), same.next()) { + (Some(c), None) => Some(c.free), + (None, _) if cards.len() == 1 => cards.first().map(|c| c.free), + _ => None, + } +} + +/// The last answer for one adapter: when it was asked, the answer, and since when a newer one is +/// being asked for. +struct Answer { + adapter: Adapter, + at: Instant, + free: Option, + asking: Option, +} + +type Ask = fn(&Adapter) -> Option; + +/// Adapters remembered (a renderer, a face finder and a model may each use another device). +const ADAPTERS: usize = 4; + +/// A background query not done after this is taken as lost, and the next question asks again. +const LOST: Duration = Duration::from_secs(10); + +struct Cache { + ttl: Duration, + answers: Mutex>, +} + +impl Cache { + const fn new(ttl: Duration) -> Self { + Cache { ttl, answers: Mutex::new(Vec::new()) } + } + + /// The answer of `ask` for `adapter`: cached, refreshed in the background once it is older than the + /// TTL (in the caller where no thread can be started), and asked for directly the first time. + fn get(&'static self, adapter: &Adapter, ask: Ask) -> Option { + { + let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) { + let busy = a.asking.is_some_and(|t| t.elapsed() < LOST); + if a.at.elapsed() >= self.ttl && !busy { + let adapter = *adapter; + let refresh = std::thread::Builder::new().name("vram-query".into()).spawn(move || self.store(adapter, ask(&adapter))); + if refresh.is_err() { + drop(answers); + return self.ask_now(&adapter, ask); + } + a.asking = Some(Instant::now()); + } + return a.free; + } + } + self.ask_now(adapter, ask) + } + + fn ask_now(&self, adapter: &Adapter, ask: Ask) -> Option { + let free = ask(adapter); + self.store(*adapter, free); + free + } + + /// Keep `adapter`'s answer (each adapter has its own; the oldest one goes when the list is full). + fn store(&self, adapter: Adapter, free: Option) { + let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner); + answers.retain(|a| a.adapter != adapter); + if answers.len() >= ADAPTERS { + answers.remove(0); + } + answers.push(Answer { adapter, at: Instant::now(), free, asking: None }); + } + + /// Make `adapter`'s answer as old as the TTL (tests: no waiting, so no answer goes stale by itself + /// on a slow machine). `false` when there is no answer, or the clock does not reach that far back. + #[cfg(test)] + fn expire(&self, adapter: &Adapter) -> bool { + let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner); + let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) else { return false }; + let Some(at) = a.at.checked_sub(self.ttl) else { return false }; + a.at = at; + true + } + + #[cfg(test)] + fn asking(&self, adapter: &Adapter) -> bool { + self.answers.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|a| a.adapter == *adapter && a.asking.is_some()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn query(adapter: &Adapter) -> Option { + match adapter.vendor { + NVIDIA => nvidia(adapter), + AMD => amdgpu(adapter), + _ => None, + } +} + +/// `nvidia-smi --query-gpu=pci.bus_id,pci.device_id,memory.free`: one line per GPU, +/// `DDDDDDDD:BB:DD.F, 0xDDDDVVVV, `. +#[cfg(not(target_arch = "wasm32"))] +fn nvidia(adapter: &Adapter) -> Option { + let out = run_with_timeout("nvidia-smi", &["--query-gpu=pci.bus_id,pci.device_id,memory.free", "--format=csv,noheader,nounits"])?; + pick(&parse_nvidia(&out), adapter) +} + +/// The cards `nvidia-smi` lists, free memory in bytes. +fn parse_nvidia(out: &str) -> Vec { + out.lines() + .filter_map(|l| { + let mut f = l.split(','); + let (bus, id, free) = (f.next()?, f.next()?, f.next()?); + let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?; + let free = free.trim().parse::().ok()?.checked_mul(1 << 20)?; + Some(Card { bus: pci_address(bus), device: id >> 16, free }) + }) + .collect() +} + +/// `mem_info_vram_total - mem_info_vram_used` of the amdgpu card (its sysfs device directory is named +/// by its PCI address). +#[cfg(not(target_arch = "wasm32"))] +fn amdgpu(adapter: &Adapter) -> Option { + let read_hex = |p: &std::path::Path| -> Option { + let s = std::fs::read_to_string(p).ok()?; + u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok() + }; + let read_u64 = |p: &std::path::Path| -> Option { std::fs::read_to_string(p).ok()?.trim().parse().ok() }; + let mut cards: Vec = Vec::new(); + let mut seen = Vec::new(); + for entry in std::fs::read_dir("/sys/class/drm").ok()?.flatten() { + // card0 and renderD128 are the same device + let Ok(dev) = std::fs::canonicalize(entry.path().join("device")) else { continue }; + if seen.contains(&dev) || read_hex(&dev.join("vendor")) != Some(adapter.vendor) { + continue; + } + seen.push(dev.clone()); + let (Some(device), Some(total), Some(used)) = + (read_hex(&dev.join("device")), read_u64(&dev.join("mem_info_vram_total")), read_u64(&dev.join("mem_info_vram_used"))) + else { + continue; + }; + let bus = dev.file_name().and_then(|n| pci_address(&n.to_string_lossy())); + cards.push(Card { bus, device, free: total.saturating_sub(used) }); + } + pick(&cards, adapter) +} + +/// Run a program and return its standard output, or `None` if it is missing, fails or takes too long. +#[cfg(not(target_arch = "wasm32"))] +fn run_with_timeout(program: &str, args: &[&str]) -> Option { + use std::io::Read; + use std::process::{Command, Stdio}; + let mut cmd = Command::new(program); + cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null()); + // the release app has no console: without this, Windows opens one for each query + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().ok()?; + let start = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => break, + Ok(Some(_)) | Err(_) => return None, + Ok(None) if start.elapsed() > QUERY_TIMEOUT => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + Ok(None) => std::thread::sleep(Duration::from_millis(5)), + } + } + let mut out = String::new(); + child.stdout.take()?.read_to_string(&mut out).ok()?; + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + const fn adapter(vendor: u32, device: u32) -> Adapter { + Adapter { vendor, device, bus: None } + } + + /// Wait until `flag` is set (a fake query that answers when the test says so), at most 10 s. + fn wait_for(flag: &std::sync::atomic::AtomicBool) { + let start = Instant::now(); + while !flag.load(std::sync::atomic::Ordering::SeqCst) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + } + + /// Wait until `cache` has no background query for `a` running, at most 10 s. + fn settled(cache: &Cache, a: &Adapter) { + let start = Instant::now(); + while cache.asking(a) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(!cache.asking(a), "the background query finished"); + } + + #[test] + fn a_stale_answer_is_returned_while_a_new_one_is_asked_for() { + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + static CACHE: Cache = Cache::new(Duration::from_secs(30)); + static ASKED: AtomicU64 = AtomicU64::new(0); + static ANSWER: AtomicBool = AtomicBool::new(true); + fn blocked(_: &Adapter) -> Option { + wait_for(&ANSWER); + Some(ASKED.fetch_add(1, Ordering::SeqCst) + 1) + } + let a = adapter(NVIDIA, 1); + // the first question waits for the answer + assert_eq!(CACHE.get(&a, blocked), Some(1)); + assert!(CACHE.expire(&a)); + // stale, and the driver does not answer: the old answer at once, a new one in the background + ANSWER.store(false, Ordering::SeqCst); + let t = Instant::now(); + assert_eq!(CACHE.get(&a, blocked), Some(1)); + assert_eq!(CACHE.get(&a, blocked), Some(1)); + assert!(t.elapsed() < Duration::from_secs(5), "waited {:?} for the query", t.elapsed()); + assert!(CACHE.asking(&a)); + ANSWER.store(true, Ordering::SeqCst); + settled(&CACHE, &a); + assert_eq!(CACHE.get(&a, blocked), Some(2), "the background answer is kept"); + assert_eq!(ASKED.load(Ordering::SeqCst), 2, "one query in the background, not one per question"); + // another adapter is asked for directly + assert_eq!(CACHE.get(&adapter(AMD, 2), blocked), Some(3)); + } + + #[test] + fn each_adapter_keeps_its_own_answer() { + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + static CACHE: Cache = Cache::new(Duration::from_secs(30)); + static ASKED: AtomicU64 = AtomicU64::new(0); + static ANSWER: AtomicBool = AtomicBool::new(true); + // card 1 answers when the test says so, card 2 at once; 1000s and 2000s + fn ask(a: &Adapter) -> Option { + if a.device == 1 { + wait_for(&ANSWER); + } + Some(a.device as u64 * 1000 + ASKED.fetch_add(1, Ordering::SeqCst)) + } + let (one, two) = (adapter(NVIDIA, 1), adapter(NVIDIA, 2)); + assert_eq!(CACHE.get(&one, ask), Some(1000)); + assert_eq!(CACHE.get(&two, ask), Some(2001)); + assert!(CACHE.expire(&one) && CACHE.expire(&two)); + // card 1 refreshes in the background while card 2 is asked for: neither waits, nor replaces the other + ANSWER.store(false, Ordering::SeqCst); + assert_eq!(CACHE.get(&one, ask), Some(1000)); + assert_eq!(CACHE.get(&two, ask), Some(2001)); + settled(&CACHE, &two); + ANSWER.store(true, Ordering::SeqCst); + settled(&CACHE, &one); + let asked = ASKED.load(Ordering::SeqCst); + assert_eq!(asked, 4, "one background query per card"); + let (a1, a2) = (CACHE.get(&one, ask), CACHE.get(&two, ask)); + assert!(a1.is_some_and(|v| v / 1000 == 1) && a2.is_some_and(|v| v / 1000 == 2), "{a1:?} {a2:?}"); + assert_eq!(ASKED.load(Ordering::SeqCst), asked, "fresh answers are not asked for again"); + } + + #[test] + fn pci_addresses_parse_in_both_forms() { + assert_eq!(pci_address("0000:01:00.0"), Some([0, 1, 0, 0])); + assert_eq!(pci_address("00000000:0A:00.1"), Some([0, 10, 0, 1])); + assert_eq!(pci_address(""), None); + assert_eq!(pci_address("01:00.0"), None); + assert_eq!(pci_address("0000:01:00.0:9"), None); + } + + #[test] + fn nvidia_output_is_matched_by_address_then_device_id() { + let two = "00000000:01:00.0, 0x179B10DE, 3990\n00000000:02:00.0, 0x1F0810DE, 5120\n"; + let cards = parse_nvidia(two); + assert_eq!(pick(&cards, &adapter(NVIDIA, 0x1f08)), Some(5120 << 20)); + assert_eq!(pick(&cards, &adapter(NVIDIA, 0x179b)), Some(3990 << 20)); + // several GPUs and none matches: unknown + assert_eq!(pick(&cards, &adapter(NVIDIA, 0x2204)), None); + // a single GPU is taken even if its id is reported differently + assert_eq!(pick(&parse_nvidia("00000000:01:00.0, 0x179B10DE, 3990\n"), &adapter(NVIDIA, 0x1234)), Some(3990 << 20)); + // garbage is not a number + assert!(parse_nvidia("No devices were found\n").is_empty()); + assert_eq!(pick(&parse_nvidia(""), &adapter(NVIDIA, 0x179b)), None); + } + + #[test] + fn two_cards_of_one_model_are_told_apart_by_address_or_not_at_all() { + let twins = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x1F0810DE, 6000\n"); + let at = |bus| Adapter { bus: pci_address(bus), ..adapter(NVIDIA, 0x1f08) }; + assert_eq!(pick(&twins, &at("0000:02:00.0")), Some(6000 << 20)); + assert_eq!(pick(&twins, &at("0000:01:00.0")), Some(1000 << 20)); + // without an address the model alone is ambiguous: no answer, the caller keeps its fixed budget + assert_eq!(pick(&twins, &adapter(NVIDIA, 0x1f08)), None); + assert_eq!(pick(&twins, &at("")), None); + // an address no card has is no card: the model is not looked up instead + let mixed = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x220410DE, 6000\n"); + assert_eq!(pick(&mixed, &at("0000:03:00.0")), None); + } +} diff --git a/crates/gpu/src/wgsl/nrcj.wgsl b/crates/gpu/src/wgsl/nrcj.wgsl new file mode 100644 index 0000000000..4ea60f5fcf --- /dev/null +++ b/crates/gpu/src/wgsl/nrcj.wgsl @@ -0,0 +1,489 @@ +// Joint colour noise reduction (`lightcraft_pipeline::nrc_joint`). Each kernel mirrors its CPU +// twin there, in the same order of operations; keep them in step. +// +// Buffers: `a`, `b` inputs, `dst` output. Images are interleaved: RGB / Y,R−Y,B−Y (3 per pixel), +// chroma pairs R−Y,B−Y (2 per pixel), path pairs (h, v; exp(−path), see `nrc_joint`) or weight pairs (h, v). +// Kernels with the noise model: P[0] = n, P[1] = w, P[2] = h, P[3..6] = alpha, P[6..9] = beta, +// P[9..12] = ymax, P[12] = tolerance. + +fn ja(i: u32) -> vec3 { + return vec3(a[3u * i], a[3u * i + 1u], a[3u * i + 2u]); +} + +fn jb3(i: u32) -> vec3 { + return vec3(b[3u * i], b[3u * i + 1u], b[3u * i + 2u]); +} + +fn ja2(i: u32) -> vec2 { + return vec2(a[2u * i], a[2u * i + 1u]); +} + +fn jvc(v: vec3, i: u32) -> f32 { + return select(select(v.x, v.y, i == 1u), v.z, i == 2u); +} + +// `JointNoise::var`. +fn nvar(i: u32, y: f32) -> f32 { + let yy = min(y, pf(9u + i)); + return max(pf(3u + i) * max(yy, 0.0) + pf(6u + i), 1e-14); +} + +// `nrc_joint::distance`. +fn jdist(p: vec3, q: vec3) -> f32 { + let y = 0.5 * (p.x + q.x); + let t = 0.025 * max(y, 0.0); + let allowance = t * t; + var sum = 0.0; + for (var i = 0u; i < 3u; i++) { + let v = nvar(i, y); + let d = jvc(p, i) - jvc(q, i); + let excess = max(d * d - v, 0.0); + if (excess != 0.0) { + sum += excess / (3.0 * pf(12u) * v + allowance); + } + } + return sum; +} + +// `nrc_joint::weight`. +fn jweight(d: f32, p: f32) -> f32 { + let m = max(d, p); + return select(exp(-m), 1.0, m == 0.0); +} + +// `nrc_joint::yuv` of pixel `i` of image `a`. +fn jyuv(i: u32) -> vec3 { + let c = ja(i); + let y = lum2020(c); + return vec3(y, c.x - y, c.z - y); +} + +// `nrc_joint::yuv` of `n` pixels of image `a` from pixel P[1] on (a band's rows): P[0] = n. +@compute @workgroup_size(256) +fn nrcj_yuv(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let c = jyuv(pu(1u) + i); + dst[3u * i] = c.x; + dst[3u * i + 1u] = c.y; + dst[3u * i + 2u] = c.z; +} + +// The chroma pair (R−Y, B−Y) of the transformed image `a` (P[0] = n). +@compute @workgroup_size(256) +fn nrcj_uv(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + dst[2u * i] = a[3u * i + 1u]; + dst[2u * i + 1u] = a[3u * i + 2u]; +} + +// Noise samples of image `a`, transformed on the fly (`nrc_joint::noise_model`): P[0] = sample count, +// P[1] = w, P[2] = h, P[3] = stride. Per sample 11 values: valid, brightness, 3 × 3 residuals. +@compute @workgroup_size(256) +fn nrcj_samples(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let k = lin_index(g, nw); + if (k >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let index = k * pu(3u); + let x = index % w; + let y = index / w; + let o = 11u * k; + if (x == 0u || y == 0u || x + 1u == w || y + 1u == h) { + dst[o] = 0.0; + return; + } + let c = jyuv(index); + var brightness = 0.0; + for (var s = 0u; s < 3u; s++) { + let d = min(min(min(min(1u << s, x), y), w - x - 1u), h - y - 1u); + var m = vec3(0.0); + m = m + 0.25 * jyuv(index - d); + m = m + 0.25 * jyuv(index + d); + m = m + 0.25 * jyuv(index - d * w); + m = m + 0.25 * jyuv(index + d * w); + let r = c - m; + dst[o + 2u + 3u * s] = r.x * r.x; + dst[o + 3u + 3u * s] = r.y * r.y; + dst[o + 4u + 3u * s] = r.z * r.z; + brightness += m.x / 3.0; + } + dst[o] = 1.0; + dst[o + 1u] = max(brightness, 0.0); +} + +// `nrc_joint::median8`: the same 19-comparator network, on plain variables (a private array indexed in a +// loop ends up in slow local memory on some GPUs). +fn med8(v0: f32, v1: f32, v2: f32, v3: f32, v4: f32, v5: f32, v6: f32, v7: f32) -> f32 { + var a = v0; + var b = v1; + var c = v2; + var d = v3; + var e = v4; + var f = v5; + var g = v6; + var h = v7; + let t0 = min(a, c); + c = max(a, c); + a = t0; + let t1 = min(b, d); + d = max(b, d); + b = t1; + let t2 = min(e, g); + g = max(e, g); + e = t2; + let t3 = min(f, h); + h = max(f, h); + f = t3; + let t4 = min(a, e); + e = max(a, e); + a = t4; + let t5 = min(b, f); + f = max(b, f); + b = t5; + let t6 = min(c, g); + g = max(c, g); + c = t6; + let t7 = min(d, h); + h = max(d, h); + d = t7; + let t8 = min(a, b); + b = max(a, b); + a = t8; + let t9 = min(c, d); + d = max(c, d); + c = t9; + let t10 = min(e, f); + f = max(e, f); + e = t10; + let t11 = min(g, h); + h = max(g, h); + g = t11; + let t12 = min(c, e); + e = max(c, e); + c = t12; + let t13 = min(d, f); + f = max(d, f); + d = t13; + let t14 = min(b, e); + e = max(b, e); + b = t14; + let t15 = min(d, g); + g = max(d, g); + d = t15; + let t16 = min(b, c); + c = max(b, c); + b = t16; + let t17 = min(d, e); + e = max(d, e); + d = t17; + let t18 = min(f, g); + g = max(f, g); + f = t18; + return 0.5 * (d + e); +} + +// The farther of a value's distances to the least and largest of 8 (`speck_share`'s pre-test). +fn reach8(p: f32, v0: f32, v1: f32, v2: f32, v3: f32, v4: f32, v5: f32, v6: f32, v7: f32) -> f32 { + let lo = min(min(min(v0, v1), min(v2, v3)), min(min(v4, v5), min(v6, v7))); + let hi = max(max(max(v0, v1), max(v2, v3)), max(max(v4, v5), max(v6, v7))); + return max(abs(p - lo), abs(p - hi)); +} + +// The two largest values so far (`t.x` ≥ `t.y`) with `s` added, as the CPU's fold. +fn top2(t: vec2, s: f32) -> vec2 { + return select(vec2(t.x, max(t.y, s)), vec2(s, t.x), s > t.x); +} + +// One border pixel's share of the colour shift (`speck_share`). +fn sshare(q: vec3, m: vec3, du: f32, dv: f32, vu: f32, vv: f32, excess: f32) -> f32 { + return ((q.y - m.y) * du / vu + (q.z - m.z) * dv / vv) / excess; +} + +// `nrc_joint::despeck` + `speck_share`: `a` = transformed image, writes it with the chroma of compact +// colour specks replaced. Noise parameters as `nrcj_pilot`; P[13] = threshold, P[14] = share. +@compute @workgroup_size(256) +fn nrcj_speck(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let x = i % w; + let y = i / w; + let p = ja(i); + var o = p; + if (x >= 2u && y >= 2u && x + 2u < w && y + 2u < h) { + let threshold = pf(13u); + let share = pf(14u); + let up = i - 2u * w; + let dn = i + 2u * w; + // ring: corners and edge centres of the 5 × 5 square (in the CPU's order) + let r0 = ja(up - 2u); + let r1 = ja(up); + let r2 = ja(up + 2u); + let r3 = ja(i - 2u); + let r4 = ja(i + 2u); + let r5 = ja(dn - 2u); + let r6 = ja(dn); + let r7 = ja(dn + 2u); + let ym = (((((((r0.x + r1.x) + r2.x) + r3.x) + r4.x) + r5.x) + r6.x) + r7.x) / 8.0; + let vu = nvar(1u, ym); + let vv = nvar(2u, ym); + let bu = reach8(p.y, r0.y, r1.y, r2.y, r3.y, r4.y, r5.y, r6.y, r7.y); + let bv = reach8(p.z, r0.z, r1.z, r2.z, r3.z, r4.z, r5.z, r6.z, r7.z); + if (bu * bu / vu + bv * bv / vv > threshold) { + var m = vec3(0.0, med8(r0.y, r1.y, r2.y, r3.y, r4.y, r5.y, r6.y, r7.y), med8(r0.z, r1.z, r2.z, r3.z, r4.z, r5.z, r6.z, r7.z)); + let du = p.y - m.y; + let dv = p.z - m.z; + let excess = du * du / vu + dv * dv / vv; + if (excess > threshold) { + m.x = med8(r0.x, r1.x, r2.x, r3.x, r4.x, r5.x, r6.x, r7.x); + let dy = p.x - m.x; + let luminance = dy * dy / nvar(0u, ym); + let alone = clamp((1.5 * excess - luminance) / excess, 0.0, 1.0); + if (alone > 0.0) { + // the two largest border shares (`speck_share`) + var top = vec2(0.0, 0.0); + top = top2(top, sshare(r0, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r1, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r2, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r3, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r4, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r5, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r6, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(r7, m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(up - 1u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(up + 1u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(i - w - 2u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(i - w + 2u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(i + w - 2u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(i + w + 2u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(dn - 1u), m, du, dv, vu, vv, excess)); + top = top2(top, sshare(ja(dn + 1u), m, du, dv, vu, vv, excess)); + let compact = clamp((0.8 - top.y) / 0.3, 0.0, 1.0); + let t = clamp((excess - threshold) / threshold, 0.0, 1.0); + let k = share * t * t * (3.0 - 2.0 * t) * alone * compact; + if (k > 0.0) { + o.y += k * (m.y - p.y); + o.z += k * (m.z - p.z); + } + } + } + } + } + dst[3u * i] = o.x; + dst[3u * i + 1u] = o.y; + dst[3u * i + 2u] = o.z; +} + +// `nrc_joint::pilot`: `a` = transformed image, `b` = its gaussian(0.8); writes the guide. +@compute @workgroup_size(256) +fn nrcj_pilot(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let x = i % w; + let y = i / w; + var out = jb3(i); + if (!(x == 0u || y == 0u || x + 1u == w || y + 1u == h)) { + let p = ja(i); + // 9 · noise variance per component, at the pixel's luminance + let nv = 9.0 * vec3(nvar(0u, p.x), nvar(1u, p.x), nvar(2u, p.x)); + // axis 0 (left/right) and axis 1 (up/down), written out: private arrays indexed in a loop end up in + // slow local memory on some GPUs + let qa = ja(i - 1u); + let qb = ja(i + 1u); + let mh = (qa + p + qb) / 3.0; + let ha = qa - mh; + let hp = p - mh; + let hb = qb - mh; + let th = (ha * ha + hp * hp + hb * hb) / nv; + let vh = th.x + th.y + th.z; + let ua = ja(i - w); + let ub = ja(i + w); + let mv = (ua + p + ub) / 3.0; + let va = ua - mv; + let vp = p - mv; + let vb = ub - mv; + let tv = (va * va + vp * vp + vb * vb) / nv; + let vvar = tv.x + tv.y + tv.z; + // the axis choice fades in between 0.8 and 1.25 times its bound (nrc_joint::pilot_pick) + let sv = smoothstep(0.8, 1.25, vh / max(4.0, 4.0 * vvar)); + let sh = smoothstep(0.8, 1.25, vvar / max(4.0, 4.0 * vh)); + if (sv >= 1.0) { + out = mv; + } else if (sh >= 1.0) { + out = mh; + } else { + out = out + (mv - out) * sv + (mh - out) * sh; + } + } + dst[3u * i] = out.x; + dst[3u * i + 1u] = out.y; + dst[3u * i + 2u] = out.z; +} + +// Paths of the direct neighbours, exp(−distance) (1 where there is no pair): `a` = guide; writes path pairs. +@compute @workgroup_size(256) +fn nrcj_links1(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let x = i % w; + let y = i / w; + let p = ja(i); + var q = vec2(1.0); + if (x + 1u < w) { + let d = jdist(p, ja(i + 1u)); + q.x = jweight(d, d); + } + if (y + 1u < h) { + let d = jdist(p, ja(i + w)); + q.y = jweight(d, d); + } + dst[2u * i] = q.x; + dst[2u * i + 1u] = q.y; +} + +// Paths of length 2·delta from those of length delta (`a`, path pairs): their minimum. P[3] = delta. +@compute @workgroup_size(256) +fn nrcj_paths(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let delta = pu(3u); + let x = i % w; + let y = i / w; + var ph = a[2u * i]; + var pv = a[2u * i + 1u]; + if (x + delta < w) { + ph = min(ph, a[2u * (i + delta)]); + } + if (y + delta < h) { + pv = min(pv, a[2u * (i + delta * w) + 1u]); + } + dst[2u * i] = ph; + dst[2u * i + 1u] = pv; +} + +// `nrc_joint::path_weight`. +fn jpweight(d: f32, path: f32) -> f32 { + return select(min(exp(-d), path), path, d == 0.0); +} + +// The pair weights at distance `next` from the guide (`a`) and the paths (`b`); writes weight pairs. +// Noise parameters as `nrcj_pilot`; P[13] = next. +@compute @workgroup_size(256) +fn nrcj_links(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let next = pu(13u); + let x = i % w; + let y = i / w; + let p = ja(i); + var lh = 0.0; + var lv = 0.0; + let ph = b[2u * i]; + let pv = b[2u * i + 1u]; + if (x + next < w && ph > 0.0) { + lh = jpweight(jdist(p, ja(i + next)), ph); + } + if (y + next < h && pv > 0.0) { + lv = jpweight(jdist(p, ja(i + next * w)), pv); + } + dst[2u * i] = lh; + dst[2u * i + 1u] = lv; +} + +// One horizontal diffusion step (`nrc_joint::diffuse_h`): `a` = chroma pairs, `b` = weight pairs. +// P[0] = n, P[1] = w, P[2] = h, P[3] = delta, P[4] = rate. +@compute @workgroup_size(256) +fn nrcj_dh(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let delta = pu(3u); + let rate = pf(4u); + let x = i % w; + let p = ja2(i); + var o = p; + if (x >= delta) { + o += rate * b[2u * (i - delta)] * (ja2(i - delta) - p); + } + if (x + delta < w) { + o += rate * b[2u * i] * (ja2(i + delta) - p); + } + dst[2u * i] = o.x; + dst[2u * i + 1u] = o.y; +} + +// One vertical diffusion step (`nrc_joint::v_row`), parameters as `nrcj_dh`. +@compute @workgroup_size(256) +fn nrcj_dv(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let i = lin_index(g, nw); + if (i >= pu(0u)) { + return; + } + let w = pu(1u); + let h = pu(2u); + let delta = pu(3u); + let rate = pf(4u); + let y = i / w; + let p = ja2(i); + var o = p; + if (y >= delta) { + o += rate * b[2u * (i - delta * w) + 1u] * (ja2(i - delta * w) - p); + } + if (y + delta < h) { + o += rate * b[2u * i + 1u] * (ja2(i + delta * w) - p); + } + dst[2u * i] = o.x; + dst[2u * i + 1u] = o.y; +} + +// Back to RGB with the image's own luminance, blended by the strength: `a` = image, `b` = a band's +// filtered chroma pairs, `dst` = the whole output. P[0] = pixels written, P[1] = strength, +// P[2] = first pixel written (in the image), P[3] = first pixel of the band (in the image). +@compute @workgroup_size(256) +fn nrcj_recon(@builtin(global_invocation_id) g: vec3, @builtin(num_workgroups) nw: vec3) { + let k = lin_index(g, nw); + if (k >= pu(0u)) { + return; + } + let s = pf(1u); + let i = pu(2u) + k; + let bi = i - pu(3u); + let p = ja(i); + let y = lum2020(p); + let r = y + b[2u * bi]; + let bl = y + b[2u * bi + 1u]; + let res = vec3(r, (y - 0.2627 * r - 0.0593 * bl) / 0.6780, bl); + let o = p + s * (res - p); + dst[3u * i] = o.x; + dst[3u * i + 1u] = o.y; + dst[3u * i + 2u] = o.z; +} diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 6feec0b333..4cb3388127 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -349,7 +349,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { }, // V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last // knot, the generic curve from half a stop below its white point instead of clipping (issue #1632) - Process::V5 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V5 | Process::V6 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak), None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rs index 6cfbd6d9a0..5d8a07489a 100644 --- a/crates/pipeline/src/geometry.rs +++ b/crates/pipeline/src/geometry.rs @@ -336,6 +336,43 @@ impl Frame { Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)), None => std::borrow::Cow::Borrowed(o), }; + self.sample_base(base, plan, w, h) + } + + /// [`Frame::sample`] of each of `windows` of this frame at its `full_w × full_h` output size: the + /// same pixels, with the source oriented and prefiltered once for all of them rather than per window. + pub fn sample_windows(&self, src: &Rgb32f, full_w: usize, full_h: usize, windows: &[crate::PixelWindow]) -> Vec { + let oriented = if self.orient == Orientation::Normal { None } else { Some(src.oriented(self.orient)) }; + let o = oriented.as_ref().unwrap_or(src); + let plans: Vec<(Frame, SamplePlan)> = windows + .iter() + .map(|t| { + let frame = if (t.w, t.h) == (full_w, full_h) { self.clone() } else { self.window(full_w, full_h, *t) }; + let plan = frame.sample_plan(src.width, src.height, t.w, t.h); + (frame, plan) + }) + .collect(); + let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new(); + for dims in plans.iter().filter_map(|p| p.1.prefilter) { + if !bases.iter().any(|b| b.0 == dims) { + bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell))); + } + } + plans + .into_iter() + .zip(windows) + .map(|((frame, plan), t)| { + let base = match plan.prefilter.and_then(|dims| bases.iter().find(|b| b.0 == dims)) { + Some(b) => std::borrow::Cow::Borrowed(&b.1), + None => std::borrow::Cow::Borrowed(o), + }; + frame.sample_base(base, plan, t.w, t.h) + }) + .collect() + } + + /// 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| { let mut out = Rgb32f::new(w, h); par_rows(&mut out.data, w, |y, row| { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 0c1b795ab1..d8835f4ef1 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -40,6 +40,9 @@ pub mod local_tone; pub mod lut; pub mod mask_space; pub mod masks; +pub mod nrc_joint; +#[cfg(test)] +mod nrc_joint_reference; pub mod optics; pub mod output; pub mod profiles; @@ -393,6 +396,8 @@ struct CacheEntry { geo: u64, sampled: Arc, lin: Option<(u64, Arc)>, + /// The joint colour NR's noise model of the whole frame ([`colour_noise`]), keyed by [`Plan::noise_key`]. + colour_noise: Option<(u64, nrc_joint::JointNoise)>, planes: local::Planes, } @@ -425,6 +430,9 @@ pub struct Plan<'a> { /// [`Self::lin_key`] without the noise-reduction settings: draft renders reuse the smooth /// planes of an image that differs from this one only in its noise reduction. pub pre_nr_key: u64, + /// Key of the whole frame's noise model for the joint colour NR ([`colour_noise`]): what it is + /// measured after (everything before the colour NR), not the colour NR's own settings. + pub noise_key: u64, /// Red eye / pet eye corrections with their detected pupils, in output pixels. pub eyes: Vec, /// The whole frame's dehaze airlight, for a windowed render (which can't see the whole frame). @@ -435,6 +443,8 @@ pub struct Plan<'a> { pub keep: Option, /// The source's segmentation mattes ([`SourceInfo::mattes`]). pub mattes: Option>, + /// The whole frame and its output size (a windowed render's [`Self::frame`] is part of it). + pub full: (geometry::Frame, usize, usize), } /// Long edge of the small render a windowed render estimates the whole frame's airlight from. @@ -461,8 +471,13 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R let (full_w, full_h) = req.size(&frame); // sizes and scale are those of the whole output; a window only narrows what is drawn let px_per_long = frame.px_per_long(full_w); + let src_long = src.width.max(src.height); + // (an original reported smaller than the source is the source) + let native_long = info.native_long.unwrap_or(0).max(src_long).max(1); + let detail_scale = local::detail_scale(px_per_long, native_long); let mut fixed_air = None; let mut keep = None; + let full = (frame.clone(), full_w, full_h); let (frame, w, h) = match req.window { Some(win) => { let win = win.clamped(full_w, full_h); @@ -471,8 +486,20 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R let (pw, ph) = (((full_w as f64 * k).round() as usize).max(1), ((full_h as f64 * k).round() as usize).max(1)); fixed_air = Some(local::frame_airlight(src, info, s, &frame, pw, ph)); } - // (spots grow the rendered window; only 8-bit renders are cut back to the request) - let work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win }; + // (spots grow the rendered window of 8-bit renders; a grown window is cut back to the request) + let mut work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win }; + if local::joint_colour_nr(s) + && let Some(params) = local::nrc_params(s, detail_scale) + { + // The joint diffusion reads a chain of neighbours across its scales. Keep + // those reads outside the requested zoom window, just as spot reads are, at every depth. + let halo = params.passes.last().map_or(0, |p| (6.0 * p.sigma).ceil() as usize).saturating_add(4); + let x = work.x.saturating_sub(halo); + let y = work.y.saturating_sub(halo); + let right = work.x.saturating_add(work.w).saturating_add(halo).min(full_w); + let bottom = work.y.saturating_add(work.h).saturating_add(halo).min(full_h); + work = PixelWindow { x, y, w: right.saturating_sub(x), h: bottom.saturating_sub(y) }.clamped(full_w, full_h); + } if work != win { keep = Some(PixelWindow { x: win.x - work.x, y: win.y - work.y, ..win }); } @@ -480,10 +507,6 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R } None => (frame, full_w, full_h), }; - let src_long = src.width.max(src.height); - // (an original reported smaller than the source is the source) - let native_long = info.native_long.unwrap_or(0).max(src_long).max(1); - let detail_scale = local::detail_scale(px_per_long, native_long); let geo = hash_of((format!("{frame:?}"), w, h)); let (wb_t, wb_tint) = local::effective_wb(info, s); let eyes = redeye::resolve(src, &s.red_eye, s.orientation, &frame, w, h, px_per_long); @@ -503,7 +526,10 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R pre_nr_key, [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits), detail_scale.to_bits(), + // the process picks the colour filter (Update to Current Process, undo) + local::joint_colour_nr(s), )); + let noise_key = hash_of((pre_nr_key, [d.nr_luminance, d.nr_detail].map(f64::to_bits), detail_scale.to_bits())); Plan { settings, frame, @@ -516,13 +542,64 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R geo, lin_key, pre_nr_key, + noise_key, eyes, fixed_air, keep, mattes: info.mattes.clone(), + full, } } +/// The joint colour NR's noise model of the whole frame, measured on fixed tiles of it +/// ([`nrc_joint::tiles`]) so that every window of it is filtered alike. The tiles are resampled, +/// tone-mapped, white-balanced and luminance-denoised like the frame; the retouching and defringing +/// are left out. `None` when the joint colour NR is off, or when the render is the whole frame and +/// that is a single tile: the noise is then measured on the image itself, as the CPU and the GPU do. +pub fn colour_noise(src: &Rgb32f, info: &SourceInfo, p: &Plan<'_>) -> Option { + let s = &*p.settings; + if !local::joint_colour_nr(s) || local::nrc_params(s, p.detail_scale).is_none() { + return None; + } + let (full, fw, fh) = &p.full; + let windows = nrc_joint::tiles(*fw, *fh); + if (p.w, p.h) == (*fw, *fh) && windows.len() == 1 { + return None; + } + let t = profiling().then(std::time::Instant::now); + let (lum, _) = local::nr_params(s, p.detail_scale); + // the source oriented and prefiltered once for all tiles + let sampled = full.sample_windows(src, *fw, *fh, &windows); + let tiles: Vec = windows + .into_iter() + .zip(sampled) + .map(|(t, mut img)| { + let frame = if (t.w, t.h) == (*fw, *fh) { full.clone() } else { full.window(*fw, *fh, t) }; + let tile = Plan { + settings: Cow::Borrowed(s), + frame, + w: t.w, + h: t.h, + eyes: Vec::new(), + fixed_air: None, + keep: None, + mattes: None, + full: p.full.clone(), + ..*p + }; + local_tone::apply(&mut img, info, &tile); + local::white_balance(&mut img, info, s); + local::apply_nr(&mut img, lum, None); + img + }) + .collect(); + let noise = nrc_joint::noise_of_tiles(&tiles); + if let Some(t) = t { + eprintln!(" nr colour noise model ({} tiles): {:.0} ms", tiles.len(), t.elapsed().as_secs_f64() * 1e3); + } + Some(noise) +} + /// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal). pub fn lin_needs_cpu(s: &DevelopSettings, info: &SourceInfo) -> bool { let o = &s.optics; @@ -633,13 +710,17 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende }; lap("sample", &mut t); + let mut colour_noise = cached.as_ref().and_then(|e| e.colour_noise).filter(|(k, _)| *k == plan.noise_key); let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == lin_key) { Some((_, img)) => img, None => { // Without a cache the resampled buffer is ours: work on it in place. let mut img = if shared.is_some() { (*sampled).clone() } else { Arc::unwrap_or_clone(sampled.clone()) }; lin_cpu(&mut img, info, &plan); - local::denoise(&mut img, s, detail_scale); + if colour_noise.is_none() { + colour_noise = self::colour_noise(src_img, info, &plan).map(|n| (plan.noise_key, n)); + } + local::denoise(&mut img, s, detail_scale, colour_noise.as_ref().map(|c| &c.1)); Arc::new(img) } }; @@ -659,10 +740,14 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende } lap("prepare", &mut t); if let Some((a, c)) = shared { - c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes }); + c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), colour_noise, planes }); } if req.depth != OutputDepth::U8 { let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof); + let deep = match plan.keep { + Some(k) => deep.crop(k.x, k.y, k.w, k.h), + None => deep, + }; let image = deep.to_rgba8(); let histogram = Histogram::of_srgb8(&image); lap("finish (deep)", &mut t); diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index 03c651c79a..394c7c0829 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { let camera_look = info.raw && info.camera_tone.is_some(); match s.process.process() { Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 | Process::V5 => camera_look, + Process::V4 | Process::V5 | Process::V6 => camera_look, } } diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 96177fe3fe..debb5e8db6 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 | Process::V5 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => base_detail_radius(px_per_long), } } @@ -458,9 +458,17 @@ pub fn nr_params(s: &DevelopSettings, scale: f32) -> (Option, Option) { let (lum, col) = nr_params(s, scale); + if col.is_some() && joint_colour_nr(s) { + apply_nr(img, lum, None); + if let Some(p) = nrc_params(s, scale) { + crate::nrc_joint::denoise(img, &p, (s.detail.nr_color_detail / 100.0) as f32, (s.detail.nr_color / 100.0) as f32, colour_noise); + } + return; + } apply_nr(img, lum, col); } @@ -505,6 +513,87 @@ pub fn apply_nr(img: &mut Rgb32f, lum: Option, col: Option) { } } +/// Most samples the noise level of the new colour noise reduction is measured from. The CPU and +/// the GPU sample the same pixels (see `nrc_joint::noise_sample_stride`). +pub const NRC_SAMPLES: usize = 131_072; + +/// One self-guided pass of the new colour noise reduction: Gaussian windows of `sigma` px, the +/// coefficients computed on a plane subsampled by `step`, `eps = k ×` the `pct`-quantile of the +/// local variance. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NrcPass { + pub sigma: f32, + pub step: usize, + pub k: f32, + pub pct: f32, +} + +/// Parameters of the new colour noise reduction: the offset of the square roots and the passes +/// (fine, then coarse). +#[derive(Clone, Debug, PartialEq)] +pub struct NrcParams { + pub off: f32, + pub passes: Vec, +} + +/// The new colour noise reduction's parameters at `scale` output pixels per pixel of the original +/// ([`crate::Plan::detail_scale`]), `None` when Color is 0. +pub fn nrc_params(s: &DevelopSettings, scale: f32) -> Option { + let amount = (s.detail.nr_color / 100.0) as f32; + if amount <= 0.0 { + return None; + } + let detail = (s.detail.nr_color_detail / 100.0) as f32; + let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32; + let scale = if scale.is_finite() { scale.clamp(0.05, 1.0) } else { 1.0 }; + let sigma = (2.0 + 10.0 * amount) * smooth * scale; + let k = 64.0 * amount * (1.5 - detail); + // the coefficients vary over about sigma: a grid of sigma / 2 holds them + let pass = |sigma: f32| NrcPass { sigma, step: (sigma / 2.0).floor().clamp(1.0, 16.0) as usize, k, pct: 0.2 }; + // fine, then coarse (three times wider); the joint method takes the coarse one's reach + Some(NrcParams { off: 0.003, passes: vec![pass(sigma), pass(sigma * 3.0)] }) +} + +/// Chroma noise variance per channel as a function of the local luminance: `α · Y + β` (shot plus read noise). +#[derive(Clone, Copy, Debug)] +pub struct NrcNoise { + pub alpha: [f32; 3], + pub beta: [f32; 3], +} + +impl NrcNoise { + #[inline] + pub fn var(&self, i: usize, y: f32) -> f32 { + (self.alpha[i] * y.max(0.0) + self.beta[i]).max(1e-14) + } +} + +/// Weighted least squares `v = a · l + b` over `(l, v, weight)` with `a, b ≥ 0`: the free fit if both come out +/// non-negative, else the better of the line through the origin (`b = 0`) and the constant (`a = 0`). +pub fn fit_nonneg_line(pts: &[(f64, f64, f64)]) -> (f64, f64) { + let sw: f64 = pts.iter().map(|p| p.2).sum::().max(1e-300); + let (ml, mv) = (pts.iter().map(|p| p.2 * p.0).sum::() / sw, pts.iter().map(|p| p.2 * p.1).sum::() / sw); + let (cov, vl) = pts.iter().fold((0.0, 0.0), |(c, v), p| (c + p.2 * (p.0 - ml) * (p.1 - mv), v + p.2 * (p.0 - ml) * (p.0 - ml))); + if vl > 0.0 { + let a = cov / vl; + let b = mv - a * ml; + if a >= 0.0 && b >= 0.0 { + return (a, b); + } + } + let sse = |a: f64, b: f64| pts.iter().map(|p| p.2 * (p.1 - a * p.0 - b).powi(2)).sum::(); + let ll: f64 = pts.iter().map(|p| p.2 * p.0 * p.0).sum(); + let origin = if ll > 0.0 { (pts.iter().map(|p| p.2 * p.0 * p.1).sum::() / ll).max(0.0) } else { 0.0 }; + let constant = mv.max(0.0); + if sse(origin, 0.0) < sse(0.0, constant) { (origin, 0.0) } else { (0.0, constant) } +} + +/// Whether `s` gets the joint colour noise reduction (`nrc_joint`, process V6 on), else main's +/// blurred chromaticity. +pub fn joint_colour_nr(s: &DevelopSettings) -> bool { + s.process.process() >= lightcraft_develop::Process::V6 +} + pub fn log_lum(c: [f32; 3]) -> f32 { (luminance_2020(c).max(1e-7) / crate::tone::GREY).log2() } @@ -811,6 +900,250 @@ pub fn airlight_of(mut v: Vec) -> f32 { #[cfg(test)] mod tests { + /// Edits saved under V1 to V5 keep main's colour noise reduction (blurred chromaticity); V6 gets + /// the joint method of `nrc_joint`. + #[test] + fn colour_nr_follows_the_process() { + use lightcraft_develop::{DevelopSettings, Process}; + let (w, h) = (96usize, 64usize); + let img = Rgb32f::from_fn(w, h, |x, y| { + let n = |c: u32| { + let mut v = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b) ^ c.wrapping_mul(0xc2b2_ae35) | 1; + v ^= v << 13; + v ^= v >> 17; + v ^= v << 5; + (v as f32 / u32::MAX as f32 - 0.5) * 0.02 + }; + let base = if x < w / 2 { [0.06, 0.03, 0.02] } else { [0.02, 0.04, 0.06] }; + [base[0] + n(1), base[1] + n(2), base[2] + n(3)] + }); + let run = |p: Process| { + let mut s = DevelopSettings { process: p.version(), ..Default::default() }; + s.detail.nr_color = 50.0; + let mut o = img.clone(); + denoise(&mut o, &s, 1.0, None); + o + }; + let (v1, v2, v5, v6) = (run(Process::V1), run(Process::V2), run(Process::V5), run(Process::V6)); + assert!(v1.data == v2.data && v2.data == v5.data, "V1 to V5 share main's colour NR"); + // main's colour NR clamps at 0 and keeps each pixel's luminance; the joint method keeps it too + assert!(v5.data != v6.data, "V6 takes the joint colour NR"); + let mut s = DevelopSettings { process: Process::V6.version(), ..Default::default() }; + s.detail.nr_color = 50.0; + let mut joint = img.clone(); + let p = nrc_params(&s, 1.0).expect("Color 50 has parameters"); + crate::nrc_joint::denoise(&mut joint, &p, (s.detail.nr_color_detail / 100.0) as f32, 0.5, None); + assert!(joint.data == v6.data, "V6 is the joint method"); + } + + /// Float mean of a flat, noisy dark patch over three noise realisations; linear modes assert drift bounds. + #[test] + #[ignore] + fn probe_nrc_mean_drift() { + use lightcraft_develop::DevelopSettings; + let (w, h) = (768usize, 768usize); + let mut worst = 0.0f64; + for seed0 in [0x2545_f491_4f6c_dd1du64, 0x9e37_79b9_7f4a_7c15, 0x1234_5678_9abc_def1] { + let mut seed = seed0; + let mut gauss = || { + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 + }) + .sum::() + * 1.732 + }; + for (name, base, sigma) in [ + ("dark warm, blue near 0", [0.006f32, 0.004, 0.0008], [0.002f32, 0.0015, 0.003]), + ("cat-like, red near 0", [0.0015, 0.004, 0.009], [0.004, 0.003, 0.005]), + ] { + let mut img = Rgb32f::new(w, h); + for p in img.data.iter_mut() { + *p = [0, 1, 2].map(|i| base[i] + sigma[i] * gauss()); + } + let mean = |im: &Rgb32f| { + let n = im.data.len() as f64; + [0, 1, 2].map(|i| im.data.iter().map(|p| p[i] as f64).sum::() / n) + }; + let m0 = mean(&img); + for nr in [25.0, 100.0] { + let mut s = DevelopSettings::default(); + s.detail.nr_color = nr; + let mut a = img.clone(); + denoise(&mut a, &s, 1.0, None); + let m = mean(&a); + let clipped0 = mean(&img.map(|p| p.map(|v| v.max(0.0)))); + let sd = |im: &Rgb32f, mm: [f64; 3]| { + [0, 1, 2].map(|i| (im.data.iter().map(|p| (p[i] as f64 - mm[i]).powi(2)).sum::() / im.data.len() as f64).sqrt()) + }; + worst = worst.max([0, 1, 2].iter().map(|&i| (m[i] / m0[i] - 1.0).abs()).fold(0.0, f64::max)); + println!( + "{name} NR {nr}: true mean {m0:.5?}, clipped noisy mean {clipped0:.5?}, after v2 {m:.5?} → {:+.3?} % vs true; noise sd {:.5?} → {:.5?}", + [0, 1, 2].map(|i| 100.0 * (m[i] / m0[i] - 1.0)), + sd(&img, m0), + sd(&a, m) + ); + } + } + } + println!("worst mean deviation {:.4} %", 100.0 * worst); + assert!(worst < 0.0005, "the joint colour NR moved a channel's mean by {:.3} %", 100.0 * worst); + } + + /// PROBE (prints, never fails): what colour NR v2 keeps of real colour. A clean synthetic scene (an + /// equal-luminance red/green edge, a 2 px red line on grey, a saturated blue patch near black, a flat grey + /// patch) plus noise; each measure compares the output with the clean scene. + #[test] + #[ignore] + fn probe_nrc_real_colour() { + use lightcraft_develop::DevelopSettings; + let (w, h) = (768usize, 512usize); + let y_of = |c: [f32; 3]| luminance_2020(c); + // two colours of the same luminance 0.03 + let red = [0.08f32, 0.0155, 0.02]; + let green = { + let g = [0.012f32, 0.04, 0.015]; + let k = y_of(red) / y_of(g); + g.map(|v| v * k) + }; + let grey = [0.03f32; 3]; + let blue_dark = [0.001f32, 0.0015, 0.02]; + // a bright saturated green next to black (a lit leaf against a dark background) + let leaf = [0.02f32, 0.12, 0.01]; + let clean = |x: usize, y: usize| -> [f32; 3] { + if y < 256 { + if x < 384 { red } else { green } + } else if x < 384 { + if (190..192).contains(&x) { red } else { grey } + } else if x < 576 { + blue_dark + } else if y < 384 { + grey + } else if x < 672 { + leaf + } else { + [0.0005f32; 3] + } + }; + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut gauss = || { + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 + }) + .sum::() + * 1.732 + }; + let mut img = Rgb32f::new(w, h); + for y in 0..h { + for x in 0..w { + let c = clean(x, y); + // shot + read noise per channel + img.data[y * w + x] = c.map(|v| v + (0.00002 + 0.004 * v.max(0.0)).sqrt() * 0.6 * gauss()); + } + } + let chroma = |c: [f32; 3]| { + let y = y_of(c); + c.map(|v| v - y) + }; + let dist = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); + for nr in [25.0, 100.0] { + let mut s = DevelopSettings::default(); + s.detail.nr_color = nr; + let mut o = img.clone(); + denoise(&mut o, &s, 1.0, None); + let px = |x: usize, y: usize| o.data[y * w + x]; + // edge: chroma error 1..8 px either side, relative to the step between the two colours + let step = dist(chroma(red), chroma(green)); + let mut e = 0.0; + let mut n = 0.0; + for y in 40..216 { + for d in 1..=8 { + for x in [384 - d, 383 + d] { + e += dist(chroma(px(x, y)), chroma(clean(x, y))); + n += 1.0; + } + } + } + // line: share of the line's chroma kept (mean over its rows) + let (mut kept, mut m) = (0.0, 0.0); + for y in 300..480 { + for x in 190..192 { + let c = chroma(px(x, y)); + let r = chroma(red); + let rg = chroma(grey); + let full = [0, 1, 2].map(|i| r[i] - rg[i]); + let got = [0, 1, 2].map(|i| c[i] - rg[i]); + kept += (got[0] * full[0] + got[1] * full[1] + got[2] * full[2]) / (full[0] * full[0] + full[1] * full[1] + full[2] * full[2]); + m += 1.0; + } + } + // saturated blue near black: chroma of the patch's mean kept + let mut acc = [0.0f32; 3]; + let mut cnt = 0.0; + for y in 300..480 { + for x in 420..540 { + acc = [0, 1, 2].map(|i| acc[i] + px(x, y)[i]); + cnt += 1.0; + } + } + let mean = acc.map(|v| v / cnt); + let sat_kept = dist(chroma(mean), [0.0; 3]) / dist(chroma(blue_dark), [0.0; 3]); + // grey: residual chroma noise + let mut sd = 0.0; + let mut k = 0.0; + for y in 270..370 { + for x in 600..760 { + sd += dist(chroma(px(x, y)), [0.0; 3]).powi(2); + k += 1.0; + } + } + let mut sd0 = 0.0; + for y in 270..370 { + for x in 600..760 { + sd0 += dist(chroma(img.data[y * w + x]), [0.0; 3]).powi(2); + } + } + // leaf next to black: chroma kept in the leaf's 12 px next to the black (mean over rows) + let (mut lk, mut ln) = (0.0f32, 0.0f32); + for y in 400..500 { + for x in 660..672 { + let c = chroma(px(x, y)); + let r = chroma(leaf); + lk += (c[0] * r[0] + c[1] * r[1] + c[2] * r[2]) / (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]); + ln += 1.0; + } + } + println!("NR {nr}: leaf next to black keeps {:.0} % of its chroma (12 px next to the black)", 100.0 * lk / ln); + println!( + "NR {nr}: edge error {:.1} % of the step | red line kept {:.0} % | dark blue chroma kept {:.0} % | grey chroma noise {:.5} → {:.5}", + 100.0 * e / n / step, + 100.0 * kept / m, + 100.0 * sat_kept, + (sd0 / k).sqrt(), + (sd / k).sqrt() + ); + } + } + + #[test] + fn nrc_noise_fit_is_non_negative() { + // a falling cloud would give a negative slope: the constant fits instead + let (a, b) = fit_nonneg_line(&[(0.0, 4.0, 1.0), (1.0, 3.0, 1.0), (2.0, 2.0, 1.0)]); + assert!(a == 0.0 && (b - 3.0).abs() < 1e-9); + // a line through a negative intercept: refitted through the origin + let (a, b) = fit_nonneg_line(&[(1.0, 1.0, 1.0), (2.0, 3.0, 1.0), (3.0, 5.0, 1.0)]); + assert!(a > 0.0 && b == 0.0); + // an exact shot + read noise line is found as it is + let (a, b) = fit_nonneg_line(&[(0.0, 2.0, 1.0), (1.0, 5.0, 1.0), (2.0, 8.0, 1.0)]); + assert!((a - 3.0).abs() < 1e-9 && (b - 2.0).abs() < 1e-9); + } use super::*; use lightcraft_color::cct::xy_to_uv; @@ -1057,7 +1390,7 @@ mod nr_tests { let (v0, m0) = var(&img); let mut s = DevelopSettings::default(); s.detail.nr_luminance = 80.0; - denoise(&mut img, &s, 1.0); + denoise(&mut img, &s, 1.0, None); let (v1, m1) = var(&img); assert!(v1 < v0 * 0.5, "{v0} -> {v1}"); assert!((m1 - m0).abs() < 0.01); diff --git a/crates/pipeline/src/nrc_joint.rs b/crates/pipeline/src/nrc_joint.rs new file mode 100644 index 0000000000..37a55d07fb --- /dev/null +++ b/crates/pipeline/src/nrc_joint.rs @@ -0,0 +1,1175 @@ +//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; +//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma +//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including +//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. + +use lightcraft_color::luminance_2020; +use lightcraft_raster::{Rgb32f, blur::gaussian, resample::Filter}; + +use crate::{ + for_rows, + local::{NrcNoise, NrcParams, fit_nonneg_line}, +}; + +#[derive(Clone, Copy, Debug)] +pub struct JointNoise { + pub model: NrcNoise, + /// Do not extrapolate beyond bands that contain usable noise measurements. + pub ymax: [f32; 3], + pub tolerance: f32, +} + +impl JointNoise { + pub fn var(&self, i: usize, y: f32) -> f32 { + self.model.var(i, y.min(self.ymax[i])) + } +} + +fn yuv(c: [f32; 3]) -> [f32; 3] { + let y = luminance_2020(c); + [y, c[0] - y, c[2] - y] +} + +/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance +/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. +/// Luminance bands with predominantly texture may only lower their weight in the fit: they +/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. +fn noise_model(img: &Rgb32f) -> JointNoise { + if img.width < 3 || img.height < 3 { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + let mut samples = Vec::new(); + push_samples(img, noise_sample_stride(img.len()), &mut samples); + noise_from_samples(samples) +} + +/// The noise samples of `img` (Y, R-Y, B-Y) every `stride` pixels, in pixel order (see [`noise_model`]). +fn push_samples(img: &Rgb32f, stride: usize, samples: &mut Vec) { + if img.width < 3 || img.height < 3 { + return; + } + for index in (0..img.len()).step_by(stride) { + let (x, y) = (index % img.width, index / img.width); + if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { + continue; + } + let Some(c) = img.data.get(index) else { continue }; + let mut residual = [[0.0f32; 3]; 3]; + let mut brightness = 0.0; + let mut valid = true; + for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { + // Tiny images use the nearest supported scale rather than extending an edge + // into the noise samples. + let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); + let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; + let mut m = [0.0f32; 3]; + for n in neighbours { + if let Some(p) = img.data.get(n) { + m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); + } + } + residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); + brightness += m[0] / 3.0; + valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); + } + if valid { + samples.push((brightness.max(0.0), residual)); + } + } +} + +/// Side of the tiles a frame's noise is measured on (px). +const TILE: usize = 128; +/// Tiles per row and column: many small tiles follow a mostly dark frame's few bright parts better +/// than a few large ones. +const GRID: usize = 12; + +/// The windows of a `full_w × full_h` frame its noise is measured on: the whole frame up to the +/// area of `GRID²` tiles, else `GRID × GRID` tiles spread evenly over it. A windowed render sees +/// only part of the frame; measured on these, every window of it gets the same noise model. +pub fn tiles(full_w: usize, full_h: usize) -> Vec { + if full_w * full_h <= GRID * GRID * TILE * TILE || full_w < 2 * TILE || full_h < 2 * TILE { + return vec![crate::PixelWindow { x: 0, y: 0, w: full_w, h: full_h }]; + } + let at = |n: usize, k: usize| ((n - TILE) as f64 * (k as f64 + 0.5) / GRID as f64).round() as usize; + (0..GRID * GRID).map(|k| crate::PixelWindow { x: at(full_w, k % GRID), y: at(full_h, k / GRID), w: TILE, h: TILE }).collect() +} + +/// The noise model of `tiles` of a frame (linear RGB at output scale, see [`tiles`]): the same +/// measurement as for a whole image, with the samples of all tiles together. +pub fn noise_of_tiles(tiles: &[Rgb32f]) -> JointNoise { + let transformed: Vec = tiles.iter().map(|t| t.map(yuv)).collect(); + let stride = noise_sample_stride(transformed.iter().map(Rgb32f::len).sum()); + let mut samples = Vec::new(); + for t in &transformed { + push_samples(t, stride, &mut samples); + } + if samples.is_empty() { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + noise_from_samples(samples) +} + +/// Distance between the noise samples of a `len`-pixel plane (CPU and GPU take the same pixels). +pub fn noise_sample_stride(len: usize) -> usize { + len.div_ceil(crate::local::NRC_SAMPLES).max(1) | 1 +} + +/// One noise sample: the mean brightness of its neighbourhoods and the squared high-pass residual of +/// Y, R−Y, B−Y at spacings 1, 2 and 4. +pub type NoiseSample = (f32, [[f32; 3]; 3]); + +/// The fitted noise model from the samples, in pixel order (see `noise_model`). +pub fn noise_from_samples(samples: Vec) -> JointNoise { + // Moving a slider re-renders the same image: the last fit is reused for identical samples (64-bit + // hash of their bits and count; the samples alone determine the fit). + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut hash = 0xcbf2_9ce4_8422_2325u64 ^ samples.len() as u64; + for s in &samples { + for v in std::iter::once(s.0).chain(s.1.iter().flatten().copied()) { + hash = (hash ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(5); + } + } + if let Some((h, noise)) = *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + && h == hash + { + return noise; + } + let noise = fit_noise(samples); + *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((hash, noise)); + noise +} + +fn fit_noise(samples: Vec) -> JointNoise { + // brightness order, ties in pixel order (as a stable sort): sort compact keys (the bits `total_cmp` + // compares by, then the index), then gather + let mut keys: Vec<(i32, u32)> = samples + .iter() + .enumerate() + .map(|(k, s)| { + let bits = s.0.to_bits() as i32; + (bits ^ (((bits >> 31) as u32) >> 1) as i32, k as u32) + }) + .collect(); + keys.sort_unstable(); + let samples: Vec = keys.iter().filter_map(|&(_, k)| samples.get(k as usize).copied()).collect(); + const BANDS: usize = 16; + let per = samples.len().div_ceil(BANDS).max(32); + let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); + let mut r: Vec = Vec::with_capacity(per); + for band in samples.chunks(per).filter(|b| b.len() >= 32) { + let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; + for (i, pts) in pts.iter_mut().enumerate() { + let mut variance = 1e-14f64; + for scale in 0..3 { + r.clear(); + r.extend(band.iter().map(|p| p.1[scale][i])); + let middle = r.len() / 2; + let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); + // Each kernel has norm squared 1.25. Larger spacings recover noise + // hidden by the positive spatial correlations of demosaiced RGB. + variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); + } + pts.push((y, variance, band.len() as f64)); + } + } + let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; + let mut ymax = [0.0; 3]; + for (i, pts) in pts.iter().enumerate() { + if pts.is_empty() { + continue; + } + let (a, b, top) = robust_line(pts); + ymax[i] = top; + model.alpha[i] = a as f32; + model.beta[i] = (b as f32).max(1e-14); + } + JointNoise { model, ymax, tolerance: 1.0 } +} + +/// The noise line `v = a·y + b` through the bands `(y, variance, weight)` and the brightest band it +/// rests on. Seeded from the darker half, then all bands with a bounded influence for unexpectedly +/// high residuals (foliage etc.); refit rather than clamp the intercept. +pub(crate) fn robust_line(pts: &[(f64, f64, f64)]) -> (f64, f64, f32) { + let (mut a, mut b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); + let mut ymax = 0.0; + for _ in 0..4 { + // A band's weight fades to 0 between 4 and 5 times the fitted noise instead of dropping at + // 4: a band at the bound must not flip in or out with the last bits of the samples (the + // GPU's differ from the CPU's there), which moved the fit by a few percent. + let weighted: Vec<_> = pts + .iter() + .filter_map(|&(y, v, w)| { + let excess = v / (a * y + b).max(1e-14); + let fade = (5.0 - excess).clamp(0.0, 1.0); + (fade > 0.0).then_some((y, v, w * (2.0 / excess.max(2.0)).powi(4) * fade)) + }) + .collect(); + if !weighted.is_empty() { + (a, b) = fit_nonneg_line(&weighted); + ymax = weighted.iter().map(|p| p.0 as f32).fold(0.0, f32::max); + } + } + (a, b, ymax) +} + +/// Squared distance beyond the expected noise in a difference of two guide samples. A small +/// relative luminance allowance lets a smooth surface exchange colour without crossing a +/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. +/// (The filter runs `distance_run`, the same operations over planes; this per-pair form is its test reference.) +#[cfg(test)] +fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { + let y = 0.5 * (a[0] + b[0]); + let allowance = (0.025 * y.max(0.0)).powi(2); + let terms: [f32; 3] = std::array::from_fn(|i| { + let v = noise.var(i, y); + let excess = ((a[i] - b[i]).powi(2) - v).max(0.0); + // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative + // allowance for correlations left by demosaicing and grid resampling. + // (A difference within the noise adds exactly 0: no division needed.) + if excess == 0.0 { 0.0 } else { excess / (3.0 * noise.tolerance * v + allowance) } + }); + terms.into_iter().sum::() +} + +/// The guide as three planes (Y, R−Y, B−Y): `distance_run` over them vectorises. +struct Planes { + c: [Vec; 3], + w: usize, +} + +impl Planes { + /// `len` pixels of row `y` from column `from`. + fn run(&self, y: usize, from: usize, len: usize) -> Option<[&[f32]; 3]> { + let start = y.checked_mul(self.w)?.checked_add(from)?; + let end = start.checked_add(len)?; + let [a, b, c] = &self.c; + Some([a.get(start..end)?, b.get(start..end)?, c.get(start..end)?]) + } +} + +/// `distance` of each pair of guide pixels `(a[k], b[k])` into `out[k]`, the same operations in the same +/// order (bit for bit), without branches so the compiler can work on several pixels at once. +fn distance_run(a: [&[f32]; 3], b: [&[f32]; 3], noise: &JointNoise, out: &mut [f32]) { + let ([ay, au, av], [by, bu, bv]) = (a, b); + let (alpha, beta, ymax, tolerance) = (noise.model.alpha, noise.model.beta, noise.ymax, noise.tolerance); + for ((((((o, &ay), &au), &av), &by), &bu), &bv) in out.iter_mut().zip(ay).zip(au).zip(av).zip(by).zip(bu).zip(bv) { + let y = 0.5 * (ay + by); + let allowance = (0.025 * y.max(0.0)).powi(2); + // `JointNoise::var`; an excess of 0 divides to exactly 0, as the branch in `distance` gives + let term = |i: usize, d: f32| { + let v = (alpha[i] * y.min(ymax[i]).max(0.0) + beta[i]).max(1e-14); + let excess = (d.powi(2) - v).max(0.0); + excess / (3.0 * tolerance * v + allowance) + }; + *o = term(0, ay - by) + term(1, au - bu) + term(2, av - bv); + } +} + +/// The exchange weight `exp(−max(distance, path))`; exactly 1 when both are 0 (no `exp` needed). +#[inline] +fn weight(distance: f32, path: f32) -> f32 { + let m = distance.max(path); + if m == 0.0 { 1.0 } else { (-m).exp() } +} + +/// `weight(distance, path)` with the path given as exp(−path): min(exp(−distance), that), and no `exp` +/// for a distance of 0. +#[inline] +fn path_weight(distance: f32, path: f32) -> f32 { + if distance == 0.0 { path } else { (-distance).exp().min(path) } +} + +/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur +/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or +/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. +/// Written straight into planes (see `Planes`), one row at a time without branches per pixel. +fn pilot(original: &Rgb32f, noise: &JointNoise) -> Planes { + use rayon::prelude::*; + let blurred = gaussian(original, 0.8); + let (w, h) = (original.width, original.height); + let mut planes = Planes { c: std::array::from_fn(|_| vec![0.0; original.len()]), w }; + let [py, pu, pv] = &mut planes.c; + py.par_chunks_mut(w.max(1)).zip(pu.par_chunks_mut(w.max(1))).zip(pv.par_chunks_mut(w.max(1))).enumerate().for_each_init( + Vec::new, + |out: &mut Vec<[f32; 3]>, (y, ((ry, ru), rv))| { + let Some(blur) = blurred.data.get(y * w..(y + 1) * w) else { return }; + out.clear(); + out.extend_from_slice(blur); + if y > 0 + && y + 1 < h + && let (Some(up), Some(mid), Some(down)) = + (original.data.get((y - 1) * w..y * w), original.data.get(y * w..(y + 1) * w), original.data.get((y + 1) * w..(y + 2) * w)) + { + // columns 1 .. w − 1: the pixel, its left/right (axis 0) and upper/lower (axis 1) neighbours + for (((o, win), &u), &d) in out.iter_mut().skip(1).zip(mid.windows(3)).zip(up.iter().skip(1)).zip(down.iter().skip(1)) { + let &[l, p, r] = win else { continue }; + let var: [f32; 3] = std::array::from_fn(|i| 9.0 * noise.var(i, p[0])); + let axis = |a: [f32; 3], b: [f32; 3]| { + let m: [f32; 3] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); + let t = |i: usize| ((a[i] - m[i]).powi(2) + (p[i] - m[i]).powi(2) + (b[i] - m[i]).powi(2)) / var[i]; + (m, t(0) + t(1) + t(2)) + }; + let (mh, vh) = axis(l, r); + let (mv, vvar) = axis(u, d); + *o = pilot_pick(*o, mh, vh, mv, vvar); + } + } + for (((c, y), u), v) in out.iter().zip(ry.iter_mut()).zip(ru.iter_mut()).zip(rv.iter_mut()) { + (*y, *u, *v) = (c[0], c[1], c[2]); + } + }, + ); + planes +} + +/// The pilot at one pixel from its isotropic blur `o`, the horizontal mean `mh` and noise-normalised +/// variance `vh`, and the vertical ones `mv`, `vvar`: the mean along the clearly smoother axis where +/// the other is more than 4 times as rough (and above 4), the blur where neither is. The choice fades +/// in between 0.8 and 1.25 times that bound instead of switching at it, so a pixel near the bound +/// takes nearly the same pilot when the noise model moves by a hair. +pub(crate) fn pilot_pick(o: [f32; 3], mh: [f32; 3], vh: f32, mv: [f32; 3], vvar: f32) -> [f32; 3] { + let sv = smoothstep(0.8, 1.25, vh / 4.0f32.max(4.0 * vvar)); + let sh = smoothstep(0.8, 1.25, vvar / 4.0f32.max(4.0 * vh)); + if sv >= 1.0 { + mv + } else if sh >= 1.0 { + mh + } else { + std::array::from_fn(|i| o[i] + (mv[i] - o[i]) * sv + (mh[i] - o[i]) * sh) + } +} + +/// The two chroma components `R − Y`, `B − Y`, or a pair of per-axis values (horizontal, vertical). +type Pair = [f32; 2]; +type PairImage = lightcraft_raster::Image; + +fn rgb2(y: f32, uv: Pair) -> [f32; 3] { + let r = y + uv[0]; + let b = y + uv[1]; + [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] +} + +/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the +/// guide is never replaced by the filtered result. Long taps also account for the intervening +/// guide edges, so a wide pass cannot jump over a thin differently coloured object. +/// +/// Per pixel: `out = p`, then the lower neighbour's exchange, then the upper one's, in that order +/// (the order the result depends on, bit for bit). +fn diffuse(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, vertical: bool, rate: f32) { + if vertical { diffuse_v(src, dst, links, delta, rate) } else { diffuse_h(src, dst, links, delta, rate) } +} + +#[inline(always)] +fn exchange(out: &mut Pair, p: Pair, q: Pair, weight: f32) { + out[0] += weight * (q[0] - p[0]); + out[1] += weight * (q[1] - p[1]); +} + +fn diffuse_h(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { + let w = src.width; + for_rows(&mut dst.data, w, |y, out| { + let (Some(s), Some(l)) = (src.data.get(y * w..(y + 1) * w), links.data.get(y * w..(y + 1) * w)) else { return }; + for (x, o) in out.iter_mut().enumerate() { + let p = s[x]; + *o = p; + if x >= delta { + exchange(o, p, s[x - delta], rate * l[x - delta][0]); + } + if x + delta < w { + exchange(o, p, s[x + delta], rate * l[x][0]); + } + } + }); +} + +fn diffuse_v(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { + let (w, h) = (src.width, src.height); + for_rows(&mut dst.data, w, |y, out| { + let Some(s) = src.data.get(y * w..(y + 1) * w) else { return }; + out.copy_from_slice(s); + if y >= delta + && let (Some(up), Some(lu)) = (src.data.get((y - delta) * w..(y - delta + 1) * w), links.data.get((y - delta) * w..(y - delta + 1) * w)) + { + for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(up).zip(lu) { + exchange(o, p, q, rate * lk[1]); + } + } + if y + delta < h + && let (Some(down), Some(ld)) = (src.data.get((y + delta) * w..(y + delta + 1) * w), links.data.get(y * w..(y + 1) * w)) + { + for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(down).zip(ld) { + exchange(o, p, q, rate * lk[1]); + } + } + }); +} + +/// The diffusion scales for a final spatial `sigma` (in grid pixels) on a `w × h` grid: each step's +/// neighbour distance and rate, in order. CPU and GPU run exactly these. +pub fn scale_plan(sigma: f32, w: usize, h: usize) -> Vec<(usize, f32)> { + let mut plan = Vec::new(); + let mut remaining = sigma * sigma; + let mut delta = 1usize; + while remaining > 0.01 && delta <= w.max(h) { + let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); + plan.push((delta, rate)); + remaining -= 4.0 * rate * (delta as f32).powi(2); + delta = delta.saturating_mul(2); + } + plan +} + +/// Share of the filtered colour at Color `amount` (0..=1): a ramp up to the default 25. +pub fn strength(amount: f32) -> f32 { + (4.0 * amount).clamp(0.0, 1.0) +} + +/// Edge tolerance at Color Detail `detail` (0..=1). +pub fn tolerance(detail: f32) -> f32 { + (1.5 - detail).clamp(0.5, 1.5) +} + +/// The speck brake at Color `amount` (0..=1): the chroma excess (in noise variances of the two chroma +/// components together) from which a pixel starts to count as a colour speck (fully at twice that), and +/// the largest share of its colour that is replaced. Weak at the default 25 (only extreme specks, at most +/// half), stronger up to 100. Below 25 the final blend (`strength`) fades it out with the rest. +pub fn speck_brake(amount: f32) -> SpeckBrake { + let t = ((amount - 0.25) / 0.75).clamp(0.0, 1.0); + SpeckBrake { threshold: 64.0 - 39.0 * t, share: 0.5 + 0.5 * t } +} + +/// See [`speck_brake`]; `share` 0 turns the brake off. +#[derive(Clone, Copy, Debug)] +pub struct SpeckBrake { + pub threshold: f32, + pub share: f32, +} + +impl SpeckBrake { + pub const OFF: SpeckBrake = SpeckBrake { threshold: f32::INFINITY, share: 0.0 }; +} + +/// The median (mean of the middle two) of 8 values, by an optimal 19-comparator sorting network +/// (the GPU kernel uses the same one). +fn median8(v: [f32; 8]) -> f32 { + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = v; + let cmp = |x: &mut f32, y: &mut f32| { + let (lo, hi) = (x.min(*y), x.max(*y)); + (*x, *y) = (lo, hi); + }; + cmp(&mut a, &mut c); + cmp(&mut b, &mut d); + cmp(&mut e, &mut g); + cmp(&mut f, &mut h); + cmp(&mut a, &mut e); + cmp(&mut b, &mut f); + cmp(&mut c, &mut g); + cmp(&mut d, &mut h); + cmp(&mut a, &mut b); + cmp(&mut c, &mut d); + cmp(&mut e, &mut f); + cmp(&mut g, &mut h); + cmp(&mut c, &mut e); + cmp(&mut d, &mut f); + cmp(&mut b, &mut e); + cmp(&mut d, &mut g); + cmp(&mut b, &mut c); + cmp(&mut d, &mut e); + cmp(&mut f, &mut g); + let _ = (a, b, c, f, g, h); + 0.5 * (d + e) +} + +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) +} + +/// How much of a pixel's chroma the speck brake replaces by the median of the ring around it, and that +/// median (Y, R−Y, B−Y), from the pixel `p`, the ring `ring` and the rest of the 5 × 5 border `rest`. A +/// speck stands out in colour far beyond the noise, but not in luminance (a star, a lit point or any real +/// small detail almost always has a luminance step), and it is compact: the colour shift does not reach +/// the border (a line or an edge carries it on). Demosaicing spreads high-ISO specks over 2 × 2 to +/// 3 × 3 pixels, which all lie inside. The noise is taken at the ring's mean luminance (a median of it +/// is only needed for the few pixels past the threshold). +fn speck_share(p: [f32; 3], ring: &[[f32; 3]; 8], rest: impl Iterator, noise: &JointNoise, brake: SpeckBrake) -> (f32, [f32; 3]) { + let y = ring.iter().map(|q| q[0]).sum::() / 8.0; + let (vu, vv) = (noise.var(1, y), noise.var(2, y)); + // The medians lie between the ring's least and largest value, so the farther of the two bounds the + // excess from above (rounding keeps that order): most pixels are decided without the medians. + let reach = |c: usize| { + let (lo, hi) = ring.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), q| (lo.min(q[c]), hi.max(q[c]))); + (p[c] - lo).abs().max((p[c] - hi).abs()) + }; + let (bu, bv) = (reach(1), reach(2)); + if bu * bu / vu + bv * bv / vv <= brake.threshold { + return (0.0, [0.0; 3]); + } + let m = [0.0, median8(ring.map(|q| q[1])), median8(ring.map(|q| q[2]))]; + let (du, dv) = (p[1] - m[1], p[2] - m[2]); + let excess = du * du / vu + dv * dv / vv; + if excess <= brake.threshold { + return (0.0, m); + } + let m = [median8(ring.map(|q| q[0])), m[1], m[2]]; + // luminance: full brake up to half the chroma excess, none from 1.5 times it + let dy = p[0] - m[0]; + let luminance = dy * dy / noise.var(0, y); + let alone = ((1.5 * excess - luminance) / excess).clamp(0.0, 1.0); + if alone <= 0.0 { + return (0.0, m); + } + // compactness: the second largest share of the pixel's colour shift that a border pixel also has (a + // line or an edge through the pixel crosses the border at least twice; one noisy border pixel that + // happens to lean the same way does not protect a speck) + let (_, second) = ring + .iter() + .copied() + .chain(rest) + .map(|q| ((q[1] - m[1]) * du / vu + (q[2] - m[2]) * dv / vv) / excess) + .fold((0.0f32, 0.0f32), |(a, b), s| if s > a { (s, a) } else { (a, b.max(s)) }); + let compact = ((0.8 - second) / 0.3).clamp(0.0, 1.0); + (brake.share * smoothstep(brake.threshold, 2.0 * brake.threshold, excess) * alone * compact, m) +} + +/// Replace the chroma of compact colour specks by that of their surroundings (see `speck_share`), in the +/// transformed image (Y, R−Y, B−Y); luminance is never touched. Runs before the guide is built, so a speck +/// is neither kept by the edge-aware weights nor spread by them. +fn despeck(img: &mut Rgb32f, noise: &JointNoise, brake: SpeckBrake) { + use rayon::prelude::*; + if brake.share <= 0.0 || img.width < 5 || img.height < 5 { + return; + } + let (w, h) = (img.width, img.height); + let source = &*img; + // few pixels change: collect their new chroma per row from the unchanged image, then write them + let changes: Vec> = (2..h - 2) + .into_par_iter() + .map(|y| { + let mut changed = Vec::new(); + let rows: [Option<&[[f32; 3]]>; 5] = std::array::from_fn(|k| source.data.get((y + k - 2) * w..(y + k - 1) * w)); + let [Some(r0), Some(r1), Some(r2), Some(r3), Some(r4)] = rows else { return changed }; + for (x, ((((w0, w1), w2), w3), w4)) in + r0.windows(5).zip(r1.windows(5)).zip(r2.windows(5)).zip(r3.windows(5)).zip(r4.windows(5)).enumerate() + { + let (&[a0, a1, a2, a3, a4], &[b0, _, _, _, b4], &[c0, _, p, _, c4], &[d0, _, _, _, d4], &[e0, e1, e2, e3, e4]) = (w0, w1, w2, w3, w4) + else { + continue; + }; + // the ring: corners and edge centres of the 5 × 5 square, far enough that a speck spread over + // its direct neighbours by demosaicing does not reach them; the rest of the border: with the + // ring, every thin line or edge through the pixel crosses at least one of the 16 at any angle + let ring = [a0, a2, a4, c0, c4, e0, e2, e4]; + let rest = [a1, a3, b0, b4, d0, d4, e1, e3]; + let (k, m) = speck_share(p, &ring, rest.into_iter(), noise, brake); + if k > 0.0 { + changed.push((y * w + x + 2, [p[1] + k * (m[1] - p[1]), p[2] + k * (m[2] - p[2])])); + } + } + changed + }) + .collect(); + for (index, uv) in changes.into_iter().flatten() { + if let Some(o) = img.data.get_mut(index) { + (o[1], o[2]) = (uv[0], uv[1]); + } + } +} + +/// `noise`: the frame's noise model (see [`noise_of_tiles`]); `None` measures it on `img`. +pub(crate) fn denoise(img: &mut Rgb32f, params: &NrcParams, detail: f32, amount: f32, noise: Option<&JointNoise>) { + // Continuous ramp from zero; from the ordinary default Color=25 onward the spatial + // scale controls the extra smoothing. Noise calibration and edge decisions stay fixed. + denoise_with(img, params, 1, detail, strength(amount), speck_brake(amount), noise); +} + +#[cfg(test)] +fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake) { + denoise_with(img, params, step, detail, strength, brake, None); +} + +fn denoise_with(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake, noise: Option<&JointNoise>) { + if img.is_empty() || strength <= 0.0 { + return; + } + let start = crate::profiling().then(std::time::Instant::now); + // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid + // grew to 16x with the radius, making the colour loss inseparable from slider strength. + let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; + let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); + // Transform before resampling; negative linear differences are valid throughout. + let mut original = Rgb32f::new(w, h); + if step == 1 { + // the generic loop below with one sample per pixel, same operations (0 + c, / 1) + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + if let Some(&c) = img.data.get(y * w + x) { + let c = yuv(c); + *p = c.map(|v| (0.0f32 + v) / 1.0f32); + } + } + }); + } else { + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let mut count = 0.0f32; + for sy in y * step..((y + 1) * step).min(img.height) { + for sx in x * step..((x + 1) * step).min(img.width) { + if let Some(&c) = img.data.get(sy * img.width + sx) { + let c = yuv(c); + *p = std::array::from_fn(|i| p[i] + c[i]); + count += 1.0; + } + } + } + *p = p.map(|v| v / count.max(1.0)); + } + }); + } + let lap = |what: &str, t: &mut Option| { + if let Some(t0) = t { + eprintln!(" joint {what}: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3); + *t = Some(std::time::Instant::now()); + } + }; + let mut tt = start; + lap("transform", &mut tt); + let mut noise = match noise { + Some(n) => *n, + None => noise_model(&original), + }; + lap("noise model", &mut tt); + noise.tolerance = tolerance(detail); + despeck(&mut original, &noise, brake); + lap("speck brake", &mut tt); + let planes = pilot(&original, &noise); + lap("pilot", &mut tt); + if start.is_some() { + eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax); + } + // Working buffers carry the two chroma components only (Y is restored from the image at the end). + let mut filtered: PairImage = original.map(|p| [p[1], p[2]]); + // the full-resolution reconstruction reads Y from `img`: the transformed copy is no longer needed + let original = (step != 1).then_some(original); + let mut scratch = PairImage::new(w, h); + let mut paths = PairImage::new(w, h); + let mut links = PairImage::new(w, h); + // Direct neighbours: the path over one step is the pair's own distance, and its weight is exp(−distance). + // `paths` holds exp(−path), the largest distance along a path, exponentiated: exp(−max(a, b)) is + // min(exp(−a), exp(−b)) bit for bit (exp is monotonic), so longer paths take minima and a weight with + // a new distance of 0 needs no `exp`; a path of 0 (no pair, at the border) is 1. + // the distances of row `y` to the pixels `offset` to the right and `offset` rows down + let row_distances = |y: usize, offset: usize, dh: &mut Vec, dv: &mut Vec| { + let n = w.saturating_sub(offset); + dh.resize(w, 0.0); + dv.resize(w, 0.0); + if let (Some(a), Some(b), Some(out)) = (planes.run(y, 0, n), planes.run(y, offset, n), dh.get_mut(..n)) { + distance_run(a, b, &noise, out); + } + if y + offset < h + && let (Some(a), Some(b)) = (planes.run(y, 0, w), planes.run(y + offset, 0, w)) + { + distance_run(a, b, &noise, dv); + } + }; + { + use rayon::prelude::*; + paths.data.par_chunks_mut(w).zip(links.data.par_chunks_mut(w)).enumerate().for_each_init( + || (Vec::new(), Vec::new()), + |(dh, dv), (y, (prow, lrow))| { + row_distances(y, 1, dh, dv); + for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { + *link = [0.0; 2]; + *out = [1.0; 2]; + if x + 1 < w { + link[0] = weight(d0, d0); + out[0] = link[0]; + } + if y + 1 < h { + link[1] = weight(d1, d1); + out[1] = link[1]; + } + } + }, + ); + } + lap("links 1", &mut tt); + // Scale is independent of the edge decision. K has no role in deciding whether a leaf + // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. + let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); + let plan = scale_plan(sigma, w, h); + for (k, &(delta, rate)) in plan.iter().enumerate() { + for _ in 0..2 { + diffuse(&filtered, &mut scratch, &links, delta, false, rate); + std::mem::swap(&mut filtered, &mut scratch); + diffuse(&filtered, &mut scratch, &links, delta, true, rate); + std::mem::swap(&mut filtered, &mut scratch); + } + lap(&format!("scale {delta}"), &mut tt); + let Some(&(next, _)) = plan.get(k + 1) else { break }; + // In one pass: paths of length 2·delta (from the two adjacent delta-length paths, read from + // `paths`, written to `scratch`) and the next scale's pair weights from them. + { + use rayon::prelude::*; + let old = &paths; + scratch.data.par_chunks_mut(w).zip(links.data.par_chunks_mut(w)).enumerate().for_each_init( + || (Vec::new(), Vec::new()), + |(dh, dv), (y, (prow, lrow))| { + row_distances(y, next, dh, dv); + let (Some(here), below) = (old.data.get(y * w..(y + 1) * w), old.data.get((y + delta) * w..(y + delta + 1) * w)) else { return }; + for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { + let Some(&p) = here.get(x) else { continue }; + *out = p; + if x + delta < w + && let Some(q) = here.get(x + delta) + { + out[0] = out[0].min(q[0]); + } + if y + delta < h + && let Some(q) = below.and_then(|b| b.get(x)) + { + out[1] = out[1].min(q[1]); + } + *link = [0.0; 2]; + if x + next < w { + link[0] = path_weight(d0, out[0]); + } + if y + next < h { + link[1] = path_weight(d1, out[1]); + } + } + }, + ); + } + std::mem::swap(&mut paths, &mut scratch); + } + drop(scratch); + drop(paths); + drop(links); + match &original { + None => { + let fw = img.width; + for_rows(&mut img.data, fw, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let Some(&q) = filtered.data.get(y * w + x) else { continue }; + let result = rgb2(luminance_2020(*p), q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } + Some(original) => { + // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted + // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. + let mean = gaussian(original, 1.0); + let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); + let share = corr.zip_map(&mean, |c, m| { + let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; + [snr / (snr + 8.0); 3] + }); + let share = gaussian(&share, 0.8); + // Resize one output row at a time using the raster resampler's exact pixel centres. + use lightcraft_raster::resample::weights; + let ux = weights(w, img.width, Filter::Bilinear); + let uy = weights(h, img.height, Filter::Bilinear); + let ow = img.width; + for_rows(&mut img.data, ow, |y, row| { + let Some((y0, wy)) = uy.get(y) else { return }; + for (x, p) in row.iter_mut().enumerate() { + let Some((x0, wx)) = ux.get(x) else { continue }; + let (mut f, mut o, mut a) = ([0.0; 2], [0.0; 3], 0.0); + for (j, &dy) in wy.iter().enumerate() { + for (i, &dx) in wx.iter().enumerate() { + let index = (y0 + j) * w + x0 + i; + if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { + let weight = dx * dy; + f = std::array::from_fn(|c| f[c] + weight * q[c]); + o = std::array::from_fn(|c| o[c] + weight * r[c]); + a += weight * s[0]; + } + } + } + let c = yuv(*p); + let q = [f[0] + a * (c[1] - o[1]), f[1] + a * (c[2] - o[2])]; + let result = rgb2(c[0], q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } + } + if let Some(start) = start { + eprintln!(" nr joint: {:.1} ms", start.elapsed().as_secs_f64() * 1e3); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::local::NrcPass; + + fn params(step: usize) -> NrcParams { + NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 4.0, step, k: 64.0, pct: 0.2 }, NrcPass { sigma: 12.0, step, k: 64.0, pct: 0.2 }] } + } + + fn noisy(clean: &Rgb32f, seed: u64, sigma: f32) -> Rgb32f { + let mut result = clean.clone(); + let mut seed = seed; + for p in &mut result.data { + for v in p { + let mut n = 0.0; + for _ in 0..4 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + n += (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5; + } + *v += sigma * 1.732 * n; + } + } + result + } + + /// The optimised filter reproduces the reference implementation (8b89526d) bit for bit: same scales, + /// weights, paths and reconstruction, only fewer passes and smaller buffers. + #[test] + fn joint_matches_the_reference_bit_for_bit() { + let mut scene = Rgb32f::new(97, 83); + for (i, p) in scene.data.iter_mut().enumerate() { + let (x, y) = (i % 97, i / 97); + // edges, a thin line, a dark patch and a gradient + *p = if x < 30 { + [0.08, 0.016, 0.02] + } else if x < 32 { + [0.01, 0.05, 0.01] + } else if y < 40 { + [0.0015, 0.004, 0.009] + } else { + [0.02 + 0.001 * x as f32, 0.03, 0.01 + 0.0005 * y as f32] + }; + } + for (w, h) in [(97usize, 83usize), (96, 82), (5, 3), (1, 7)] { + let mut clean = Rgb32f::new(w, h); + for y in 0..h { + for x in 0..w { + clean.data[y * w + x] = scene.data[y * 97 + x]; + } + } + for seed in [0x2545_f491_4f6c_dd1d, 0x9e37_79b9_7f4a_7c15] { + let input = noisy(&clean, seed, 0.004); + for step in [1, 2] { + for (detail, strength, sigma) in [(0.5, 1.0, 12.0), (0.25, 0.6, 4.0), (0.9, 1.0, 27.0)] { + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma, step, k: 64.0, pct: 0.2 }] }; + let (mut a, mut b) = (input.clone(), input.clone()); + denoise_grid(&mut a, &p, step, detail, strength, SpeckBrake::OFF); + crate::nrc_joint_reference::denoise_grid(&mut b, &p, step, detail, strength); + for (i, (x, y)) in a.data.iter().zip(&b.data).enumerate() { + for c in 0..3 { + assert!( + x[c].to_bits() == y[c].to_bits(), + "{w}x{h} step {step} sigma {sigma}: pixel {i} channel {c}: {} vs {}", + x[c], + y[c] + ); + } + } + } + } + } + } + } + + /// BENCH (ignored, prints): the optimised filter against the reference on the same 24 MP image, + /// interleaved so both see the same machine load. Median of 3 each. + #[test] + #[ignore] + fn bench_joint_against_reference() { + let (w, h) = (6000usize, 4000usize); + let mut clean = Rgb32f::new(w, h); + for (i, p) in clean.data.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + *p = if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }; + } + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; + let (mut new, mut old) = (Vec::new(), Vec::new()); + for _ in 0..3 { + let mut a = input.clone(); + let t = std::time::Instant::now(); + denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); + new.push(t.elapsed().as_secs_f64()); + let mut b = input.clone(); + let t = std::time::Instant::now(); + crate::nrc_joint_reference::denoise_grid(&mut b, &p, 1, 0.5, 1.0); + old.push(t.elapsed().as_secs_f64()); + } + new.sort_by(f64::total_cmp); + old.sort_by(f64::total_cmp); + println!("joint 24 MP: optimised {:.2} s, reference {:.2} s (medians of {new:.2?} / {old:.2?})", new[1], old[1]); + } + + /// BENCH (ignored, prints): fitting the noise model to 130 000 samples (a 33 MP image's), median of 5. + #[test] + #[ignore] + fn bench_noise_fit() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 + }; + let samples: Vec = (0..130_000) + .map(|_| { + let y = rnd() * 0.3; + (y, std::array::from_fn(|_| std::array::from_fn(|_| (1e-5 + 1e-4 * y) * rnd() * 2.0))) + }) + .collect(); + let mut times: Vec = (0..5) + .map(|_| { + let s = samples.clone(); + let t = std::time::Instant::now(); + let model = fit_noise(s); + assert!(model.model.beta[0] > 0.0); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(f64::total_cmp); + println!("noise fit, 130 000 samples: {:.1} ms (of {times:.1?})", times[2]); + } + + /// BENCH (ignored, prints): the speck brake alone against the whole joint filter on one 24 MP image, + /// interleaved. Median of 3 each. + #[test] + #[ignore] + fn bench_speck_brake() { + let (w, h) = (6000usize, 4000usize); + let clean = Rgb32f::from_fn(w, h, |x, y| if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; + let transformed = input.map(yuv); + let noise = noise_model(&transformed); + let (mut brake, mut joint) = (Vec::new(), Vec::new()); + for _ in 0..3 { + let mut out = transformed.clone(); + let t = std::time::Instant::now(); + despeck(&mut out, &noise, speck_brake(1.0)); + brake.push(t.elapsed().as_secs_f64()); + let mut a = input.clone(); + let t = std::time::Instant::now(); + denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); + joint.push(t.elapsed().as_secs_f64()); + } + brake.sort_by(f64::total_cmp); + joint.sort_by(f64::total_cmp); + println!("24 MP: speck brake {:.3} s, joint without it {:.2} s (medians of {brake:.3?} / {joint:.2?})", brake[1], joint[1]); + } + + #[test] + fn joint_keeps_negative_means_luminance_and_reduces_chroma_noise() { + for (w, h) in [(128, 96), (127, 95), (1, 19), (19, 1)] { + let clean = Rgb32f::filled(w, h, [0.006, 0.004, 0.0008]); + for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { + let input = noisy(&clean, seed, 0.003); + for step in [1, 2] { + let mut output = input.clone(); + denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); + assert!(output.data.iter().flatten().all(|v| v.is_finite())); + for (a, b) in input.data.iter().zip(&output.data) { + assert!((luminance_2020(*a) - luminance_2020(*b)).abs() < 1e-7); + } + // Thin inputs cannot support a spatial noise estimate; finite/luminance + // checks above still apply, but their sample mean is too noisy for this bound. + if w < 3 || h < 3 { + continue; + } + for c in 0..3 { + let difference = input.data.iter().zip(&output.data).map(|(a, b)| (b[c] - a[c]) as f64).sum::() / input.len() as f64; + assert!(difference.abs() < 2e-6, "step {step}, {w}x{h}, mean error {difference}"); + } + let energy = |im: &Rgb32f| { + im.data + .iter() + .map(|&p| { + let p = yuv(p); + let c = yuv(clean.data[0]); + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) + }) + .sum::() + / im.len() as f32 + }; + assert!(energy(&output) < 0.08 * energy(&input)); + assert!(output.data.iter().any(|p| p.iter().any(|&v| v < 0.0)), "negative values were clipped"); + } + } + } + } + + #[test] + fn joint_protects_leaf_and_isoluminant_edges_without_chroma_halos() { + let leaf = [0.02, 0.12, 0.01]; + let black = [0.0005; 3]; + let red = [0.08, 0.0155, 0.02]; + let mut green = [0.012, 0.04, 0.015]; + let gain = luminance_2020(red) / luminance_2020(green); + green = green.map(|v| v * gain); + for (left, right) in [(leaf, black), (red, green)] { + let clean = Rgb32f::from_fn(192, 128, |x, _| if x < 96 { left } else { right }); + for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { + let input = noisy(&clean, seed, 0.003); + for step in [1, 2] { + let mut output = input.clone(); + denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); + let step_uv = [yuv(left)[1] - yuv(right)[1], yuv(left)[2] - yuv(right)[2]]; + let length = step_uv.iter().map(|v| v * v).sum::().sqrt(); + for x in [92, 93, 98, 99] { + let mut mean = [0.0; 3]; + for y in 16..112 { + let p = yuv(output.get(x, y)); + mean = std::array::from_fn(|i| mean[i] + p[i] / 96.0); + } + let expected = yuv(if x < 96 { left } else { right }); + let error = ((mean[1] - expected[1]).powi(2) + (mean[2] - expected[2]).powi(2)).sqrt() / length; + assert!(error < 0.08, "step {step}, x {x}, colour error {}%", 100.0 * error); + } + } + } + } + } + + #[test] + fn joint_noise_fit_does_not_treat_bright_texture_as_shot_noise() { + let clean = Rgb32f::from_fn(256, 192, |x, y| { + let l = if x < 192 { 0.003 + x as f32 * 0.00002 } else { 0.15 + if (x + y) % 2 == 0 { 0.08 } else { -0.08 } }; + [l; 3] + }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.002).map(yuv); + let model = noise_model(&input); + for i in 0..3 { + assert!(model.var(i, 0.15) < 5.0 * model.var(i, 0.005), "texture dominated noise fit: {model:?}"); + } + } + + #[test] + fn joint_keeps_a_two_pixel_isoluminant_line() { + let grey = [0.03; 3]; + let mut red = [0.08, 0.0155, 0.02]; + let gain = luminance_2020(grey) / luminance_2020(red); + red = red.map(|v| v * gain); + let clean = Rgb32f::from_fn(192, 128, |x, _| if (94..96).contains(&x) { red } else { grey }); + let mut output = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.006); + denoise_grid(&mut output, ¶ms(1), 1, 0.5, 1.0, speck_brake(1.0)); + let reference = yuv(red); + let mut mean = [0.0; 3]; + for y in 16..112 { + for x in 94..96 { + let p = yuv(output.get(x, y)); + mean = std::array::from_fn(|i| mean[i] + p[i] / 192.0); + } + } + let kept = (mean[1] * reference[1] + mean[2] * reference[2]) / (reference[1].powi(2) + reference[2].powi(2)); + assert!(kept > 0.85, "thin line keeps only {}%", 100.0 * kept); + } + + #[test] + fn joint_estimates_correlated_noise_at_a_matching_scale() { + let clean = Rgb32f::filled(256, 192, [0.03; 3]); + let correlated = gaussian(&noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.012), 0.8).map(yuv); + let model = noise_model(&correlated); + for i in 0..3 { + let mean = correlated.data.iter().map(|p| p[i] as f64).sum::() / correlated.len() as f64; + let variance = correlated.data.iter().map(|p| (p[i] as f64 - mean).powi(2)).sum::() / correlated.len() as f64; + let predicted = model.var(i, 0.03) as f64; + assert!(predicted > 0.6 * variance && predicted < 1.6 * variance, "channel {i}: estimated {predicted}, actual {variance}"); + } + } + + /// The speck brake takes the colour out of a compact, isoluminant 2 × 2 speck (as demosaicing leaves + /// them at high ISO), more at Color 100 than at 25, but leaves a coloured star (a luminance peak) alone. + #[test] + fn noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound() { + // The luminance bands of a 640-px preview of demo scene 0 after luminance NR. Its band at + // 0.593 sat at 4 times the first fit: the CPU's samples put it just above, the GPU's just + // below, and the fits came out 2.6 % apart (CPU and GPU renders then differed by 10 levels). + let mut pts: Vec<(f64, f64, f64)> = [ + (0.009, 5.028e-7), + (0.022, 1.554e-4), + (0.063, 1.459e-4), + (0.147, 9.728e-6), + (0.213, 2.701e-5), + (0.272, 5.077e-6), + (0.315, 3.236e-5), + (0.356, 2.531e-5), + (0.390, 5.329e-6), + (0.420, 4.924e-6), + (0.467, 5.453e-5), + (0.530, 1.823e-5), + (0.593, 0.0), + (0.648, 1.501e-8), + (0.667, 1.898e-8), + (0.996, 3.490e-7), + ] + .map(|(y, v)| (y, v, 5649.0)) + .to_vec(); + let (a, b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); + let bound = 4.0 * (a * 0.593 + b); + let mut fit = |k: f64| { + pts[12].1 = bound * k; + robust_line(&pts) + }; + let (below, above) = (fit(1.0 - 1e-6), fit(1.0 + 1e-6)); + assert!((below.1 / above.1 - 1.0).abs() < 1e-4, "{below:?} vs {above:?}"); + assert!((below.0 - above.0).abs() <= 1e-4 * below.0.abs().max(1e-12), "{below:?} vs {above:?}"); + } + + #[test] + fn speck_brake_removes_compact_colour_specks_but_not_stars() { + let dark = [0.004f32; 3]; + let mut magenta = [0.024, 0.0, 0.024]; + magenta[1] = (luminance_2020(dark) - 0.2627 * magenta[0] - 0.0593 * magenta[2]) / 0.6780; + let star = [0.3, 0.2, 0.1]; + let clean = Rgb32f::from_fn(128, 96, |x, y| match (x, y) { + (40..42, 40..42) => magenta, + (90..92, 40..42) => star, + _ => dark, + }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.001); + // share of the object's chroma (against the background) left in its 2 × 2 pixels + let kept = |out: &Rgb32f, x0: usize, colour: [f32; 3]| { + let (r, b) = (yuv(colour), yuv(dark)); + let reference = [r[1] - b[1], r[2] - b[2]]; + let mut mean = [0.0f32; 2]; + for (x, y) in [(x0, 40), (x0 + 1, 40), (x0, 41), (x0 + 1, 41)] { + let p = yuv(out.get(x, y)); + mean = [mean[0] + 0.25 * (p[1] - b[1]), mean[1] + 0.25 * (p[2] - b[2])]; + } + (mean[0] * reference[0] + mean[1] * reference[1]) / (reference[0].powi(2) + reference[1].powi(2)) + }; + let run = |brake| { + let mut out = input.clone(); + denoise_grid(&mut out, ¶ms(1), 1, 0.5, 1.0, brake); + (kept(&out, 40, magenta), kept(&out, 90, star)) + }; + let (off, star_off) = run(SpeckBrake::OFF); + let (weak, _) = run(speck_brake(0.25)); + let (strong, star_strong) = run(speck_brake(1.0)); + assert!(off > 0.5, "without the brake the speck keeps {off}"); + assert!(weak < 0.8 * off && strong < 0.2, "speck kept: off {off}, at 25 {weak}, at 100 {strong}"); + assert!(strong < weak, "the brake is stronger at 100 ({strong}) than at 25 ({weak})"); + assert!((star_strong - star_off).abs() < 0.02, "star colour {star_off} -> {star_strong}"); + } + + /// `distance_run` (planes, no branches) gives `distance` bit for bit. + #[test] + fn distance_run_matches_distance() { + let clean = Rgb32f::from_fn(64, 3, |x, _| [0.002 * x as f32, 0.01, 0.03 - 0.0004 * x as f32]); + let img = noisy(&clean, 0x9e37_79b9_7f4a_7c15, 0.01).map(yuv); + let mut noise = noise_model(&noisy(&Rgb32f::filled(64, 64, [0.02; 3]), 7, 0.004).map(yuv)); + noise.tolerance = 0.7; + let planes = Planes { c: std::array::from_fn(|i| img.data.iter().map(|p| p[i]).collect()), w: 64 }; + let mut out = vec![0.0; 64]; + distance_run(planes.run(0, 0, 64).unwrap(), planes.run(2, 0, 64).unwrap(), &noise, &mut out); + for (x, d) in out.iter().enumerate() { + assert_eq!(d.to_bits(), distance(img.get(x, 0), img.get(x, 2), &noise).to_bits(), "pixel {x}"); + } + } +} diff --git a/crates/pipeline/src/nrc_joint_reference.rs b/crates/pipeline/src/nrc_joint_reference.rs new file mode 100644 index 0000000000..13e2c46b95 --- /dev/null +++ b/crates/pipeline/src/nrc_joint_reference.rs @@ -0,0 +1,352 @@ +//! TEST ONLY: the joint colour NR as of 8b89526d, kept as the reference the optimised `nrc_joint` +//! must reproduce bit for bit. Changed since only where `nrc_joint` changed its result on purpose: +//! the noise line's outlier bands fade out (`nrc_joint::robust_line`) and the pilot's axis choice +//! fades in (`nrc_joint::pilot_pick`). +//! +//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; +//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma +//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including +//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. + +use lightcraft_color::luminance_2020; +use lightcraft_raster::{Rgb32f, blur::gaussian, resample::Filter}; + +use crate::{ + for_rows, + local::{NrcNoise, NrcParams}, +}; + +#[derive(Debug)] +struct JointNoise { + model: NrcNoise, + /// Do not extrapolate beyond bands that contain usable noise measurements. + ymax: [f32; 3], + tolerance: f32, +} + +impl JointNoise { + fn var(&self, i: usize, y: f32) -> f32 { + self.model.var(i, y.min(self.ymax[i])) + } +} + +fn yuv(c: [f32; 3]) -> [f32; 3] { + let y = luminance_2020(c); + [y, c[0] - y, c[2] - y] +} + +fn rgb(y: f32, uv: [f32; 3]) -> [f32; 3] { + let r = y + uv[1]; + let b = y + uv[2]; + [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] +} + +/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance +/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. +/// Luminance bands with predominantly texture may only lower their weight in the fit: they +/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. +fn noise_model(img: &Rgb32f) -> JointNoise { + const BANDS: usize = 16; + let mut samples = Vec::new(); + let stride = img.len().div_ceil(crate::local::NRC_SAMPLES).max(1) | 1; + if img.width < 3 || img.height < 3 { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + for index in (0..img.len()).step_by(stride) { + let (x, y) = (index % img.width, index / img.width); + if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { + continue; + } + let Some(c) = img.data.get(index) else { continue }; + let mut residual = [[0.0f32; 3]; 3]; + let mut brightness = 0.0; + let mut valid = true; + for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { + // Tiny images use the nearest supported scale rather than extending an edge + // into the noise samples. + let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); + let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; + let mut m = [0.0f32; 3]; + for n in neighbours { + if let Some(p) = img.data.get(n) { + m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); + } + } + residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); + brightness += m[0] / 3.0; + valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); + } + if valid { + samples.push((brightness.max(0.0), residual)); + } + } + samples.sort_by(|a, b| a.0.total_cmp(&b.0)); + let per = samples.len().div_ceil(BANDS).max(32); + let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); + for band in samples.chunks(per).filter(|b| b.len() >= 32) { + let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; + for (i, pts) in pts.iter_mut().enumerate() { + let mut variance = 1e-14f64; + for scale in 0..3 { + let mut r: Vec = band.iter().map(|p| p.1[scale][i]).collect(); + let middle = r.len() / 2; + let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); + // Each kernel has norm squared 1.25. Larger spacings recover noise + // hidden by the positive spatial correlations of demosaiced RGB. + variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); + } + pts.push((y, variance, band.len() as f64)); + } + } + let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; + let mut ymax = [0.0; 3]; + for (i, pts) in pts.iter().enumerate() { + if pts.is_empty() { + continue; + } + // Seed from the darker half, then include all bands with a bounded influence for + // unexpectedly high residuals (foliage etc.). Refit rather than clamp the intercept. + let (a, b, top) = crate::nrc_joint::robust_line(pts); + ymax[i] = top; + model.alpha[i] = a as f32; + model.beta[i] = (b as f32).max(1e-14); + } + JointNoise { model, ymax, tolerance: 1.0 } +} + +/// Squared distance beyond the expected noise in a difference of two guide samples. A small +/// relative luminance allowance lets a smooth surface exchange colour without crossing a +/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. +fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { + let y = 0.5 * (a[0] + b[0]); + let allowance = (0.025 * y.max(0.0)).powi(2); + (0..3) + .map(|i| { + let v = noise.var(i, y); + // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative + // allowance for correlations left by demosaicing and grid resampling. + ((a[i] - b[i]).powi(2) - v).max(0.0) / (3.0 * noise.tolerance * v + allowance) + }) + .sum::() +} + +/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur +/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or +/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. +fn pilot(original: &Rgb32f, noise: &JointNoise) -> Rgb32f { + let mut guide = gaussian(original, 0.8); + let (w, h) = (original.width, original.height); + for_rows(&mut guide.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + if x == 0 || y == 0 || x + 1 == w || y + 1 == h { + continue; + } + let index = y * w + x; + let Some(&p) = original.data.get(index) else { continue }; + let mut means = [[0.0f32; 3]; 2]; + let mut variances = [0.0; 2]; + for (axis, offset) in [1, w].into_iter().enumerate() { + let (Some(&a), Some(&b)) = (original.data.get(index - offset), original.data.get(index + offset)) else { continue }; + means[axis] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); + variances[axis] = (0..3) + .map(|i| { + let m = means[axis][i]; + ((a[i] - m).powi(2) + (p[i] - m).powi(2) + (b[i] - m).powi(2)) / (9.0 * noise.var(i, p[0])) + }) + .sum::(); + } + *out = crate::nrc_joint::pilot_pick(*out, means[0], variances[0], means[1], variances[1]); + } + }); + guide +} + +/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the +/// guide is never replaced by the filtered result. Long taps also account for the intervening +/// guide edges, so a wide pass cannot jump over a thin differently coloured object. +fn diffuse(src: &Rgb32f, dst: &mut Rgb32f, links: &Rgb32f, delta: usize, vertical: bool, rate: f32) { + let (w, h) = (src.width, src.height); + for_rows(&mut dst.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&p) = src.data.get(index) else { continue }; + *out = p; + let coordinate = if vertical { y } else { x }; + let length = if vertical { h } else { w }; + for neighbour in [coordinate.checked_sub(delta), coordinate.checked_add(delta).filter(|&v| v < length)].into_iter().flatten() { + let ni = if vertical { neighbour * w + x } else { y * w + neighbour }; + let start = coordinate.min(neighbour); + let pi = if vertical { start * w + x } else { y * w + start }; + let (Some(&q), Some(link)) = (src.data.get(ni), links.data.get(pi)) else { continue }; + let weight = rate * link[usize::from(vertical)]; + for i in 1..3 { + out[i] += weight * (q[i] - p[i]); + } + } + } + }); +} + +pub(crate) fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32) { + if img.is_empty() || strength <= 0.0 { + return; + } + let start = crate::profiling().then(std::time::Instant::now); + // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid + // grew to 16x with the radius, making the colour loss inseparable from slider strength. + let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; + let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); + // Transform before resampling; negative linear differences are valid throughout. + let mut original = Rgb32f::new(w, h); + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let mut count = 0.0f32; + for sy in y * step..((y + 1) * step).min(img.height) { + for sx in x * step..((x + 1) * step).min(img.width) { + if let Some(&c) = img.data.get(sy * img.width + sx) { + let c = yuv(c); + *p = std::array::from_fn(|i| p[i] + c[i]); + count += 1.0; + } + } + } + *p = p.map(|v| v / count.max(1.0)); + } + }); + let lap = |what: &str, t: &mut Option| { + if let Some(t0) = t { + eprintln!(" joint {what}: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3); + *t = Some(std::time::Instant::now()); + } + }; + let mut tt = start; + lap("transform", &mut tt); + let mut noise = noise_model(&original); + lap("noise model", &mut tt); + noise.tolerance = (1.5 - detail).clamp(0.5, 1.5); + let guide = pilot(&original, &noise); + lap("pilot", &mut tt); + if std::env::var_os("NRV2_DEBUG").is_some() { + eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax); + } + let mut filtered = original.clone(); + let mut scratch = Rgb32f::new(w, h); + let mut paths = Rgb32f::new(w, h); + let mut links = Rgb32f::new(w, h); + for_rows(&mut paths.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&g) = guide.data.get(index) else { continue }; + if x + 1 < w + && let Some(&b) = guide.data.get(index + 1) + { + out[0] = distance(g, b, &noise); + } + if y + 1 < h + && let Some(&b) = guide.data.get(index + w) + { + out[1] = distance(g, b, &noise); + } + } + }); + // Scale is independent of the edge decision. K has no role in deciding whether a leaf + // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. + let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); + let mut remaining = sigma * sigma; + let mut delta = 1usize; + while remaining > 0.01 && delta <= w.max(h) { + let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); + // Each symmetric pair weight is evaluated once per scale and reused by both + // diffusion sweeps and both ends of the pair. + for_rows(&mut links.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let (Some(&g), Some(path)) = (guide.data.get(index), paths.data.get(index)) else { continue }; + *out = [0.0; 3]; + for (axis, offset, valid) in [(0, delta, x + delta < w), (1, delta * w, y + delta < h)] { + if valid && let Some(&other) = guide.data.get(index + offset) { + out[axis] = (-distance(g, other, &noise).max(path[axis])).exp(); + } + } + } + }); + for _ in 0..2 { + diffuse(&filtered, &mut scratch, &links, delta, false, rate); + std::mem::swap(&mut filtered, &mut scratch); + diffuse(&filtered, &mut scratch, &links, delta, true, rate); + std::mem::swap(&mut filtered, &mut scratch); + } + remaining -= 4.0 * rate * (delta as f32).powi(2); + // Maxima over paths of length 2*delta, using the two adjacent delta-length paths. + // Reuse the diffusion scratch so a long tap costs O(1), irrespective of radius. + for_rows(&mut scratch.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&p) = paths.data.get(index) else { continue }; + *out = p; + if x + delta < w + && let Some(q) = paths.data.get(index + delta) + { + out[0] = out[0].max(q[0]); + } + if y + delta < h + && let Some(q) = paths.data.get(index + delta * w) + { + out[1] = out[1].max(q[1]); + } + } + }); + std::mem::swap(&mut paths, &mut scratch); + lap(&format!("scale {delta}"), &mut tt); + delta = delta.saturating_mul(2); + } + drop(scratch); + drop(paths); + drop(links); + if step == 1 { + for (p, q) in img.data.iter_mut().zip(&filtered.data) { + let result = rgb(luminance_2020(*p), *q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + } else { + // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted + // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. + let mean = gaussian(&original, 1.0); + let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); + let share = corr.zip_map(&mean, |c, m| { + let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; + [snr / (snr + 8.0); 3] + }); + let share = gaussian(&share, 0.8); + // Resize one output row at a time using the raster resampler's exact pixel centres. + use lightcraft_raster::resample::weights; + let ux = weights(w, img.width, Filter::Bilinear); + let uy = weights(h, img.height, Filter::Bilinear); + let ow = img.width; + for_rows(&mut img.data, ow, |y, row| { + let Some((y0, wy)) = uy.get(y) else { return }; + for (x, p) in row.iter_mut().enumerate() { + let Some((x0, wx)) = ux.get(x) else { continue }; + let (mut f, mut o, mut a) = ([0.0; 3], [0.0; 3], 0.0); + for (j, &dy) in wy.iter().enumerate() { + for (i, &dx) in wx.iter().enumerate() { + let index = (y0 + j) * w + x0 + i; + if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { + let weight = dx * dy; + f = std::array::from_fn(|c| f[c] + weight * q[c]); + o = std::array::from_fn(|c| o[c] + weight * r[c]); + a += weight * s[0]; + } + } + } + let c = yuv(*p); + let q = std::array::from_fn(|i| f[i] + a * (c[i] - o[i])); + let result = rgb(c[0], q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } + if let Some(start) = start { + eprintln!(" nr joint: {:.1} ms", start.elapsed().as_secs_f64() * 1e3); + } +} diff --git a/crates/pipeline/src/output.rs b/crates/pipeline/src/output.rs index 09f2bbe6a4..b514c25503 100644 --- a/crates/pipeline/src/output.rs +++ b/crates/pipeline/src/output.rs @@ -364,6 +364,27 @@ impl DeepImage { } out } + + /// Crop to `[x0, x0+w) × [y0, y0+h)` (clamped to the image). + pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Self { + let x0 = x0.min(self.width); + let y0 = y0.min(self.height); + let w = w.min(self.width - x0); + let h = h.min(self.height - y0); + fn rows(v: &[T], width: usize, x0: usize, y0: usize, w: usize, h: usize) -> Vec { + let mut out = Vec::with_capacity(3 * w * h); + for y in y0..y0 + h { + let at = 3 * (y * width + x0); + out.extend_from_slice(v.get(at..at + 3 * w).unwrap_or_default()); + } + out + } + let samples = match &self.samples { + DeepSamples::U16(v) => DeepSamples::U16(rows(v, self.width, x0, y0, w, h)), + DeepSamples::F32(v) => DeepSamples::F32(rows(v, self.width, x0, y0, w, h)), + }; + Self { width: w, height: h, space: self.space, samples } + } } trait IntoRgba { diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index cee4ec1ffb..f1229bd569 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -845,6 +845,48 @@ fn sliver_crops_render_quickly_with_wide_stages_on() { } } +// Given a cached render with one process, a change to a process with another colour filter (Update +// to Current Process, undo) renders like a fresh render, not the cached denoised image +#[test] +fn a_process_change_does_not_reuse_the_other_colour_filter() { + use crate::{StageCache, render_cached}; + use lightcraft_develop::Process; + use std::sync::Arc; + let src = Arc::new(colour_noise_scene(128, 96, 128)); + let info = SourceInfo::default(); + let req = RenderRequest::fit(128, 96); + let cache = StageCache::default(); + let mut old = DevelopSettings::default(); + old.detail.nr_color = 25.0; + old.detail.nr_color_smoothness = 0.0; + old.process = Process::V2.version(); + let current = DevelopSettings { process: Process::LATEST.version(), ..old.clone() }; + let first = render_cached(&src, &info, &old, &req, &cache).image; + let fresh = render(&src, &info, ¤t, &req).image; + assert!(max_diff(&first, &fresh) > 0, "the two colour filters differ on this scene"); + assert_eq!(render_cached(&src, &info, ¤t, &req, &cache).image, fresh, "process update"); + assert_eq!(render_cached(&src, &info, &old, &req, &cache).image, first, "undo"); +} + +/// Flat grey with chroma noise: `quiet` columns on the left with little noise, the rest with much. +pub(crate) fn colour_noise_scene(w: usize, h: usize, quiet: usize) -> Rgb32f { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut noise = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + ((seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5) * 2.0 + }; + let mut img = Rgb32f::new(w, h); + for (i, p) in img.data.iter_mut().enumerate() { + let sigma = if i % w < quiet { 0.001 } else { 0.015 }; + let y = 0.04f32; + let (r, b) = (y + noise() * sigma, y + noise() * sigma); + *p = [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b]; + } + img +} + /// A crop of no width used to give grain NaN coordinates (and NaN pixels); the render stays finite. #[test] fn zero_width_crop_with_grain_renders_finite_pixels() { diff --git a/crates/pipeline/src/tests_nr_scale.rs b/crates/pipeline/src/tests_nr_scale.rs index 3247422fa5..c7dd86db2b 100644 --- a/crates/pipeline/src/tests_nr_scale.rs +++ b/crates/pipeline/src/tests_nr_scale.rs @@ -70,14 +70,14 @@ fn rms_chroma(a: &Rgb32f, b: &Rgb32f) -> f32 { fn preview_error(s: &DevelopSettings, scales: &[f32], metric: fn(&Rgb32f, &Rgb32f) -> f32) -> Vec<(f32, f32, f32)> { let src = noisy_scene(0.15); let mut full = src.clone(); - denoise(&mut full, s, 1.0); + denoise(&mut full, s, 1.0, None); scales .iter() .map(|&k| { let reference = scaled(&full, k); let plain = scaled(&src, k); let mut preview = plain.clone(); - denoise(&mut preview, s, k); + denoise(&mut preview, s, k, None); (k, metric(&preview, &reference), metric(&plain, &reference)) }) .collect() diff --git a/crates/pipeline/src/tests_window.rs b/crates/pipeline/src/tests_window.rs index 0d7508bc20..e5fb6ea801 100644 --- a/crates/pipeline/src/tests_window.rs +++ b/crates/pipeline/src/tests_window.rs @@ -422,6 +422,46 @@ fn auto_mask_strokes_match_the_whole_render() { check_noisy("auto mask", &s, PixelWindow { x: 400, y: 300, w: 300, h: 250 }, 2, 0.1); } +// Given the joint colour NR, a window is filtered with the whole frame's noise model: a quiet part of +// the frame does not make a window of its noisy part (or the other way round) smooth differently +#[test] +fn joint_colour_nr_measures_the_noise_of_the_whole_frame() { + let mut s = DevelopSettings::default(); + s.detail.nr_color = 25.0; + s.detail.nr_color_smoothness = 0.0; + // a frame that is one noise tile, and one of many tiles (`nrc_joint::tiles`) + for (w, h, win) in [(768, 128, PixelWindow { x: 640, y: 32, w: 64, h: 64 }), (1664, 1536, PixelWindow { x: 1400, y: 700, w: 128, h: 128 })] { + let src = crate::tests::colour_noise_scene(w, h, w * 2 / 3); + let req = RenderRequest::fit(w, h); + let f = render(&src, &SourceInfo::default(), &s, &req).image; + let part = render(&src, &SourceInfo::default(), &s, &RenderRequest { window: Some(win), ..req }).image; + let (max, mean) = compare_inset(&f, &part, win, win.w / 4); + assert!(max <= 2 && mean <= 0.1, "{w}×{h}: max {max}, mean {mean:.3}"); + } +} + +// Given a 16-bit or float render of a window with the joint colour NR, then its edges are the whole +// render's too: the window is grown by the filter's reach and cut back +#[test] +fn a_deep_window_with_colour_noise_reduction_matches_the_whole_render() { + use crate::OutputDepth; + let (w, h, win) = (768, 128, PixelWindow { x: 600, y: 32, w: 96, h: 64 }); + let src = crate::tests::colour_noise_scene(w, h, w * 2 / 3); + let mut s = DevelopSettings::default(); + s.detail.nr_color = 25.0; + s.detail.nr_color_smoothness = 0.0; + for depth in [OutputDepth::U16, OutputDepth::F32Linear] { + let req = RenderRequest { depth, ..RenderRequest::fit(w, h) }; + let deep = |req: &RenderRequest| render(&src, &SourceInfo::default(), &s, req).deep.map(|d| d.to_rgba8()); + let (Some(f), Some(part)) = (deep(&req), deep(&RenderRequest { window: Some(win), ..req })) else { + panic!("{depth:?}: no deep image"); + }; + assert_eq!((part.width, part.height), (win.w, win.h), "{depth:?}: the window's own size"); + let (max, mean) = compare_inset(&f, &part, win, 0); + assert!(max <= 1 && mean <= 0.01, "{depth:?}: max {max}, mean {mean:.3}"); + } +} + /// The margin the loupe's windows carry around what they show at this size (`region::margin_for`: /// 4.5 % of the long edge). const OVERLAY_INSET: usize = W * 45 / 1000; diff --git a/docs/nr-color-joint.md b/docs/nr-color-joint.md new file mode 100644 index 0000000000..d31c598e17 --- /dev/null +++ b/docs/nr-color-joint.md @@ -0,0 +1,64 @@ +# Colour NR: joint guide + +From process V6 (`docs/process-versions.md`) colour noise reduction uses this method on the CPU +(`crates/pipeline/src/nrc_joint.rs`) and the GPU (`crates/gpu/src/wgsl/nrcj.wgsl`, in bands of rows +whose halo covers the filter's reach). Edits on V1 and V2 keep the blurred chromaticity. The history +of the method, including the square-root and per-channel variants it replaced, is in +`docs/nr-color-v2-history.md`. + +## Method + +- Filter signed, linear `R-Y` and `B-Y`, with original Rec.2020 luminance restored at each + pixel. No channel clipping, root transform or Jensen correction is used in this filter. +- Estimate Y/chroma noise from median squared high-pass residuals at spacings 1, 2 and 4. + Larger spacings account for positive correlations from demosaicing. Fit equal-count + luminance bands with nonnegative coefficients, reject texture-dominated outliers and + stop extrapolating beyond the bands supported by usable noise measurements. +- Speck brake (before the guide): a pixel whose chroma stands out from the median of the 8 + pixels at distance 2 by more than a threshold (in noise variances), whose luminance step is + small against that colour step, and whose colour shift does not reach the 16-pixel border of + its 5 × 5 square at two places (a line or an edge through it always does) gets its chroma moved + towards that median. + Threshold 64 and at most half at Color 25, threshold 25 and fully at 100. Luminance is never + changed, so a bright point (a star) keeps its brightness and, by the luminance test, its colour. +- Make a fixed, lightly denoised guide. At a clear directional edge, average along the + smoother axis; this keeps thin isoluminant lines visible to the guide. +- Apply conservative, symmetric colour exchanges at increasing spatial scales. The two + chroma components have identical neighbour weights. Subtract the expected noise from + guide distances; luminance texture cannot simply increase the raw-pixel retention factor. + Long taps also check the guide edges between their endpoints. +- Symmetric exchanges preserve channel sums on the full-resolution grid, including its + borders. This does not promise identical means inside arbitrary cropped regions. +- Colour amount controls the radius and ramps the filtered contribution continuously from + zero to the normal default of 25. Colour Detail changes edge tolerance; Smoothness changes + radius (`local::nrc_params`: the coarse reach is three times `(2 + 10 · Color) · (1 + Smoothness)` + px at full size, scaled with the output). +- Windowed 8-bit renders request extra surrounding pixels for the diffusion's spatial + dependencies. The existing window/full-frame comparison retains its original tolerance. +- The noise model belongs to the whole frame, not to the pixels a render holds + (`lightcraft_pipeline::colour_noise`). A frame larger than 12 × 12 tiles of 128 px is measured + on that grid of tiles spread over it (`nrc_joint::tiles`), resampled, tone-mapped, white-balanced and + luminance-denoised like the frame (retouching and defringe are left out); a smaller frame + rendered whole is measured on itself, a window of it on the whole frame. So a loupe window + is filtered like the same pixels of the full render or the export + (`joint_colour_nr_measures_the_noise_of_the_whole_frame`). The model is kept in the stage + cache with the image before the noise reduction: moving a colour slider does not measure again. +- The stage cache keys the denoised image by the colour filter in use, so a change of process + (Update to Current Process, undo) never reuses the other filter's result + (`a_process_change_does_not_reuse_the_other_colour_filter`). + +## Local checks + +```sh +cargo test --release -p lightcraft-pipeline --lib nrc_joint +cargo test --release -p lightcraft-pipeline --lib probe_nrc -- --ignored --nocapture +cargo test --release -p lightcraft-gpu --test equivalence +LIGHTCRAFT_GPU=0 cargo run --release -p lightcraft-cli -- render INPUT.ARW -o OUTPUT.png --set detail.nrColor=100 +``` + +`LIGHTCRAFT_PROFILE=1` prints the filter's steps and times and the fitted Y/R-Y/B-Y model. + +The regression tests cover signed dark means, luminance, chroma-noise reduction, leaf/black and +isoluminant edges, a two-pixel isoluminant line, structured highlights, spatially correlated noise, +the speck brake (specks removed, stars kept) and the routing by process (`colour_nr_follows_the_process`). +`nrc_joint_reference.rs` keeps an earlier version of the filter for bit-for-bit checks of later speedups. diff --git a/docs/nr-color-v2-history.md b/docs/nr-color-v2-history.md new file mode 100644 index 0000000000..5f92ab806e --- /dev/null +++ b/docs/nr-color-v2-history.md @@ -0,0 +1,183 @@ +# Colour noise reduction V2: what was tried, measured and dropped + +Prototype branch `nr-color-v2` for storytold/lightcraft#815 (dark-scene colour noise also in #820). This file +records every approach that was tried, including the ones that failed on quality or speed, so later work does +not repeat them. Method details of the current version: [`nr-color-joint.md`](nr-color-joint.md). All numbers +are our own measurements (October 2026); test files: the two ILCE-7M4 raws from #820 ("candle", ISO 3200; +"cat", ISO 25600) and own Sony α77 II / α99 II raws. + +## Summary + +| Version | Idea | Outcome | +|---|---|---| +| main (V1) | chroma as `rgb / Y`, plain Gaussian, mixed in by `t = amount·(1 − detail/2)` | weak at 25, colour fringes at 100, blows up near black | +| V2 "root" | `√(c+off) − √(Y+off)`, self-guided filter, ε from a global 20 % quantile | strong at 25, but **shifts dark-area colour** (clipping), loses edge chroma at ISO 25600, preview ≠ export | +| V2 "linear" | `c − Y`, additive, noise model `σ² = α·Y + β` | mean colour fixed, but **desaturated textured colour** (−48 % leaf chroma at 100) | +| **V2 "joint" (current)** | linear R−Y / B−Y, shared edge-aware weights, multi-scale diffusion with path maxima, measured noise | colour kept, no fringes; on GPU 0.2–0.4 s on a current card; known limits below | + +## 1. V2 "root" + +- Reviewer measurements (#815): blue −25…−45 % in dark patches already at 25, green/cyan cast at ISO 25600, + up to −57 % chroma at colour edges at ISO 25600, the blue shift flips sign between 1600 px and full size. +- **Jensen correction** (add the removed variance back when squaring): only ~3 points better + (−37.6 → −34.4 %). Not the main cause. +- **Float test without 8-bit clipping** (`probe_nrc_mean_drift`): a channel near 0 gains **+90 %** + (0.00080 → 0.00152), almost exactly what rectifying negative noise gives (0.00165). Cause: `v.max(0.0)` in + `nrc_chroma` and `.max(0.0)` in `nrc_recombine`. +- **Measurement pitfall:** comparisons against an 8-bit Color 0 render are biased, because that reference is + itself clipped (a channel near 0 is lifted by rectified noise). Re-rendering at +2.5 EV does not remove the + bias (noise and mean scale together). Check means in float. + +## 2. V2 "linear" (`c − Y`) + +Mean kept within 0.05 % in float (3 seeds × 2 patches × 2 strengths). Noise model fitted per channel on +equal-count luminance bands with a truly non-negative fit (`fit_nonneg_line`). Synthetic checks +(`probe_nrc_real_colour`): an isoluminant red/green edge, a 2 px red line on grey, saturated blue near black, +a flat grey patch, later a bright leaf next to black. + +| Tried | Result | +|---|---| +| per channel, K 16 | dark blue 99 % kept (root: 69 %), but the thin line only 27 % (root: 78 %); compare only at equal residual noise | +| **shared weights** (one `a` for all channels) | **worse** than per channel: edge error 12.7 % vs 9.6 %, line 52 % vs 59 % at equal noise | +| luminance guide in the shared mode | no measurable effect (the test line is isoluminant on purpose) | +| coarse pass with the same K | destroys thin lines (94 % without coarse pass, but too much residual noise) | +| coarse pass with K × 0.1 | synthetic fine, **real ISO 25600 file far too weak** (spread 13.3 vs 6.0): real noise is blotchy after demosaicing | +| coarse pass smoothing only the coarse part | line survives (75–86 %); the cat needs K 128 to match root V2, then the line drops to 37 % | +| **per channel, K 64, coarse-only (shipped in a test package)** | **failed:** lit leaves at Color 100 keep only **52 %** of their chroma (V1 96 %, root 98 %); the synthetic leaf test (95 %) did **not** catch it | +| luminance guide per channel | leaves 92 %, but flat dark areas less smoothed (cat 10.6 vs 6.0): luminance noise counted as structure | + +Pitfalls of this phase: flat-patch selection used interleaved columns instead of spatial quadrants (fixed); +environment knobs read per pixel made the linear mode 11× slower (fixed: read once); a CLI not rebuilt after +changing defaults measured the old mode; renders without the #858 fix showed white dots in every variant; +background load from other jobs made single timings useless (compare in one process, interleaved). + +## 3. V2 "joint" (current) + +- Results at Color 25 / 100 (cat: spread / blotch in flat dark patches; candle: chroma of the lit leaves): + + | | Cat 25 | Cat 100 | Leaves 25 / 100 | + |---|---|---|---| + | V1 | 14.8 / 5.5 | – | 100 % / 96 % | + | root V2 | 5.1 / 1.8 | 3.4 / 0.6 | 99 % / 97 % | + | **joint** | 6.5 / 2.8 | 6.1 / 2.4 | 97 % / 97 % | + +- Dark-area mean colour against the Color 0 render (8-bit, see the pitfall above): cat R −14 % at 25 and 100 + (V1 −13 % at 25, −51 % at 100; root V2 −43 %). +- `tests_window::noise_reduction_does_not_depend_on_the_window` passes (root and linear V2 failed it). + +### Known limits + +- Specks that the speck brake leaves (section 3a): ones with their own luminance step (they stay as + grey or bright dots, as in V1) and, at Color 25, all but the strongest (on purpose, see below). +- Flat dark areas are smoothed somewhat less than by root V2 (cat spread 6.5 vs 5.1 at 25). +- The Color slider changes little above 25 (the blend is complete at 25; only the reach grows). To us 25 already + removes the visible colour noise. +- Prototype switches (`NRV2_*`, `LIGHTCRAFT_NR_V2`) instead of a process version; debug output; a test-only copy + of an earlier version (`nrc_joint_reference.rs`) for bit-exactness checks. + +## 3a. Speck brake + +Isolated, strongly coloured pixels in dark areas (a red, a blue speck) were treated as real detail by the +edge-aware weights and stayed visible at Color 100, while V1's blind blur largely removed them. Measured on +dumps of the transformed image (`NRV2_DUMP`) of the two #820 files: + +- The specks are not single pixels at ISO 25600: demosaicing spreads them over 2 × 2 to 3 × 3 pixels. A first + test "no direct neighbour shares the colour shift" therefore protected them; the brake now asks whether the + shift reaches the 16-pixel border of the 5 × 5 square (any thin line or edge through the pixel does). +- In the centre of the remaining cat specks the chroma excess is 250–1500 noise variances, the luminance step + 0.02–0.17 of it, the border share ≤ 0.4: all three tests pass clearly. What stays visible afterwards is a grey + or bright dot (luminance noise, as in V1). +- Real noise has far heavier tails than a Gaussian: 570 000 pixels of the candle exceed 36 (a Gaussian: 0.5). + A threshold of 12 at Color 100 also moved the mean of a synthetic flat patch (2.2e-6, the test allows 2e-6); + now 64 at 25 and 25 at 100, at most half the colour replaced at 25. + +- First compactness rule "the largest border share stays below 0.6": one noisy border pixel leaning the same + way protected a speck (the three dots below a lit leaf tip in the candle file: border shares 0.44 and 0.71 + kept two of them). Now the **second** largest share decides (0.5 → full brake, 0.8 → none): a line or an + edge through the pixel always crosses the border at least twice. + +| Full-size, 8-bit, against the same build without the brake | Joint | with brake | +|---|---|---| +| Leaves (candle), C* at 25 / 100 | 97 % / 97 % | 97 % / 98 % | +| Cat dark mean R / G / B at 100 | −14.1 / +1.2 / +6.7 % | −11.9 / +2.0 / +2.9 % | +| Candle dark mean B at 25 / 100 | −26.1 / −26.0 % | −26.4 / −29.8 % | +| Cat flat dark spread / blotch at 25 | 6.46 / 2.78 | 5.81 / 2.57 | +| Cat flat dark spread / blotch at 100 | 6.11 / 2.37 | 4.17 / 1.47 | +| Candle flat dark spread / blotch at 100 | 4.67 / 3.13 | 4.10 / 2.97 | + +Crops of the 10 most visible specks per file: blue specks on black become grey at 100, a magenta speck in +orange almost disappears, the three dots below the candle's leaf tip go except for faint dark traces +(luminance); at 25 they are only weakened. The largest changes in bright areas are specks too +(pink dots in the cat's blue, yellow dots in cream); no edge or line changed visibly. Synthetic test +`speck_brake_removes_compact_colour_specks_but_not_stars`: an isoluminant 2 × 2 speck loses most of its colour +at 100, less at 25; a coloured 2 × 2 star keeps its colour within 2 %. + +Cost (machine under heavy load, so rough): CPU 24 MP synthetic 0.54 s against 4.1 s for the rest of the filter +(a sort per median: 1.8 s; now a sorting network and the luminance median only past the threshold). GPU +(Intel HD 630, 33 MP, white balance + NR stage): median 6.19 s with, 5.61 s without. GPU and CPU agree to 1/255 +on the cat; on the candle 26 pixels differ by up to 30/255 with and without the brake (not caused by it). + +## 4. Speed + +CPU, all bit-identical to the first joint version (`8b89526d`): + +| Change | Result | +|---|---| +| no duplicate distance pass, paths + next weights in one pass, none after the last scale, two-channel buffers, parallel reconstruction | 6.2 → 5.0 s (33 MP), buffers 2.36 → 1.44 GB | +| separate H/V slice loops, zero-difference shortcut (no division, weight 1 without `exp`) | 24 MP synthetic 4.5 → 2.7 s | +| **cache-blocked H→V→H→V per band** (bands 4–256 rows, deltas up to 2/4/8) | **no gain** (2.77–3.22 s), slower at delta 8; dropped | +| remaining cost | next-scale weights (`exp` + distance), hard to reduce without changing results | + +GPU (`crates/gpu/src/wgsl/nrcj.wgsl`, kernels mirror the CPU steps, the noise model is fitted on the CPU from +GPU samples; at most 1/255 from the CPU): + +| Tried | Result | +|---|---| +| a new path/weight buffer per scale, only `flush` | out of device memory, whole render fell back to the CPU | +| two ping-pong buffers + `flush` | still out of memory: **3950 MiB real use** (nvidia-smi) while lightcraft counted 1.9 GB – the driver frees dropped buffers only when the GPU is done with them | +| **`sync` after large drops** | fixes it (3.27 GB one piece, 2.4 GB in bands) | +| bands with halo 4·Σδ + 8 | correct but slow at small budgets; now 2·Σδ + δmax + 8 (bands vs one piece: ≤ 1/255 in a few dozen pixels, from the box blur's running sums) | +| band budget | free device memory where it can be asked without `unsafe` (nvidia-smi; amdgpu sysfs) + own pooled buffers − 384 MB, else 2 GB | + +Measured (white balance + noise reduction stage on the GPU, median of 3; CPU: colour NR only): + +| | 24 MP | 33 MP | 43 MP | preview 2560 px | +|---|---|---|---|---| +| Radeon RX 9070 XT (Windows) | 0.19 s | 0.28 s | 0.34 s | 55 ms | +| Quadro M2200 4 GB (Linux) | 1.07 s | 1.54 s | 2.01 s | 0.2 s | +| Intel HD 630 | 3.0 s | 4.3 s | 5.6 s | | +| CPU Ryzen 7 5800X3D | 1.5 s | 2.3 s | 2.9 s | | +| CPU i7-7820HQ | 2.6 s | 3.7 s | 4.8 s | | + +V1 on the same Radeon: 0.08–0.12 s. A Windows test build made with MinGW was ~3× slower than Linux in the +camera-colour step (not in the noise reduction); the official MSVC release still has to be compared. + +### Second round (after the speck brake; 33 MP candle at Color 100, median of 3–6, interleaved) + +| Change | Result | +|---|---| +| guide as three planes, distances one row at a time without branches (the compiler vectorises the three divisions) | CPU next-scale weights ~360 → ~190 ms per scale; bit for bit (test `distance_run_matches_distance`) | +| paths stored as exp(−path): longer paths take minima, a new distance of 0 needs no `exp` (exp is monotonic, so bit for bit) | alone no measurable gain on the CPU (distance, not `exp`, was the cost); kept, it halves the GPU path buffers | +| pilot straight into the planes; speck brake in place (it changes < 1 % of pixels) with a min/max pre-test before the medians | brake 492 → 252 ms; pilot + planes 713 → 568 ms | +| vertical diffusion in one loop, horizontal interior split from the borders | **no gain** (3.59 vs 3.54 s): the diffusion is memory-bound (~24 bytes per pixel and pass); dropped | +| skipping the `exp` also where the new distance is below the path's | counted: only 2–24 % of pairs beyond the 40–67 % with distance 0, ~15 ms per scale for one more buffer; not done | +| GPU: separate path and weight pairs (2 + 2 instead of two 4-value quads), next paths into the free scratch buffer | 60 → 48 bytes per pixel planned; 33 MP fits in one piece in 2 GB (before: two bands with 328-row halos) | +| GPU: medians and pilot without private arrays indexed in loops (those go to slow local memory) | speck brake on the Quadro 0.33 → 0.05 s; pilot ~2 % | +| GPU: dropping the `sync` calls | Quadro: out of device memory (4032 of 4096 MiB), CPU fallback; kept | +| noise model: fit cached for identical samples (moving a slider); compact key sort | fit 13–37 ms (noisy); helps repeated previews only | + +Totals, white balance + NR stage (GPU) / colour NR (CPU), before → after this round: + +| | full 33 MP | preview 2560 px | +|---|---|---| +| Quadro M2200 | 2.15 → 1.47 s | 323 → 248 ms | +| Intel HD 630 | 5.66 → 4.26 s | 818 → 776 ms | +| CPU i7-7820HQ | 5.17 → 3.54 s | | + +CPU output is bit for bit the same as before; GPU output agrees with the previous GPU build to 1/255. + +## 5. Not part of this work + +- White dots near black in #820 came from the camera look's hue/saturation table, fixed by #858. +- A raw-level hot pixel filter was prototyped on a separate branch; the #820 dots were not hot pixels (their + positions don't repeat between frames), so it is not part of this change. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 99381ec5f5..49bfe4ec9c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -207,7 +207,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | | LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | ✅ | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Process V3: pixel-scale sharpening, working Radius and Detail, original-photo scale in previews and exports; V1/V2 preserve the previous rendering (`crates/pipeline/src/tests_sharpen.rs`). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960). Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale | -| LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960) | +| LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960). From process V6 the joint method (#815, `docs/nr-color-joint.md`): linear R−Y / B−Y, edge-aware weights from a denoised guide, a speck brake; acts clearly at the default 25 and keeps colour edges at 100. CPU and GPU within 1/255 | | LR-EDIT-DETAIL-DENOISE | AI denoise | P2 | 🟡 | cmd:denoise.toggle, cmd:denoise.models.install, cmd:denoise.queue, ctl:enhance.denoise, `crates/denoise/`, `docs/denoise.md` | non-destructive Bayer RAW, works out of the box with a built-in classical denoiser (block-matching collaborative filtering, `crates/denoise-core/src/builtin.rs`; its filter runs on the graphics card when there is one that is faster, `crates/gpu/src/bm3d.rs`), optional user-installed weights, pure-Rust CPU/GPU; GPU convolution uses independently written shared scalars (Metal equivalence regression, issue #479); tiles can also run on another computer's graphics card (`lightcraft-cli denoise-serve`, `crates/denoise/src/remote.rs`); X-Trans/linear RGB, model policy and Lightroom fidelity remain; there is no model set-up step to abandon (#922) | | LR-EDIT-DETAIL-RAWDETAILS | Improved demosaic toggle | P2 | ⬜ | | | | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | ⬜ | | | @@ -804,6 +804,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove |---|---|---| | 2026-11-04 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Olympus compressed ORF bitstream decoder implemented (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 and E-M10 Mark III verified on CC0 files; 58 bodies newly unlocked (78 total across Olympus and OM) | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | +| 2026-11-06 | minor | LR-EDIT-DETAIL-CNR, LRC-DEV-PROCESS: process V6 takes colour noise reduction to the joint method on linear R−Y / B−Y (issue #815); status unchanged | | 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | | 2026-11-05 | minor | LR-LIB-PEOPLE: face boxes another app drew on the photo as stored land on the upright photo (#2674) | | 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | diff --git a/docs/process-versions.md b/docs/process-versions.md index 5a96152f79..7d1ae1927c 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -13,7 +13,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | | **V3** | Pixel-scale sharpening (issue #757): Radius uses the original photo’s pixels, Detail controls halo damping, and downsized sources retain a response-matched sharpening band. V1 and V2 keep texture-band sharpening exactly. The sharpen plane is keyed by radius and process and invalidated after noise-reduction changes. The Highlights/Shadows base and tone map are unchanged from V2. | | **V4** | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). | -| **V5** (the latest) | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. | +| **V5** | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. | +| **V6** (the latest) | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. | ## The rule diff --git a/docs/whats-new.md b/docs/whats-new.md index c0b75f74c6..ab0f90c033 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,13 @@ ## Unreleased +### Colour noise reduction (process V6) +- Colour noise reduction removes colour noise at the raw default 25, where it used to leave most of it, and keeps + colour edges at high values instead of bleeding them into fringes (issue #815). It filters the colour differences + R−Y and B−Y, leaving brightness exactly as it was, along edges found in a denoised guide, and takes isolated + coloured specks out. New photos get it; photos edited before keep their look until Update to Current Process. A zoomed + view is smoothed like the same part of the whole photo and the export. + ### The web build can be embedded - A page framing LightCraft in an iframe can open it with `?host=parent` and speak to it over `postMessage`, the protocol PdfCraft, GridCraft and DeckCraft share: it hands photos in, receives exports and backups instead of diff --git a/tools/nrc-metrics.py b/tools/nrc-metrics.py new file mode 100644 index 0000000000..2849faf6f4 --- /dev/null +++ b/tools/nrc-metrics.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Compare colour NR exports using spatial quadrants and one fixed reference mask. + +PNG comparisons assess the displayed result, not an unclipped float ground truth. +Usage: python3 tools/nrc-metrics.py REF.png VARIANT.png ... [--crop X Y W H] +""" +import argparse +import json +from pathlib import Path + +import numpy as np +from PIL import Image + + +def linear(p): + p = np.asarray(p, dtype=np.float64) / 255.0 + return np.where(p <= 0.04045, p / 12.92, ((p + 0.055) / 1.055) ** 2.4) + + +def lab(p): + p = linear(p) + xyz = p @ np.array([[0.4124, 0.2126, 0.0193], [0.3576, 0.7152, 0.1192], [0.1805, 0.0722, 0.9505]]) + xyz /= np.array([0.95047, 1.0, 1.08883]) + f = np.where(xyz > 0.008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116) + return np.stack((116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])), axis=-1) + + +def tiles(reference): + """Four actual 48x48 quadrants; tiles selected only on the reference.""" + result = [] + for y in range(0, reference.height - 95, 192): + for x in range(0, reference.width - 95, 192): + p = linear(reference.crop((x, y, x + 96, y + 96)))[::4, ::4] + luminance = p @ np.array([0.2126, 0.7152, 0.0722]) + mean = luminance.mean() + lightness = 116 * (np.cbrt(mean) if mean > 0.008856 else 7.787 * mean + 16 / 116) - 16 + quadrants = luminance.reshape(2, 12, 2, 12).mean(axis=(1, 3)) + if 6 <= lightness <= 25 and np.ptp(quadrants) < 0.15 * mean: + result.append((x, y)) + return result[:60] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("files", nargs="+") + parser.add_argument("--crop", nargs=4, type=int, default=[1325, 2085, 360, 240]) + args = parser.parse_args() + reference = Image.open(args.files[0]).convert("RGB") + regions = tiles(reference) + x, y, w, h = args.crop + box = (x, y, x + w, y + h) + if x < 0 or y < 0 or w <= 0 or h <= 0 or x + w > reference.width or y + h > reference.height: + parser.error("crop must lie inside the image") + ref_lab = lab(reference.crop(box)) + mask = ref_lab[..., 0] > 20 + if not mask.any(): + parser.error("crop contains no reference pixels with L* > 20") + reference_ab = ref_lab[..., 1:][mask].mean(axis=0) + reference_c = np.linalg.norm(ref_lab[..., 1:][mask], axis=-1).mean() + records = [] + for file in args.files: + image = Image.open(file).convert("RGB") + if image.size != reference.size: + parser.error(f"size differs from reference: {file}") + spreads, blotches, means = [], [], [] + for tx, ty in regions: + patch = np.asarray(image.crop((tx, ty, tx + 96, ty + 96))) + ab = lab(patch)[..., 1:] + spreads.append(np.sqrt(ab.var(axis=(0, 1)).sum())) + blocks = ab.reshape(12, 8, 12, 8, 2).mean(axis=(1, 3)) + blotches.append(np.sqrt(blocks.var(axis=(0, 1)).sum())) + means.append(linear(patch).mean(axis=(0, 1))) + ab = lab(image.crop(box))[..., 1:][mask] + mean_ab = ab.mean(axis=0) + records.append({ + "file": str(Path(file)), "flat_tiles": len(regions), + "spread": float(np.mean(spreads)) if spreads else None, + "blotch": float(np.mean(blotches)) if blotches else None, + "dark_rgb": np.mean(means, axis=0).tolist() if means else None, + "crop_mean_ab": mean_ab.tolist(), + "crop_mean_colour_delta": float(np.linalg.norm(mean_ab - reference_ab)), + "crop_mean_chroma_percent": float(100 * np.linalg.norm(mean_ab) / max(np.linalg.norm(reference_ab), 1e-12)), + "crop_pixel_chroma_percent": float(100 * np.linalg.norm(ab, axis=-1).mean() / max(reference_c, 1e-12)), + "crop_hue_delta_degrees": float(np.degrees(np.arctan2(np.sin(np.arctan2(mean_ab[1], mean_ab[0]) - np.arctan2(reference_ab[1], reference_ab[0])), np.cos(np.arctan2(mean_ab[1], mean_ab[0]) - np.arctan2(reference_ab[1], reference_ab[0]))))), + }) + print(json.dumps({"reference": args.files[0], "crop": args.crop, "results": records}, indent=2)) + + +if __name__ == "__main__": + main() From 2a35db6bcf78401bd05e900d89375c3c298cbb07 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:14:19 +0200 Subject: [PATCH 11/30] Add flash, exposure bias and serial rules to smart albums (#3821) * Add flash, exposure bias and serial rules to smart albums Smart albums cannot filter by flash fired, exposure bias or camera serial even though the file metadata is already parsed. Add flash, exposure_bias and camera_serial to Meta, copy them in meta_of and on reload, and add flash, exposureBias and cameraSerial rule fields evaluated in Rule::matches. Test: flash_exposure_bias_and_serial_rules failed before the change and passes after. * Rules editor: Exposure Bias takes negative values Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/catalog/src/model.rs | 9 +++++++++ crates/catalog/src/rules.rs | 10 ++++++++-- crates/catalog/src/rules/tests.rs | 21 +++++++++++++++++++++ crates/engine/src/cmd/convert.rs | 5 +++++ crates/engine/src/files/probe.rs | 3 +++ crates/ui-egui/src/dialogs/rules_editor.rs | 1 + 6 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index cc28609941..69a99bd803 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -176,6 +176,15 @@ pub struct Meta { pub aperture: Option, pub shutter: String, pub iso: Option, + /// Whether the flash fired, from Exif `Flash`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub flash: Option, + /// Exposure compensation in EV, from Exif `ExposureBiasValue`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exposure_bias: Option, + /// The camera body's serial number. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub serial_number: String, /// Place (sublocation, e.g. a landmark). pub location: String, pub city: String, diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 50960cc9a8..6b8c272dc0 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -105,6 +105,9 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("aperture", "Aperture", Kind::Number), ("shutterSpeed", "Shutter Speed", Kind::Number), ("iso", "ISO Speed", Kind::Number), + ("flash", "Flash", Kind::Bool), + ("exposureBias", "Exposure Bias", Kind::Number), + ("cameraSerial", "Camera Serial Number", Kind::Text), // Location ("location", "Location", Kind::Text), ("city", "City", Kind::Text), @@ -136,7 +139,7 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[ ("Date", &["captureDate", "importDate", "editDate"]), ("Keywords & People", &["keywords", "keywordCount", "person", "personCount"]), ("Description", &["title", "caption", "altText", "creator", "copyright", "copyrightStatus"]), - ("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"]), + ("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]), ("Location", &["location", "city", "state", "country", "hasGps"]), ("Size", &["longEdge", "shortEdge", "aspect", "megapixels"]), ("Develop", &["edited", "cropped", "treatment"]), @@ -1099,6 +1102,9 @@ impl Rule { "editDate" => date_op(op, p.edited.as_deref(), value), "shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)), "iso" => num_op(op, m.iso.map(|v| v as f64), value), + "flash" => yes(m.flash.unwrap_or(false)), + "exposureBias" => num_op(op, m.exposure_bias.map(f32_as_decimal), value), + "cameraSerial" => text(&m.serial_number), "aperture" => num_op(op, m.aperture.map(f32_as_decimal), value), "focalLength" => num_op(op, m.focal_mm.map(f32_as_decimal), value), "longEdge" | "shortEdge" => { @@ -1146,7 +1152,7 @@ impl Rule { "text" | "filePath" | "location" => COST_TEXT, "keywords" | "person" | "personCount" | "stacked" | "copyName" | "fileName" | "extension" | "format" | "title" | "caption" | "altText" | "city" | "state" | "country" | "camera" | "lens" | "creator" | "copyright" | "captureDate" | "importDate" - | "editDate" | "shutterSpeed" | "aspect" => COST_SMALL, + | "editDate" | "shutterSpeed" | "aspect" | "flash" | "cameraSerial" | "exposureBias" => COST_SMALL, _ => COST_SCALAR, }, } diff --git a/crates/catalog/src/rules/tests.rs b/crates/catalog/src/rules/tests.rs index 8d9d649b9a..e3685997a0 100644 --- a/crates/catalog/src/rules/tests.rs +++ b/crates/catalog/src/rules/tests.rs @@ -385,6 +385,27 @@ fn in_the_last_survives_hostile_counts() { set_now(None); } +/// Flash, exposure bias and camera serial number can be tested by a rule, like the other +/// camera info; an unrecorded one is empty (or zero bias is no bias). +#[test] +fn flash_exposure_bias_and_serial_rules() { + let cat = Catalog::new(); + // the values arrive with the photo's metadata, as fields on its meta, as probed from a file + let mut v = serde_json::to_value(photo(1)).unwrap(); + let meta = v.get_mut("meta").unwrap(); + meta["flash"] = json!(true); + meta["exposure_bias"] = json!(-0.67); + meta["serial_number"] = json!("SN-X2"); + let p: Photo = serde_json::from_value(v).unwrap(); + let m = |field: &str, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(&p, &cat); + assert!(m("flash", "is", json!(true)) && !m("flash", "is", json!(false))); + assert!(m("exposureBias", "lt", json!(0)) && m("exposureBias", "between", json!([-1.0, -0.3]))); + assert!(m("cameraSerial", "contains", json!("x2"))); + assert_eq!(field_group("flash"), Some("Camera Info")); + assert_eq!(field_group("exposureBias"), Some("Camera Info")); + assert_eq!(field_group("cameraSerial"), Some("Camera Info")); +} + /// Every rule's value is checked against its field, so a rule that can't mean anything is /// reported instead of quietly matching nothing (or everything). Each problem says which rule /// it is about: "rule 2", or "rule 2.1" inside a group. diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 24b4165278..c3dd8733f1 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -239,6 +239,11 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P m.focal_mm = m.focal_mm.or(src.focal_mm); m.aperture = m.aperture.or(src.aperture); m.iso = m.iso.or(src.iso); + m.flash = m.flash.or(src.flash); + m.exposure_bias = m.exposure_bias.or(src.exposure_bias); + if m.serial_number.is_empty() { + m.serial_number = src.serial_number.clone(); + } m.gps = m.gps.or(src.gps); // the camera's focus point: photos imported before it was read get it here if m.focus.is_none() { diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index a63446401e..481d4aabc9 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -13,6 +13,9 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { aperture: m.f_number.map(|f| f as f32), shutter, iso: m.iso, + flash: m.flash.map(|f| f.fired), + exposure_bias: m.exposure_bias.map(|v| v as f32), + serial_number: m.serial_number.clone().unwrap_or_default(), location: m.sublocation.clone().unwrap_or_default(), city: m.city.clone().unwrap_or_default(), state: m.state.clone().unwrap_or_default(), diff --git a/crates/ui-egui/src/dialogs/rules_editor.rs b/crates/ui-egui/src/dialogs/rules_editor.rs index 67f5e4bb49..23677cfd70 100644 --- a/crates/ui-egui/src/dialogs/rules_editor.rs +++ b/crates/ui-egui/src/dialogs/rules_editor.rs @@ -80,6 +80,7 @@ fn number_value(ui: &mut egui::Ui, v: &mut Value, field: &str) { "rating" => (0.0, 5.0, 0.05), "iso" => (0.0, 409_600.0, 10.0), "aperture" => (0.0, 64.0, 0.05), + "exposureBias" => (-20.0, 20.0, 0.05), "keywordCount" | "personCount" => (0.0, 1000.0, 0.05), "longEdge" | "shortEdge" => (0.0, 100_000.0, 10.0), _ => (0.0, 100_000.0, 0.5), From b2007e06a939f02a2aa6707d112a394e16ce59d2 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:16:52 +0200 Subject: [PATCH 12/30] Remove the dead Cloud button from the top bar (#3832) * Remove the dead Cloud button from the top bar A clickable top-bar button that does nothing confuses users and contradicts LightCraft's no-cloud design; removing it ends the confusion while save status stays visible through toasts (lib.rs save_status) and library.info. Drop the cloud entry from the top bar's right-hand icon loop in topbar.rs, which also removes its tied warning badge; nothing else in the repo references it. Test: top_bar_has_no_cloud_widget failed before the change and passes after. * Top bar: the cloud icon only shows as the warning that saving is failing Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/panels/topbar.rs | 9 ++++++--- crates/ui-egui/src/tests/appearance.rs | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index 35e24a781b..407fc5f02f 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -172,9 +172,9 @@ fn filter_button(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rec fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rect) -> f32 { // right icons let mut x = full.right() - 18.0; - // saving is failing: the cloud icon turns into a warning until a save succeeds + // saving is failing: a warning shows until a save succeeds (nothing is shown otherwise) let unsaved = app.session.unsaved().map(|(n, e)| unsaved_tip(n, e)); - let cloud_tip = unsaved.as_deref().unwrap_or("Local library — no cloud account needed"); + let cloud_tip = unsaved.as_deref().unwrap_or_default(); // Import Photos… beside Export, always one click away, with the key it is bound to now let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; let import_tip = match crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "file.addPhotos") { @@ -189,6 +189,10 @@ fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rec ("import", Icon::Plus, import_tip.as_str(), "file.addPhotos"), ("bell", Icon::Bell, "Activity", "panel.activity"), ] { + let warn = id == "cloud" && unsaved.is_some(); + if id == "cloud" && !warn { + continue; + } let r = Rect::from_center_size(pos2(x, full.center().y), vec2(28.0, 28.0)); let tip = crate::i18n::tr(tip); let resp = ui.interact(r, egui::Id::unique(("top", id)), Sense::click()); @@ -196,7 +200,6 @@ fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rec let resp = resp.on_hover_text(tip); crate::widgets::announce(&resp, name); register(ui, format!("icon:{id}"), r); - let warn = id == "cloud" && unsaved.is_some(); let colour = if warn { t.caution } else if resp.hovered() { diff --git a/crates/ui-egui/src/tests/appearance.rs b/crates/ui-egui/src/tests/appearance.rs index 3703f02193..0579fe474e 100644 --- a/crates/ui-egui/src/tests/appearance.rs +++ b/crates/ui-egui/src/tests/appearance.rs @@ -190,6 +190,15 @@ fn the_top_bar_button_and_settings_cards_drive_the_mode() { assert_eq!(crate::theme::current(&h.view.ctx), Some(ThemeKind::Charcoal)); } +#[test] +fn top_bar_has_no_cloud_widget() { + // LightCraft has no cloud service: the icon only shows as the warning that saving is failing + // (`tests/unsaved.rs`), not as a button that does nothing. + let mut h = Headless::new(app(), [1400.0, 900.0], 1.0); + h.settle(T); + assert!(!h.app.widgets.iter().any(|(id, _)| id == "icon:cloud"), "the top bar still registers a dead cloud button"); +} + #[test] fn interface_settings_fit_small_windows_and_stack_theme_choices() { // Desktop windows have a 900×560 minimum; also stress a smaller headless viewport. From 09f0550751226cae2508e9337c1e44bfc187b920 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:29:52 +0200 Subject: [PATCH 13/30] Face boxes: drag a box's body to move it (#3846) * Add test that dragging a face box body reports a move edit The test exercises region_overlay through the existing RegionEdit::Resize enumeration and CanvasMap/Photo types, asserting that a drag inside a box body reports a move. It fails on current main because region_overlay returns None for such drags. Add a #[cfg(test)] mod move_tests with a single test that builds a CanvasMap and Photo with one face region, simulates a pointer drag from the box body centre to a new position via egui RawInput, calls region_overlay, and asserts it returns Some(RegionEdit::Resize(_, moved)) with size preserved and rect clamped into [0,1]. Test: a_moved_face_box_keeps_its_size_and_stays_inside_the_photo failed before the change and passes after. * Face boxes: body drag in its own function, no edit for a box that ends where it began, tools keep the drag Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/panels/detail.rs | 3 +- crates/ui-egui/src/panels/detail/masks.rs | 121 +++++++++++++++++++++- 2 files changed, 121 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index b827d14306..71b0ef8b60 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -434,7 +434,8 @@ fn face_boxes( let people = if app.ui.name_edit.is_some() { app.caches.person_names(&app.session.catalog) } else { Default::default() }; // while the name box is open and recognition is not set up, the box offers the next step let setup = if app.ui.name_edit.is_some() { super::faces::setup(app, ui.ctx()) } else { super::faces::Setup::Running }; - let regions = RegionContext { photo, orient: d.orientation, hints: hints.as_deref(), people: &people, setup }; + let movable = !matches!(app.ui.right, RightPanel::Crop | RightPanel::Masking | RightPanel::Remove | RightPanel::RedEye); + let regions = RegionContext { photo, orient: d.orientation, hints: hints.as_deref(), people: &people, setup, movable }; match region_overlay(ui, p, map, ®ions, &mut app.ui.name_edit) { Some(RegionEdit::SetUp) => { app.ui.name_edit = None; diff --git a/crates/ui-egui/src/panels/detail/masks.rs b/crates/ui-egui/src/panels/detail/masks.rs index 2150d513b8..ebcb35e611 100644 --- a/crates/ui-egui/src/panels/detail/masks.rs +++ b/crates/ui-egui/src/panels/detail/masks.rs @@ -29,7 +29,8 @@ const REGION_HANDLES: [(f32, f32, egui::CursorIcon); 8] = [ ]; /// Face/pet/focus regions read from XMP (MWG-RS), drawn as boxes over the photo. Hovering a box shows -/// a × in its corner and eight resize handles. A drag previews the new box live and is reported once, +/// a × in its corner and eight resize handles, and dragging its body moves it (not under a tool that +/// draws on the photo). A drag previews the new box live and is reported once, /// on release (one undo step); the × reports the region to remove. Both are catalog-only edits: /// LightCraft doesn't write regions to XMP. Regions are stored on the upright (EXIF-oriented) photo; /// `orient` is the user's Rotate / Flip on top of it, which the loupe's normalized frame includes. @@ -42,6 +43,52 @@ pub(super) struct RegionContext<'a> { /// the names to offer when a region is named pub people: &'a [String], pub setup: crate::panels::faces::Setup, + /// Dragging a box's body moves it: not while a tool that works on the photo owns the drag. + pub movable: bool, +} + +/// Dragging the body of a box moves it. It is laid out before the handles and the × so they win an +/// overlapping press. The press point and the box at press time are remembered, so the box follows the +/// pointer from where it was grabbed. The move is reported on release, unless the box ends where it began. +fn region_body_drag( + ui: &egui::Ui, + map: &CanvasMap, + rect: Rect, + (index, norm): (usize, lightcraft_geom::Rect), + orient: lightcraft_geom::Orientation, + drag_key: egui::Id, +) -> Option { + let body_key = egui::Id::unique(("region-body", index)); + let body_resp = ui.interact(rect, body_key, Sense::drag()); + if body_resp.drag_started() { + let press = ui.input(|i| i.pointer.press_origin()).unwrap_or(body_resp.interact_pointer_pos().unwrap_or(rect.center())); + let start = map.norm(press); + ui.data_mut(|d| d.insert_temp(body_key, (start, norm))); + } + // (the release frame reports `dragged()` too, so the last position is taken before the stop) + if body_resp.dragged() || body_resp.drag_stopped() { + let pp = body_resp.interact_pointer_pos(); + let shown = ui.data(|d| d.get_temp::<(Point, lightcraft_geom::Rect)>(body_key)); + if let (Some(pp), Some((start, shown))) = (pp, shown) { + let now = map.norm(pp); + let (w, h) = (shown.x1 - shown.x0, shown.y1 - shown.y0); + let (x0, y0) = ((shown.x0 + now.x - start.x).clamp(0.0, (1.0 - w).max(0.0)), (shown.y0 + now.y - start.y).clamp(0.0, (1.0 - h).max(0.0))); + let moved = lightcraft_geom::Rect { x0, y0, x1: x0 + w, y1: y0 + h }; + if moved == shown { + ui.data_mut(|d| d.remove_temp::<(usize, lightcraft_geom::Rect)>(drag_key)); + } else { + ui.data_mut(|d| d.insert_temp(drag_key, (index, orient.inverse().map_norm_rect(moved)))); + } + ui.ctx().request_repaint(); + } + } + if !body_resp.drag_stopped() { + return None; + } + let edit = ui.data(|d| d.get_temp::<(usize, lightcraft_geom::Rect)>(drag_key)).map(|(i, new)| RegionEdit::Resize(i, new)); + ui.data_mut(|d| d.remove_temp::<(usize, lightcraft_geom::Rect)>(drag_key)); + ui.data_mut(|d| d.remove_temp::<(Point, lightcraft_geom::Rect)>(body_key)); + edit } pub(super) fn region_overlay( @@ -51,7 +98,7 @@ pub(super) fn region_overlay( regions: &RegionContext, editing: &mut Option, ) -> Option { - let RegionContext { photo, orient, hints, people, setup } = *regions; + let RegionContext { photo, orient, hints, people, setup, movable } = *regions; let t = Tokens::get(p.ctx()); let clip = p.clip_rect(); let pointer = ui.input(|i| i.pointer.hover_pos()); @@ -66,6 +113,9 @@ pub(super) fn region_overlay( // white with a black keyline just outside it, so the box shows on any background p.rect_stroke(rect.expand(1.0), 0.0, Stroke::new(1.0, Color32::from_black_alpha(190)), StrokeKind::Outside); p.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::WHITE), StrokeKind::Outside); + if movable && let Some(moved) = region_body_drag(ui, map, rect, (index, norm), orient, drag_key) { + edit = Some(moved); + } if dragging.is_some() || (live.is_none() && pointer.is_some_and(|h| rect.expand(8.0).contains(h))) { for (h, (fx, fy, cursor)) in REGION_HANDLES.iter().enumerate() { let c = pos2(rect.left() + fx * rect.width(), rect.top() + fy * rect.height()); @@ -905,3 +955,70 @@ mod pen_tests { assert_eq!(pen_force(&i), Some(1.0)); } } + +#[cfg(test)] +mod region_drag_tests { + use super::*; + + /// Dragging the body of a face box (not a handle) moves the whole box by the drag, keeps its + /// size, and stays inside the photo; the move is reported once, on release. + #[test] + fn a_moved_face_box_keeps_its_size_and_stays_inside_the_photo() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx); + let canvas = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 400.0)); + let frame = lightcraft_pipeline::geometry::Frame::new(100, 100, &DevelopSettings::default(), true); + let map = CanvasMap::new(&frame, canvas); + let mut photo = lightcraft_catalog::Photo::new( + lightcraft_catalog::PhotoId(1), + lightcraft_catalog::Source::Demo { scene: 0 }, + "a.jpg", + "JPEG", + 100, + 100, + "2026-10-01T00:00:00", + ); + photo.meta.regions = vec![lightcraft_meta::Region { + rect: lightcraft_geom::Rect { x0: 0.2, y0: 0.2, x1: 0.4, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Jane".to_string()), + description: None, + }]; + let mut editing = None; + let mut run_frame = |events: &[egui::Event]| -> Option { + let mut edit = None; + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(canvas), events: events.to_vec(), ..Default::default() }, |ui| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + let p = ui.painter_at(canvas); + let regions = RegionContext { + photo: &photo, + orient: lightcraft_geom::Orientation::Normal, + hints: None, + people: &[], + setup: crate::panels::faces::Setup::Running, + movable: true, + }; + edit = region_overlay(ui, &p, &map, ®ions, &mut editing); + }); + }); + output.textures_delta.clear(); + edit + }; + // the box is at 80..160 px on screen; drag its centre (120, 120) by 40 x 20 px + let press = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run_frame(&[egui::Event::PointerMoved(pos2(120.0, 120.0))]); + run_frame(&[press(pos2(120.0, 120.0), true)]); + run_frame(&[egui::Event::PointerMoved(pos2(140.0, 130.0))]); + run_frame(&[egui::Event::PointerMoved(pos2(160.0, 140.0))]); + let edit = run_frame(&[press(pos2(160.0, 140.0), false)]); + assert!(matches!(edit, Some(RegionEdit::Resize(0, _))), "dragging the face box body reports the moved box"); + let Some(RegionEdit::Resize(index, moved)) = edit else { return }; + assert_eq!(index, 0); + assert!(((moved.x1 - moved.x0) - 0.2).abs() < 0.02, "width kept: {moved:?}"); + assert!(((moved.y1 - moved.y0) - 0.2).abs() < 0.02, "height kept: {moved:?}"); + assert!((moved.x0 - 0.3).abs() < 0.02 && (moved.y0 - 0.25).abs() < 0.02, "moved by the drag: {moved:?}"); + assert!(moved.x0 >= 0.0 && moved.y0 >= 0.0 && moved.x1 <= 1.0 && moved.y1 <= 1.0, "inside the photo: {moved:?}"); + } +} From 9c07f427f0e1dee37ab1d6b458ae9fd5d2cacd23 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:46:24 +0200 Subject: [PATCH 14/30] Arm the window renderer marker before probing the driver (#3817) * Arm the window renderer marker before probing the driver The issue's own table says the window renderer is created without a crash marker, so a launch that dies in the driver writes nothing and repeats itself. The window does have a marker, but it is armed only after the risky probe has already run, which is exactly the case the reporter's Windows launch hit. Arm the window-init.marker with the renderer name before each probe in pick_probed, so the marker on disk names the renderer being tried while the driver is touched, and re-arm it for the next renderer when a probe fails. The next launch then reads that renderer via take_failed and reports it (the existing 'the window could not start with its ... renderer last time' notice) instead of failing silently again. Test: the_window_marker_is_written_while_the_renderer_is_probed failed before the change and passes after. * Window marker: fix the test's closing brace, skip it under forced glow, sync the marker to disk Co-Authored-By: Claude Opus 5.5 * Format Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 38 ++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 1b3e2d6809..04e85136a8 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -54,7 +54,12 @@ impl Files { if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); } - if let Err(e) = std::fs::write(&p, format!("{}\n", r.name())) { + // on disk before the driver is touched: a driver fault can take the machine down with it + let written = std::fs::File::create(&p).and_then(|mut f| { + std::io::Write::write_all(&mut f, format!("{}\n", r.name()).as_bytes())?; + f.sync_all() + }); + if let Err(e) = written { log::warn!("window: could not write {}: {e}", p.display()); } } @@ -95,7 +100,7 @@ pub fn choose(files: &Files, compose_window: bool) -> Chosen { let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true); let mut problems = Vec::new(); let chosen = if cfg!(windows) { - pick_probed(&order, &mut problems, compose_window) + pick_probed(files, &order, &mut problems, compose_window) } else if forced == Some(WindowRenderer::Glow) || (forced.is_none() && failed.is_some_and(|f| f != WindowRenderer::Glow)) { // elsewhere eframe's own wgpu set-up stays the default; glow after a failed start Some((WindowRenderer::Glow, None)) @@ -168,11 +173,20 @@ pub fn base_options() -> WgpuConfiguration { } /// The first renderer of `order` that probes cleanly (glow is taken without a probe). -fn pick_probed(order: &[WindowRenderer], problems: &mut Vec, compose_window: bool) -> Option<(WindowRenderer, Option)> { +fn pick_probed( + files: &Files, + order: &[WindowRenderer], + problems: &mut Vec, + compose_window: bool, +) -> Option<(WindowRenderer, Option)> { for &r in order { match r { WindowRenderer::Glow => return Some((r, None)), WindowRenderer::Wgpu(b) => { + // name the renderer being probed before the crash-prone device + // creation and egui pipeline compile: if the driver kills the + // start, the marker survives so the next launch tries it last + files.arm(r); let probed = std::panic::catch_unwind(|| probe(b, compose_window)).unwrap_or_else(|_| Err("panicked".into())); match probed { Ok(e) => return Some((r, Some(e))), @@ -400,4 +414,22 @@ mod tests { } assert!(!composes_window(true, WindowRenderer::Glow)); } + + /// The probe builds egui's pipeline on a live device before the window opens; a driver crash + /// there must leave the window-init marker on disk so the next launch tries another renderer. + #[cfg(windows)] + #[test] + fn the_window_marker_is_written_while_the_renderer_is_probed() { + // glow is taken without a probe, so a forced glow arms nothing here + let forced = + backend::forced_window_renderer(std::env::var("LIGHTCRAFT_GPU_BACKEND").ok().as_deref(), std::env::var("WGPU_BACKEND").ok().as_deref()); + if forced == Some(WindowRenderer::Glow) { + return; + } + let d = dir("probe-marker"); + let f = Files::new(Some(d.clone())); + choose(&f, false); + assert!(f.armed(), "the window-init marker must be written while the renderer is probed"); + let _ = std::fs::remove_dir_all(&d); + } } From a856df5f422bc07044a6beaf5bfdb920292bb1c7 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:56:51 +0200 Subject: [PATCH 15/30] Write camera make and lens make to EXIF on export (#3828) * Write camera make and lens make to EXIF on export PTGui and similar stitching tools read EXIF Make/LensMake to identify camera and lens; without them, exported JPEGs from CR2 files are not recognized the same way as Adobe's export. Add make and lens_make fields to catalog Meta, populate them from the raw's EXIF on import in meta_of, and write them as EXIF Make and LensMake tags in export_metadata. Test: export_writes_camera_make_and_lens_make_to_exif failed before the change and passes after. * Export: read Make and LensMake on import and write them, with Model on its own Co-Authored-By: Claude Opus 5.5 * Export: strip the maker from Model only as a separate word Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/catalog/src/model.rs | 6 ++++++ crates/engine/src/cmd/convert.rs | 6 ++++++ crates/engine/src/export/encoding.rs | 6 +++++- crates/engine/src/files/probe.rs | 2 ++ crates/engine/src/tests/export.rs | 24 ++++++++++++++++++++++++ 5 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 69a99bd803..ebf2d1ef08 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -171,7 +171,13 @@ pub fn parse_shutter_seconds(s: &str) -> Option { #[serde(default)] pub struct Meta { pub camera: String, + /// The camera's maker, from Exif `Make` (`camera` is maker and model together). + #[serde(skip_serializing_if = "String::is_empty")] + pub make: String, pub lens: String, + /// The lens's maker, from Exif `LensMake`. + #[serde(skip_serializing_if = "String::is_empty")] + pub lens_make: String, pub focal_mm: Option, pub aperture: Option, pub shutter: String, diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index c3dd8733f1..261a4dd018 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -233,6 +233,12 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P if m.lens.is_empty() { m.lens = src.lens.clone(); } + if m.make.is_empty() { + m.make = src.make.clone(); + } + if m.lens_make.is_empty() { + m.lens_make = src.lens_make.clone(); + } if m.shutter.is_empty() { m.shutter = src.shutter.clone(); } diff --git a/crates/engine/src/export/encoding.rs b/crates/engine/src/export/encoding.rs index 862c72cd01..ecdc32aa31 100644 --- a/crates/engine/src/export/encoding.rs +++ b/crates/engine/src/export/encoding.rs @@ -334,7 +334,11 @@ pub fn export_metadata(photo: &lightcraft_catalog::Photo, catalog: &lightcraft_c out.gps = m.gps.map(|(latitude, longitude)| Gps { latitude, longitude, altitude: None }); } if o.metadata == MetadataPolicy::All { - out.model = text(&m.camera); + // `camera` is maker and model together: Exif keeps them apart, and a photo from before + // the maker was read keeps the whole string as its Model + out.make = text(&m.make); + out.model = text(m.camera.strip_prefix(m.make.as_str()).and_then(|rest| rest.strip_prefix(' ')).unwrap_or(&m.camera)); + out.lens_make = text(&m.lens_make); out.lens_model = text(&m.lens); out.focal_length = m.focal_mm.map(f64::from); out.f_number = m.aperture.map(f64::from); diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 481d4aabc9..b4e88943e6 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -7,6 +7,8 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string(); let meta = Meta { camera, + make: m.make.clone().unwrap_or_default(), + lens_make: m.lens_make.clone().unwrap_or_default(), // (a camera that writes no lens name, like Nikon's DSLRs, still says what range the lens covers) lens: m.lens_model.clone().or_else(|| m.lens_spec.and_then(lightcraft_meta::lens_spec_name)).unwrap_or_default(), focal_mm: m.focal_length.map(|f| f as f32), diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index bd5124d71e..1bddd2c44c 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -945,6 +945,30 @@ fn metadata_none_in_any_case_exports_no_metadata() { assert!(m.gps.is_none() && m.city.is_none(), "{m:?}"); } +/// A raw's Exif Make, Model and LensMake reach an exported JPEG apart, as stitching tools read them. +#[test] +fn export_writes_camera_make_and_lens_make_to_exif() { + let dir = temp_dir("export-raw-exif"); + let src = dir.join("Canon.dng"); + let meta = lightcraft_meta::Metadata { + make: Some("Canon".into()), + model: Some("EOS R5".into()), + lens_make: Some("Sigma".into()), + lens_model: Some("RF 24-105mm f/4L IS USM".into()), + ..Default::default() + }; + std::fs::write(&src, synthetic_dng_with(None, meta)).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = s.catalog.photos().next().unwrap().id; + let e = export_photo(&mut s, id, &ExportOptions::from_json(&json!({"format": "jpeg", "longEdge": 64, "metadata": "all"})), 1).unwrap(); + let back = lightcraft_meta::extract(&e.bytes); + assert_eq!(back.make.as_deref(), Some("Canon"), "EXIF Make is missing: {back:?}"); + assert_eq!(back.model.as_deref(), Some("EOS R5"), "EXIF Model holds the model alone: {back:?}"); + assert_eq!(back.lens_make.as_deref(), Some("Sigma"), "EXIF LensMake is missing: {back:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// An original raw whose own metadata holds GPS is refused under "Remove location info". #[test] fn remove_location_refuses_a_raw_that_embeds_gps() { From d2bf0810bdfa2363ee8b5dc5ddbdaf6df1514a99 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 11:56:57 +0200 Subject: [PATCH 16/30] Fix mismatched source/destination rects in before/after zoom window renders (#3842) * Fix mismatched source/destination rects in before/after zoom window renders Both panes of Before/After cut the zoom window from one rect but paste it over another, which is exactly the inconsistent-offset and artifact behavior reported in issue #1035; a headless test exercising click-zoom in both panes with a fixed camera raw would catch the regression. Detail view: compute `visible` relative to `v.img` instead of `v.target` so the window's source and destination share the animated rect. Compare/Reference view: compute `visible` relative to `display` (the rect actually drawn) instead of `img` so texture-aspect fits land in the right place. Test: compare_zoom_window_tracks_the_zoomed_pane failed before the change and passes after. * Compare: keep before_target, return both rects so Survey's remove button stays on the photo Co-Authored-By: Claude Opus 5.5 * Format Co-Authored-By: Claude Opus 5.5 * Compare: the early return gives both rects Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/panels/compare.rs | 28 +++++++--- crates/ui-egui/src/tests/compare.rs | 80 ++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index d3f11733b8..c6475a7017 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -210,12 +210,20 @@ fn request_tile_renders(app: &mut LightcraftApp, id: PhotoId, slot: Slot, want: /// Draw one photo fitted into `area` (rendered at its display size into `slot`), with its caption /// strip below. Returns the image rect and the click/drag response. -fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slot, area: Rect, label: &str, zoom: Zoom) -> (Rect, egui::Response) { +fn photo_tile( + app: &mut LightcraftApp, + ui: &mut egui::Ui, + id: PhotoId, + slot: Slot, + area: Rect, + label: &str, + zoom: Zoom, +) -> (Rect, Rect, egui::Response) { let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); let resp = ui.interact(area, egui::Id::unique(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag()); crate::widgets::announce(&resp, app.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_default()); - let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, resp) }; + let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, area, resp) }; let caption_h = 26.0; let img_area = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - caption_h)); let frame = lightcraft_pipeline::geometry::Frame::with_lens( @@ -279,7 +287,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan); p.image(tex.id(), display, uv, Color32::WHITE); if let Some(i) = window { - draw_window(&p, app, i, id, photo.develop.hash64(), display); + draw_window(&p, app, i, id, photo.develop.hash64(), img); } } else if let Some(tex) = app.renderer.textures.get(&Slot::Thumb(id)) { let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32; @@ -369,7 +377,10 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo register(ui, format!("cull:{}:label", id.0), lr); } register(ui, format!("cull:{}", id.0), display); - (display, resp) + // The frame rect the window was requested in (`img`) and the texture's rect (`display`): they + // differ when the texture's aspect differs from the frame's. The first is the window's + // reference, the second is the photo as painted. + (img, display, resp) } /// Panes that get window renders: Compare's Select and Candidate, Reference's two sides. @@ -510,7 +521,7 @@ pub fn show_compare(app: &mut LightcraftApp, ui: &mut egui::Ui) { ]; let zoom = app.ui.zoom; for (id, r, label, i) in panes { - let (img, resp) = photo_tile(app, ui, id, Slot::Compare(i), r, label, zoom); + let (img, _, resp) = photo_tile(app, ui, id, Slot::Compare(i), r, label, zoom); if i == 1 { app.image_rect = Some(img); } @@ -565,7 +576,8 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) { for (i, id) in photos.iter().enumerate() { let (c, r) = (i % cols, i / cols); let cell = Rect::from_min_size(pos2(area.left() + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch)).shrink(6.0); - let (img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit); + // (Survey tiles are fit views with no windows: what counts is the photo as painted) + let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit); if app.session.selection.active == Some(*id) { app.image_rect = Some(img); } @@ -620,8 +632,8 @@ pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) { let zoom = app.ui.zoom; let left = Rect::from_min_size(area.min, vec2(half, area.height())); let right = Rect::from_min_size(pos2(area.right() - half, area.top()), vec2(half, area.height())); - let (_, lresp) = photo_tile(app, ui, r, Slot::Compare(0), left, "Reference", zoom); - let (img, _) = photo_tile(app, ui, active, Slot::Compare(1), right, "Active", zoom); + let (_, _, lresp) = photo_tile(app, ui, r, Slot::Compare(0), left, "Reference", zoom); + let (img, _, _) = photo_tile(app, ui, active, Slot::Compare(1), right, "Active", zoom); app.image_rect = Some(img); crate::widgets::context_menu(&lresp, |ui| { if ui.button(crate::i18n::tr("Clear Reference")).clicked() { diff --git a/crates/ui-egui/src/tests/compare.rs b/crates/ui-egui/src/tests/compare.rs index 0baffa06b6..4ce0341fb1 100644 --- a/crates/ui-egui/src/tests/compare.rs +++ b/crates/ui-egui/src/tests/compare.rs @@ -285,6 +285,86 @@ fn deleting_the_pinned_reference_stops_drawing_it_and_reentry_uses_a_live_photo( assert!(h.app.renderer.textures.get(&crate::render::Slot::Compare(0)).is_some_and(|t| t.photo == reference)); } +/// The zoom window is checked against the reference frame the request was made for: a window is a +/// part of the frame, so its bounds are the window's pixels laid over that frame, not over whatever +/// rect the whole-frame texture happens to be fitted into. In the candidate pane that frame is the +/// one recorded for the pane: the tile is laid over it, so any other frame rect is the texture's. +#[test] +fn compare_zoom_window_tracks_the_zoomed_pane() { + use crate::render::Slot; + let mut h = demo(); + let vis: Vec = h.app.session.visible_cloned().iter().map(|p| p.0).collect(); + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [vis[0], vis[1]], "active": vis[0]}}), T); + let r = h.request("engine.execute", json!({"command": "view.compare"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.zoom = Zoom::Percent(100.0); + h.settle(SETTLE); + let candidate = vis[1]; + let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(candidate)).cloned().expect("photo"); + let frame = lightcraft_pipeline::geometry::Frame::with_lens( + photo.width.max(1) as usize, + photo.height.max(1) as usize, + &photo.develop, + true, + photo.embedded_lens.as_ref(), + ); + let aspect = frame.aspect() as f32; + let native = crate::panels::detail::output_px(&frame); + let view = h.app.compare_windows[1].expect("a zoom window"); + assert_eq!(view.photo, lightcraft_catalog::PhotoId(candidate)); + let tex = h.app.renderer.textures.get(&Slot::CompareRegion(1)).expect("window texture"); + assert_eq!(tex.photo, lightcraft_catalog::PhotoId(candidate)); + let tex_id = tex.tex.id(); + // Lay the whole-frame texture over the same reference frame with an aspect just inside the + // same-frame tolerance: the drawn rect moves, the request stays valid, and the window is + // drawn over the moved texture rect. Hold the replacement renders so the existing window is + // the one drawn, magnified, over the texture. + let texture_size = { + let whole = h.app.renderer.textures.get_mut(&Slot::Compare(1)).expect("whole-frame texture"); + let target_aspect = aspect * 1.015; + whole.size[1] = (whole.size[0] as f32 / target_aspect).round().max(8.0) as usize; + whole.size + }; + let texture_aspect = texture_size[0].max(1) as f32 / texture_size[1].max(1) as f32; + assert!(crate::region::same_aspect(texture_aspect, aspect), "a trace off the frame's aspect stays in tolerance: {texture_aspect} {}", aspect); + let open = std::rc::Rc::new(std::cell::Cell::new(false)); + h.app.renderer.set_offload(Box::new(crate::headless::RenderGate::new(open.clone()))); + h.app.session.begin_interaction("Exposure").unwrap(); + h.step(); + let pane_img = h.app.image_rect.expect("the candidate pane's frame"); + let img_area = egui::Rect::from_min_max(pane_img.min, egui::pos2(pane_img.right(), pane_img.bottom())); + let img = pane_img; + let display = crate::panels::detail::fit_rect(img_area, texture_aspect, h.app.ui.zoom, native, 1.0, h.app.ui.pan); + let expected = egui::Rect::from_min_size( + img.min + egui::vec2(view.window.x as f32 / view.full.0 as f32 * img.width(), view.window.y as f32 / view.full.1 as f32 * img.height()), + egui::vec2(view.window.w as f32 / view.full.0 as f32 * img.width(), view.window.h as f32 / view.full.1 as f32 * img.height()), + ); + let wrong = egui::Rect::from_min_size( + display.min + + egui::vec2(view.window.x as f32 / view.full.0 as f32 * display.width(), view.window.y as f32 / view.full.1 as f32 * display.height()), + egui::vec2(view.window.w as f32 / view.full.0 as f32 * display.width(), view.window.h as f32 / view.full.1 as f32 * display.height()), + ); + assert!( + (wrong.min - expected.min).abs().max_elem() > 3.0, + "the frame rect and the texture rect must differ for this check: {img:?} vs {display:?}" + ); + let drawn: Vec = h + .view + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::epaint::Shape::Mesh(m) if m.texture_id == tex_id => Some(m.calc_bounds()), + _ => None, + }) + .collect(); + let bounds = drawn.iter().copied().find(|b| (b.min - wrong.min).abs().max_elem() < 1.0).or_else(|| drawn.first().copied()); + let bounds = bounds.expect("the window tile is painted"); + assert!( + (bounds.min - expected.min).abs().max_elem() < 1.0 && (bounds.max - expected.max).abs().max_elem() < 1.0, + "the tile {bounds:?} must sit in the zoomed pane's frame {expected:?}, not in the texture's rect {wrong:?}" + ); +} + /// Clicking a colour label (or stars) in the Info panel while culling labels the active photo /// only, as the label keys and the bottom bar's stars and flags do, and the label shows under that /// photo in Compare (#2398: "Can't assign color to photo when culling"). From 0b23cc638447a9d48956f4034add94467afe9820 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:01 +0100 Subject: [PATCH 17/30] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 +++++ AGENTS.md | 67 ++++++++++-- CLAUDE.md | 167 +----------------------------- 3 files changed, 87 insertions(+), 175 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index f179510775..354aa2b8d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,11 +1,63 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # LightCraft — instructions for agents LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions. ## Start every session here -1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers). -2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots). -3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for +`plan/` is an optional gitignored notebook (status, execution notes, `plan/lightroom/`). Do not ask for it and do not stop when it is absent. +1. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that *exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail: @@ -16,9 +68,7 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` / `docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and path the tracker cites still exists, and `cargo xtask parity --write` refreshes its summary. -5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local-only). +`plan/` stays optional. Do not stop to ask except for the house-rule list. **Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green branches can still break each other (e.g. a new struct field vs. a new constructor). @@ -66,9 +116,8 @@ of it. - **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd. - **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm). -- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. +- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) - **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not. @@ -126,7 +175,7 @@ of it. - **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl` and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work. - **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders - with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe + with `/usr/bin/time`. Timings may go in the optional `plan/` notebook. Budgets: slider update ≤ 16 ms (draft) / loupe ≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG. - Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`. - **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it diff --git a/CLAUDE.md b/CLAUDE.md index 6ef579697e..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,166 +1 @@ -# LightCraft — instructions for agents - -LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructive raw developer targeting Adobe Lightroom parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../pdfcraft` (Acrobat), `../photocraft` (Photoshop), `../vectorcraft` (Illustrator) and `../filmcraft` (Premiere), with the same conventions. - -## Start every session here -1. Read `plan/STATUS.md` (current milestone, next unchecked task, blockers). -2. Read the task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README/docs of the crate you touch. Behaviour/visual reference: `plan/lightroom/` (incl. `10-observed-ui.md` + screenshots). -3. **Know where we stand:** read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, every dimension) and, for - method and evidence, [`docs/target-app-parity.md`](docs/target-app-parity.md). The checklist counts features that - *exist*; the real gaps are quality and coverage: camera colour calibration, CR3 / compressed raws, per-model - verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail: - [`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is - wrong or incomplete, downgrade it to 🟡 with a note. -4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row - tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut). - When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` / - `docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and - path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write` - refreshes its summary. -5. Follow the autonomous operation protocol (`plan/execution-plan.md` §7). Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local-only). - -**Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green -branches can still break each other (e.g. a new struct field vs. a new constructor). - -**Resuming after a crash / another session:** check `git status` on main, `git worktree list`, and each worktree's -`git log main..HEAD` + `git status` for unmerged commits or uncommitted work before starting anything new. Commit small -and often so a crash loses minutes, not hours. - -## Never crash (outranks feature work) -People trust LightCraft with their photo libraries and edits; a crash loses their work. A malformed raw/JPEG/XMP, a bad -command, control or MCP argument, a corrupt catalog or settings file, or a full disk must produce an error the user (or -agent) can act on, never a panic. Don't ship a feature by adding a panic path, and fix a crash before building on top -of it. -- **Non-test code never panics:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`, and - no `unsafe`. Return the crate's error type through `Result` and `?`; use `ok_or(..)?`, `let … else`, `if let`, or a - fallback (`unwrap_or…`) only where it can't silently corrupt a document. An unfinished feature returns an - "unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]` - + `.expect("why it can't fail")`. -- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed - allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile - Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every - other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper - crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it. -- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or - arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative - casts to `usize`; cap allocations sized by input; slice strings only at char boundaries. -- **Bound recursion** (depth limits or seen-sets: IFD chains, nested metadata, collections). **Don't cascade:** - `lock().unwrap_or_else(PoisonError::into_inner)` or an error; worker-thread joins are `Result`s. -- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped - panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native. -- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. -- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace - denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with - `[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root - (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, - clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include - `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include - the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` - (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` - web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). - -## Non-negotiables -- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). -- **Pure Rust** in the product. No C/C++ dependencies. -- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd. -- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. -- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything - that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind, - label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses - `Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row. -- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages' - tests, layers, assets, roots, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR - (`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see - the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). -- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment. - -## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) -- **Never use any iconography, image, artwork, font, sound or other asset from Adobe products** (no Lightroom/Creative Cloud icons, no screenshots, no presets/profiles/LUTs, no UI bitmaps — not even as a temporary placeholder or "reference copy"). Observing Adobe's UI to imitate *layout and behaviour* is allowed; copying or tracing its assets is not. -- **This includes Adobe's open-licensed assets**: no Source Sans/Serif/Code or Source Han fonts, no Adobe Fonts, no - Adobe-published icon sets, sample photos, colour profiles or LUTs — even when OFL/MIT. The UI font is Inter (OFL); - Japanese and Chinese fonts come from craft-fonts (below). **One exception (maintainer decision, 2026-10-07): Noto - Sans/Serif CJK** (Google-branded, OFL, co-developed with Adobe as Source Han) is allowed via craft-fonts for Chinese - text, because nearly every OFL Chinese face derives from it. Use it unmodified under its OFL; this does not open the - door to Source Han under Adobe's name or to any other Adobe asset. -- Every asset in the repository must be one of: **our own original work** (e.g. icons drawn in code as vectors, procedurally generated demo photos), **public domain / CC0**, **Creative Commons** (CC-BY / CC-BY-SA with attribution honoured), **OFL** (fonts), or **permissive open-source** (MIT/Apache-2.0/BSD/ISC) — or contributed by a person who created the asset and licenses it openly. -- **Exception: `docs/brand/`.** The ArtCraft name, wordmark and logos there are ArtCraft Team trademarks, not open source and not covered by LightCraft's MIT OR Apache-2.0 licence (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`); their terms are in `docs/brand/LICENSE-brand.txt`. Use them only unmodified and never redraw, recolour or derive from them. -- **Every asset must have an entry in `assets/ATTRIBUTION.md`** (path, title, author/creator, source URL or "original work", licence, date added, modifications) and its licence text when required (e.g. `assets/fonts/OFL-*.txt`). Add the entry in the same commit as the asset. Assets without an attribution entry must not be committed. -- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo.** Don't commit - font files here (Inter, already in `assets/fonts/`, is the one exception); add new fonts to craft-fonts. LightCraft - uses it as the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts` - then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs` - embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web` - ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI - (`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset, - `CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build - with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip - without it; the FreeBSD CI job runs them with it. -- Icons drawn in code (e.g. `crates/ui-egui/src/icons.rs`) are original work and are recorded in `assets/ATTRIBUTION.md` as such; do not trace them from Adobe icons. -- Demo/test images: generated procedurally by `lightcraft-scenes`, or CC0 downloads kept in the gitignored `corpus/` with their source recorded. Screenshots of Adobe apps live only in the gitignored `plan/` and are never committed or published. -- **Enforced:** `cargo xtask assets` (in `ci`) fails when an image/icon/font/sound/video/raw/ICC/XMP file is not matched - by a path pattern in the first column of `assets/ATTRIBUTION.md`, when a referenced licence file is missing, when a - file name suggests Adobe material, or when an Adobe profile/template format (`.dcp`, `.lcp`, `.lrtemplate`, …) appears. - Never weaken this check to make a commit pass — fix the attribution or remove the asset. -- When in doubt about an asset's licence: don't use it. - -## Running and looking at the app -- `cargo run --release -p lightcraft -- --control 7980` opens the desktop app with the JSON-lines control server (see `docs/control-protocol.md`). -- **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility - automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only - through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots. -- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`. -- **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed: - `lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests, - one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use - `ui.screenshot {"path": …, "headless": true}`; windowed screenshots fall back to headless after 2 s. -- MCP: `lightcraft-cli mcp` (headless, `--demo` for the procedural library) or `lightcraft-cli mcp --connect` (drives - the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`. -- Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in - `crates/ui-egui/src/menus.rs`. -- Text boxes use `crates/ui-egui/src/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the - Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id - that is unique on screen. Older fields still on `TextEdit` move over as they are touched. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. -- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). -- Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. -- Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - -## Testing & performance (do this often) -- Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`, - `apps/lightcraft-cli/tests/`). New features need at least one test that would fail without them. -- **Run the app after every user-visible change**: launch with `--control 7980`, drive it with a JSON-lines script - (`docs/showcase/run.py file.jsonl`), take `ui.screenshot`, and look at it. Check `ui.inspect` → `perf`. -- **Benchmarks:** `cargo xtask bench` (24 MP raw from corpus; CPU and GPU columns) appends to `target/bench/history.jsonl` - and flags CPU-time regressions > 20 % vs the previous run (`--strict` to fail). Run it before and after perf work. -- **Measure, don't guess**: `LIGHTCRAFT_PROFILE=1` prints per-stage pipeline timings to stderr; time CLI renders - with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe - ≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG. -- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`. -- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it - passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with - `#[ignore = "flaky: #"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its - own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that - hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under - nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do. -- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")` - before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and - data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR). - -## Map of the code -`geom`, `color`, `raster`, `tiff` (L0) → `raw`, `codecs`, `meta`, `develop` (L1) → `pipeline` → `catalog` → `engine` -→ `ui-egui`, `mcp` (L5) → apps `lightcraft` (desktop), `lightcraft-cli` (render/commands/MCP). `scenes` generates demo -photos. `xtask` = tooling (`ci`, `layers`, `assets`, `parity`, `wasm`, `corpus`, `stats`); `testkit` = test helpers -(dev-dependency only). `flake.nix` + -`nix/package.nix` = the Nix package (`nix build` builds both binaries with the craft-fonts input, installs the -desktop file/icons/AppStream metadata and runs `cargo test --workspace`; `nix develop` = dev shell). Community-maintained; CI only -evaluates it (`.github/workflows/nix.yml`), so the build may lag behind the workspace; see README → Quick start. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- `ci.yml` is the Linux gate, on every pull request. `ci-windows.yml` adds a Windows leg (clippy and tests of the crates with `cfg(windows)` code) when a pull request changes the paths it lists; add the `full-ci` label to run it on any other pull request. When you add `cfg(windows)` code in a new file, add the file to its `paths` in a CI PR. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md From a941d706c33011bce35fa6eaf55ba96e8bca30ef Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 13:31:38 +0200 Subject: [PATCH 18/30] Picture Package and Custom Package pages can print cut guides at each cell's corners (#3843) * Picture Package and Custom Package pages can print cut guides at each cell's corners Picture Package and Custom Package pages can print cut guides at each cell's corners Picture Package and Custom Package pages can print cut guides at each cell's corners Test: picture_package_and_custom_package_pages_can_print_cut_guide failed before the change and passes after. * Print: Cut Guides in the package preview, page panel in its own function, tests follow the guides Co-Authored-By: Claude Opus 5.5 * Print: Cut Guides sit at each cell's corners, outside any border Co-Authored-By: Claude Opus 5.5 * Print: shorten the scroll position comment to what the code does Co-Authored-By: Claude Opus 5.5 * Print: back to one scroll position for the settings column Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/print/compose.rs | 14 ++++-- crates/engine/src/print/compose/tests.rs | 10 +++- crates/ui-egui/src/dialogs/print_view.rs | 58 ++++++++++++++---------- crates/ui-egui/src/tests/print.rs | 34 +++++++++++++- 4 files changed, 85 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/print/compose.rs b/crates/engine/src/print/compose.rs index 16c683a84a..a45df4e7a2 100644 --- a/crates/engine/src/print/compose.rs +++ b/crates/engine/src/print/compose.rs @@ -98,7 +98,7 @@ pub struct PageStyle { pub page_numbers: bool, /// The print settings (sharpening, profile, resolution) at the bottom left of each page. pub page_info: bool, - /// Marks at the corners of each photo to cut along. + /// Marks at the corners of each photo to cut along (the packages' Cut Guides reuse this). pub crop_marks: bool, } @@ -116,7 +116,8 @@ pub fn rec2020_from_srgb8(c: [u8; 3]) -> [u16; 3] { } /// Whether a layout style prints the Page Options (page numbers, page info, crop marks): -/// Lightroom offers them for Single Image and Contact Sheet; its packages have Cut Guides instead. +/// Lightroom offers them for Single Image and Contact Sheet. Its packages have Cut Guides +/// instead, which print whatever this says ([`PageStyle::crop_marks`]). pub fn has_page_options(style: Style) -> bool { !style.is_package() } @@ -452,6 +453,8 @@ struct Marks { crop: Option<(usize, usize, usize)>, numbers: bool, info: Option, + /// Marks go at each cell's corners (a package's Cut Guides, outside any border), not the photo's. + around_cells: bool, ink: [u16; 3], text_px: f32, /// The printable area: the text sits in the margin below it, aligned with its sides. @@ -464,9 +467,10 @@ impl Marks { let page = &settings.page; let px = |inches: f64| (inches * ppi).round() as usize; Marks { - crop: (on && page.crop_marks).then(|| (px(CROP_MARK_IN), px(CROP_MARK_GAP_IN), px(CROP_MARK_PT / 72.0).max(1))), + crop: page.crop_marks.then(|| (px(CROP_MARK_IN), px(CROP_MARK_GAP_IN), px(CROP_MARK_PT / 72.0).max(1))), numbers: on && page.page_numbers, info: (on && page.page_info).then(|| page_info_text(settings)), + around_cells: !on, ink: rec2020_from_srgb8(mark_ink(page.background)), text_px: (PAGE_TEXT_PT / 72.0 * ppi) as f32, area: settings.layout.printable().ok().and_then(|a| px_rect(&a, ppi, pw, ph)), @@ -609,7 +613,9 @@ impl Prepared { } }; let photo = &cache.get(at).ok_or("render cache lost an entry")?.1; - placed.push(draw_cell(&mut page, photo, item.cell, &self.style).map_err(|e| format!("{}: {e}", item.name))?); + let cell = item.cell; + let drawn = draw_cell(&mut page, photo, cell, &self.style).map_err(|e| format!("{}: {e}", item.name))?; + placed.push(if self.marks.around_cells { cell } else { drawn }); } self.marks.draw(&mut page, &placed, index + 1); out.push(PageRaster { width: w as u32, height: h as u32, ppi: self.ppi, rgb: page.rgb }); diff --git a/crates/engine/src/print/compose/tests.rs b/crates/engine/src/print/compose/tests.rs index f1e979cc0a..830d3f0764 100644 --- a/crates/engine/src/print/compose/tests.rs +++ b/crates/engine/src/print/compose/tests.rs @@ -373,13 +373,19 @@ fn page_numbers_and_info_print_in_the_bottom_margin() { for p in &info { assert!(inked(p, left.0, left.1, 550, 600) > 10, "the print settings line"); } - // the packages have no Page Options in Lightroom: nothing is drawn - let all = PageStyle { page_numbers: true, page_info: true, crop_marks: true, ..Default::default() }; + // the packages have no page numbers or page info in Lightroom: nothing is drawn + let all = PageStyle { page_numbers: true, page_info: true, ..Default::default() }; let package = page_options_pages(&mut s, Style::PicturePackage, all); assert_eq!(package.len(), 2); for p in &package { assert_eq!(inked(p, 0, 400, 550, 600) + inked(p, 0, 400, 0, 50), 0); } + // their Cut Guides are the crop marks, at each photo's corners + let guides = page_options_pages(&mut s, Style::PicturePackage, PageStyle { crop_marks: true, ..Default::default() }); + assert_eq!(guides.len(), 2); + for (g, p) in guides.iter().zip(&package) { + assert!(inked(g, 0, 400, 0, 600) > inked(p, 0, 400, 0, 600), "the guides add ink"); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index 3161aa96f7..fda115e6c1 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -286,6 +286,32 @@ fn image_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSet }); } +/// The Page panel: the background, and the Page Options or, on a package, Cut Guides. +fn page_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, st: &PrintSettings) { + let ctx = ui.ctx().clone(); + heading(ui, t, "Page"); + row(ui, t, "Background", |ui| { + if let Some(c) = colour(ui, "printBackground", st.page.background) { + patch(app, &ctx, json!({"page": {"background": c}})); + } + }); + if compose::has_page_options(st.layout.style) { + ui.label(egui::RichText::new(crate::i18n::tr("Page Options")).color(t.text_label)); + let p = &st.page; + for (id, label, on, key) in [ + ("printPageNumbers", "Page Numbers", p.page_numbers, "pageNumbers"), + ("printPageInfo", "Page Info", p.page_info, "pageInfo"), + ("printCropMarks", "Crop Marks", p.crop_marks, "cropMarks"), + ] { + if let Some(v) = check(ui, id, label, on) { + patch(app, &ctx, json!({"page": {(key): v}})); + } + } + } else if let Some(v) = check(ui, "printCropMarks", "Cut Guides", st.page.crop_marks) { + patch(app, &ctx, json!({"page": {"cropMarks": v}})); + } +} + fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, st: &PrintSettings, photos: usize) { let ctx = ui.ctx().clone(); let l = &st.layout; @@ -461,25 +487,7 @@ fn settings(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, }); } - heading(ui, t, "Page"); - row(ui, t, "Background", |ui| { - if let Some(c) = colour(ui, "printBackground", st.page.background) { - patch(app, &ctx, json!({"page": {"background": c}})); - } - }); - if compose::has_page_options(l.style) { - ui.label(egui::RichText::new(crate::i18n::tr("Page Options")).color(t.text_label)); - let p = &st.page; - for (id, label, on, key) in [ - ("printPageNumbers", "Page Numbers", p.page_numbers, "pageNumbers"), - ("printPageInfo", "Page Info", p.page_info, "pageInfo"), - ("printCropMarks", "Crop Marks", p.crop_marks, "cropMarks"), - ] { - if let Some(v) = check(ui, id, label, on) { - patch(app, &ctx, json!({"page": {(key): v}})); - } - } - } + page_section(app, ui, t, st); heading(ui, t, "Print Job"); row(ui, t, "Resolution", |ui| { @@ -720,10 +728,12 @@ fn package_cells( let ctx = ui.ctx().clone(); let first = ids.first().copied(); let cells: Vec = st.layout.cells_on_page(pu.page as u32).cloned().collect(); + let mut shown = Vec::new(); for c in &cells { let photo = if st.layout.style == Style::CustomPackage { c.photo.map(PhotoId).or(first) } else { first }; let rect = sheet.rect(&c.rect); paint_cell(app, painter, t, st, rect, photo, sheet, &c.rect); + shown.push(rect); let resp = ui.interact(rect, egui::Id::unique(("print-cell", c.id)), Sense::click_and_drag()); register(ui, format!("print:cell:{}", c.id), rect); if resp.clicked() || resp.drag_started() { @@ -760,6 +770,7 @@ fn package_cells( } }); } + page_options(painter, st, sheet, &shown, pu.page + 1); // the selected cell's outline and resize handle go over everything let Some(sel) = pu.selected.and_then(|s| cells.iter().find(|c| c.id == s)) else { return }; let rect = sheet.rect(&sel.rect); @@ -925,11 +936,9 @@ fn paint_cell( /// The Page Options as the print draws them ([`compose`]): crop marks at the corners of each /// photo, the page number at the bottom right and the print settings at the bottom left. -/// Packages draw none of them, as the print doesn't ([`compose::has_page_options`]). +/// Packages draw only the crop marks, as their Cut Guides at each cell's corners +/// ([`compose::has_page_options`]). fn page_options(painter: &egui::Painter, st: &PrintSettings, sheet: &Sheet, photos: &[Rect], number: usize) { - if !compose::has_page_options(st.layout.style) { - return; - } let p = &st.page; let ink = compose::mark_ink(p.background); let ink = Color32::from_rgb(ink[0], ink[1], ink[2]); @@ -946,6 +955,9 @@ fn page_options(painter: &egui::Painter, st: &PrintSettings, sheet: &Sheet, phot } } let Ok(area) = st.layout.printable() else { return }; + if !compose::has_page_options(st.layout.style) { + return; + } let area = sheet.rect(&area); let font = egui::FontId::proportional((compose::PAGE_TEXT_PT as f32 / 72.0 * sheet.scale).max(4.0)); let y = (area.bottom() + sheet.page.bottom()) / 2.0; diff --git a/crates/ui-egui/src/tests/print.rs b/crates/ui-egui/src/tests/print.rs index 68f3d328d0..7a6c380e4f 100644 --- a/crates/ui-egui/src/tests/print.rs +++ b/crates/ui-egui/src/tests/print.rs @@ -454,7 +454,37 @@ fn page_options_checkboxes_set_the_page_and_hide_for_packages() { scroll(&mut h, 600.0); click(&mut h, "button:printStyle-1"); assert!(has(&h, "check:printCropMarks"), "a contact sheet has Page Options"); - // Lightroom's packages have no Page Options + // Lightroom's packages have no page numbers or page info (they have Cut Guides, tested below) click(&mut h, "button:printStyle-2"); - assert!(!has(&h, "check:printPageNumbers") && !has(&h, "check:printCropMarks")); + assert!(!has(&h, "check:printPageNumbers") && !has(&h, "check:printPageInfo")); +} + +#[test] +fn picture_package_and_custom_package_pages_can_print_cut_guide() { + let mut h = demo(Services::default()); + open_print(&mut h); + let scroll = |h: &mut Headless, dy: f32| { + // The pointer position from the last widget interaction stays over the settings column, + // so scrolling keeps working even after combo:printPaper is out of view. + for _ in 0..4 { + h.request("ui.scroll", json!({"dy": dy}), T); + h.settle(T); + } + }; + // picture package (style 2) and custom package (style 3) both offer Cut Guides, not the + // Page Options: only crop marks, reusing page.cropMarks, labelled for packages + for style in ["button:printStyle-2", "button:printStyle-3"] { + click(&mut h, style); + scroll(&mut h, -600.0); + assert!(has(&h, "check:printCropMarks"), "{style}: a package has Cut Guides"); + assert!(!has(&h, "check:printPageNumbers") && !has(&h, "check:printPageInfo"), "{style}: packages have no page numbers or page info"); + assert!(h.painted_text().iter().any(|t| t == "Cut Guides"), "{style}: the checkbox is labelled Cut Guides: {:?}", h.painted_text()); + assert!(!h.painted_text().iter().any(|t| t == "Crop Marks"), "{style}: packages do not label it Crop Marks: {:?}", h.painted_text()); + assert!(!h.app.session.print.page.crop_marks); + click(&mut h, "check:printCropMarks"); + assert!(h.app.session.print.page.crop_marks, "{style}: Cut Guides sets crop_marks"); + click(&mut h, "check:printCropMarks"); + assert!(!h.app.session.print.page.crop_marks, "{style}: the reuse keeps reading page.cropMarks"); + scroll(&mut h, 600.0); + } } From 52134ffc952f1adf0497f58e3a9d69377cd97e38 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:37:13 +0100 Subject: [PATCH 19/30] docs: preserve local guidance in house-rules rollout --- AGENTS.md | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 354aa2b8d4..8d0ca31a60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,11 +63,12 @@ LightCraft is a clean-room, open-source, pure-Rust photo library + non-destructi verification, render fidelity against Lightroom, AI models, HDR / video / Classic modules (raw detail: [`docs/raw-parity.md`](docs/raw-parity.md)). A ✅ row is not proof of parity — if you find a ✅ feature that is wrong or incomplete, downgrade it to 🟡 with a note. -4. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row +2. **Pick work** from [`docs/gaps.md`](docs/gaps.md) (ranked by user impact; `B` marks beta blockers). The row-by-row tracker is [`docs/parity-checklist.md`](docs/parity-checklist.md) (one row per feature, menu item and shortcut). When you land a feature, update its row(s) and the gap entry in the same commit, and the numbers in `ROADMAP.md` / `docs/target-app-parity.md` when a listed gap closes (add a row to each doc's revision history; the header line keeps only `Last reviewed`, `Target` and the `Changes` link, never a `Last updated` date or a change note, which every PR would edit and conflict on); `cargo xtask parity` (part of `ci`) checks that every `cmd:`/`ctl:` id and - path the tracker cites still exists, and `cargo xtask parity --write` refreshes its summary. + path the tracker cites still exists and that `docs/gaps.md` lists each gap once, and `cargo xtask parity --write` + refreshes its summary. `plan/` stays optional. Do not stop to ask except for the house-rule list. **Merging agent branches:** merge one branch, run `cargo xtask ci`, fix, commit — then the next. Two individually green @@ -102,10 +103,10 @@ of it. - **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix. - Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with - `[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root + `workspace = true` under a `[lints]` table, and `sysmem` repeats those denies in its local lint table. Every production crate root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include - `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include + `workspace = true` under a `[lints]` table in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots` (part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib` web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception). @@ -113,10 +114,17 @@ of it. ## Non-negotiables - **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…). - **Pure Rust** in the product. No C/C++ dependencies. -- **Layering** (`plan/architecture.md` §3, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd. +- **Layering** (enforced by `cargo xtask layers`; `plan/architecture.md` §3 is optional background): nothing below L5 depends on egui/eframe/winit/rfd. - **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec. +- **Long-running work shows in the activity stack** ([`docs/background-tasks.md`](docs/background-tasks.md)): anything + that runs off the UI thread and can take more than a moment holds a `TaskGuard` from `session.activity.start(kind, + label, cancel)` for its whole run. It adopts the cancel flag the job already checks (`Cancel::Flag`), or uses + `Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row. - **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm). + For iteration, `cargo xtask ci --quick` runs fmt, clippy, changed packages' tests, layers, assets, roots, + and heif / parity / wasm when touched; it does not replace the full gate before merging branches. + One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`). - **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. ## Assets: icons, images, fonts (ABSOLUTE RULE — never violate) @@ -136,7 +144,7 @@ of it. then `CRAFT_FONTS_DIR=../craft-fonts cargo run -p lightcraft` (or any cargo/xtask command). `crates/engine/build.rs` embeds the manifest's fonts as `lightcraft_engine::CRAFT_FONTS` (wasm32: BIZ UDPGothic Regular only); `cargo xtask web` ships Noto Sans CJK SC Regular as a separate asset loaded by the UI before startup. The UI - (`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter. Unset, + (`theme::font_definitions`) and the export watermark renderer use CJK faces (picked by script) as fallbacks after Inter; the UI also falls back on the faces of other scripts (Thai, Arabic, …). Unset, `CRAFT_FONTS` is empty: everything builds, tests and runs, but Chinese and Japanese text lack glyphs. Releases always build with it (`release.yml`, `CRAFT_FONTS_REQUIRED=1`) and ship the fonts' OFL licences. Tests that need these fonts skip without it; the FreeBSD CI job runs them with it. @@ -153,7 +161,9 @@ of it. - **Never send OS-level synthetic input** (osascript/System Events keystrokes or clicks, `cliclick`, accessibility automation): it goes to whatever window is frontmost — the user's terminal or other apps. Drive LightCraft only through its control channel (`ui.key`, `ui.pointer`, `ui.clickWidget`, `ui.menu.invoke`) or headless snapshots. -- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`, compare with `plan/lightroom/screenshots/`. +- For UI work, **look at the result**: drive via the control channel and take `ui.screenshot`. Compare with + `plan/lightroom/screenshots/` when available. Without that optional notebook, verify the result against the + task's requirements, committed documentation and regression tests; do not request the notebook or block work. - **Unattended (display asleep/locked, CI, nightly runs): prefer headless snapshots** — no window needed: `lightcraft-cli snapshot --demo --script tour.jsonl -o out.png --size 1600x1000` (control-protocol requests, one per line; see `docs/control-protocol.md` → Headless rendering). In a running app use @@ -162,7 +172,9 @@ of it. the running app). See `docs/mcp.md`. Quick non-UI checks: `lightcraft-cli render in.jpg -o out.jpg --set light.exposure=1`. - Export goes through `lightcraft_engine::export` (one encoder for app, CLI, MCP and web); UI-only commands live in `crates/ui-egui/src/menus.rs`. -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. +- Text boxes use `crates/ui-egui/src/widgets/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the + Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id + that is unique on screen. Older fields still on `TextEdit` move over as they are touched. - Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). - Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. - Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. From ba8caf8fa61b19fa372452b65ca3254cc41c9d81 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:49:28 +0200 Subject: [PATCH 20/30] Honor inverted Lightroom masks when importing catalog edits Users importing a Lightroom catalog see masks that darken or lighten the wrong part of the photo, even though the mask exposure value itself looks correct. Carry the inverted flag through catalog mask orientation handling for develop and XMP masks, and add a regression test with an inverted radial mask. Test: inverted_radial_mask_keeps_its_inversion_on_import failed before the change and passes after. --- crates/engine/src/lightroom_catalog.rs | 25 +++++++++++++++++++- crates/engine/src/lightroom_catalog/tests.rs | 16 +++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 8647be9b39..f1602eabde 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -705,7 +705,12 @@ fn mapped_settings( ) -> Result<(Value, Vec), String> { let mut root = crate::preset_import::parse_lua(text)?; let deferred = strip_lua_sentinels(&mut root); - let (mut props, values) = crate::preset_import::lua_settings_props(&root)?; + let (mut props, mut values) = crate::preset_import::lua_settings_props(&root)?; + // Catalog Lua names the component inversion `Inverted` while XMP's is `MaskInverted`; + // rename it so an inverted mask keeps its inversion instead of importing as normal. + for v in values.values_mut() { + alias_catalog_inverted(v); + } // A catalog's develop settings carry the crop edges and angle but no `HasCrop` (XMP has it): // any crop field means the photo is cropped. const CROP: [&str; 5] = ["crs:CropLeft", "crs:CropTop", "crs:CropRight", "crs:CropBottom", "crs:CropAngle"]; @@ -787,6 +792,24 @@ fn in_photo_frame(catalog: Orientation, user: Orientation) -> Orientation { (0..turns).fold(o, |o, _| o.rotated(true)) } +/// Rename a catalog Lua component's `Inverted` to XMP's `MaskInverted` (see [`mapped_settings`]); +/// a `crs:MaskInverted` already present wins, and this does not touch `Flipped`. +fn alias_catalog_inverted(v: &mut lightcraft_meta::XmpValue) { + use lightcraft_meta::XmpValue; + match v { + XmpValue::Array(items) => items.iter_mut().for_each(alias_catalog_inverted), + XmpValue::Struct(map) => { + if let Some(inverted) = map.remove("crs:Inverted") + && !map.contains_key("crs:MaskInverted") + { + map.insert("crs:MaskInverted".into(), inverted); + } + map.values_mut().for_each(alias_catalog_inverted); + } + XmpValue::Text(_) => {} + } +} + /// Lightroom's masks in LightCraft's frame. Like the crop's corners, their positions are on the /// stored image (before orientation), normalized to its size; LightCraft's are on the oriented /// image. So the points go through the orientation, a radial's radii (in long-edge units, from the diff --git a/crates/engine/src/lightroom_catalog/tests.rs b/crates/engine/src/lightroom_catalog/tests.rs index e2952fd000..f1d0dd1fc6 100644 --- a/crates/engine/src/lightroom_catalog/tests.rs +++ b/crates/engine/src/lightroom_catalog/tests.rs @@ -850,6 +850,22 @@ fn catalog_masks_follow_the_photo_orientation() { assert!(close(&radial["rx"], 0.1) && close(&radial["ry"], 0.1), "{radial}"); } +#[test] +fn inverted_radial_mask_keeps_its_inversion_on_import() { + // #2475: an inverted radial (LocalExposure2012 applies outside the ellipse) keeps its + // inversion when the catalog import also turns the mask for the photo's orientation + let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = { + { What = "Mask/CircularGradient", Left = 0, Right = 0.2, Top = 0.1, Bottom = 0.3, Angle = 10, Feather = 50, Version = 2, Flipped = true, Inverted = true } } } } }"#; + let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap(); + let c = &partial["masks"][0]["components"][0]; + let close = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-9; + // the orientation is applied: (x, y) → (1 − y, x), a quarter turn clockwise; the radii swap + let shape = &c["shape"]; + assert!(close(&shape["center"]["x"], 0.8) && close(&shape["center"]["y"], 0.1), "{shape}"); + // but the effect stays outside the ellipse + assert!(c["invert"].as_bool().unwrap_or(false) || shape["invert"].as_bool().unwrap_or(false), "{c}"); +} + /// The `crs` corners and angle Lightroom would store for LightCraft crop `g` on a stored image /// of aspect `w` (height 1) shown with orientation `o`. fn lightroom_crop(g: CropGeometry, o: Orientation, w: f64) -> String { From 081190c92f4f74340a7fc4125fce1fe6d2b60ed9 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 14:05:15 +0200 Subject: [PATCH 21/30] Match renamed missing files by content when size is unknown (#3852) Libraries created on another OS may have no recorded file size for some photos. After moving OS and renaming the file, Find Missing should still relink it by its content hash instead of leaving it missing. Allow plan_find_missing to match renamed files by content hash when size is unknown by hashing unused candidate files, and add a regression test with a Windows-style path, unknown size, known hash and a renamed file in the searched folder. Test: find_missing_matches_renamed_file_by_content_without_size failed before the change and passes after. Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> --- crates/engine/src/cmd/missing.rs | 37 +++++++++++++++++-------------- crates/engine/src/tests/import.rs | 34 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 17454cac26..0c77d709cd 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -266,7 +266,7 @@ pub fn find_candidates(cat: &Catalog) -> Vec { pub enum MatchBy { /// Same name and size (and content, when the library knows its hash). Name, - /// Renamed: same size and content hash. + /// Renamed: same content hash (and size, when the library knows it). Content, } @@ -360,8 +360,8 @@ fn name_key(path: &str) -> String { /// Matching, per photo: /// 1. a file with the same name ([`name_key`]: any letter case), the same size and the same /// content hash; -/// 2. renamed: a file of the same size with the same content hash (only same-size files are -/// read, so this stays cheap); +/// 2. renamed: a file with the same content hash (and the same size, when one is on record; with +/// no size on record every file is read, but the hash alone confirms identity); /// 3. without a hash to confirm (or the file was edited in place): the one file with the same /// name and size. Several such files are ambiguous: the photo is skipped and reported in /// `ambiguous`, never guessed (two cameras' `IMG_0001.CR3` of one size are different photos). @@ -406,24 +406,27 @@ pub fn plan_find_missing(candidates: &[FindCandidate], folder: &str) -> std::res // 1. same name and size, confirmed by the content hash let mut hit: Option<(String, MatchBy)> = hash.and_then(|h| named.iter().find(|f| hash_of(f).as_deref() == Some(h))).map(|f| (f.to_string(), MatchBy::Name)); - // 2. renamed: same size and content + // 2. renamed: same content, and same size when one is on record if hit.is_none() && let Some(h) = hash - && size > 0 { - let sizes = by_size.get_or_insert_with(|| { - let mut m: HashMap> = HashMap::new(); - for f in &files { - if let Some(n) = size_of(f) { - m.entry(n).or_default().push(f.clone()); + if size > 0 { + let sizes = by_size.get_or_insert_with(|| { + let mut m: HashMap> = HashMap::new(); + for f in &files { + if let Some(n) = size_of(f) { + m.entry(n).or_default().push(f.clone()); + } } - } - m - }); - hit = sizes - .get(&size) - .and_then(|v| v.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h))) - .map(|f| (f.clone(), MatchBy::Content)); + m + }); + hit = sizes + .get(&size) + .and_then(|v| v.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h))) + .map(|f| (f.clone(), MatchBy::Content)); + } else { + hit = files.iter().find(|f| !used.contains(*f) && hash_of(f).as_deref() == Some(h)).map(|f| (f.clone(), MatchBy::Content)); + } } // 3. same name and size only (no hash, or the file was edited in place): one candidate // is taken, several are ambiguous and skipped rather than guessed diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 34e301a6fd..4885b5d30b 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -494,6 +494,40 @@ fn find_missing_matches_renamed_files_by_content() { let _ = std::fs::remove_dir_all(&dir); } +/// A renamed file whose size is unknown (0) but whose content hash is known is still found by +/// content: the hash alone is enough to confirm it is the same photo. +#[test] +fn find_missing_matches_renamed_file_by_content_without_size() { + use lightcraft_catalog::{Op, Photo, Source}; + let dir = temp_dir("missing-no-size"); + std::fs::create_dir_all(dir.join("found")).unwrap(); + let content = b"same pixels as the original"; + let renamed = dir.join("found").join("Trip-001.png"); + std::fs::write(&renamed, content).unwrap(); + let hash = lightcraft_preview::hash_bytes(content).to_string(); + let mut s = Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new( + id, + Source::File { path: dir.join("gone").join("orig.png").to_string_lossy().into_owned() }, + "orig.png", + "PNG", + 48, + 32, + "2026-01-01T10:00:00", + ); + p.file_size = 0; + p.content_hash = Some(hash); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let r = s.execute("library.findMissing", &json!({"folder": dir.join("found").to_string_lossy()})).unwrap(); + let found = r["found"].as_array().map(Vec::len); + assert_eq!(found, Some(1), "renamed file matched by content without a recorded size: {r}"); + assert_eq!(r["found"][0]["to"], json!(renamed.to_string_lossy().to_string()), "{r}"); + assert_eq!(r["found"][0]["by"], json!("content"), "{r}"); + assert_eq!(r["missing"], 0, "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// Issue #104: the app plans Find Missing on a worker thread (no session) and relinks the plan /// afterwards; that gives exactly what the synchronous command gives — renamed files by content, /// impostors and look-alikes skipped (`ambiguous`). From 8f638b33bd3bc3f31ae4d66c9fdd003df783aba1 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 15:46:11 +0200 Subject: [PATCH 22/30] Treat a first intersect mask component as its base selection (#3854) * Treat a first intersect mask component as its base selection A mask created with Intersect as its first component currently renders as empty, so the overlay and local adjustments never appear. Using that component as the base matches how Add and Subtract first components already behave. Change evaluate_one so the first component always sets the base alpha regardless of its combine op. Add a regression test with a single Intersect linear-gradient component asserting the start side is selected. Test: intersect_first_component_selects_its_shape failed before the change and passes after. * Masks: the GPU treats a first Intersect as the base too, and the process doc says so Co-Authored-By: Claude Opus 5.5 * Docs: what changes for masks that start with Intersect Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/gpu/src/render.rs | 2 +- crates/pipeline/src/masks.rs | 2 +- crates/pipeline/src/masks/tests.rs | 11 +++++++++++ docs/process-versions.md | 6 ++++++ 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 8e6afa3700..de8c7ff16c 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -1480,7 +1480,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho let mut first = true; for comp in &m.components { let op = match comp.op { - _ if first && comp.op != MaskOp::Intersect => 0u32, + _ if first => 0u32, MaskOp::Add => 1, MaskOp::Subtract => 2, MaskOp::Intersect => 3, diff --git a/crates/pipeline/src/masks.rs b/crates/pipeline/src/masks.rs index 097e080a7e..b40e3dcd97 100644 --- a/crates/pipeline/src/masks.rs +++ b/crates/pipeline/src/masks.rs @@ -161,7 +161,7 @@ pub fn evaluate_one(m: &Mask, frame: &Frame, w: usize, h: usize, img: &Rgb32f, l if comp.invert { c.data.iter_mut().for_each(|v| *v = 1.0 - *v); } - if first && comp.op != MaskOp::Intersect { + if first { alpha = c; first = false; continue; diff --git a/crates/pipeline/src/masks/tests.rs b/crates/pipeline/src/masks/tests.rs index c97cd290e4..b57f9f6688 100644 --- a/crates/pipeline/src/masks/tests.rs +++ b/crates/pipeline/src/masks/tests.rs @@ -629,3 +629,14 @@ fn people_and_subject_use_person_mattes() { let lips = MaskShape::People { person: 0, parts: vec!["Lips".into()] }; assert_eq!(eval(&lips), shape_alpha(&lips, &f, w, h, &img, &l, 0.0, None)); } + +#[test] +fn intersect_first_component_selects_its_shape() { + let f = frame(100, 100); + let img = Rgb32f::new(100, 100); + let l = Plane::new(100, 100); + let shape = MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.2, ry: 0.2, angle: 0.0, feather: 20.0, invert: false }; + let m = Mask { components: vec![MaskComponent { name: None, op: MaskOp::Intersect, invert: false, shape }], ..Default::default() }; + let a = evaluate_one(&m, &f, 100, 100, &img, &l, 0.0, None); + assert!(a.get(50, 50) > 0.99 && a.get(5, 5) < 0.01, "intersect first: {} {}", a.get(50, 50), a.get(5, 5)); +} diff --git a/docs/process-versions.md b/docs/process-versions.md index 7d1ae1927c..154906de0b 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -40,6 +40,12 @@ exports. Existing AI masks become 1–2 px tighter at a subject's edges, on ever inside, their outside and edges without contrast in the photo are unchanged. It landed in place as a bug fix: the outline is output that isn't in the photo nor in the edit, not a look anyone chose. +**A mask whose first component is Intersect** starts from that component, on the CPU and the GPU +(issue #1889). It used to start from nothing, so alone it selected nothing, with a later Add it gave +only what was added, and with the mask's Invert it gave the whole photo. Such masks now include the +first component, on every process. It landed in place as a bug fix: intersecting with nothing is not +a look anyone chose. + ## Adding a process 1. Add a variant to `Process` (`V2`), append it to `Process::ALL` (oldest first), give it its number in From e354de502b92d787bacc02fe3b42accd84baa230 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 16:15:23 +0200 Subject: [PATCH 23/30] Use adapter texture limit for probed window device (#3853) * Use adapter texture limit for probed window device Mixed-DPI dragging can grow the window past 8192 px; the probed device should allow the adapter's full texture size so the window keeps rendering. Change probe to request the adapter's max_texture_dimension_2d and add a GPU test asserting the probed device matches the adapter limit. Test: probed_device_uses_adapter_max_texture_size failed before the change and passes after. * Window device: the adapter's texture limit on GL too, which the conservative defaults would cap at 2048 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 04e85136a8..9c588a6f61 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -219,7 +219,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result Date: Fri, 6 Nov 2026 09:17:31 -0600 Subject: [PATCH 24/30] Issue #3768: dialog_role tests draw glyphs only craft-fonts has as boxes when built without it (#3769) Settings lists each language by its own name, and Georgian has glyphs only in the craft-fonts faces, so egui_kittest's missing-glyph panic failed settings_is_a_dialog_too in every build without CRAFT_FONTS_DIR. Allow missing glyphs there, as tests/it/accessibility.rs does: these tests check roles and titles, not glyphs. Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps --- crates/ui-egui/tests/it/dialog_role.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/dialog_role.rs b/crates/ui-egui/tests/it/dialog_role.rs index 5856c5bffa..c8b136b704 100644 --- a/crates/ui-egui/tests/it/dialog_role.rs +++ b/crates/ui-egui/tests/it/dialog_role.rs @@ -8,7 +8,14 @@ use lightcraft_ui_egui::{LightcraftApp, Services}; fn harness() -> Harness<'static, LightcraftApp> { let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); app.headless_host = true; - let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)).build_ui_state( + let mut builder = Harness::builder().with_size(vec2(1500.0, 950.0)); + // Settings lists each language by its own name, and some scripts (Georgian, the CJK + // languages) have glyphs only in the craft-fonts faces (releases always have them): without + // them the names are drawn as boxes, which this check of roles and titles doesn't need + if lightcraft_engine::CRAFT_FONTS.is_empty() { + builder = builder.allow_missing_glyphs(); + } + let mut h = builder.build_ui_state( |ui, app: &mut LightcraftApp| { app.logic(&ui.ctx().clone()); app.ui(ui); From 097dac4566e7e3979a9f2860f288c69a77176263 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:03:17 +0100 Subject: [PATCH 25/30] Stabilize sidebar month-name test fixture (#3859) Inject an empty local folder list so asynchronous host discovery cannot move rows between queued clicks. Preserve both clicks and all accessibility assertions. Fixes #3858 Co-authored-by: FredApps --- crates/ui-egui/tests/it/sidebar_names.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/sidebar_names.rs b/crates/ui-egui/tests/it/sidebar_names.rs index a6e35aca2a..a81d641345 100644 --- a/crates/ui-egui/tests/it/sidebar_names.rs +++ b/crates/ui-egui/tests/it/sidebar_names.rs @@ -51,7 +51,8 @@ fn a_month_triangle_names_its_year() { for (id, captured) in ids.into_iter().zip(["2025-03-05T10:00:00", "2026-03-05T10:00:00"]) { session.catalog.apply(lightcraft_catalog::Op::SetCaptured { id, captured: Some(captured.into()) }).expect("the capture time is set"); } - let mut app = LightcraftApp::new(session, Services { png: None, ..Default::default() }); + // Keep host-folder discovery from moving rows between a queued click and its frame (#3858). + let mut app = LightcraftApp::new(session, Services { png: None, local_places: Some(Vec::new()), ..Default::default() }); app.headless_host = true; app.ui.left_panel = true; app.ui.view = ViewMode::PhotoGrid; From 1b5b7665138c790c0396cda20207249140153fb8 Mon Sep 17 00:00:00 2001 From: lostwald Date: Fri, 6 Nov 2026 17:46:43 +0100 Subject: [PATCH 26/30] WEB-WORKER-PARITY: compare serialized jobs with the CPU reference (#3782) Fix #3778: native thumbnail jobs can use an already initialized GPU, making exact worker serialization assertions depend on test order. Keep exact image and histogram assertions against the engine CPU pipeline. The separate native window equivalence test is unchanged. Validation: reproduced on clean main 56d1cc28 using serial web tests (37 pass, 1 fail), then all 38 web tests pass both serially and in parallel. Full cargo xtask ci passes all eight gates on parent 2e66a00d with craft-fonts and Metal (152 external-data skips). Latest main has separate dithering/cutoff-test failures tracked as #3780; no GPU disabling or assertion weakening used. Assisted-by: OpenAI GPT-6.1 Sol Co-authored-by: FredApps --- apps/lightcraft-web/src/wire.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index afdb8e0e9d..e7202bbc59 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -468,7 +468,11 @@ mod tests { let mut core = WorkerCore::default(); assert_eq!(core.needs_original(&wire), None, "demo scenes are generated"); let a = core.render(&wire, None).unwrap(); - let b = job.run().rendered.unwrap(); + // The worker uses the CPU. A native thumbnail job may use an already initialized GPU, + // so exact serialization parity must use the engine's CPU reference (#3778), regardless + // of test order. The window test above separately checks native CPU/GPU equivalence. + let source = job.source.load_source().unwrap(); + let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info), &job.settings, &job.request); assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height)); assert_eq!(a.image.data, b.image.data); assert_eq!(a.histogram, b.histogram); From 8a0b91a95c30618b690374dd2db9d0684ebc9b23 Mon Sep 17 00:00:00 2001 From: eliets2 Date: Fri, 6 Nov 2026 18:59:03 +0200 Subject: [PATCH 27/30] GPU float output for the HDR render (F32Hdr) (#3856) * Render HDR rendition on GPU for HDR display drafts HDR edits on HDR displays currently pay for a second CPU float render on every full render and show only SDR during drags, making slider drags several times slower. Allow F32Hdr requests through the GPU path with a float output target matching the CPU HDR rendition, and let draft renders carry HDR again instead of being excluded. Test: gpu_handles_f32hdr_renders_for_hdr_display failed before the change and passes after. * Issue #2297: float output from the GPU's finish kernel for the HDR render The kernel wrote 8 bits only, so `handles` taking F32Hdr left no float samples. It now keeps values up to the edit's peak (highlight desaturation, vignette, gamut map, curves above SDR white, grain, LUT profiles, as finish_with does), encodes with the exact sRGB curve as a float render does on the CPU, and writes three linear floats per pixel into `out`. Written words carry the sign bit, so work that never ran still fails the render instead of reading as black. hdr_histogram keeps its Quality::Draft exclusion: it renders on the CPU, and the UI already runs a small render beside the drafts. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 1 + crates/gpu/src/lib.rs | 16 ++-- crates/gpu/src/params.rs | 15 +++- crates/gpu/src/render.rs | 45 ++++++++++- crates/gpu/src/wgsl/finish.wgsl | 91 ++++++++++++++++----- crates/gpu/tests/it/equivalence.rs | 125 ++++++++++++++++++++++++++++- crates/gpu/tests/it/fallback.rs | 9 +++ docs/gpu-pipeline.md | 10 ++- 8 files changed, 278 insertions(+), 34 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index dee6205a36..6b683783f5 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -430,6 +430,7 @@ fn constants() -> String { for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } + s += &format!("const DEEP_WRITTEN: u32 = {}u;\n", crate::params::DEEP_WRITTEN); for (name, idx) in crate::params::finish_fields() { s += &format!("const F_{name}: u32 = {idx}u;\n"); } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index faac8634d7..1e06e9f1ad 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -504,12 +504,16 @@ pub fn render(src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &R } /// Whether the GPU renders requests of this kind at all (a given render can still fall back to -/// the CPU): the kernel writes 8-bit output, so high-bit-depth exports render on the CPU, and so do -/// soft proofs against an output-device profile (`device_proof`: its 3D table is CPU-side) and -/// Visualize HDR, which needs the float HDR render. [`try_render`] follows it, and the loupe sizes -/// its slider-drag drafts by it (issue #330), so the two can't drift apart. +/// the CPU): the kernel writes 8-bit output and the float HDR render (`F32Hdr`, in +/// [`Rendered::deep`](lightcraft_pipeline::Rendered::deep)); 16-bit and linear float exports render +/// on the CPU, and so do soft proofs against an output-device profile (`device_proof`: its 3D table +/// is CPU-side) and Visualize HDR, which draws the float render over the 8-bit one. [`try_render`] +/// follows it, and the loupe sizes its slider-drag drafts by it (issue #330), so the two can't drift +/// apart. pub fn handles(depth: lightcraft_pipeline::OutputDepth, device_proof: bool, overlay: lightcraft_pipeline::Overlay) -> bool { - depth == lightcraft_pipeline::OutputDepth::U8 && !device_proof && overlay != lightcraft_pipeline::Overlay::HdrRange + matches!(depth, lightcraft_pipeline::OutputDepth::U8 | lightcraft_pipeline::OutputDepth::F32Hdr) + && !device_proof + && overlay != lightcraft_pipeline::Overlay::HdrRange } /// [`render`], reporting why this render made no GPU image: [`Fallback::NotTried`] when the GPU @@ -748,7 +752,9 @@ mod tests { fn the_gpu_handles_8_bit_unproofed_renders_without_the_hdr_range() { assert!(super::handles(OutputDepth::U8, false, Overlay::None)); assert!(super::handles(OutputDepth::U8, false, Overlay::Spots(50))); + assert!(super::handles(OutputDepth::F32Hdr, false, Overlay::None)); assert!(!super::handles(OutputDepth::U16, false, Overlay::None)); + assert!(!super::handles(OutputDepth::F32Linear, false, Overlay::None)); assert!(!super::handles(OutputDepth::U8, true, Overlay::None)); assert!(!super::handles(OutputDepth::U8, false, Overlay::HdrRange)); } diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 97244b6a04..5776c48caa 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -10,6 +10,10 @@ use crate::ctx::{FailKind, fail}; /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; +/// Set on every word of a float render's output: the values are at least 0, so the sign bit is +/// free, and it tells a written 0 from a word the kernel never reached. +pub const DEEP_WRITTEN: u32 = 1 << 31; + /// Field name and number of 32-bit words. const FIELDS: &[(&str, usize)] = &[ ("W", 1), @@ -103,6 +107,11 @@ const FIELDS: &[(&str, usize)] = &[ ("LIGHT_MODE", 2), ("LIGHT_W", 2), ("LIGHT_OFF", 1), + // the render's peak over SDR white (`FinishParams::peak`; above 1: an HDR render) + ("PEAK", 1), + // a float render (`finish_deep`): the exact sRGB curve, and three words per pixel in `out`, each + // a linear value with `DEEP_WRITTEN` set + ("DEEP", 1), ]; /// `(name, index)` of every field (for the WGSL constants). @@ -171,9 +180,11 @@ pub struct Present { /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | /// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). /// +/// `deep`: the kernel writes float samples, as the pipeline's `finish_deep` does. +/// /// A curve whose length is not [`CURVE_N`] fails the render ([`FailKind::Fatal`]) and returns an /// empty parameter block with a truncated aux table, which the caller discards (CPU fallback). -pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { +pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present, deep: bool) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); let srgb_off = aux.len(); @@ -221,6 +232,8 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr } } p.fs("LIGHT_W", &light.iter().map(|op| op.weight).collect::>()); + p.f("PEAK", fp.peak); + p.b("DEEP", deep); p.u("W", fp.w as u32); p.u("H", fp.h as u32); p.u("NMASK", masks.len() as u32); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index de8c7ff16c..2b20866e64 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -15,7 +15,7 @@ use lightcraft_raster::resample::Filter; use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8}; use crate::ctx::{Buf, FailKind, Gpu, fail, groups1, groups2}; -use crate::params::{Present, finish_block}; +use crate::params::{DEEP_WRITTEN, Present, finish_block}; /// Device-resident stages of one view, kept next to the CPU [`lightcraft_pipeline::StageCache`] /// (as its extension). Holds the last two output sizes, like the CPU cache. @@ -752,7 +752,9 @@ pub fn render( }); // soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`) fp.proof = req.proof.map(|pr| pr.params(req.space)); - if let Some(d) = &req.display { + // a float render is `finish_deep`: its samples are the output space's, whatever the display + let deep = req.depth != lightcraft_pipeline::OutputDepth::U8; + if let Some(d) = req.display.as_ref().filter(|_| !deep) { fp.for_display(d, req.proof); } let present = Present { @@ -774,13 +776,13 @@ pub fn render( (Some(b), None) | (None, Some(b)) => Some(b.clone()), (None, None) => None, }; - let (p, aux) = finish_block(&fp, &terms, &present); + let (p, aux) = finish_block(&fp, &terms, &present, deep); if crate::ctx::failed() { return None; // a malformed parameter block failed the render: the CPU fallback redoes it } let aux = gpu.upload(&aux); // cleared, so that work which never ran cannot pass for an image (see the check below) - let out = cx.zeroed(n); + let out = cx.zeroed(if deep { 3 * n } else { n }); if fault == Some(crate::Fault::Validation) { // a dispatch the device rejects (too many workgroups) cx.run("box_h", &[0; 5], &[Some(&aux), Some(&out)], [gpu.device.limits().max_compute_workgroups_per_dimension + 1, 1, 1]); @@ -808,6 +810,11 @@ pub fn render( groups2(w, rows.min(h - y0), [16, 16]), ); } + if deep { + let rendered = read_deep(&mut cx, &out, &plan, req); + lap("finish + readback (deep)", &mut t, &mut cx); + return rendered.map(Output::Image); + } if display && can_display(gpu, &plan, req) { return to_texture(&mut cx, &out, w, h).map(|(frame, histogram)| Output::Display { frame, histogram }); } @@ -890,6 +897,36 @@ pub fn render( Some(Output::Image(Rendered { image, histogram, deep: None })) } +/// The finished float output `out` (three words per pixel) read back as the CPU's float render +/// returns it, with the same checks as an 8-bit readback: every pixel written, not entirely black. +fn read_deep(cx: &mut Cx<'_>, out: &Buf, plan: &Plan<'_>, req: &RenderRequest) -> Option { + use lightcraft_pipeline::{DeepImage, DeepSamples}; + let (w, h) = (plan.w, plan.h); + let n = w * h; + let words: Vec = cx.read(out, 3 * n); + if crate::ctx::failed() { + return None; + } + let unwritten = words.as_chunks::<3>().0.iter().filter(|p| p.iter().any(|v| v & DEEP_WRITTEN == 0)).count(); + if unwritten > 0 { + fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {n} pixels unwritten)")); + return None; + } + let samples = words.into_iter().map(|v| f32::from_bits(v & !DEEP_WRITTEN)).collect(); + let deep = DeepImage { width: w, height: h, space: req.space, samples: DeepSamples::F32(samples) }; + let deep = match plan.keep { + Some(k) => deep.crop(k.x, k.y, k.w, k.h), + None => deep, + }; + let image = deep.to_rgba8(); + let histogram = Histogram::of_srgb8(&image); + if n >= 4096 && [&histogram.r, &histogram.g, &histogram.b].iter().all(|c| c.first() == Some(&histogram.total)) { + fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into()); + return None; + } + Some(Rendered { image, histogram, deep: Some(deep) }) +} + /// The finished output `out` (`w × h` packed RGBA8) as a texture on the device, with its /// histogram; the same checks as a readback (every pixel written, not entirely black), done on /// the device: only the histogram and a pixel count come back. diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 9e589f4ca9..266599644a 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -1,7 +1,8 @@ // The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it). // Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the // blurred chromaticity when HAS_CHROMA), aux -// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8). +// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8; a float render: +// three words per pixel, see `F_DEEP`). fn tone_apply(y: f32) -> f32 { if (y <= 0.0) { @@ -39,12 +40,33 @@ fn encode_srgb(v: f32) -> f32 { return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; } +// `linear_to_srgb`: the exact sRGB curve, unbounded above 1 (a float render encodes with it). +fn srgb_exact(v: f32) -> f32 { + if (v <= 0.0031308) { + return v * 12.92; + } + return 1.055 * pow(v, 1.0 / 2.4) - 0.055; +} + +// `srgb_to_linear`. +fn srgb_linear(v: f32) -> f32 { + if (v <= 0.04045) { + return v / 12.92; + } + return pow((v + 0.055) / 1.055, 2.4); +} + +// Above SDR white (an HDR render) the curves continue with slope 1 from their end point. fn curve(ch: u32, x: f32) -> f32 { let o = pu(F_CURVE_OFF) + ch * CURVE_N; let f = clamp(x, 0.0, 1.0) * f32(CURVE_N - 1u); let i = min(u32(f), CURVE_N - 2u); let t = f - f32(i); - return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; + let v = aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; + if (x > 1.0 && pf(F_PEAK) > 1.0) { + return v + (x - 1.0); + } + return v; } // Process V4's calibrated Contrast, Blacks (`lightcraft_pipeline::light_v3`): operator `k`'s @@ -65,6 +87,9 @@ fn light_channel(k: u32, x: f32) -> f32 { if (x < 0.0) { return aux[pu(F_LIGHT_OFF) + k * LIGHT_N] + x; } + if (pu(F_DEEP) != 0u) { + return light_eval(k, srgb_exact(x)); + } return light_eval(k, encode_srgb(x)); } @@ -365,25 +390,25 @@ fn out_encode(v: f32) -> f32 { return 1.099 * pow(l, 0.45) - 0.099; } -// `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ... -fn gamut_scale(r: vec3, luma: vec3) -> f32 { - let yy = clamp(dot(luma, r), 0.0, 1.0); +// `finish::gamut_map_to`: the chroma scale that brings `r` into 0..top towards its luminance (1: in gamut) ... +fn gamut_scale(r: vec3, luma: vec3, top: f32) -> f32 { + let yy = clamp(dot(luma, r), 0.0, top); var tg = 1.0; for (var k = 0u; k < 3u; k++) { let cc = r[k]; if (cc < 0.0) { tg = min(tg, yy / max(yy - cc, 1e-9)); - } else if (cc > 1.0) { - tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9)); + } else if (cc > top) { + tg = min(tg, (top - yy) / max(cc - yy, 1e-9)); } } return tg; } // ... and `r` scaled by it. -fn gamut_apply(r: vec3, luma: vec3, tg: f32) -> vec3 { +fn gamut_apply(r: vec3, luma: vec3, tg: f32, top: f32) -> vec3 { if (tg < 1.0) { - let yy = clamp(dot(luma, r), 0.0, 1.0); + let yy = clamp(dot(luma, r), 0.0, top); return yy + (r - yy) * tg; } return r; @@ -402,6 +427,9 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let n = w * h; let gain = pf(F_GAIN); let ev = pf(F_EV); + let peak = pf(F_PEAK); + let hdr = peak > 1.0; + let deep = pu(F_DEEP) != 0u; var c = vec3(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]); if (gain != 1.0) { c = c * gain; @@ -567,8 +595,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { d = vec3(o) + (d - vec3(o)) * k; } let mx = max(d.x, max(d.y, d.z)); - if (mx > 1.0) { - let t = clamp((mx - 1.0) / max(mx - o, 1e-6), 0.0, 1.0); + if (mx > peak) { + let t = clamp((mx - peak) / max(mx - o, 1e-6), 0.0, 1.0); d = d + (o - d) * t; } @@ -615,6 +643,9 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } else { d = d * f; } + } else if (hdr) { + // lighten towards SDR white; never pull HDR highlights down to it + d = d + max(1.0 - d, vec3(0.0)) * amount * t * 0.85; } else { d = d + (1.0 - d) * amount * t * 0.85; } @@ -628,23 +659,28 @@ fn main(@builtin(global_invocation_id) gid: vec3) { var r: vec3; if (pu(F_PROOF) != 0u) { let q0 = mul3(mat_at(F_PROOF_M), d); - let tq = gamut_scale(q0, vec3(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u))); + let tq = gamut_scale(q0, vec3(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), peak); if (pu(F_PROOF_DEST_WARN) != 0u && out_of_gamut(q0, tq)) { warn = 1u; } - r = mul3(mat_at(F_PROOF_OUT), gamut_apply(q0, vec3(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), tq)); + r = mul3(mat_at(F_PROOF_OUT), gamut_apply(q0, vec3(pf(F_PROOF_Y), pf(F_PROOF_Y + 1u), pf(F_PROOF_Y + 2u)), tq, peak)); } else { r = mul3(mat_at(F_OUT_M), d); } let oy = vec3(pf(F_OUT_Y), pf(F_OUT_Y + 1u), pf(F_OUT_Y + 2u)); - let tg = gamut_scale(r, oy); + let tg = gamut_scale(r, oy, peak); if (pu(F_PROOF) != 0u && pu(F_PROOF_DISP_WARN) != 0u && warn == 0u && out_of_gamut(r, tg)) { warn = 2u; } - r = gamut_apply(r, oy, tg); + r = gamut_apply(r, oy, tg, peak); // --- encode, curves, grain var e = vec3(encode_srgb(r.x), encode_srgb(r.y), encode_srgb(r.z)); + if (deep) { + // the exact curve; an HDR render's values above SDR white encode above 1 + let q = select(clamp(r, vec3(0.0), vec3(1.0)), max(r, vec3(0.0)), hdr); + e = vec3(srgb_exact(q.x), srgb_exact(q.y), srgb_exact(q.z)); + } if (pu(F_CURVES) != 0u) { let e0 = e; e = vec3(curve(0u, e.x), curve(1u, e.y), curve(2u, e.z)); @@ -663,19 +699,38 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let seed = pu(F_GRAIN_SEED); var g = grain_noise(gx * sc, gy * sc, seed); g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; - let lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; + var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; + if (hdr) { + lum = clamp(lum, 0.0, 1.0); + } let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); e = e + k; } if (pu(F_LUT) != 0u) { - let m = lut_apply(clamp(e, vec3(0.0), vec3(1.0))); - e = e + (m - e) * pf(F_LUT_AMT); + let lc = clamp(e, vec3(0.0), vec3(1.0)); + let m = lut_apply(lc); + if (hdr) { + // the LUT sees SDR values; the part above SDR white is carried over + e = e + (m - lc) * pf(F_LUT_AMT); + } else { + e = e + (m - e) * pf(F_LUT_AMT); + } } if (warn == 1u) { e = vec3(PROOF_DEST_R, PROOF_DEST_G, PROOF_DEST_B); } else if (warn == 2u) { e = vec3(PROOF_DISP_R, PROOF_DISP_G, PROOF_DISP_B); } + if (deep) { + // `finish_deep`: linear, 0..peak. The sign bit a value in that range leaves free says the + // word was written (`DEEP_WRITTEN`: `out` starts cleared, and 0 is a valid value). + let o3 = 3u * i; + for (var k = 0u; k < 3u; k++) { + let v = select(0.0, min(srgb_linear(e[k]), peak), e[k] > 0.0); + out[o3 + k] = bitcast(v) | DEEP_WRITTEN; + } + return; + } e = vec3(out_encode(e.x), out_encode(e.y), out_encode(e.z)); let abs_x = u32(pf(F_VIG_VIEW)) + x; let abs_y = u32(pf(F_VIG_VIEW + 1u)) + y; diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 24359dbe8e..8c87dd7e26 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -16,6 +16,9 @@ use lightcraft_raster::{Rgb32f, Rgba8}; const MEAN_LSB: f64 = 0.5; const MAX_LSB: u8 = 3; +/// Float renders have no dither to allow for: the bounds of [`check_hdr`], in 8-bit steps. +const HDR_MEAN_STEPS: f64 = 0.02; +const HDR_MAX_STEPS: f64 = 1.0; fn gpu() -> bool { let ok = lightcraft_gpu::available(); @@ -743,9 +746,9 @@ fn light_v3_operators_match() { s.hdr.enabled = true; s.hdr.max_ev = 2.0; check("V4 HDR preview", &src, &info, &s, &req); - // High-bit-depth exports use the CPU; the GPU kernel writes 8-bit previews. - let hdr_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req }; - assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &hdr_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried)); + // Other high-bit-depth exports use the CPU; the GPU kernel writes 8 bits or the float HDR render. + let deep_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::U16, ..req }; + assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &deep_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried)); s.hdr.enabled = false; let cache = StageCache::default(); for k in 0..3 { @@ -1160,6 +1163,122 @@ fn lut_profiles_match() { } } +/// [`check`] for the float HDR render, compared on the sRGB curve (unbounded above SDR white) in +/// 8-bit steps. `over`: the samples must leave SDR. +fn check_hdr(name: &str, src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, over: bool) { + use lightcraft_color::transfer::linear_to_srgb; + use lightcraft_pipeline::{DeepSamples, OutputDepth}; + let req = RenderRequest { depth: OutputDepth::F32Hdr, ..*req }; + let cpu = render(src, info, s, &req); + let gpu = lightcraft_gpu::try_render(src, info, s, &req, None).expect("a float render on the GPU, without the CPU fallback"); + let (cd, gd) = (cpu.deep.expect("CPU float samples"), gpu.deep.expect("GPU float samples")); + assert_eq!((cd.width, cd.height, cd.space), (gd.width, gd.height, gd.space), "{name}"); + let (DeepSamples::F32(c), DeepSamples::F32(g)) = (&cd.samples, &gd.samples) else { panic!("{name}: float samples") }; + assert_eq!(c.len(), g.len(), "{name}"); + let peak = s.hdr.peak(); + assert!(g.iter().all(|v| (0.0..=peak).contains(v)), "{name}: GPU samples outside 0..{peak}"); + let above = g.iter().filter(|v| **v > 1.0).count() as f64 / g.len() as f64; + assert_eq!(above > 0.0, over, "{name}: {:.3}% of the samples above SDR white", above * 100.0); + let (mut sum, mut max) = (0f64, 0f64); + for (a, b) in c.iter().zip(g) { + let d = f64::from((linear_to_srgb(*a) - linear_to_srgb(*b)).abs()) * 255.0; + sum += d; + max = max.max(d); + } + let mean = sum / c.len() as f64; + eprintln!("{name:<36} {}x{} mean {mean:.4} max {max:.3} above SDR {:.2}%", cd.width, cd.height, above * 100.0); + assert!(mean < HDR_MEAN_STEPS && max <= HDR_MAX_STEPS, "{name}: mean {mean:.4}, max {max:.3} steps"); + let (mean, max, _) = diff(&cpu.image, &gpu.image); + assert!(mean < MEAN_LSB && max <= MAX_LSB, "{name}: 8-bit image mean {mean:.4}, max {max}"); + assert_eq!(cpu.histogram.total, gpu.histogram.total, "{name}"); +} + +/// The float HDR render matches the CPU's on every process, through every stage with an HDR rule: +/// tone map and highlight desaturation to the peak, V4's operators, vignette, gamut map, curves +/// above SDR white, grain and LUT profiles. +#[test] +fn hdr_float_render_matches() { + if !gpu() { + return; + } + let src = scene(1, 900, 600); + let raw = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(640, 640); + let hdr = |p: Process| { + let mut s = DevelopSettings { process: p.version(), ..Default::default() }; + s.hdr.enabled = true; + s.hdr.max_ev = 3.0; + s.light.exposure = 1.5; + s + }; + for p in Process::ALL { + let mut s = hdr(p); + check_hdr(&format!("{p:?} HDR"), &src, &raw, &s, &req, true); + typical(&mut s); + s.light.exposure = 1.5; + s.light.contrast = 35.0; + s.light.whites = 40.0; + s.light.blacks = -30.0; + check_hdr(&format!("{p:?} HDR typical"), &src, &raw, &s, &req, true); + } + lightcraft_pipeline::lut::register("lut:gpu-test-hdr", look_lut(17, 1.0)); + let cases: [(&str, Edit); 7] = [ + ("HDR vignette out", |s| s.vignette.amount = -40.0), + ("HDR vignette lighten", |s| s.vignette.amount = 40.0), + ("HDR saturated", saturated), + ("HDR curves", |s| { + s.curve.master = vec![Point::new(0.0, 0.05), Point::new(0.5, 0.55), Point::new(1.0, 0.95)]; + s.curve.blue = vec![Point::new(0.0, 0.0), Point::new(0.5, 0.45), Point::new(1.0, 1.0)]; + s.curve.refine_saturation = 20.0; + }), + ("HDR grain", |s| { + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), + ("HDR LUT", |s| { + s.profile.id = "lut:gpu-test-hdr".into(); + s.profile.amount = 80.0; + }), + ("HDR peak 1 stop", |s| s.hdr.max_ev = 1.0), + ]; + for (name, edit) in cases { + let mut s = hdr(Process::LATEST); + edit(&mut s); + check_hdr(name, &src, &raw, &s, &req, true); + } + let s = hdr(Process::LATEST); + for space in lightcraft_pipeline::OutputSpace::ALL { + check_hdr(&format!("HDR in {space:?}"), &src, &raw, &s, &RenderRequest { space, ..req }, true); + } + let win = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 200, y: 100, w: 320, h: 240 }), ..RenderRequest::fit(900, 600) }; + check_hdr("HDR window", &src, &raw, &s, &win, true); + check_hdr("HDR draft", &src, &raw, &s, &RenderRequest { quality: Quality::Draft, ..req }, true); + let proof = + Some(lightcraft_pipeline::Proof { space: lightcraft_pipeline::OutputSpace::Srgb, dest_warning: false, display_warning: false, profile: 0 }); + check_hdr("HDR soft proof", &src, &raw, &s, &RenderRequest { space: lightcraft_pipeline::OutputSpace::Rec2020, proof, ..req }, true); + // an edit with HDR off: the same request is the linear float render, 0..1 + let mut s = DevelopSettings::default(); + typical(&mut s); + check_hdr("HDR off", &src, &raw, &s, &req, false); +} + +/// The float output in several bands of rows, with position-dependent grain. +#[test] +fn hdr_float_render_matches_in_bands() { + if !gpu() { + return; + } + let src = scene(3, 3000, 2000); + let mut s = DevelopSettings::default(); + typical(&mut s); + s.hdr.enabled = true; + s.hdr.max_ev = 2.0; + s.light.exposure = 1.5; + s.grain.amount = 30.0; + check_hdr("HDR banded", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(3000, 2000), true); +} + /// Refine Edges on a mask is the cross guided filter on the device, blended by √refine. #[test] fn refine_edges_match() { diff --git a/crates/gpu/tests/it/fallback.rs b/crates/gpu/tests/it/fallback.rs index 05347b4469..ee91757068 100644 --- a/crates/gpu/tests/it/fallback.rs +++ b/crates/gpu/tests/it/fallback.rs @@ -106,6 +106,15 @@ fn failed_gpu_renders_fall_back_with_a_reason() { assert!(!lightcraft_gpu::available()); lightcraft_gpu::reset_failures(); ok("after dropped work"); + // ... and the float render, where a cleared word would pass for a valid 0 + lightcraft_gpu::inject_fault(Fault::DropWork); + let hdr = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req }; + match lightcraft_gpu::try_render(&src, &info, &s, &hdr, None) { + Err(Fallback::Failed(why)) => assert!(why.contains("incomplete"), "an unwritten float image must not be returned: {why}"), + other => panic!("a float render with dropped work is redone on the CPU: {:?}", other.map(|_| ())), + } + lightcraft_gpu::reset_failures(); + ok("after dropped float work"); // a black photo is still rendered (on the CPU, to be sure) let black = Arc::new(lightcraft_raster::Rgb32f::from_fn(256, 256, |_, _| [0.0; 3])); diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 506f8fd929..0e9816b7bb 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -189,9 +189,13 @@ walks the drive. `aux` buffer, trilinear like `Lut3d::apply`, after grain), masks with Refine Edges (the cross guided filter of Auto Mask, blended by √refine before the mask's invert and amount) and soft proofs into a colour space (proof-space gamut mapping and both gamut warnings, into an output - space or a display). These render on the CPU: high-bit-depth exports and Visualize HDR (both - need float output), soft proofs to an output device's profile (a printer or paper profile), and - photos with a content-aware Fill spot (no GPU kernel for it). + space or a display). The float HDR render (`OutputDepth::F32Hdr`) takes the GPU path too: the + `finish` kernel keeps values up to the edit's peak, encodes with the exact sRGB curve and writes + three linear floats per pixel into `out` (within 1 step of 8 on the sRGB curve of the CPU's float + render, 0.02 on average: `hdr_float_render_matches`). These render on the CPU: 16-bit and linear float exports, + Visualize HDR (it draws the float render over the 8-bit one), soft proofs to an output device's + profile (a printer or paper profile), and photos with a content-aware Fill spot (no GPU kernel + for it). - Anything the GPU path cannot do returns `None` and the CPU renders instead: no adapter (CI machines, software-only adapters), `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` (whole process; see [Backends](#backends-environment-variables-and-troubleshooting-issue-136)), the `app.gpu {enabled}` From 3b209a40b7c41e64f21d20199a008290898ba20e Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:58:35 +0200 Subject: [PATCH 28/30] Cover DxO demosaiced Fujifilm DNGs for Kelvin white balance DxO demosaiced DNGs from Fujifilm RAF files should offer the same Kelvin white-balance editing as the original RAF and Adobe demosaiced DNGs, instead of only a relative slider. Treat a DxO make on a DNG as transparent when checking Fujifilm (and other listed) models in covers, so the Kelvin scale is offered for those files. Test: dxo_dng_fujifilm_model_is_covered_for_kelvin failed before the change and passes after. --- crates/raw/src/kelvin_presets.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/kelvin_presets.rs b/crates/raw/src/kelvin_presets.rs index 58ed396257..e5a908d5c7 100644 --- a/crates/raw/src/kelvin_presets.rs +++ b/crates/raw/src/kelvin_presets.rs @@ -82,7 +82,9 @@ pub fn covers(make: Option<&str>, model: &str) -> bool { .map_or(model, |(_, rest)| rest.trim_start()) }; let listed = MODELS.iter().any(|(b, m)| brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare_of(b).eq_ignore_ascii_case(m)); - let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM")) && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m)); + // A DxO demosaiced DNG keeps the Fujifilm model but carries DxO as its make. + let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM") || b.eq_ignore_ascii_case("DxO")) + && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m)); listed || fuji } @@ -408,6 +410,14 @@ mod tests { } } + #[test] + fn dxo_dng_fujifilm_model_is_covered_for_kelvin() { + // A DxO demosaiced DNG carries DxO as its make, not FUJIFILM, but it is still a Fujifilm model. + assert!(covers(Some("DxO"), "X-T2")); + assert!(covers(Some("DxO"), "FUJIFILM X-T2")); + assert!(covers_camera("DxO X-T2")); + } + #[test] fn covered_models() { assert!(covers_camera("NIKON CORPORATION NIKON Z5_2") && covers_camera("NIKON Z5_2") && !covers_camera("NIKON CORPORATION NIKON Z6")); From 10db03b09127a57d3f53b4fcd03fb53c74d27824 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:56:03 +0100 Subject: [PATCH 29/30] LR-IMP-FORMATS: withdraw compressed ORF decoding pending provenance review (#3916) * LR-IMP-FORMATS: withdraw compressed ORF decoding Remove the decoder introduced in #3775 pending provenance review while preserving uncompressed ORF layouts and embedded previews. Add unsupported probe/decode regressions, remove the prior provenance narrative, and restore camera coverage records to preview-only. * LR-IMP-FORMATS: refresh ORF support status and render caches * LR-IMP-FORMATS: document ORF withdrawal regressions --- README.md | 4 +- ROADMAP.md | 8 +- crates/catalog/src/lib.rs | 4 +- crates/catalog/src/model.rs | 21 +- crates/catalog/src/tests.rs | 20 + crates/engine/src/cmd/convert.rs | 2 +- crates/engine/src/cmd/recheck.rs | 16 +- crates/engine/src/media/quick.rs | 21 +- crates/engine/src/media/session.rs | 21 +- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/orf_withdrawal.rs | 207 ++++++++ crates/raw/src/lib.rs | 5 +- crates/raw/src/vendor.rs | 1 - crates/raw/src/vendor/orf.rs | 36 +- crates/raw/src/vendor/orfc.rs | 489 ------------------ crates/raw/tests/it/corpus.rs | 2 + crates/raw/tests/it/olympus_samsung_corpus.rs | 22 +- docs/gaps.md | 9 +- docs/orf-compression.md | 108 +--- docs/parity-checklist.md | 5 +- docs/raw-parity.md | 51 +- docs/raw/coverage.py | 4 +- docs/raw/coverage.tsv | 122 ++--- docs/raw/evidence.tsv | 4 +- docs/roadmap.md | 4 +- docs/target-app-parity.md | 31 +- 26 files changed, 460 insertions(+), 758 deletions(-) create mode 100644 crates/engine/tests/it/orf_withdrawal.rs delete mode 100644 crates/raw/src/vendor/orfc.rs diff --git a/README.md b/README.md index 21ff4306ec..a3e4981360 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera. - **The biggest gaps:** - **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix; - - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); + - **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF is unsupported for sensor decoding and uses embedded JPEG previews when available ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md); - **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md); @@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det | Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ | | Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) | | Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ | -| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | +| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) | | Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ | | Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill | | Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ | diff --git a/ROADMAP.md b/ROADMAP.md index 8804f42701..ee50aed31b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -30,7 +30,7 @@ Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%): The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens -as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and +as preview, as does compressed ORF when an embedded preview is available; rendering is tuned by eye, AI masks are heuristics, there is no lens database, and tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon, ~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows @@ -107,14 +107,16 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ 3. Render-fidelity suite against Lightroom, then tuning (30–60 h) 4. ~~Full-resolution zoom~~ (done 2026-10-12) 5. AI masks: Subject / Sky / People (40–70 h + model decision) -6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h) +6. Compressed ORF (support withdrawn; estimate pending provenance review) and HE NEF (20–40 h) 7. Lens profile database of our own (40–80 h, #329) 8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h) 9. Per-model raw verification (20–35 h) ## Progress log -- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%). +- 2026-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md). + +- 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. - 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判 (89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200), 六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 5a82d2a67d..f106e753f7 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -221,8 +221,8 @@ pub enum Op { /// `None` = its raw data decodes (or it isn't a raw). #[serde(default, skip_serializing_if = "Option::is_none")] preview_only: Option, - /// The app version that decided `preview_only` (see [`Photo::preview_checked`]); empty - /// when it is `None`. + /// The app version that decided `preview_only` (see [`Photo::preview_checked`]); also + /// retained for supported ORF files so their withdrawal recheck runs only once. #[serde(default, skip_serializing_if = "String::is_empty")] preview_checked: String, }, diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index ebf2d1ef08..37749e5f1f 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -316,10 +316,10 @@ pub struct Photo { /// picture style baked in — so it is treated as a rendered (non-raw) source. #[serde(default, skip_serializing_if = "Option::is_none")] pub preview_only: Option, - /// The app version (`CARGO_PKG_VERSION`) whose decoder set [`Photo::preview_only`]; empty when - /// it isn't set, and in catalogs from before format v9. A preview-only photo whose stamp - /// differs from the running version is rechecked when its library opens (issue #662): newer - /// builds may decode the file, older ones may decode less. + /// The app version (`CARGO_PKG_VERSION`) whose decoder checked [`Photo::preview_only`]. + /// Also set for supported ORF files: compressed ORF support was withdrawn after #3775, so + /// old sensor-decodable records need rechecking too. Empty for other supported formats and + /// legacy records. A stale stamp is rechecked when the library opens (issue #662). #[serde(default, skip_serializing_if = "String::is_empty")] pub preview_checked: String, /// A Local record: the fingerprint of its state when the browse catalogued it, to tell @@ -429,13 +429,18 @@ impl Photo { } /// Sets [`Photo::preview_only`] as this build decided it, with its stamp. pub fn set_preview_only(&mut self, preview_only: Option) { - self.preview_checked = preview_stamp(&preview_only); + self.preview_checked = self.preview_stamp(&preview_only); self.preview_only = preview_only; } - /// A preview-only photo whose flag was set by another app version (or before stamps existed), - /// so this build should probe its file again (issue #662). + /// The stamp for a fresh probe. Supported ORFs keep it too, so the support-withdrawal + /// recheck runs once, without repeatedly probing uncompressed ORFs on every library open. + pub fn preview_stamp(&self, preview_only: &Option) -> String { + if self.format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) } + } + /// A preview-only photo or ORF whose support was checked by another app version (or before + /// stamps existed), so this build should probe its file again (issues #662 and #3775). pub fn preview_only_stale(&self) -> bool { - self.preview_only.is_some() && self.preview_checked != APP_VERSION + (self.preview_only.is_some() || self.format.eq_ignore_ascii_case("orf")) && self.preview_checked != APP_VERSION } /// A raw file developed from its sensor data: not a rendered image, and not a raw shown from /// its embedded preview ([`Photo::preview_only`]). diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 19817d78da..8688d87a30 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -12,6 +12,26 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId { id } +/// ORF probes record both supported and preview-only outcomes, without changing other formats. +#[test] +fn orf_support_checks_keep_a_stamp_even_when_sensor_data_decodes() { + let mut p = Photo::new(PhotoId(1), Source::File { path: "a.orf".into() }, "a.orf", "ORF", 4, 3, "2026-01-01"); + p.kind = MediaKind::Raw; + assert!(p.preview_only_stale(), "legacy supported ORF needs the withdrawal recheck"); + p.set_preview_only(None); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.preview_only_stale()); + assert!(p.develops_raw(), "supported uncompressed ORF remains sensor-decodable"); + p.set_preview_only(Some("Olympus compressed ORF".into())); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.preview_only_stale()); + assert!(!p.develops_raw()); + p.format = "DNG".into(); + p.set_preview_only(None); + assert!(p.preview_checked.is_empty(), "other supported formats keep their existing semantics"); + assert!(!p.preview_only_stale()); +} + #[test] fn date_token_matches_time_part_case_insensitively() { let mut c = Catalog::new(); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 261a4dd018..f6bcd8fe8d 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -206,7 +206,7 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts: /// preview-only photo this version hasn't checked yet: its stamp is refreshed so it isn't probed /// again (see [`lightcraft_catalog::Photo::preview_checked`]). pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option { - let preview_checked = lightcraft_catalog::preview_stamp(&info.preview_only); + let preview_checked = ph.preview_stamp(&info.preview_only); let same = info.content_hash == ph.content_hash && info.file_size == ph.file_size && (info.width, info.height) == (ph.width, ph.height) diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index 494426b90c..a7d40a8370 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -4,6 +4,8 @@ //! library opens in another version, its stale preview-only photos are probed again and get //! exactly what Reload from Disk would give them: a file that decodes now loses the flag, one that //! still doesn't gets the new reason and a fresh stamp, so it isn't probed again. +//! ORF records are rechecked even when previously sensor-decodable: compressed sensor support +//! was withdrawn after #3775. Supported uncompressed ORFs also keep a stamp to avoid repeat work. //! //! The work is split so the app can probe on a worker thread: [`stale`] lists what to probe (no //! file-system calls), [`probe`] reads the files without the session, and [`apply`] applies the @@ -17,7 +19,7 @@ use super::{CommandSpec, always, bad, cmd}; use crate::media::{FileProbe, ProbeInfo}; use crate::{Result, Session}; -/// A preview-only photo to probe, and what the library knew about it when it was listed (so a +/// A photo to probe, and what the library knew about it when it was listed (so a /// result for a photo that changed meanwhile is dropped). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Stale { @@ -40,12 +42,12 @@ impl Stale { } } -/// The library's preview-only photos whose flag another app version set (or every preview-only -/// photo, with `all`): library photos with a file, not virtual copies (they follow the photo they -/// were copied from). No file-system calls. +/// The library's preview-only photos and ORFs whose support another app version checked (or +/// every such photo, with `all`): library photos with a file, not virtual copies (they follow +/// the photo they were copied from). No file-system calls. pub fn stale(cat: &Catalog, all: bool) -> Vec { cat.photos() - .filter(|p| p.copy_of.is_none() && p.preview_only.is_some() && (all || p.preview_only_stale())) + .filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf"))))) .filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path))) .collect() } @@ -92,7 +94,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result Vec { "Recheck Preview-Only Raws", [], None, - "{all?: bool} — probe again the raws shown from their embedded preview whose flag another LightCraft version set (the app does this in the background when a library opens; `all` rechecks every preview-only raw, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", + "{all?: bool} — probe again preview-only raws and ORFs whose support another LightCraft version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", always, recheck )] diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 25c93e9f81..f7163b0693 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -131,14 +131,31 @@ pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 { Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish() } -/// What identifies a photo's pixels for caching: its content hash, else its source. -/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile +/// ORF decoding changed when compressed sensor support was withdrawn. Keep its old renders +/// out even before catalog rechecking finishes, and distinguish sensor from preview-only +/// pixels after Reload. Other formats keep their existing keys. This is deliberately not +/// part of `content_key`: smart previews and denoise products identify the original file. +pub(super) fn decoder_key(p: &Photo) -> u64 { + if !p.format.eq_ignore_ascii_case("ORF") { + return 0; + } + // Spread the status bit: this salt is XORed with frontend dimensions, so adjacent + // integers could cancel a small resize occurring at the same time as a recheck. + let h = Hasher128::new().str("orf-withdrawal-v1").u64(u64::from(p.preview_only.is_some())).finish(); + ((h.0 as u64) ^ ((h.0 >> 64) as u64)) | 1 +} + +/// Which decode of a photo a loaded source is: its file's content, decoder identity and database lens profile /// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still /// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never /// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources. pub fn source_identity(p: &Photo) -> Hash128 { let mut k = Hasher128::new(); k.str(&content_key(p)); + let decoder = decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } let lens = lens_key(p); if lens != 0 { k.u64(lens); diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index a3d5069177..4bf40bbf57 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -57,6 +57,7 @@ impl crate::Session { let content_key = content_key(&p); let content = Hasher128::new().str(&content_key).finish().0 as u64; let source_key = super::quick::source_identity(&p); + let decoder = super::quick::decoder_key(&p); // 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) }; @@ -72,7 +73,8 @@ impl crate::Session { ^ content.rotate_left(17) ^ salt ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37); + ^ lens.rotate_left(37) + ^ decoder.rotate_left(43); let cache = thumb_bucket.map(|b| { let mut k = Hasher128::new(); k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION); @@ -89,6 +91,9 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + if decoder != 0 { + k.str("decoder").u64(decoder); + } (self.media.rendered.clone(), k.finish()) }); Some(RenderJob { @@ -131,6 +136,7 @@ impl crate::Session { let profile_salt = self.media.camera_profile_salt(&settings.profile.id); // (the photo's database lens profile stays part of it: a profile looked up again renders afresh) let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p)); + let decoder = super::quick::decoder_key(&p); job.key = settings.hash64() ^ crate::files::hot_pixel_key(settings) ^ ((max_w as u64) << 40) @@ -138,7 +144,8 @@ impl crate::Session { ^ (apply_crop as u64) ^ (job.level as u64) << 60 ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37); + ^ lens.rotate_left(37) + ^ decoder.rotate_left(43); Some(job) } @@ -159,6 +166,10 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + let decoder = super::quick::decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } k.finish() } @@ -294,6 +305,10 @@ impl crate::Session { if lens != 0 { k.u64(lens); } + let decoder = super::quick::decoder_key(p); + if decoder != 0 { + k.str("decoder").u64(decoder); + } k.finish() } @@ -422,7 +437,7 @@ impl crate::Session { .u64(id.0) .u64(profile_salt) .finish(); - let key = h.0 as u64; + let key = h.0 as u64 ^ super::quick::decoder_key(&p).rotate_left(43); let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge()))); let embedded_cache = embedded.as_ref().map(|(_, _, edge)| { let cache = self.media.rendered.clone(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2c52d87e9d..c92411938f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,4 +4,5 @@ mod denoise_cpu; #[cfg(feature = "denoise")] mod denoise_real; +mod orf_withdrawal; mod preview_read; diff --git a/crates/engine/tests/it/orf_withdrawal.rs b/crates/engine/tests/it/orf_withdrawal.rs new file mode 100644 index 0000000000..a29c8d06fc --- /dev/null +++ b/crates/engine/tests/it/orf_withdrawal.rs @@ -0,0 +1,207 @@ +//! Compressed ORF withdrawal: public import/recheck and render identities stay consistent. + +use std::path::PathBuf; +use std::sync::Arc; + +use lightcraft_catalog::{APP_VERSION, MediaKind, Op, Photo, PhotoId, Source}; +use lightcraft_engine::{Session, cmd::recheck, media::content_key}; +use lightcraft_pipeline::SourceInfo; +use lightcraft_preview::Hash128; +use lightcraft_raster::Rgb32f; +use serde_json::json; + +struct OrfLibrary { + s: Session, + dir: PathBuf, + lib: PathBuf, + id: PhotoId, +} + +impl Drop for OrfLibrary { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// A fixed original and settings isolate decoder status from every other render-key input. +fn decoder_session(format: &str) -> Session { + let mut s = Session::new(); + let mut p = Photo::new(PhotoId(1), Source::File { path: "same-original.orf".into() }, "same-original.orf", format, 6000, 4000, "2026-01-01"); + p.kind = MediaKind::Raw; + p.content_hash = Some("unchanged-file-bytes".into()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s +} + +/// Include the frontend's ordinary, hover and quick-view identities as well as all persistent +/// render families. The original-file identity must not change along with any of these. +fn decoder_keys(s: &mut Session) -> (Vec, Vec, String) { + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + let thumb = s.thumb_job(p.id, 256).unwrap(); + let render = s.render_job(p.id, 640, 480, false, true).unwrap(); + let hover = s.preview_job(p.id, 640, 480, true, &p.develop).unwrap(); + let quick = s.quick_view_job(p.id, 640, true).unwrap(); + ( + vec![thumb.key, render.key, hover.key, quick.key], + vec![ + thumb.cache.unwrap().1, + s.loupe_job(p.id, 640, 480, true).unwrap().view_cache.unwrap().1, + Session::variant_key(&p, &p.develop, 256, 0), + render.source_key.unwrap(), + ], + content_key(&p), + ) +} + +/// Old ORF renders cannot stand in after withdrawal; other formats and original-file identities stay stable. +#[test] +fn withdrawn_orf_decoder_has_distinct_render_keys_without_changing_file_identity() { + // Before the withdrawal, format was not part of any of these keys: an otherwise identical + // non-ORF photo gives the old keys, preserved for every other camera and ordinary image. + let legacy = decoder_keys(&mut decoder_session("DNG")); + assert_eq!(legacy, decoder_keys(&mut decoder_session("JPEG"))); + let orf = decoder_keys(&mut decoder_session("ORF")); + for (old, new) in legacy.0.iter().zip(&orf.0) { + assert_ne!(old, new, "old ORF frontend render must not be reused"); + } + for (old, new) in legacy.1.iter().zip(&orf.1) { + assert_ne!(old, new, "old ORF persistent render or decoded source must not be reused"); + } + assert_eq!(legacy.2, orf.2, "smart previews and denoise products still identify the original file"); + assert_eq!(orf, decoder_keys(&mut decoder_session("orf"))); +} + +/// Apply the same-byte capability transition that Reload or the background recheck records. +fn mark_orf_preview_only(s: &mut Session) { + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + s.catalog + .apply(Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: Some("Olympus compressed ORF".into()), + preview_checked: lightcraft_catalog::APP_VERSION.into(), + }) + .unwrap(); + s.media.forget(p.id); +} + +/// A support-status change invalidates every render family, even when a resize happens at the same time. +#[test] +fn orf_preview_transition_changes_render_keys_with_identical_bytes_and_settings() { + let mut s = decoder_session("ORF"); + let before = decoder_keys(&mut s); + mark_orf_preview_only(&mut s); + let after = decoder_keys(&mut s); + for (old, new) in before.0.iter().zip(&after.0) { + assert_ne!(old, new, "Reload changes frontend render identity"); + } + for (old, new) in before.1.iter().zip(&after.1) { + assert_ne!(old, new, "Reload changes persistent render and decoded source identity"); + } + assert_eq!(before.2, after.2, "Reload does not change the original file's identity"); + let p = s.catalog.photo(PhotoId(1)).unwrap().clone(); + assert_ne!(before.0[1], s.render_job(p.id, 648, 480, false, true).unwrap().key, "a resize must not cancel the status salt"); + assert_ne!(before.0[2], s.preview_job(p.id, 648, 480, true, &p.develop).unwrap().key, "a hover resize must not cancel the status salt"); +} + +/// An in-flight sensor decode must not refill a source cache cleared by the preview-only transition. +#[test] +fn source_from_before_orf_preview_transition_is_not_accepted() { + let mut s = decoder_session("ORF"); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); + assert!(old.loaded.is_some()); + mark_orf_preview_only(&mut s); + s.accept(&old); + assert_eq!(s.media.source_usage().0, 0, "a sensor decode finishing after Reload cannot repopulate its source cache"); +} + +/// A legacy ORF record and a controlled probe let the upgrade tests exercise catalog migration +/// without downloading camera files. The raw crate separately tests the actual ORF probe. +fn legacy_orf(name: &str, preview_only: Option) -> OrfLibrary { + let dir = std::env::temp_dir().join(format!("lc-orf-recheck-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let lib = dir.join("lib"); + let file = dir.join("legacy.orf"); + let mut s = Session::new(); + s.open_library(&lib, false).unwrap(); + let id = s.catalog.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: file.to_string_lossy().into() }, "legacy.orf", "ORF", 96, 64, "2026-01-01"); + p.kind = MediaKind::Raw; + p.file_size = 1024; + p.content_hash = Some("same-file".into()); + let info = lightcraft_engine::media::ProbeInfo { + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + format: p.format.clone(), + kind: p.kind, + preview_only, + ..Default::default() + }; + s.commit("Legacy ORF", Op::AddPhoto { photo: Box::new(p) }).unwrap(); + s.selection = lightcraft_engine::Selection::single(id); + s.media.file_probe = Some(Arc::new(move |_| Ok(info.clone()))); + OrfLibrary { s, dir, lib, id } +} + +/// Previously supported compressed ORFs and their copies migrate without losing edits, history or persistence. +#[test] +fn legacy_compressed_orf_and_copies_become_preview_only_without_losing_edits() { + let mut x = legacy_orf("compressed", Some("Olympus compressed ORF".into())); + x.s.execute("develop.set", &json!({"ids": [x.id.0], "control": "light.exposure", "value": 0.5})).unwrap(); + let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let undo = x.s.undo.len(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [x.id.0, copy.0], "cleared": []})); + for id in [x.id, copy] { + let p = x.s.catalog.photo(id).unwrap(); + assert_eq!(p.preview_only.as_deref(), Some("Olympus compressed ORF")); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(!p.develops_raw()); + assert_eq!(*p.develop, *before.develop); + } + assert_eq!(x.s.catalog.photo(x.id).unwrap().history, before.history); + assert_eq!(x.s.undo.len(), undo, "bookkeeping is not an undo step"); + x.s.persist().unwrap(); + x.s = Session::new(); + x.s.open_library(&x.lib, false).unwrap(); + assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some()); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); +} + +/// Supported uncompressed ORF is checked once and never reported as newly recovered sensor support. +#[test] +fn legacy_uncompressed_orf_is_stamped_once_without_a_false_recovery_notice() { + let mut x = legacy_orf("supported", None); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [x.id.0], "cleared": []})); + let p = x.s.catalog.photo(x.id).unwrap(); + assert!(p.develops_raw()); + assert_eq!(p.preview_checked, APP_VERSION); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1); + x.s.persist().unwrap(); + x.s = Session::new(); + x.s.open_library(&x.lib, false).unwrap(); + assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert!(x.s.catalog.photo(x.id).unwrap().develops_raw()); +} + +/// An offline original keeps its catalog state and remains eligible for a later recheck. +#[test] +fn unavailable_legacy_orf_is_unchanged_and_retried() { + let mut x = legacy_orf("offline", None); + x.s.media.file_probe = Some(std::sync::Arc::new(|_| Err("offline".into()))); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r, json!({"checked": 1, "updated": [], "cleared": []})); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); + assert_eq!(recheck::stale(&x.s.catalog, false).len(), 1); +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index c7538c6b11..ff9ee048b7 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -18,8 +18,9 @@ //! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived //! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer //! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8, -//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500; compressed: 12-bit entropy-coded sensor differences across interchangeable-lens and modern compact bodies). -//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources +//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, +//! two-field 12-bit samples and 12-bit 16-byte blocks of the E-300/E-330/E-500). +//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed Olympus ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources //! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no //! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and //! otherwise [`color`] falls back to a documented neutral model. The decoders never panic on malformed input. diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index 6b27843d56..a44262a2c4 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -21,7 +21,6 @@ pub mod nef; mod nef_lens; pub mod nefc; pub mod orf; -pub(crate) mod orfc; pub mod pef; pub mod raf; mod raf_lens; diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 97a640ddff..8c2bd28398 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -1,4 +1,4 @@ -//! Olympus ORF — uncompressed and compressed variants. +//! Olympus ORF — uncompressed variants; compressed sensor data is unsupported. //! //! Sources: TIFF 6.0 (the `IIRO`/`MMOR` container is a TIFF with a different magic number), Exif 2.3 (`CFAPattern`, //! tag `0xa302`), the ExifTool Olympus tag-name documentation (maker-note sub-directories `0x2020` CameraSettings — @@ -28,9 +28,8 @@ //! (last), the bit order and the pixel order were fixed by measurement on the CC0 files 2878 (E-300), 3540 (E-500) //! and 3624 (E-330), as was the sensor-origin RGGB anchoring (the maker-note crop offsets are odd). The E-M5 Mark II //! and PEN-F files were only checked for smoothness, not for CFA anchoring or black level. -//! - Olympus's compressed ORF (interchangeable-lens bodies and compacts using the 12/14-bit entropy coding stream): -//! decoded clean-room in `orfc.rs` from Olympus patents US7333035B2 and US7715639B2 (Takashi Ishikawa) and black-box -//! CC0 samples (OM-D E-M1, E-M10 Mark III). No GPL/LibRaw code was consulted. See `docs/orf-compression.md`. +//! - Compressed ORF sensor data is unsupported. The previous decoder was removed pending provenance +//! resolution; embedded previews remain available. See `docs/orf-compression.md`. //! - The colour-filter layout is the file's Exif `CFAPattern`: GRBG on the E-1 and E-400, RGGB on the XZ-2, where //! the colours of the decoded mosaic follow the embedded JPEG best with exactly that layout //! (`corpus_orf_cfa_patterns`). The samples' active areas start at even offsets, so they can't tell whether the @@ -200,7 +199,7 @@ fn field_rows(strips: &[(u64, u64)], w: usize, h: usize, file_len: usize) -> Opt Some(rows) } -/// Decode an Olympus ORF container into a mosaic raw image, supporting uncompressed 16-bit, packed 12-bit, and compressed formats. +/// Decode the supported uncompressed Olympus ORF layouts into a mosaic raw image. pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let tiff = Tiff::parse(bytes)?; let ifd0 = &tiff.ifds[0]; @@ -232,20 +231,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { Vec::new() }; (RawData::U16(d), 12, false) - } else if let Some((params, stream)) = (|| { - let params = super::orfc::CompressionParameters::from_ifd(ip.as_ref()?, mn.as_ref())?; - let chunk = chunks.first()?; - let src = chunk_bytes(bytes, chunk)?; - if !super::orfc::validate_stream_header(src, params.header_prefix_len) { - return None; - } - let stream = src.get(params.header_prefix_len.saturating_add(2)..)?; - Some((params, stream)) - })() { - let d = if mode == Mode::Full || stated.is_none() { super::orfc::decompress_stream(stream, w, h, ¶ms)? } else { Vec::new() }; - (RawData::U16(d), params.valid_bits, false) - } else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { + } else if info.bits() == 12 && total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 { let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?; + // Only the declared 12-bit layout is supported here. A compressed stream in a 16-bit + // ORF container must not fall through to packed decoding just because its length fits. // the strip as it is in the file (clipped at its end), not as its tag states it: one too short // for the samples is a truncated file, refused before they are allocated if (src.len() as u64).saturating_mul(8) < (n as u64).saturating_mul(12) { @@ -413,6 +402,17 @@ mod tests { b } + /// A 16-bit container with a short sensor stream is not the supported 12-bit packed layout. + /// Both entry points must report unsupported rather than returning fabricated sensor pixels. + #[test] + fn compressed_sensor_data_is_unsupported_in_probe_and_decode() { + for strip_len in [8, 24, 25] { + let bytes = orf_with(4, 4, 16, vec![0; strip_len], Some(&[2, 0, 2, 0, 0, 1, 1, 2])); + assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF")); + assert!(matches!(crate::probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF")); + } + } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. #[test] fn strip_byte_counts_past_u64_max_do_not_overflow() { diff --git a/crates/raw/src/vendor/orfc.rs b/crates/raw/src/vendor/orfc.rs deleted file mode 100644 index a8df663bc4..0000000000 --- a/crates/raw/src/vendor/orfc.rs +++ /dev/null @@ -1,489 +0,0 @@ -//! Olympus compressed ORF entropy and predictive decoding. -//! -//! Clean-room implementation derived strictly from patent specifications and black-box CC0 samples: -//! - Olympus Patent US7333035B2 (Takashi Ishikawa): directional edge-directed prediction across Bayer channels -//! and run-length adaptive Golomb-Rice entropy coding with quotient escape codes. -//! - Olympus Patent US7715639B2 (Takashi Ishikawa): direct low-order bitfield splitting and residual difference -//! correction filters. -//! - ImageProcessing maker-note directory (`0x2040`) parameters (`0x0640`–`0x0653`) and valid sensor bit depth (`0x102c`). -//! - Verification against CC0 sample files from raw.pixls.us (OM-D E-M1, OM-D E-M10 Mark III). -//! -//! No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used. -//! See `docs/orf-compression.md` for format specification and verification records. - -use crate::{RawError, Result}; -use lightcraft_tiff::Ifd; -use lightcraft_tiff::makernote::MakerNote; - -/// Valid bits tag in Olympus MakerNote. -const MN_VALID_BITS: u16 = 0x102c; - -/// Bitstream reader for big-endian, MSB-first compressed ORF bitstreams. -struct BitStream<'a> { - data: &'a [u8], - cursor: usize, - buffer: u32, - bits_available: u32, - bits_loaded: u64, -} - -impl<'a> BitStream<'a> { - /// Create a new bitstream reader over the supplied byte slice. - fn new(data: &'a [u8]) -> Self { - Self { data, cursor: 0, buffer: 0, bits_available: 0, bits_loaded: 0 } - } - - /// Refill the bit buffer with a 32-bit big-endian word. - fn refill_word(&mut self) { - self.bits_loaded = self.bits_loaded.saturating_add(32); - if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(4)) { - self.buffer = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - self.cursor = self.cursor.saturating_add(4); - self.bits_available = 32; - } else { - let mut chunk = [0u8; 4]; - let remaining = self.data.len().saturating_sub(self.cursor); - if remaining > 0 { - if let Some(src) = self.data.get(self.cursor..self.cursor.saturating_add(remaining)) { - chunk[..remaining].copy_from_slice(src); - } - self.cursor = self.data.len(); - } - self.buffer = u32::from_be_bytes(chunk); - self.bits_available = 32; - } - } - - /// Append up to 16 bits to the lower part of the active bit buffer. - fn refill_halfword(&mut self) { - self.bits_loaded = self.bits_loaded.saturating_add(16); - let next = if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(2)) { - self.cursor = self.cursor.saturating_add(2); - u16::from_be_bytes([chunk[0], chunk[1]]) - } else if let Some(&single) = self.data.get(self.cursor) { - self.cursor = self.cursor.saturating_add(1); - (single as u16) << 8 - } else { - 0 - }; - self.buffer = (self.buffer << 16) | u32::from(next); - self.bits_available = self.bits_available.saturating_add(16); - } - - /// Read up to 16 bits from the bitstream. - fn read_bits(&mut self, width: u32) -> u32 { - if width == 0 { - return 0; - } - while self.bits_available < width { - self.refill_halfword(); - } - let shift = self.bits_available & 0x1f; - let value = (self.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - width); - self.bits_available = self.bits_available.saturating_sub(width); - value - } - - /// Advance by one bit, refilling the 32-bit buffer if necessary. - fn advance_single_bit(&mut self, state: &mut u32) { - if *state == 0 { - self.refill_word(); - self.bits_available = self.bits_available.saturating_sub(1); - *state = self.bits_available; - } else { - *state = state.saturating_sub(1); - self.bits_available = *state; - } - } -} - -/// Parameters extracted from ImageProcessing SubIFD (`0x2040`) controlling compressed ORF decoding. -pub(crate) struct CompressionParameters { - /// Low-order direct bits extracted without prediction (tag `0x0640`). - pub(crate) direct_bits_low0: u32, - /// Gradient difference exponent threshold for edge classification (tag `0x0641`). - pub(crate) gradient_thresh_exp_641: u32, - /// Default spatial predictor boundary value (tag `0x0642`). - pub(crate) boundary_predictor_642: i32, - /// Direct residual sub-bits width (tag `0x0643`). - pub(crate) direct_bits_sub3: u32, - /// Vertical feedback shift exponent (tag `0x0644`). - pub(crate) feedback_shift_644: u32, - /// Flatness threshold exponent (tag `0x0645`). - pub(crate) flatness_thresh_exp_645: u32, - /// Flatness run threshold (tag `0x0646`). - pub(crate) run_thresh_646: i32, - /// Adaptive Rice parameter table offset A (tag `0x0647`). - pub(crate) table_647: i32, - /// Adaptive Rice parameter table limit A (tag `0x0648`). - pub(crate) table_648: i32, - /// Adaptive Rice parameter table offset B (tag `0x0649`). - pub(crate) table_649: i32, - /// Adaptive Rice parameter table limit B (tag `0x0650`). - pub(crate) table_650: i32, - /// Maximum Rice parameter allowed (tag `0x0651`). - pub(crate) max_rice_k: i32, - /// Maximum unary quotient run length before escape coding (tag `0x0652`). - pub(crate) max_unary_run: u32, - /// Prefix length of the compressed stream header in bytes (tag `0x0653`). - pub(crate) header_prefix_len: usize, - /// Valid sensor bit depth from MakerNote `0x102c`. - pub(crate) valid_bits: u32, -} - -impl CompressionParameters { - /// Parse and validate compression parameters from the ImageProcessing IFD and MakerNote. - pub(crate) fn from_ifd(ip: &Ifd, mn: Option<&MakerNote>) -> Option { - let header_prefix_len = usize::try_from(ip.u64(0x0653)?).ok()?; - if header_prefix_len == 0 || header_prefix_len > 8 { - return None; - } - if ip.u64(0x0640).is_some_and(|v| v > 16) || ip.u64(0x0643).is_some_and(|v| v > 16) { - return None; - } - if ip.u64(0x0644).is_some_and(|v| v == 0 || v > 15) { - return None; - } - let direct_bits_low0 = ip.u64(0x0640).and_then(|v| u32::try_from(v).ok()).unwrap_or(0); - let gradient_thresh_exp_641 = ip.u64(0x0641).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); - let boundary_predictor_642 = ip.i64(0x0642).and_then(|v| i32::try_from(v).ok()).filter(|&v| (-65536..=65536).contains(&v)).unwrap_or(0); - let direct_bits_sub3 = ip.u64(0x0643).and_then(|v| u32::try_from(v).ok()).unwrap_or(2); - let feedback_shift_644 = ip.u64(0x0644).and_then(|v| u32::try_from(v).ok()).unwrap_or(5); - let flatness_thresh_exp_645 = ip.u64(0x0645).and_then(|v| u32::try_from(v).ok()).unwrap_or(4); - let run_thresh_646 = ip.u64(0x0646).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); - let table_647 = ip.u64(0x0647).and_then(|v| i32::try_from(v).ok()).unwrap_or(2); - let table_648 = ip.u64(0x0648).and_then(|v| i32::try_from(v).ok()).unwrap_or(3); - let table_649 = ip.u64(0x0649).and_then(|v| i32::try_from(v).ok()).unwrap_or(4); - let table_650 = ip.u64(0x0650).and_then(|v| i32::try_from(v).ok()).unwrap_or(7); - let max_rice_k = ip.u64(0x0651).and_then(|v| i32::try_from(v).ok()).unwrap_or(15); - let max_unary_run = ip.u64(0x0652).and_then(|v| u32::try_from(v).ok()).unwrap_or(12).clamp(1, 32); - let valid_bits = mn.and_then(|m| m.ifd.u64(MN_VALID_BITS)).and_then(|v| u32::try_from(v).ok()).filter(|b| (8..=16).contains(b)).unwrap_or(12); - - Some(Self { - direct_bits_low0, - gradient_thresh_exp_641, - boundary_predictor_642, - direct_bits_sub3, - feedback_shift_644, - flatness_thresh_exp_645, - run_thresh_646, - table_647, - table_648, - table_649, - table_650, - max_rice_k, - max_unary_run, - header_prefix_len, - valid_bits, - }) - } -} - -/// Check the stream header prefix: $N$ big-endian bytes equal to 1, followed by two zero bytes. -pub(crate) fn validate_stream_header(src: &[u8], prefix_bytes: usize) -> bool { - if prefix_bytes == 0 || prefix_bytes > 8 || src.len() < prefix_bytes.saturating_add(2) { - return false; - } - let mut prefix_int = 0u64; - for &b in src.get(..prefix_bytes).unwrap_or(&[]) { - prefix_int = (prefix_int << 8) | u64::from(b); - } - if prefix_int != 1 { - return false; - } - let Some(delimiter) = src.get(prefix_bytes..prefix_bytes.saturating_add(2)) else { - return false; - }; - delimiter == [0x00, 0x00] -} - -/// Decoded entropy-coded symbol components for one photosite. -struct DecodedSymbol { - signed_residual: i32, - raw_magnitude: u32, - direct_bits_low0: u32, - direct_bits_sub3: u32, -} - -/// Decode the next Golomb-Rice entropy residual symbol according to the patent specification. -fn decode_entropy_symbol(reader: &mut BitStream<'_>, rice_k: u32, params: &CompressionParameters) -> DecodedSymbol { - if reader.bits_available == 0 { - reader.refill_word(); - } - reader.bits_available = reader.bits_available.saturating_sub(1); - let sign_bit = (reader.buffer >> (reader.bits_available & 0x1f)) & 1; - - let direct_bits_sub3 = if params.direct_bits_sub3 > 0 { reader.read_bits(params.direct_bits_sub3) } else { 0 }; - let direct_bits_low0 = if params.direct_bits_low0 > 0 { reader.read_bits(params.direct_bits_low0) } else { 0 }; - - let mut state = reader.bits_available; - let mut quotient = 0u32; - - loop { - reader.advance_single_bit(&mut state); - if ((reader.buffer >> (state & 0x1f)) & 1) != 0 { - break; - } - quotient = quotient.saturating_add(1); - if quotient == params.max_unary_run { - quotient = 0; - if rice_k != 15 { - let bits_needed = 15u32.saturating_sub(rice_k); - while state < bits_needed { - reader.refill_halfword(); - state = reader.bits_available; - } - let shift = state & 0x1f; - quotient = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (rice_k + 17); - state = state.saturating_sub(bits_needed); - reader.bits_available = state; - } - reader.advance_single_bit(&mut state); - break; - } - } - - let remainder = if rice_k == 0 { - 0 - } else { - while state < rice_k { - reader.refill_halfword(); - state = reader.bits_available; - } - let shift = state & 0x1f; - let rem = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - (rice_k & 0x1f)); - reader.bits_available = state.saturating_sub(rice_k); - rem - }; - - let raw_magnitude = remainder | (quotient << rice_k); - let sign_mask = if sign_bit != 0 { 0xffff_ffff } else { 0 }; - let signed_residual = (raw_magnitude ^ sign_mask) as i32; - - DecodedSymbol { signed_residual, raw_magnitude, direct_bits_low0, direct_bits_sub3 } -} - -/// Decompress an entire Olympus compressed entropy bitstream into mosaic sensor samples. -pub(crate) fn decompress_stream(stream: &[u8], width: usize, height: usize, params: &CompressionParameters) -> Result> { - let total_pixels = width.checked_mul(height).ok_or(RawError::Limit("ORF image dimensions overflow"))?; - if total_pixels > 0 && stream.is_empty() { - return Err(RawError::Corrupt("ORF compressed stream is empty".into())); - } - // Reject streams too short to encode even 1 bit per pixel (prevents large allocation - // from a truncated file before we start decoding). - if total_pixels > 0 && (stream.len() as u64).saturating_mul(8) < total_pixels as u64 { - return Err(RawError::Corrupt("ORF compressed stream too short for frame".into())); - } - let mut pixels = vec![0u16; total_pixels]; - let mut reader = BitStream::new(stream); - - let gradient_threshold = 1u32.checked_shl(params.gradient_thresh_exp_641.min(30)).unwrap_or(1 << 5); - let flatness_threshold = 1i32.checked_shl(params.flatness_thresh_exp_645.min(30)).unwrap_or(1 << 4); - - let mut context = [0i32; 4]; - let mut last_predicted_sum = 0i32; - let mut pred1 = 0i32; - let mut raw_magnitude = 0u32; - let mut prev_magnitude_signed = 0i32; - - for row in 0..height { - let row_offset = row.checked_mul(width).ok_or(RawError::Limit("ORF row overflow"))?; - for col in 0..width { - let p = prev_magnitude_signed; - prev_magnitude_signed = raw_magnitude as i32; - - let psel = if col > 1 && flatness_threshold >= p { context[3].saturating_add(1) } else { 0 }; - context[3] = context[2]; - context[2] = psel; - - let mut rice_k = if col > 1 { - let p16 = (p as u32 & 0xffff) as u16; - let high_bit_count = if p16 == 0 { 0i32 } else { (16 - p16.leading_zeros()) as i32 }; - let t1 = if psel >= params.run_thresh_646 { params.table_648 } else { params.table_650 }; - let t2 = if psel >= params.run_thresh_646 { params.table_647 } else { params.table_649 }; - let tt = (high_bit_count - t1).max(-1); - t2.saturating_add(tt).saturating_add(1) - } else { - params.table_649 - }; - - if rice_k > params.max_rice_k { - rice_k = params.max_rice_k; - } - if rice_k >= 16 { - return Err(RawError::Corrupt("ORF compressed Rice parameter out of range".into())); - } - - let symbol = decode_entropy_symbol(&mut reader, rice_k.max(0) as u32, params); - let residual = symbol.signed_residual; - raw_magnitude = symbol.raw_magnitude; - let direct_bits_low0 = symbol.direct_bits_low0; - let direct_bits_sub3 = symbol.direct_bits_sub3; - - let (adjusted_residual, feedback_bits) = if params.direct_bits_sub3 > 0 { - let v = if col < 2 { 0 } else { pred1 }; - let v_plus_g = v.checked_add(residual).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - if params.direct_bits_sub3 == 1 { - let g_mult = v_plus_g.checked_mul(2).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let v_res = v.checked_add(g >> 1).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - (g, v_res) - } else { - let g_mult = v_plus_g.checked_mul(4).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - let half_g = ((g >> 1) as u32 & 0xffff_fffe) as i32; - let v_res = half_g - .checked_add(v) - .and_then(|x| x.checked_add(g >> 2)) - .ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - (g, v_res) - } - } else { - (residual, 0) - }; - - pred1 = context[0]; - context[0] = feedback_bits >> params.feedback_shift_644.min(30); - - let west = if col < 2 { params.boundary_predictor_642 } else { context[1] }; - let mut north = if row < 2 { - params.boundary_predictor_642 - } else { - pixels.get((row - 2) * width + col).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) - }; - let north_west = if row < 2 || col < 2 { - params.boundary_predictor_642 - } else { - pixels.get((row - 2) * width + col - 2).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15)) - }; - - context[1] = last_predicted_sum; - - // Directional edge-directed spatial prediction across Bayer channels (2-step distance) - if west < north || north_west < west { - if north_west <= north && west >= north { - north = west; - } else if north_west < north || west >= north { - if north_west > west || west >= north { - let diff_n_nw = north.abs_diff(north_west); - let diff_w_nw = west.abs_diff(north_west); - if diff_n_nw > gradient_threshold { - north = north.saturating_add(west.saturating_sub(north_west)); - } else if diff_w_nw <= gradient_threshold { - north = (north.saturating_add(west)) >> 1; - } else { - north = north.saturating_add(west.saturating_sub(north_west)); - } - } - } else { - north = west; - } - } - - let sum = adjusted_residual.checked_add(north).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?; - last_predicted_sum = sum; - let final_sample = i64::from(direct_bits_low0).saturating_add(i64::from(sum) << params.direct_bits_low0.min(15)); - if let Some(px) = pixels.get_mut(row_offset + col) { - *px = final_sample.clamp(0, i64::from(u16::MAX)) as u16; - } - } - } - - let consumed_bits = reader.bits_loaded.saturating_sub(u64::from(reader.bits_available)); - if consumed_bits > (stream.len() as u64).saturating_mul(8) { - return Err(RawError::Corrupt("ORF compressed bitstream terminates prematurely".into())); - } - - Ok(pixels) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn stream_header_validation() { - assert!(validate_stream_header(&[0, 0, 0, 1, 0, 0], 4)); - assert!(validate_stream_header(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 8)); - assert!(!validate_stream_header(&[0, 0, 0, 2, 0, 0], 4)); // prefix != 1 - assert!(!validate_stream_header(&[0, 0, 0, 1, 0, 1], 4)); // trailer != [0, 0] - assert!(!validate_stream_header(&[0, 0, 0, 0], 5)); // truncated - assert!(!validate_stream_header(&[], 0)); // zero length - assert!(!validate_stream_header(&[0; 20], 9)); // > 8 bytes - } - - #[test] - fn bitstream_reader_operations() { - let data = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc]; - let mut stream = BitStream::new(&data); - assert_eq!(stream.read_bits(4), 1); - assert_eq!(stream.read_bits(4), 2); - assert_eq!(stream.read_bits(8), 0x34); - assert_eq!(stream.read_bits(16), 0x5678); - assert_eq!(stream.read_bits(8), 0x9a); - assert_eq!(stream.read_bits(8), 0xbc); - // past EOF reads padded zeros without panicking - assert_eq!(stream.read_bits(8), 0); - } - - #[test] - fn decompress_bounds_and_safety() { - let params = CompressionParameters { - direct_bits_low0: 0, - gradient_thresh_exp_641: 5, - boundary_predictor_642: 0, - direct_bits_sub3: 2, - feedback_shift_644: 5, - flatness_thresh_exp_645: 4, - run_thresh_646: 3, - table_647: 2, - table_648: 3, - table_649: 4, - table_650: 7, - max_rice_k: 15, - max_unary_run: 12, - header_prefix_len: 5, - valid_bits: 12, - }; - // empty stream returns error for nonempty image, succeeds for 0x0 - assert!(decompress_stream(&[], 10, 10, ¶ms).is_err()); - assert_eq!(decompress_stream(&[], 0, 0, ¶ms).unwrap(), Vec::::new()); - // truncated stream (too short for requested dimensions) returns error - assert!(decompress_stream(&[0xff; 2], 10, 10, ¶ms).is_err()); - assert!(decompress_stream(&[0x00; 2], 10, 10, ¶ms).is_err()); - - // invalid Rice parameter returns error - let mut bad_params = params; - bad_params.table_649 = 20; - bad_params.max_rice_k = 20; - assert!(decompress_stream(&[0xff; 32], 4, 4, &bad_params).is_err()); - } - - #[test] - fn predictor_extreme_difference_never_panics() { - assert_eq!(i32::MIN.abs_diff(0), 2_147_483_648u32); - assert_eq!(i32::MIN.abs_diff(i32::MAX), 4_294_967_295u32); - - let params = CompressionParameters { - direct_bits_low0: 0, - gradient_thresh_exp_641: 5, - boundary_predictor_642: 0, - direct_bits_sub3: 0, - feedback_shift_644: 5, - flatness_thresh_exp_645: 4, - run_thresh_646: 3, - table_647: 2, - table_648: 3, - table_649: 4, - table_650: 7, - max_rice_k: 15, - max_unary_run: 12, - header_prefix_len: 5, - valid_bits: 12, - }; - for fill in [0x00, 0x55, 0xaa, 0xff] { - let stream = vec![fill; 64]; - let _ = decompress_stream(&stream, 4, 4, ¶ms); - } - } -} diff --git a/crates/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index 2fd0c04796..0be98991de 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -17,6 +17,8 @@ fn corpus_root() -> PathBuf { /// Variants known not to decode yet (see the crate docs): matched against the lower-case file name. const KNOWN_UNSUPPORTED: &[&str] = &[ + "orf-olympus-em1.orf", // Compressed Olympus sensor decoding withdrawn pending provenance resolution. + "orf-olympus-em10iii.orf", "cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs. "-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193 "sraw", // Canon sRAW / mRAW diff --git a/crates/raw/tests/it/olympus_samsung_corpus.rs b/crates/raw/tests/it/olympus_samsung_corpus.rs index f5579ba0a1..9218b4b93d 100644 --- a/crates/raw/tests/it/olympus_samsung_corpus.rs +++ b/crates/raw/tests/it/olympus_samsung_corpus.rs @@ -8,7 +8,7 @@ //! pinned only (its small JPEG gives r 0.59); its render was inspected by eye. //! Missing files are reported as skipped. -use lightcraft_raw::{RawData, decode, embedded_preview, probe_info}; +use lightcraft_raw::{RawData, RawError, RawFormat, decode, embedded_preview, probe, probe_info}; use std::path::{Path, PathBuf}; fn corpus() -> PathBuf { @@ -67,8 +67,6 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() { ("orf-olympus-e-330.orf", (3280, 2450), 0xc938_38fa_9822_c81a, true), ("orf-olympus-e-500.orf", (3360, 2504), 0x5e22_2ac8_17ed_89d9, true), ("orf-olympus-e-m5-mark-ii.orf", (9280, 6932), 0xa222_be38_c767_7782, true), - ("orf-olympus-em1.orf", (4640, 3472), 0xc61b_0bb3_5170_4735, true), - ("orf-olympus-em10iii.orf", (4640, 3472), 0xedc1_ec6d_15a8_a303, true), ("orf-olympus-pen-f.orf", (10400, 7796), 0x415e_bf27_092e_9897, true), ("orf-olympus-sh-2.orf", (4624, 3470), 0xb25b_8d24_4ade_1f3d, true), ("orf-olympus-sp510uz.orf", (3088, 2309), 0xa885_b7ca_83ba_02f1, true), @@ -114,3 +112,21 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() { } eprintln!("Olympus / Samsung bodies checked on {seen} files"); } + +/// The withdrawn compressed decoder must stay out of both sensor-decode and import-probe paths. +/// Camera JPEG extraction is independent of sensor decoding and remains available for preview-only imports. +#[test] +fn compressed_olympus_bodies_are_unsupported_with_embedded_previews() { + for name in ["orf-olympus-em1.orf", "orf-olympus-em10iii.orf"] { + let path = corpus().join("raw").join(name); + let Ok(bytes) = std::fs::read(&path) else { + lightcraft_testkit::skip!(Corpus, "{} absent", path.display()); + continue; + }; + assert_eq!(probe(&bytes), Some(RawFormat::Orf), "{name}"); + assert!(matches!(decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}"); + assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}"); + let jpeg = embedded_preview(&bytes).unwrap_or_else(|| panic!("{name}: no camera JPEG")); + assert!(jpeg.starts_with(&[0xff, 0xd8]) && jpeg.ends_with(&[0xff, 0xd9]), "{name}: invalid camera JPEG"); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 08cebce09d..f11acd4747 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -20,7 +20,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | -| 6 | ~~Compressed ORF~~ (every Olympus / OM body since ~2008): closed 2026-11-04, see Closed recently | checklist row 🟡 (LR-IMP-FORMATS remains 🟡: other raw formats open); bitstream entropy decoder in `crates/raw/src/vendor/orfc.rs`; OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (preview 187 → 129; 78 total across Olympus and OM) | — | 0 | [orf-compression](orf-compression.md) | +| 6 | **Compressed ORF** (support withdrawn) | #3775 decoder removed pending provenance review; uncompressed support remains | compressed files use embedded JPEG previews when available, not sensor data | pending review | [orf-compression](orf-compression.md) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | | 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS, run on Windows only for Windows code, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; its Windows leg (`ci-windows.yml`) runs clippy and the tests of the crates with `cfg(windows)` code (wincolor, catalog, engine, ui-egui, lightcraft) on windows-latest when a pull request or a push to `main` changes that code, and on pull requests labelled `full-ci`; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, ci-windows, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS, on Windows in code outside the Windows leg's paths, or only on a GPU, reaches users; the full `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | @@ -61,8 +61,6 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) -- 2026-11-04: Gap 6 closed: compressed Olympus ORF decodes from sensor data (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 58 bodies newly unlocked (78 total across Olympus and OM). - - 2026-10-29: the import review has a remembered 80–320 pt thumbnail-size slider, density-aware previews and bounded visible retention (#2237, part of #2056). Small sources do not reconstruct the same preview job every frame. The pre-import loupe and keyboard culling remain open in #2056; no ranked gap or headline feature count closes. - 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. @@ -92,7 +90,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | Gap 6 closed: Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`), OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM; OM / Olympus fully working 6% → 81%) | +| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | +| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-11-05 | minor | Gap 3: process V5 rolls a raw's tone curve off into white in stops, so raising Exposure keeps the highlights the sensor recorded (#1632); the gap stays open (no Lightroom comparison) and hours are unchanged | | 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed | | 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed | @@ -177,7 +176,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | 2026-10-11 | minor | Reviewed against main after 0.6.0: CR3 entry names the CRX variants `crx.rs` still refuses and the R7 / R6 Mark II C-RAW state (decoding, not verified, so the measured numbers don't move); CI and Windows / Linux entries note the riscv64 release build (#844); R7 fix added to Closed recently. Panel docking (UI.9, #869) closes no listed gap | | 2026-10-11 | minor | Camera colour entry: raws with a black-and-white camera JPEG take its tone curve (#577); gap not closed | | 2026-10-11 | minor | Gap 4: Compare and Reference views get zoom windows per pane (1:1 was a 2,560 px render magnified); overlays and soft proofing remain, 8–15 h → 4–8 h | -| 2026-10-10 | minor | Compressed ORF entry links the two Olympus patents that describe the method | +| 2026-10-10 | minor | Compressed ORF patent references were added; these do not establish the provenance of the subsequently withdrawn #3775 decoder | | 2026-10-11 | minor | Gap 14: `crs:HDREditMode` is read from XMP (#663); the headroom limit and SDR rendition still aren't | | 2026-10-11 | minor | Gaps 2 and 10 shrink: EOS R5 Mark II CR3 decodes and is verified (fourth CR3 body, Canon 12 verified, 235 models, ~42% on a verified body); CR3 gain +6.5 → +6.2 points | | 2026-10-10 | minor | RAW gaps re-measured model by model (raw-parity.md): CR3, compressed ORF and verification entries carry measured shares; HE NEF no longer a beta blocker (+1.1 points for 20–40 h); verification entry absorbs the cheap per-body fixes (#769, #702, A200 series) | diff --git a/docs/orf-compression.md b/docs/orf-compression.md index 1469a10d05..7fe5439c88 100644 --- a/docs/orf-compression.md +++ b/docs/orf-compression.md @@ -1,107 +1,11 @@ -# Olympus compressed ORF +# Olympus compressed ORF: support withdrawn -LightCraft decodes uncompressed 16-bit, packed 12-bit, two-field 12-bit, 12.8 bpp blocks and compressed ORF sensor data in pure Rust. The shared RAW decoder serves import, desktop previews, editing, CLI rendering, web and export. +Compressed ORF sensor decoding introduced in #3775 has been removed while its provenance remains unresolved. The earlier clean-room and derivation claims are withdrawn; this note makes no legal determination and is not a format specification. -Compressed ORF sensor decoding is implemented clean-room in `crates/raw/src/vendor/orfc.rs` without any dependency on or consultation of LibRaw, dcraw, or any GPL/LGPL/AGPL software. +Compressed ORF files are unsupported for sensor decoding. They use an embedded JPEG preview when one is available; a file without a usable preview cannot be rendered. Preview-only editing and export operate on that rendered preview, not the raw sensor data. -## Format and implementation +Uncompressed 16-bit, packed 12-bit, two-field 12-bit and 12.8 bpp ORF support remains in `crates/raw/src/vendor/orf.rs`. This includes supported uncompressed high-resolution modes; it does not imply compressed-mode support on the same camera. -The compressed format is used by virtually all Olympus and OM System digital interchangeable-lens cameras (PEN, OM-D series, OM System) and high-end compacts since approximately 2008. - -### Container and Header - -Compressed ORF files use the standard Olympus TIFF container format (magic bytes `IIRO` for little-endian or `MMOR` for big-endian). IFD0 contains the image dimensions, strip offsets, and strip byte counts. - -The raw entropy bitstream is preceded by a short prefix: -1. Maker note tag `0x2040` (ImageProcessing), SubIFD tag `0x0653` specifies the prefix length $N$ in bytes (typically 4 or 8 bytes). -2. The first $N$ bytes of the raw strip encode a big-endian integer equal to 1. -3. The prefix is immediately followed by a two-byte null delimiter `[0x00, 0x00]`. -4. The entropy-coded bitstream begins immediately after byte $N + 2$. - -### ImageProcessing Metadata Parameters - -The decompression engine reads operational parameters from the `0x2040` (ImageProcessing) SubIFD: -- **`0x0640` ($S_0$)**: Low-order sample bits extracted directly from the bitstream without prediction (0 to 16 bits). -- **`0x0641` ($T_{641}$)**: Directional gradient threshold exponent; edge threshold is $2^{T_{641}}$. -- **`0x0642` ($P_0$)**: Initial boundary predictor value for outer image margins ($x < 2$ or $y < 2$). -- **`0x0643` ($S_3$)**: Residual sub-bit width for high-frequency difference adjustments (typically 0, 1, or 2). -- **`0x0644` ($S_4$)**: Context feedback divisor exponent. -- **`0x0645` ($T_{645}$)**: Threshold power for tracking local flat-region context runs. -- **`0x0646` ($R_0$)**: Run-length threshold triggering alternate Rice parameter adaptation. -- **`0x0647`–`0x0650`**: Parameter tables for Rice parameter base values and offsets depending on context activity. -- **`0x0651` ($k_{\max}$)**: Maximum allowable Golomb-Rice parameter $k$. -- **`0x0652` ($Q_{\max}$)**: Maximum unary quotient run length before switching to an escape sequence. -- **`0x0653` ($N$)**: Stream header prefix length in bytes. -- Maker note tag `0x102c` specifies valid sensor bits (typically 12 bits). - -### Bitstream and Entropy Decoding - -The bitstream is packed MSB-first in big-endian words. For each sample in row-major order: -1. **Sign bit**: One bit is read to determine the sign of the residual. -2. **Direct bitfields**: - - If $S_3 > 0$, $S_3$ bits are read directly. - - If $S_0 > 0$, $S_0$ bits are read directly. -3. **Golomb quotient ($Q$)**: - - Bitstream bits are inspected sequentially, counting consecutive zeros until a `1` bit is found. - - If the zero count reaches $Q_{\max}$ (`tag0x652`): - - An escape code is triggered. - - $(15 - k)$ bits are read directly from the bitstream. - - One trailing boundary bit is consumed. -4. **Golomb remainder ($R$)**: - - If $k > 0$, $k$ bits are read from the stream; otherwise $R = 0$. -5. **Residual magnitude**: - - Unsigned magnitude $M = (Q \ll k) \mid R$. - - If the sign bit was set, two's complement sign mapping is applied. - -### Context Adaptation - -Between consecutive pixels in a row: -- The previous symbol magnitude $M$ updates the flatness context detector. -- If $M \le 2^{T_{645}}$, local flatness run counters increment. -- The Rice parameter $k$ adapts dynamically based on the highest bit position of preceding magnitudes and the local context state, clamped to $[0, k_{\max}]$. - -### Spatial Directional Predictor - -Olympus ORF images are Bayer color filter arrays. Because color filters alternate every pixel, same-color photosites are located 2 pixels apart: -- West neighbor $W$: $(x - 2, y)$ -- North neighbor $N$: $(x, y - 2)$ -- North-West neighbor $NW$: $(x - 2, y - 2)$ - -Boundary sites where $x < 2$ or $y < 2$ substitute the default level $P_0$ (tag `0x0642`). - -An edge-directed predictor selects the expected value: -- The horizontal difference $|W - NW|$ and vertical difference $|N - NW|$ are compared against the gradient threshold $2^{T_{641}}$. -- Along strong vertical edges, the vertical neighbor $N$ is prioritized. -- Along strong horizontal edges, the horizontal neighbor $W$ is prioritized. -- In smooth planar regions, plane extrapolation $N + W - NW$ or average $(N + W) / 2$ is applied. - -### Reconstruction - -The final sensor sample is reconstructed by combining: -1. The predicted baseline from spatial neighbors. -2. The adjusted entropy-decoded residual. -3. Shifting by $S_0$ and adding the direct low-order bits $S_0$. -4. Clamping the result to the 16-bit integer range $[0, 65535]$. - -## Verification - -The clean-room implementation was verified against real CC0 files from raw.pixls.us: - -| Camera Model | Sensor Dimensions | Pinned FNV-1a Hash | Pearson $r$ vs Embedded Preview | -|---|---|---|---| -| Olympus OM-D E-M1 | 4640 × 3472 | `0xc61b_0bb3_5170_4735` | 0.995 | -| Olympus OM-D E-M10 Mark III | 4640 × 3472 | `0xedc1_ec6d_15a8_a303` | 0.929 | - -The regression test `olympus_and_samsung_bodies_decode_like_the_camera_jpeg` in `crates/raw/tests/it/olympus_samsung_corpus.rs` verifies that: -1. Every decoded pixel matches the pinned 64-bit FNV-1a sensor checksum. -2. Green photosite luminance across the active sensor area strongly correlates ($r > 0.6$) with the camera's embedded JPEG preview. - -## Sources and Clean-Room Provenance - -- **US Patent US7333035B2**: Takashi Ishikawa, Olympus Corporation, *"Image data compression apparatus, image data decompression apparatus, image data compression method, and image data decompression method"*, describing edge-directed median prediction for Bayer patterns and run-length adaptive Golomb-Rice entropy coding. -- **US Patent US7715639B2**: Takashi Ishikawa, Olympus Corporation, *"Image data compression apparatus, image data compression method, and computer-readable recording medium"*, describing low-order bit splitting and residual correction. -- **TIFF 6.0 Specification**: Aldus / Adobe, baseline container structure. -- **Exif 2.3 Specification**: JEITA, `CFAPattern` and MakerNote storage. -- **CC0 Samples**: raw.pixls.us public sample library. -- **Prohibition compliance**: No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used in this implementation. +Existing ORF records are rechecked in the background when a library opens, including files previously marked as sensor-decodable. Supported uncompressed ORFs remain supported; compressed files become preview-only. Missing or offline files are left unchanged and retried on the next open. **Reload from Disk** (`photo.reload`) can also refresh this status manually. ORF render-cache identities invalidate older sensor-derived thumbnails and loupe renders. Existing edits may look different when applied to the camera JPEG instead of sensor data. +Coverage records no longer count the removed decoder as support or verification. See [raw-parity.md](raw-parity.md) and [raw/coverage.tsv](raw/coverage.tsv). Any future compressed ORF decoder requires independently established provenance and validation before support is claimed again. Git history is preserved. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 49bfe4ec9c..cf6ab0de74 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -81,7 +81,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed and compressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed: 12-bit entropy-coded sensor differences in `crates/raw/src/vendor/orfc.rs`, OM-D E-M1 and E-M10 Mark III verified against camera JPEGs, r = 0.995 and 0.929), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | @@ -802,7 +802,8 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Olympus compressed ORF bitstream decoder implemented (`crates/raw/src/vendor/orfc.rs`); OM-D E-M1 and E-M10 Mark III verified on CC0 files; 58 bodies newly unlocked (78 total across Olympus and OM) | +| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | +| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | | 2026-11-06 | minor | LR-EDIT-DETAIL-CNR, LRC-DEV-PROCESS: process V6 takes colour noise reduction to the joint method on linear R−Y / B−Y (issue #815); status unchanged | | 2026-11-05 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V5 rolls a raw's tone curve off into white in stops, past a camera curve's last knot and from half a stop below the generic curve's white point, so raising Exposure no longer turns recorded highlights white (#1632); statuses and counts unchanged | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 3e4463a185..67d50bfa6c 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -15,12 +15,12 @@ ranked in [gaps.md](gaps.md). Details per format: [cr3.md](cr3.md), [orf-compres | Measure | Value | Kind | |---|---:|---| | Adobe-listed camera models | **1,446** | measured: [raw/adobe-cameras.tsv](raw/adobe-cameras.tsv) | -| Decoded from sensor data and **verified** on a real file | **559** (39%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | -| Decoder path should handle it, **unverified** | **721** (50%) | measured from the format rules (631 of them DNG, mostly phones) | -| **Preview-only** (embedded JPEG) | **129** (9%) | measured | +| Decoded from sensor data and **verified** on a real file | **557** (39%) | measured: [raw/evidence.tsv](raw/evidence.tsv) | +| Decoder path should handle it, **unverified** | **665** (46%) | measured from the format rules (631 of them DNG, mostly phones) | +| **Preview-only** (embedded JPEG) | **187** (13%) | measured | | **Unsupported** (not imported, refused or decodes wrongly) | **37** (3%) | measured | -| Models added since 2017 (Camera Raw 10+): verified / unverified / preview / unsupported | 183 / 558 / 5 / 8 of 754 | measured | -| **Share of photographers whose camera fully works** (decodes from sensor data), use-weighted | **~97%** | estimated: measured classes × written usage weights × per-format confidence | +| Models added since 2017 (Camera Raw 10+): verified / unverified / preview / unsupported | 182 / 542 / 22 / 8 of 754 | measured | +| **Share of photographers whose camera fully works** (decodes from sensor data), use-weighted | **~94%** | estimated: measured classes × written usage weights × per-format confidence | | …of which on a body we have verified | **~86%** | estimated, same weights | | Camera colour: Adobe profiles vs ours | 1,500 Adobe Standard profiles, 481 models with Camera Matching profiles vs **9 bundled profiles** + per-file fits + 52 spectral matrices (plus same-sensor aliases) + chart-measured matrices (1 model, the EOS D60) | measured (bundle listing, Adobe list, `assets/camera-profiles`) | | Lens profiles: Adobe vs ours | **3,635 vs 0** (in-file corrections only) | measured | @@ -93,7 +93,7 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Nikon | 99 | 77 | 19 | 0 | 3 | COOLPIX 5700 / 8400 / 8800 decode wrongly (two stacked half-height fields, CMYG read as RGB); HE / HE★ is a per-shot setting, preview-only | | Fujifilm | 97 | 65 | 9 | 23 | 0 | pre-X FinePix RAF without a raw IFD (estimated split) | | Google | 88 | 5 | 83 | 0 | 0 | — | -| Olympus | 71 | 19 | 52 | 0 | 0 | — | +| Olympus | 71 | 17 | 3 | 51 | 0 | compressed ORF | | Leica | 61 | 27 | 34 | 0 | 0 | — | | Xiaomi, Oppo, LG, Huawei, OnePlus, Motorola, Nokia | 139 | 0 | 139 | 0 | 0 | — (DNG) | | Pentax / Ricoh | 60 | 40 | 20 | 0 | 0 | — | @@ -101,9 +101,9 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Phase One / Leaf / Mamiya | 59 | 1 | 0 | 43 | 15 | IIQ, MOS preview; TIFF raws not imported (MEF decodes) | | Casio | 26 | 0 | 26 | 0 | 0 | — (DNG) | | DJI | 21 | 4 | 17 | 0 | 0 | DNG | -| OM Digital Solutions | 7 | 0 | 7 | 0 | 0 | — | +| OM Digital Solutions | 7 | 0 | 0 | 7 | 0 | compressed ORF | | Kodak, Konica Minolta, Epson, Sigma, GoPro, Contax, others | 56 | 12 | 16 | 13 | 15 | DCR, GPR not imported; KDC, X3F preview (Epson ERF and Minolta MRW decode) | -| **All** | **1,446** | **559 (39%)** | **721 (50%)** | **129 (9%)** | **37 (3%)** | | +| **All** | **1,446** | **557 (39%)** | **665 (46%)** | **187 (13%)** | **37 (3%)** | | ## By use (estimated) @@ -114,15 +114,15 @@ unsupported to preview-only in the counts; sensor-decoding readiness is unchange | Nikon | 16% | 98% | 89% | decoders cover every NEF coding but HE; 77 bodies verified | | Fujifilm | 10% | 94% | 92% | | | Panasonic | 4% | 100% | 98% | bulk-checked | -| OM / Olympus | 3% | 81% | 6% | — | +| OM / Olympus | 3% | 6% | 5% | compressed ORF preview-only | | Phones | 3% | 93% | 4% | DNG | | Pentax / Ricoh | 1.5% | 99% | 80% | | | Leica | 1% | 99% | 72% | the Q3 verified, 13 more bodies pinned on CC0 files | | DJI | 1% | 96% | 19% | | | Medium format and others | 0.5% | 35% | 11% | IIQ, 3FR, X3F | -| **Weighted** | 100% | **97%** | **86%** | | +| **Weighted** | 100% | **94%** | **86%** | | -About 97 in 100 raw photographers' cameras decode, and about 6 in 7 use a body we have actually +About 94 in 100 raw photographers' cameras decode, and about 6 in 7 use a body we have actually checked (the per-model CC0 sweeps of October 2026). ## Variant matrix (depth per format) @@ -158,7 +158,7 @@ checked (the per-model CC0 sweeps of October 2026). | RAF | uncompressed, lossless and lossy compressed; Bayer and X-Trans; GFX 14/16-bit | ✅ | 24 files from 13 bodies exact | | RAF | pre-X FinePix without a raw IFD | ⬜ | `raf.rs` refuses (26 Adobe models, estimated split) | | ORF | uncompressed 16-bit, 12-bit packed, two-field 12-bit, 12.8 bpp | ✅ | E-1, E-400, XZ-2 corpus; #651 | -| ORF | **compressed** (every Olympus / OM body since ~2008) | 🟡 | `crates/raw/src/vendor/orfc.rs` decodes; OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; other bodies unverified | +| ORF | **compressed** | ⬜ | sensor decoding withdrawn pending provenance review; embedded JPEG preview when available | | RW2 / RWL / RAW | formats 2, 4, 5, 6, 7, 8 and 16-bit words | ✅ | 118 bodies (#215) | | PEF | uncompressed, Huffman, packed 12-bit | ✅ | K10D, K-3, K-5 IIs; files without area tags lose their masked, empty and saturated border lines (#1271: KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) | | PEF / DNG | Pentax pixel shift | ⬜ | frames not combined | @@ -177,20 +177,14 @@ checked (the per-model CC0 sweeps of October 2026). | MEF | uncompressed 12-bit (Mamiya ZD) | ✅ | 1 CC0 corpus file; crop and WB from its uncompressed RGB preview (no JPEG, no WB tag); `vendor/mef.rs` | | DCR, MFW, DXO, GPR, TIFF raws | all | ⬜ | not imported | -### Compressed ORF: a clean-room starting point +### Compressed ORF: support withdrawn -Two Olympus patents by Takashi Ishikawa describe the *method* of lossless RAW compression in prose; neither names ORF -and neither gives the file layout. See the closed #240 and the open #360 for why a decoder has to be derived from the -files and prose rather than from dcraw-family code. - -- [US7333035B2](https://patents.google.com/patent/US7333035): lossless RAW compression for SLR cameras: - median-edge-detector prediction from the left, upper and upper-left neighbours, a separately coded sign, Golomb-Rice - codes whose parameter `k` comes from flatness run counters, counters reset per line. -- [US7715639B2](https://patents.google.com/patent/US7715639B2/en): a sibling with predictor variants, `k` derived from - neighbouring positions, raw low-order bits and a correction filter. - -They give the algorithm's shape; the full clean-room specification and derivation are documented in [orf-compression.md](orf-compression.md) and implemented in pure Rust in `crates/raw/src/vendor/orfc.rs`. +The decoder introduced in #3775 has been removed pending provenance review. Earlier clean-room and derivation claims are withdrawn. Compressed files use embedded JPEG previews when available; uncompressed support remains. See [ORF status](orf-compression.md). +Public references retained from the earlier research notes: Olympus patents +[US7333035B2](https://patents.google.com/patent/US7333035) and +[US7715639B2](https://patents.google.com/patent/US7715639B2/en). +Neither names ORF or specifies its file layout. These references do not establish the provenance of the withdrawn decoder. ## Demosaic, levels, crops and lens metadata @@ -255,6 +249,8 @@ drone DNG users (~9% of photographers by the weights above); Adobe reaches nearl ## Scores +These earlier readiness estimates have not been re-scored by the compressed ORF removal. Current camera coverage is reported above. + | Part | Weight | Score | Basis | |---|---:|---:|---| | Decoding | 60% | **83%** | use-weighted 92% × 0.9 (82.8%) for per-body decode bugs still surfacing (levels, crops, WB: #535, #455, #461, #702) | @@ -275,7 +271,7 @@ works, from [raw/usage-weights.tsv](raw/usage-weights.tsv). | # | Camera / variant | Gain (points of photographers) | Hours | Gain per hour | Needs | |---:|---|---:|---:|---:|---| -| 1 | ~~Compressed ORF (every Olympus / OM body since ~2008)~~ | (+2.6, taken) | — | — | done | +| 1 | Compressed ORF (support withdrawn) | not re-estimated | pending review | — | independently established provenance and validation; [status](orf-compression.md) | | 2 | CR3: remaining CRX variants (no public file uses them) | +0.3 | 10–25 | ~0.02 | files that open as a preview, from users | | 3 | ~~Verify popular Nikon, Fujifilm, Canon CR2 and Pentax bodies (one CC0 file each, fix what breaks)~~ done (#1045, #1081) | (+2.0, taken) | — | — | public samples | | 4 | Nikon packed 14-bit under a compressed tag (Z 6II uncompressed, #769) | +0.2 | 1–2 | ~0.13 | PR #671 exists | @@ -298,7 +294,8 @@ Beyond decoding: | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | Compressed ORF decoded (clean-room pure-Rust bitstream decoder, `crates/raw/src/vendor/orfc.rs`, `docs/orf-compression.md`): OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) verified; 559 verified, 721 unverified, 129 preview; OM / Olympus fully working 6% → 81%, weighted coverage 94% → 97% | +| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | +| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-26 | patch | Bundled camera profile count 5 → 9 (Nikon Z 6II, Z 8 and D5300, ILCE-7RM5); counts only | | 2026-10-23 | minor | Lens profiles: Sony ILCE-6700 (APS-C) in-file distortion through the ILCE-7RM6 conversion, knots spanning its own crop; lens score unchanged (~10%: one more body) | | 2026-10-25 | patch | CRW variant rows split by verification status (EOS and G1/G6 verified; G2/G3/G4/Pro1/S-series unverified; G5 preview); the CIFF heap walk is bounded by a per-file record budget, so a block of sub-heap records pointing back at their parent no longer hangs decode | @@ -326,7 +323,7 @@ Beyond decoding: | 2026-10-12 | minor | 22 more CR3 bodies verified (one CC0 raw.pixls.us file each, pinned, checked against the camera JPEG; all 110 CC0 CR3s decode); EOS R6 Mark III ColorData 66 white balance: 259 verified, 919 unverified; use-weighted 92% (59% on verified bodies); Canon 73% → 94%; decoding 83%, RAW readiness ~56% → ~60%; CR3 gain +6.2 → +0.3 | | 2026-10-12 | minor | 117 Nikon and Fujifilm bodies verified (one CC0 raw.pixls.us file each, pinned, checked against the camera JPEG; `body_corpus.rs`); COOLPIX 5700 / 8400 / 8800 decode wrongly (now unsupported); #702 fixed, A100 preview-only: 354 verified, 824 unverified, 230 preview, 38 unsupported; use-weighted 86% (58% on verified bodies); decoding 77% unchanged | | 2026-10-11 | minor | Nikon: every body without `CropArea` surveyed (#1053); 36 model / size / depth groups cropped to their measured camera frame (#976, #914), 6 pending; NEF row no longer claims every coding but HE decodes (compressed NEFs without a linearization table listed) | -| 2026-10-10 | minor | Compressed ORF: pointer to the two Olympus patents that describe the method, as a clean-room starting point | +| 2026-10-10 | minor | Compressed ORF: patent references were added; these do not establish the provenance of the subsequently withdrawn #3775 decoder | | 2026-10-12 | minor | PEF without area tags: masked border rows and columns trimmed against the BlackPoint (issue #1271; KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z); counts unchanged | | 2026-10-13 | minor | Lens profiles: Nikon in-file distortion (NikonNEFInfo `0xc7d5`) for the Z 6II, Z 8 and Z f, validated on 83 frames from three lenses and the CC0 Z f sample (`docs/nikon-lens-corrections.md`); lens score unchanged | | 2026-10-11 | minor | EOS R5 Mark II verified (CRX QP-map first literal and limited-length escape, odd-height Bayer planes; 4 CC0 files pinned, QP maps of 33,665 private files): 235 verified, 942 unverified; use-weighted 85% (42% on verified bodies); decoding 77%, RAW readiness unchanged at ~56% | diff --git a/docs/raw/coverage.py b/docs/raw/coverage.py index c7187d023c..9beb6a9eb0 100644 --- a/docs/raw/coverage.py +++ b/docs/raw/coverage.py @@ -81,7 +81,9 @@ def classify(maker, camera, ext_field): if e == "PEF": return "unverified", "PEF", "PEF decoder (uncompressed, Huffman, packed 12-bit)" if e == "ORF": - return "unverified", "ORF", "ORF decoder (uncompressed, packed, compressed)" + if ORF_DECODED.search(camera): + return "unverified", "ORF", "uncompressed / packed ORF" + return "preview", "ORF", "compressed ORF is unsupported; embedded preview when available" if e == "SRW": if SRW_COMPRESSED.search(camera): return "preview", "SRW", "compressed SRW is not decoded" diff --git a/docs/raw/coverage.tsv b/docs/raw/coverage.tsv index 66daaaf62b..c7a8835096 100644 --- a/docs/raw/coverage.tsv +++ b/docs/raw/coverage.tsv @@ -779,84 +779,84 @@ Nikon ZR NEF 2024 unverified NEF decoder (uncompressed, lossless, lossy, lossy a Nokia Lumia 1020 DNG 2013 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Nokia HMD Global Nokia 9 PureView Front Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) Nokia HMD Global Nokia 9 PureView Rear Camera DNG 2018 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) -OM Digital Solutions OM System OM-1 ORF 2021 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM System OM-5 ORF 2022 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM System TG - 7 ORF 2023 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM System OM-1 MARK II ORF 2023 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM System OM-3 ORF 2024 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM-5 Mark II ORF 2024 unverified ORF decoder (uncompressed, packed, compressed) -OM Digital Solutions OM-3 Astro ORF 2025 unverified ORF decoder (uncompressed, packed, compressed) -Olympus AIR A01 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus Camedia C-5050 Zoom ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) +OM Digital Solutions OM System OM-1 ORF 2021 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM System OM-5 ORF 2022 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM System TG - 7 ORF 2023 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM System OM-1 MARK II ORF 2023 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM System OM-3 ORF 2024 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM-5 Mark II ORF 2024 preview compressed ORF is unsupported; embedded preview when available +OM Digital Solutions OM-3 Astro ORF 2025 preview compressed ORF is unsupported; embedded preview when available +Olympus AIR A01 ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus Camedia C-5050 Zoom ORF 2003 unverified uncompressed / packed ORF Olympus Camedia C-5060 Zoom ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus Camedia C-7070 Wide Zoom ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Camedia C-8080 Wide Zoom ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Camedia C-8080 Wide Zoom ORF 2003 unverified uncompressed / packed ORF Olympus E-1 ORF 2003 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) -Olympus E-3 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-5 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-3 ORF 2007 preview compressed ORF is unsupported; embedded preview when available +Olympus E-5 ORF 2010 preview compressed ORF is unsupported; embedded preview when available Olympus E-10 ORF 2003 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash) -Olympus E-20 ORF 2003 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-30 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-420 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-450 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-520 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-600 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus E-620 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) +Olympus E-20 ORF 2003 unverified uncompressed / packed ORF +Olympus E-30 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus E-420 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus E-450 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus E-520 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus E-600 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus E-620 ORF 2008 preview compressed ORF is unsupported; embedded preview when available Olympus EVOLT E-300 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus EVOLT E-330 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus EVOLT E-400 ORF 2005 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) -Olympus EVOLT E-410 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) +Olympus EVOLT E-410 ORF 2007 preview compressed ORF is unsupported; embedded preview when available Olympus EVOLT E-500 ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus EVOLT E-510 ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M1 ORF 2013 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M1X ORF 2018 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M1 Mark II ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M1 Mark III ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M5 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) +Olympus EVOLT E-510 ORF 2007 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M1 ORF 2013 preview compressed ORF support withdrawn pending provenance review; embedded JPEG +Olympus OM-D E-M1X ORF 2018 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M1 Mark II ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M1 Mark III ORF 2019 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M5 ORF 2012 preview compressed ORF is unsupported; embedded preview when available Olympus OM-D E-M5 Mark II ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M5 Mark III ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M10 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M10 Mark II ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M10 Mark III ORF 2017 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M10 Mark III S ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) -Olympus OM-D E-M10 Mark IV ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-P1 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-P2 ORF 2008 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-P3 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-P5 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-P7 ORF 2020 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL1s ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL10 ORF 2019 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL2 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL3 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL6 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL5 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL7 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL8 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PL9 ORF 2017 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PM1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) -Olympus PEN E-PM2 ORF 2012 unverified ORF decoder (uncompressed, packed, compressed) +Olympus OM-D E-M5 Mark III ORF 2019 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M10 ORF 2013 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M10 Mark II ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M10 Mark III ORF 2017 preview compressed ORF support withdrawn pending provenance review; embedded JPEG +Olympus OM-D E-M10 Mark III S ORF 2019 preview compressed ORF is unsupported; embedded preview when available +Olympus OM-D E-M10 Mark IV ORF 2019 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-P1 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-P2 ORF 2008 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-P3 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-P5 ORF 2013 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-P7 ORF 2020 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL1 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL1s ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL10 ORF 2019 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL2 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL3 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL6 ORF 2013 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL5 ORF 2012 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL7 ORF 2013 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL8 ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PL9 ORF 2017 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PM1 ORF 2010 preview compressed ORF is unsupported; embedded preview when available +Olympus PEN E-PM2 ORF 2012 preview compressed ORF is unsupported; embedded preview when available Olympus PEN-F ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-310 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) -Olympus SP-320 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) -Olympus SP-350 ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) -Olympus SP-500 UZ ORF 2005 unverified ORF decoder (uncompressed, packed, compressed) +Olympus SP-310 ORF 2005 preview compressed ORF is unsupported; embedded preview when available +Olympus SP-320 ORF 2005 preview compressed ORF is unsupported; embedded preview when available +Olympus SP-350 ORF 2005 preview compressed ORF is unsupported; embedded preview when available +Olympus SP-500 UZ ORF 2005 preview compressed ORF is unsupported; embedded preview when available Olympus SP-510 UZ ORF 2005 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-550 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus SP-560 UZ ORF 2007 unverified ORF decoder (uncompressed, packed, compressed) +Olympus SP-560 UZ ORF 2007 preview compressed ORF is unsupported; embedded preview when available Olympus SP-565 UZ ORF 2008 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) Olympus SP-570 UZ ORF 2007 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus 1 ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) -Olympus Stylus 1s ORF 2013 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus 1 ORF 2013 preview compressed ORF is unsupported; embedded preview when available +Olympus Stylus 1s ORF 2013 preview compressed ORF is unsupported; embedded preview when available Olympus Stylus SH-2 ORF 2015 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus Stylus SH-3 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus Stylus Tough TG-4 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus Stylus Tough TG-5 ORF 2015 unverified ORF decoder (uncompressed, packed, compressed) -Olympus Stylus Tough TG-6 ORF 2018 unverified ORF decoder (uncompressed, packed, compressed) +Olympus Stylus SH-3 ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus Stylus Tough TG-4 ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus Stylus Tough TG-5 ORF 2015 preview compressed ORF is unsupported; embedded preview when available +Olympus Stylus Tough TG-6 ORF 2018 preview compressed ORF is unsupported; embedded preview when available Olympus Stylus XZ-2 iHS ORF 2012 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Olympus Stylus XZ-10 ORF 2012 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus XZ-1 ORF 2010 unverified ORF decoder (uncompressed, packed, compressed) +Olympus XZ-1 ORF 2010 preview compressed ORF is unsupported; embedded preview when available OnePlus 7T Front Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) OnePlus 7T Rear Main Camera DNG 2019 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) OnePlus 8 Front Camera DNG 2020 unverified DNG decoder (uncompressed, LJ92, lossy, Deflate, JPEG XL, LinearRaw) diff --git a/docs/raw/evidence.tsv b/docs/raw/evidence.tsv index 7a03fa43ae..de71f44c65 100644 --- a/docs/raw/evidence.tsv +++ b/docs/raw/evidence.tsv @@ -576,5 +576,5 @@ Canon EOS 300D (EOS Digital Rebel, EOS Kiss Digital) verified corpus: crates/raw Canon PowerShot G1 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G6 verified corpus: crates/raw/tests/it/corpus.rs (xtask RAW_SAMPLES) Canon PowerShot G5 preview CRW entropy anomaly (craft-libs crates/crw/clean-room/02-crw-format.md section 4); embedded JPEG -Olympus OM-D E-M1 verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) -Olympus OM-D E-M10 Mark III verified corpus: crates/raw/tests/it/olympus_samsung_corpus.rs (pinned sensor hash, camera-JPEG check) +Olympus OM-D E-M1 preview compressed ORF support withdrawn pending provenance review; embedded JPEG +Olympus OM-D E-M10 Mark III preview compressed ORF support withdrawn pending provenance review; embedded JPEG diff --git a/docs/roadmap.md b/docs/roadmap.md index b847560438..d6be22f7fc 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,7 +21,7 @@ Toward **beta** (~340–600 Opus 5.5 agent hours; ranked, each a gap in [gaps.md 4. **Full-resolution zoom** (gap 4, 8–15 h): visible-region rendering so 100% shows original pixels. 5. **AI masks** (gap 5, 40–70 h): Subject / Sky / People on licensable weights; configure the SAM 3 mirror. Needs the maintainer's model decision. -6. **~~Compressed ORF~~ (done 2026-11-04) and HE NEF** (gap 7, 20–40 h). +6. **Compressed ORF** (gap 6 reopened; estimate pending provenance review) and **HE NEF** (gap 7, 20–40 h). 7. **Lens profiles of our own** (gap 8, 40–80 h). 8. **Tests in CI on macOS and Windows, and the GPU tests in CI** (gap 9, 6–12 h). 9. **Per-model verification** (gap 10, 20–35 h). @@ -72,7 +72,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– | M8 | Heal / Remove | content-aware remove (PatchMatch), heal, clone, brush spots, visualize spots, red/pet eye | 6–10 | 🚧 (heal, clone, auto source, visualize spots, red/pet eye ✅; PatchMatch remove ⬜) | | M9 | Presets, profiles, versions, sync | preset browser + amount, create/import presets, profile browser, versions, history, copy/paste/sync settings | 5–8 | ✅ | | M10 | Export & share | export dialog (JPEG/PNG/TIFF/DNG/AVIF/JXL/original), sizing, sharpening, metadata, watermark, naming, batch jobs, XMP sidecars, HDR export | 6–10 | 🚧 (all formats incl. DNG/original, sizing, presets, background jobs, HDR gain map JPEG / PQ AVIF ✅; JXL encode ⬜) | -| M11 | RAW II | CR3, RAF (X-Trans), ORF, RW2, PEF, SRW, 3FR, IIQ + long tail; camera calibration DB; HEIC/AVIF/JXL import | 20–35 | 🚧 (RAF all, RW2 every format, PEF, ORF uncompressed, compressed and 12.8 bpp, SRW uncompressed, HEIC ✅; CR3 🟡 (3 bodies verified); **camera colour calibration** 🚧 (per-file JPEG fits, 5 bundled profiles, 52 spectral matrices; measured database missing); compressed SRW, HE NEF, IIQ, X3F ⬜) | +| M11 | RAW II | CR3, RAF (X-Trans), ORF, RW2, PEF, SRW, 3FR, IIQ + long tail; camera calibration DB; HEIC/AVIF/JXL import | 20–35 | 🚧 (RAF all, RW2 every format, PEF, ORF uncompressed and 12.8 bpp, SRW uncompressed, HEIC ✅; CR3 🟡 (3 bodies verified); **camera colour calibration** 🚧 (per-file JPEG fits, 5 bundled profiles, 52 spectral matrices; measured database missing); compressed ORF / SRW, HE NEF, IIQ, X3F ⬜) | | M12 | AI & smart features | subject/sky/background/people/object masks, semantic search, faces/People (permissively licensed models, pure-Rust inference) | 20–40 | 🚧 (faces: detection, recognition, People view ✅; Object / Describe masks via SAM 3 🟡; Subject / Sky / People masks, semantic search ⬜) | | M13 | Merge | HDR merge (deghost), panorama (projections, boundary warp, fill edges), HDR panorama | 10–15 | ✅ | | M14 | Video | import/playback/trim via FilmCraft crates, global edits + presets on video, video export | 6–10 | ⬜ | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c27985746d..e38aeec76a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -15,8 +15,8 @@ have their own documents: [raw-parity.md](raw-parity.md), [file-format-parity.md | **Feature breadth**, checklist | **83.2%** of 543 in-scope rows (P0 97.5%, P1 94.4%, P2 56.7%) | **measured**: recount of [parity-checklist.md](parity-checklist.md) rows (✅ 1, 🟡 ½, 🚫 left out), the same rule `cargo xtask parity` uses | | **Feature breadth**, weighted by use | **~77%** | estimated: feature-area table below | | **Ready for real work** (full target) | **~62%** (range 57–67%) | estimated: weighted sum over the dimensions with written weights, see [below](#ready-for-real-work-mainstream-practitioner-and-essentials-user) | -| **Mainstream practitioner** | **~51%** (range 46–56%) | estimated: weekly areas of a working photographer, depth 75.3% × 0.804 × colour 0.85 | -| **Essentials user** | **~65%** (range 60–70%) | estimated: core features at default settings, depth 78.4% × 0.830 | +| **Mainstream practitioner** | **~51%** (range 46–56%) | estimated: weekly areas of a working photographer, depth 74.5% × 0.804 × colour 0.85 | +| **Essentials user** | **~65%** (range 60–70%) | estimated: core features at default settings, depth 78.1% × 0.830 | | Remaining to **beta** | **~340–600 h** | estimated; ~60% parallelizes | | Remaining to **full parity** | **~980–1,750 h** | estimated; ~70% parallelizes | | **Stage** | **alpha** | see [Stage](#stage) | @@ -47,7 +47,7 @@ phase #85, duplicate Local entries #22, black GPU exports on an Intel iGPU #78). | Dimension | Breadth | Ready for real work | Remaining | Doc | |---|---:|---:|---:|---| | Features (weighted areas below) | ~77% (checklist 83.2%, measured) | ~62% | 600–1,100 h | [Features](#features) | -| ↳ RAW cameras, colour and lens profiles (part of features) | 89% of Adobe's 1,446 models decode (39% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | +| ↳ RAW cameras, colour and lens profiles (part of features) | 85% of Adobe's 1,446 models decode (39% verified), measured | ~56% | 255–480 h | [raw-parity.md](raw-parity.md) | | UI/UX fidelity | ~85% | ~70% | 32–54 h | [ui-parity.md](ui-parity.md) | | File formats (non-raw: images, sidecars, presets, catalogs) | ~85% | ~70% | 30–55 h | [file-format-parity.md](file-format-parity.md) | | Hardware | ~50% | ~40% | 40–80 h (+ tethering and printing, counted under Classic modules) | [hardware-parity.md](hardware-parity.md) | @@ -67,7 +67,7 @@ from the checklist sections and the deep-dive documents. | Area | Weight | Breadth | Ready | Remaining | Notes | |---|---:|---:|---:|---:|---| | Import and library (import, folders, albums, smart albums, keywords, metadata, search, faces) | 15% | 90% | 80% | 25–45 h | checklist A–E 83–92%; robust journal; 85k-photo libraries | -| RAW decoding and camera coverage | 15% | 85% | 87% | 110–205 h | [raw-parity.md](raw-parity.md), measured model by model: 97% of photographers' cameras decode (use-weighted), × 0.9 for per-body bugs; CR3 variants, HE NEF | +| RAW decoding and camera coverage | 15% | 85% | 85% | 110–205 h | [raw-parity.md](raw-parity.md), measured model by model: 94% of photographers' cameras decode (use-weighted), × 0.9 for per-body bugs; CR3 variants, compressed ORF, HE NEF | | Colour, camera profiles, render fidelity | 10% | 65% | 35% | 80–150 h | 10 bundled profiles vs Adobe's 1,500; per-file fits median ΔE ~5 vs the camera JPEG, ~10% far off; no fidelity suite ([raw-parity.md](raw-parity.md#colour)) | | Global develop adjustments (light, colour, curves, grading, effects, detail) | 15% | 93% | 70% | 30–60 h | checklist F 91.7%; character tuned by eye | | Optics, lens profiles, crop and geometry | 6% | 80% | 50% | 40–80 h | no lens database; crop / Upright complete | @@ -119,7 +119,7 @@ work. Each has its own hours to ~95%, calibrated as in [How hours are calibrated | Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates | |---|---:|---:|---| | Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem | -| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / HE NEF; per-model ORF verification; lens database; subject / sky masks; Lightroom XMP exchange; stability | +| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / compressed ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability | | Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send | ### Full target (ready for real work): ~62% @@ -131,7 +131,7 @@ valued from the model-by-model measurement in [raw-parity.md](raw-parity.md): | Dimension | Weight | Ready | |---|---:|---:| | Features: the other 11 areas, weighted depth from [Features](#features) | 45% | 60.9% | -| RAW decoding and camera coverage | 9% | 87% (97% use-weighted × 0.9) | +| RAW decoding and camera coverage | 9% | 85% (94% use-weighted × 0.9) | | Camera colour and default rendering | 6% | 35% | | UI/UX fidelity | 8% | 70% | | File formats (non-raw) | 6% | 70% | @@ -141,7 +141,7 @@ valued from the model-by-model measurement in [raw-parity.md](raw-parity.md): | Stability | 8% | 60% | | Platforms | 4% | 60% | | Ecosystem / plug-ins | 2% | 15% | -| **Weighted sum** | 100% | **62.0% ≈ 62%** (range 57–67%) | +| **Weighted sum** | 100% | **61.7% ≈ 62%** (range 57–67%) | Mainstream comes out lower than full: its scope is the raw-develop core, where LightCraft is weakest (camera colour, CR3 coverage), and its discounts are multiplicative, while the full sum is lifted by @@ -173,18 +173,18 @@ than the user's own. |---|---:|---:| | Import and library | 18% | 80% | | Cull: views, compare, zoom, ratings | 12% | 70% | -| Raw decoding for their camera | 27% | 97% (measured use-weighted share whose camera fully works, [raw-parity.md](raw-parity.md#by-use-estimated)) | +| Raw decoding for their camera | 27% | 94% (measured use-weighted share whose camera fully works, [raw-parity.md](raw-parity.md#by-use-estimated)) | | Global develop adjustments | 15% | 70% | | Crop, geometry, lens corrections | 6% | 50% | | Masking (manual, subject / sky; no generative) | 8% | 45% | | Heal / remove (no generative), denoise | 5% | 40% | | Presets, copy / paste / sync | 5% | 85% | | Export | 4% | 75% | -| **Weighted depth** | 100% | **75.3%** | +| **Weighted depth** | 100% | **74.5%** | Colour fidelity is a written discount, **×0.85**: most raws start near the camera's own look (median ΔE ~5), about 10% far off (ΔE ~18), none calibrated to Adobe Standard, so a working photographer -corrects colour by hand (33 open colour issues). 75.3% × 0.804 × 0.85 = **~51%** (range 46–56%). +corrects colour by hand (33 open colour issues). 74.5% × 0.804 × 0.85 = **~51%** (range 46–56%). ### Essentials user: ~65% @@ -201,11 +201,11 @@ basic sliders, crop, apply a preset, undo, export JPEGs. | Crop and straighten | 10% | 80% | | Presets and profiles | 8% | 80% | | Undo and history | 5% | 90% | -| Their camera's raws: decode × default look | 10% | 73% (97% whose camera fully works × colour factor 0.75) | +| Their camera's raws: decode × default look | 10% | 70.5% (94% whose camera fully works × colour factor 0.75) | | Export JPEG | 10% | 85% | -| **Weighted depth** | 100% | **78.4%** | +| **Weighted depth** | 100% | **78.1%** | -78.4% × 0.830 = **~65%** (range 60–70%). +78.1% × 0.830 = **~65%** (range 60–70%). ### User evidence (GitHub issues, excluding the four maintainers) @@ -230,7 +230,7 @@ evidence. The stage stays **alpha**. **Alpha.** Core workflows exist end to end (import, cull, develop, mask, export, catalog migration), but ready-for-real-work is ~62%, below the ~75% beta bar, and the main file formats have blocking -gaps: Canon CR3 decodes from sensor data on 26 verified bodies, compressed ORF decodes on 58 more bodies (2 verified), and HE NEF opens as preview, while colour on every non-DNG raw is estimated rather than measured. +gaps: Canon CR3 decodes from sensor data on 26 verified bodies, compressed ORF and HE NEF use embedded previews when available, while colour on every non-DNG raw is estimated rather than measured. **Alpha gate:** all six core workflows (import, cull, develop, save and reopen, batch looks, export) work end to end on macOS; see the table in [roadmap.md](roadmap.md#alpha-gate). The partial rows (CR3 @@ -299,7 +299,8 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. | Date | Change | Summary | |---|---|---| -| 2026-11-04 | minor | Compressed ORF decoded (`crates/raw/src/vendor/orfc.rs`): OM-D E-M1 and E-M10 Mark III verified; 58 bodies newly unlocked (78 total across Olympus and OM); RAW coverage 77% → 80%, weighted camera coverage 94% → 97% | +| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | +| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-24 | patch | Stability, the stability discount, the Beta-needs list and the estimate history: tests run in CI on Linux x64 since #2667 (FreeBSD nightly), not on macOS or Windows (gap 9); percentages and hours unchanged | | 2026-10-23 | minor | AI Denoise runs without a model (built-in denoiser); percentages unchanged, since it is a classical filter and Bayer-only | | 2026-10-13 | minor | Canon CRW decoded (clean-room, craft-libs `crates/crw/clean-room/`): 551 models verified with the coverage sweep (557 with MRW after merging main), Canon preview rows 21 → 6; RAW decoding unchanged | From b3b49987d4b2c99f582b80ae91b2ec42ab24d14e Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:12:52 +0100 Subject: [PATCH 30/30] Release: refresh contributor credits for each release (#2254) (#3898) About > Contributors still showed an old snapshot, because nothing regenerated contributors/contributors.json before a release. Opt in to the shared refresh from craft-common-actions: a read-only credits job regenerates the snapshot for the release commit, and the shared release workflow installs it before every source build. The snapshot is not committed back. --- .github/workflows/release.yml | 9 ++++++++- docs/contributors.md | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a9d4d065a3..4d8a39a0d3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,6 +21,12 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -61,7 +67,7 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: @@ -70,6 +76,7 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/docs/contributors.md b/docs/contributors.md index faf47dc716..e8b23d02f2 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers. - Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from disk or the network at run time; the web build has them too): - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. + username. Release builds regenerate it for the release commit + (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated. - [`contributors/people.toml`](../contributors/people.toml): the names people chose for themselves. **Each contributor adds only their own entry**, in their own PR. - Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced