diff --git a/crates/engine/src/cmd/lens_refresh.rs b/crates/engine/src/cmd/lens_refresh.rs index c5b03ad8341..ec20e65fd46 100644 --- a/crates/engine/src/cmd/lens_refresh.rs +++ b/crates/engine/src/cmd/lens_refresh.rs @@ -16,19 +16,24 @@ use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd}; use crate::media::{FileProbe, ProbeInfo}; -use crate::{Result, Session}; +use crate::{Result, Session, lens_profiles}; -/// A photo to probe again, and its file when listed (a result for a photo moved meanwhile is dropped). +/// What [`probe`] read for each photo. +pub type Probed = Vec<(Missing, std::result::Result)>; + +/// A photo to probe again, and its file and content when listed (a result for a photo moved meanwhile is dropped). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Missing { pub id: PhotoId, pub path: String, + pub content_hash: Option, } -/// Library raws with a file, no lens profile and a lens the database `db` knows by name (`ids`: only these; virtual -/// copies follow the photo they were copied from). With `again` (the database's files were replaced, or an agent -/// asked for every photo), also the raws whose profile came from the database (the new data may give another one, or -/// none) and the raws whose file named no lens when they were imported (a newer LightCraft may read their lens). +/// Library raws with a file, no lens profile and a lens the database `db` knows by name, or no lens name and a camera +/// whose built-in lens it knows (`ids`: only these; virtual copies follow the photo they were copied from). With +/// `again` (the database's files were replaced, or an agent asked for every photo), also the raws whose profile came +/// from the database (the new data may give another one, or none) and the other raws whose file named no lens when +/// they were imported (a newer LightCraft may read their lens). /// No file-system calls. pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[PhotoId]>, again: bool) -> Vec { // a photo and its virtual copies list the photo once, in library order @@ -41,16 +46,50 @@ pub fn missing(cat: &Catalog, db: &lightcraft_lensdb::LensDb, ids: Option<&[Phot .filter(|p| { let lens = p.meta.lens.trim(); match &p.embedded_lens { - None if lens.is_empty() => again, + None if lens.is_empty() => again || crate::lens_profiles::has_built_in_lens(db, &p.meta.camera), None => crate::lens_profiles::profile_name(db, &p.meta.camera, lens).is_some(), Some(_) => again && from_database(p), } }) - .filter_map(|p| p.library_file().map(|path| Missing { id: p.id, path: path.to_string() })) + .filter_map(|p| p.library_file().map(|path| Missing { id: p.id, path: path.to_string(), content_hash: p.content_hash.clone() })) .filter(|m| seen.insert(m.id)) .collect() } +/// What the app looks up by itself: [`missing`] in the whole library, without the raws that name no lens and were read in +/// vain with the current rules and data ([`remember_tried`]), so they are not read at every start. +pub fn automatic(s: &Session, db: &lightcraft_lensdb::LensDb, again: bool) -> Vec { + let mut listed = missing(&s.catalog, db, None, again); + if !again && s.lens_tried_by == lens_profiles::rules(db) { + let names_no_lens = |id| s.catalog.photo(id).is_some_and(|p| p.meta.lens.trim().is_empty()); + listed.retain(|m| !(names_no_lens(m.id) && s.lens_tried.get(&m.id) == Some(&m.content_hash))); + } + listed +} + +/// Keep which raws that name no lens [`probe`] read without finding a profile. A file that couldn't be read is not kept, +/// so it is tried again. +pub fn remember_tried(s: &mut Session, db: &lightcraft_lensdb::LensDb, results: &Probed) -> Result<()> { + let rules = lens_profiles::rules(db); + let mut tried = if s.lens_tried_by == rules { s.lens_tried.clone() } else { Default::default() }; + for (item, info) in results { + tried.remove(&item.id); + let same_file = s.catalog.photo(item.id).filter(|p| p.library_file() == Some(item.path.as_str())); + if same_file.is_some_and(|p| p.meta.lens.trim().is_empty()) && info.as_ref().is_ok_and(|i| i.embedded_lens.is_none()) { + tried.insert(item.id, item.content_hash.clone()); + } + } + if s.lens_tried_by == rules && s.lens_tried == tried { + return Ok(()); + } + let before = (std::mem::replace(&mut s.lens_tried, tried), std::mem::replace(&mut s.lens_tried_by, rules)); + let saved = s.save_prefs(); + if saved.is_err() { + (s.lens_tried, s.lens_tried_by) = before; + } + saved +} + /// Probe each listed photo's file as Reload would. Doesn't touch the session. pub fn probe(probe: &FileProbe, list: Vec) -> Vec<(Missing, std::result::Result)> { let paths: Vec = list.iter().map(|x| x.path.clone()).collect(); diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index c777b3f0e07..cd4fd321d09 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -14,6 +14,15 @@ use std::sync::{Arc, PoisonError, RwLock}; use lightcraft_develop::{EmbeddedLens, LensSource}; use lightcraft_lensdb::{LensDb, Shot}; +/// The rules by which [`lookup`] finds a lens. Bump it when they change: each library's raws that name no lens are then +/// read once more ([`crate::cmd::lens_refresh::automatic`]). +const RULES: u32 = 1; + +/// What a lookup in `db` depends on: the rules and the data. +pub fn rules(db: &LensDb) -> (u32, u64) { + (RULES, db.revision) +} + /// The environment variable naming the lens database directory. pub const ENV: &str = "LIGHTCRAFT_LENSFUN_DIR"; @@ -147,11 +156,24 @@ fn summary(dir: &Path, whose: &str, db: &LensDb) -> (log::Level, String) { } } +/// The database's camera for `camera`, the make and model as the library shows them ("Canon PowerShot G7 X"). The +/// make can have several words ("RICOH IMAGING COMPANY, LTD. RICOH GR III"), so each split is tried, first word first. +fn camera_named<'a>(db: &'a LensDb, camera: &str) -> Option<&'a lightcraft_lensdb::Camera> { + let (first, _) = camera.split_once(' ')?; + camera.match_indices(' ').find_map(|(i, _)| db.find_camera(camera.get(..i)?, camera.get(i + 1..)?)).or_else(|| db.find_camera(first, camera)) +} + +/// Whether the database may have the built-in lens of `camera` (the make and model as the library shows them): its +/// mount marks a fixed lens and has a profile. Which profile, if any, [`lookup`] decides from the file, whose lens +/// specification picks among several (the lens alone, the lens with a converter). +pub fn has_built_in_lens(db: &LensDb, camera: &str) -> bool { + camera_named(db, camera).is_some_and(|cam| cam.mount.starts_with(char::is_lowercase) && db.lenses.iter().any(|l| l.mounts.contains(&cam.mount))) +} + /// The database's name for the lens a photo's file calls `lens` (taken with `camera`, the make and model as the /// library shows them): "Canon EF 70-200mm f/2.8L IS II USM". `None` without a database or a match. pub fn profile_name(db: &LensDb, camera: &str, lens: &str) -> Option { - let cam = camera.split_once(' ').and_then(|(make, model)| db.find_camera(make, model).or_else(|| db.find_camera(make, camera))); - let p = db.find_lens(None, lens, cam)?; + let p = db.find_lens(None, lens, camera_named(db, camera))?; let model = p.models.first()?; Some(if model.to_lowercase().starts_with(&p.maker.to_lowercase()) || p.maker.is_empty() { model.clone() } else { format!("{} {model}", p.maker) }) } @@ -230,7 +252,8 @@ fn cache_key_for(db: Option<&LensDb>) -> u64 { } /// The database profile for a photo with metadata `m`, for its `w × h` (unoriented, default-cropped) image, -/// re-expressed after `orientation`. Without a lens name/specification, a unique fixed-mount profile may identify it. +/// re-expressed after `orientation`. Without a lens name, a fixed-lens camera's own mount may identify it: by the +/// lens specification's focal range, or as the mount's only profile when the file has no specification. /// `None` without a database, focal length or unambiguous matching profile. pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orientation: lightcraft_geom::Orientation) -> Option { let focal = m.focal_length.filter(|f| f.is_finite() && *f > 0.0)?; @@ -238,27 +261,14 @@ pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orient let lens = match m.lens_model.as_deref() { Some(model) => db.find_lens(m.lens_make.as_deref(), model, camera)?, // Nikon DSLRs record only the lens specification ("24-70mm f/2.8"); a profile must be named exactly that - // (a user's alias), since the specification fits other makers' lenses too + // (a user's alias), since the specification fits other makers' lenses too. A compact's lens can't be changed, + // so its camera's own mount narrows the choice to that lens's profiles (an RX100 II ARW). None => match m.lens_spec { Some(spec) => { let name = lightcraft_lensdb::spec_name(spec); - db.find_lens_named(m.lens_make.as_deref(), &name, camera)? - } - None => { - let camera = camera?; - // Lensfun reserves lowercase initial mount names for fixed-lens cameras: - // https://lensfun.github.io/manual/latest/el_mount.html - // This is an exact identity, never interchangeable-mount compatibility. - if !camera.mount.chars().next().is_some_and(char::is_lowercase) { - return None; - } - let mut profiles = db.lenses.iter().filter(|lens| lens.mounts.iter().any(|mount| mount == &camera.mount)); - let profile = profiles.next()?; - if profiles.next().is_some() { - return None; - } - profile + db.find_lens_named(m.lens_make.as_deref(), &name, camera).or_else(|| db.find_built_in_lens(&name, camera?))? } + None => db.find_built_in_lens("", camera?)?, }, }; let crop = frame_crop_factor(camera.and_then(|c| c.crop_factor), focal, m.focal_length_35mm); @@ -435,7 +445,11 @@ mod tests { changed.cameras.clear(); assert!(at(&changed, &unnamed).is_none(), "no camera means no fixed mount"); let specified = lightcraft_meta::Metadata { lens_spec: Some([18.0, 55.0, 3.5, 5.6]), ..unnamed }; - assert!(at(&db, &specified).is_none(), "unmatched specification does not fall back to a fixed mount"); + assert_eq!(at(&db, &specified), Some(expected), "the mount identifies the lens, also when its profile is named by focal length"); + for spec in [[100.0, 400.0, 4.5, 5.6], [18.0, 55.0, 2.8, 4.0], [18.0, 18.0, 3.5, 3.5], [18.0, 55.0, 3.5, 3.5]] { + let misfit = lightcraft_meta::Metadata { lens_spec: Some(spec), ..specified.clone() }; + assert!(at(&db, &misfit).is_none(), "unmatched specification does not fall back to a fixed mount: {spec:?}"); + } let wrongly_named = lightcraft_meta::Metadata { lens_model: Some("Unknown 1000mm".into()), ..meta() }; assert!(at(&db, &wrongly_named).is_none(), "unmatched lens name does not fall back"); } @@ -478,6 +492,85 @@ mod tests { assert!(lookup(&aliased, &named_other, 6000.0, 4000.0, Orientation::Normal).is_none()); } + /// A compact's raw may name no lens at all: a PowerShot G7 X CR2 has neither a lens model nor a lens + /// specification. The database gives the built-in lens the camera's own mount, and that is enough to find it + /// (issue #3855). A specification, when the file has one, picks among several profiles on that mount. + #[test] + fn a_compact_that_names_no_lens_gets_its_built_in_lens() { + const COMPACT: &str = r#" + TestcamTestcam Compact C1testcamC12.7 + TestcamTC-1T1.5 + TestcamTestcam Compact C1 & compatiblesfixed lens + testcamC12.7 + + + + + + TestcamTestcam 18-55mm f/3.5-5.6T1.5 + + "#; + let db = LensDb::parse(COMPACT).unwrap(); + let compact = lightcraft_meta::Metadata { + make: Some("Testcam".into()), + model: Some("Testcam Compact C1".into()), + lens_model: None, + lens_spec: None, + focal_length: Some(8.8), + f_number: Some(4.0), + ..Default::default() + }; + let at = |db: &LensDb, m: &lightcraft_meta::Metadata| lookup(db, m, 5472.0, 3648.0, Orientation::Normal); + let lens = at(&db, &compact).expect("the camera's built-in lens"); + assert!(lens.warp.is_some()); + assert_eq!(lens.source, LensSource::Database); + // the same profile when the file records only the lens's specification + let with_spec = lightcraft_meta::Metadata { lens_spec: Some([8.8, 36.8, 1.8, 2.8]), ..compact.clone() }; + assert_eq!(at(&db, &with_spec), Some(lens)); + // a body with interchangeable lenses that names none still gets nothing: any of its mount's lenses could be on it + let body = lightcraft_meta::Metadata { model: Some("TC-1".into()), focal_length: Some(18.0), ..compact.clone() }; + assert!(at(&db, &body).is_none()); + // nor does a camera the database doesn't list + let unknown = lightcraft_meta::Metadata { model: Some("Testcam Compact C9".into()), ..compact.clone() }; + assert!(at(&db, &unknown).is_none()); + // two profiles on the compact's mount: the specification's focal range decides, and without one neither is taken + let second = r#"TestcamTestcam Compact C1 with tele convertertestcamC1 + 2.7"#; + let two = LensDb::parse(&COMPACT.replace("", second)).unwrap(); + assert_eq!(two.lenses.len(), 3); + assert_eq!(at(&two, &with_spec), at(&db, &with_spec)); + assert!(at(&two, &compact).is_none()); + } + + /// A Sony RX100 II ARW names no lens model; lensfun files its lens under the camera's own mount + /// (`sonyRX100II`). The file's EXIF spells the maker `SONY`, and it may or may not record the lens's + /// specification: either way the built-in lens is found. + #[test] + fn an_rx100_ii_raw_gets_its_built_in_lens() { + const RX100: &str = r#" + SonyDSC-RX100M2sonyRX100II2.73 + SonyDSC-RX100 II & compatiblessonyRX100II2.73 + + + + + "#; + let db = LensDb::parse(RX100).unwrap(); + let no_lens = lightcraft_meta::Metadata { + make: Some("SONY".into()), + model: Some("DSC-RX100M2".into()), + focal_length: Some(10.4), + f_number: Some(1.8), + ..Default::default() + }; + let with_spec = lightcraft_meta::Metadata { lens_spec: Some([10.4, 37.1, 1.8, 4.9]), ..no_lens.clone() }; + for m in [&no_lens, &with_spec] { + let lens = lookup(&db, m, 5472.0, 3648.0, Orientation::Normal).expect("the RX100 II's built-in lens"); + assert_eq!(lens.source, LensSource::Database); + assert!(lens.warp.is_some()); + } + } + /// A full-frame body in APS-C / Super 35 mode (an ILCE-1M2 at 70 mm records 105 mm equivalent) frames only the /// middle of the image circle: the profile is applied at the frame's crop factor, not the body's, so the crop's /// corners don't get the full frame's corner correction. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 760a6cd27d1..b8fd6ef4998 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -333,6 +333,10 @@ pub struct Session { /// The host may offer the lens database at its start, and fetch it after the user's yes /// ([`Session::with_lens_auto_download`]; when: [`lensfun_download::fetch_on_start`]). pub lens_auto_download: bool, + /// The raws that name no lens and were read without finding a profile, by the rules and data `lens_tried_by` + /// ([`lens_profiles::rules`]), and the content hash each had. Saved with the library preferences. + pub lens_tried: std::collections::BTreeMap>, + pub lens_tried_by: (u32, u64), /// Reverse geocoding: the parsed place names and their download (`metadata.*PlaceNames`). pub place_names: cmd::geocode::PlaceNames, /// The user's own list of models to download (`catalog.json` in the models folder), as last read. @@ -570,6 +574,8 @@ impl Session { face_downloads: Default::default(), lensfun: Default::default(), lens_auto_download: false, + lens_tried_by: Default::default(), + lens_tried: Default::default(), place_names: Default::default(), face_catalog: Default::default(), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 40559bfec67..d44bd0f9a7a 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -377,6 +377,9 @@ struct PrefsFile { /// that isn't a photo id is skipped, never taking the other preferences with it. #[serde(skip_serializing_if = "Vec::is_empty")] gps_owned: Vec, + /// [`Session::lens_tried`]. + lens_tried: std::collections::BTreeMap>, + lens_tried_by: (u32, u64), } fn presets_json(s: &Session) -> String { @@ -892,6 +895,8 @@ impl Session { if let Some(notice) = self.map.load_source(prefs.map_source) { settings.warnings.push(notice); } + self.lens_tried_by = prefs.lens_tried_by; + self.lens_tried = prefs.lens_tried; self.refresh_view(); self.smart_previews_dir = prefs.smart_previews_dir.filter(|_| on_disk).map(PathBuf::from); if let Some(d) = &self.smart_previews_dir { @@ -1423,6 +1428,8 @@ impl Session { ids.sort_unstable(); ids.into_iter().map(serde_json::Value::from).collect() }, + lens_tried_by: self.lens_tried_by, + lens_tried: self.lens_tried.clone(), }) .unwrap_or_default(); let Some(lib) = self.library.as_mut() else { return Ok(()) }; diff --git a/crates/engine/src/tests/lens_refresh.rs b/crates/engine/src/tests/lens_refresh.rs index a00406a910f..dc87bd38faa 100644 --- a/crates/engine/src/tests/lens_refresh.rs +++ b/crates/engine/src/tests/lens_refresh.rs @@ -82,7 +82,7 @@ fn each_result_reaches_its_photos_virtual_copies_and_no_others() { s.catalog.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); } let probed = [1, 2].map(|id| { - let m = crate::cmd::lens_refresh::Missing { id: PhotoId(id), path: format!("/photos/{id}.cr3") }; + let m = crate::cmd::lens_refresh::Missing { id: PhotoId(id), path: format!("/photos/{id}.cr3"), content_hash: None }; (m, Ok(crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() })) }); let mut found = crate::cmd::lens_refresh::apply(&mut s, probed.into()).unwrap(); @@ -146,7 +146,7 @@ fn photos_get_their_profile_when_the_database_arrives() { let mut copy = raw(5, "300mm F4", false); copy.copy_of = Some(PhotoId(3)); s.catalog.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); - let stale = crate::cmd::lens_refresh::Missing { id: PhotoId(3), path: "/elsewhere/3.cr3".into() }; + let stale = crate::cmd::lens_refresh::Missing { id: PhotoId(3), path: "/elsewhere/3.cr3".into(), content_hash: None }; let ok = crate::media::ProbeInfo { embedded_lens: Some(lens(-0.01)), ..Default::default() }; assert!(crate::cmd::lens_refresh::apply(&mut s, vec![(stale, Ok(ok))]).unwrap().is_empty()); assert!(s.catalog.photo(PhotoId(3)).unwrap().embedded_lens.is_none(), "a stale probe changes nothing"); @@ -156,6 +156,116 @@ fn photos_get_their_profile_when_the_database_arrives() { assert!(s.execute("library.refreshLensProfiles", &json!({"ids": "x"})).is_err()); } +/// [`DB`] with two compacts: C1 has the lens alone and with a converter on its mount, C2 one profile. +fn compacts() -> lightcraft_lensdb::LensDb { + lightcraft_lensdb::LensDb::parse(&DB.replace( + "", + r#"TestcamTestcam Compact C1testcamC12.7 + TestcamTestcam Compact C1 & compatiblestestcamC12.7 + + TestcamTestcam Compact C1 with tele convertertestcamC12.7 + + TestcamCompact C2testcamC22.7 + TestcamCompact C2 & compatiblestestcamC22.7 + "#, + )) + .unwrap() +} + +/// A raw of compact C1 that names no lens. +fn compact(id: u64) -> Photo { + let mut p = raw(id, "", false); + p.meta.camera = "Testcam Compact C1".into(); + p +} + +/// A compact's raw that names no lens is looked up too, by its camera's built-in lens; a body's isn't, since any +/// lens could have been on it (issue #3855). With the lens alone and with a converter on the compact's mount, the +/// file's lens specification picks one when it is read, so the photo is listed. +#[test] +fn an_unnamed_lens_is_looked_up_when_the_camera_has_a_built_in_lens() { + let db = compacts(); + let mut s = Session::new(); + for p in [compact(1), raw(2, "", false), with_lens(compact(3), Some(lens(-0.03)), true)] { + s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + let listed = crate::cmd::lens_refresh::missing(&s.catalog, &db, None, false); + assert_eq!(listed.iter().map(|m| m.id.0).collect::>(), [1], "the compact without a profile, not the body"); + assert!(crate::lens_profiles::has_built_in_lens(&db, "Testcam Compact C1")); + // a make of several words, as the library joins EXIF make "Testcam Imaging" and model "Compact C2" + assert!(crate::lens_profiles::has_built_in_lens(&db, "Testcam Imaging Compact C2")); + assert!(!crate::lens_profiles::has_built_in_lens(&db, "Testcam TC-1") && !crate::lens_profiles::has_built_in_lens(&db, "")); +} + +/// A raw that names no lens and was read in vain is not read at every start, only when the rules that find a lens change, +/// the database's files are replaced or the user asks. One that wasn't read yet (an offline drive, a new photo) is. +#[test] +fn unnamed_lenses_are_looked_up_once_per_rules() { + use crate::cmd::lens_refresh::{Missing, automatic, missing, remember_tried}; + let dir = std::env::temp_dir().join(format!("lc-lens-rules-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let db = compacts(); + let ids = |v: Vec| v.iter().map(|m| m.id.0).collect::>(); + let add = |s: &mut Session, photos: Vec| { + s.execute_fn("test.add", |s| { + for p in photos { + s.apply_system(Op::AddPhoto { photo: Box::new(p) })?; + } + Ok(serde_json::Value::Null) + }) + .unwrap(); + }; + // photo 3 is on an offline drive, the other files give no profile + let probed = |listed: Vec| { + listed.into_iter().map(|m| if m.id.0 == 3 { (m, Err("offline".into())) } else { (m, Ok(Default::default())) }).collect() + }; + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + add(&mut s, vec![compact(1), raw(2, "50mm F1.8", false), compact(3)]); + let listed = automatic(&s, &db, false); + assert_eq!(ids(listed.clone()), [1, 2, 3], "never looked up"); + remember_tried(&mut s, &db, &probed(listed)).unwrap(); + drop(s); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3], "the next start leaves the one read in vain alone"); + add(&mut s, vec![compact(4)]); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3, 4], "but not a new one"); + assert_eq!(ids(missing(&s.catalog, &db, Some(&[PhotoId(1)]), false)), [1], "the user asked"); + let again = automatic(&s, &db, true); + assert_eq!(ids(again.clone()), [1, 2, 3, 4], "the database's files were replaced"); + remember_tried(&mut s, &db, &again.into_iter().map(|m| (m, Err("offline".into()))).collect()).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [1, 2, 3, 4], "and couldn't be read: tried again"); + let listed = automatic(&s, &db, false); + remember_tried(&mut s, &db, &probed(listed)).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3]); + let reading = probed(automatic(&s, &db, true)); + let (preview_only, preview_checked) = (None, String::new()); + let content_hash = Some("another file".into()); + s.commit("Relink Photo", Op::SetContent { id: PhotoId(4), width: 600, height: 400, file_size: 1, content_hash, preview_only, preview_checked }) + .unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3, 4], "its file was replaced"); + remember_tried(&mut s, &db, &reading).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3, 4], "while the old one was read"); + let listed = automatic(&s, &db, false); + remember_tried(&mut s, &db, &probed(listed)).unwrap(); + s.persist().unwrap(); + drop(s); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [2, 3]); + let named = s.catalog.photo(PhotoId(2)).unwrap().meta.clone(); + s.apply_system(Op::SetMeta { id: PhotoId(1), meta: Box::new(named) }).unwrap(); + assert_eq!(ids(automatic(&s, &db, false)), [1, 2, 3], "its lens is named now"); + let mut other = compacts(); + other.extend(lightcraft_lensdb::LensDb::parse(DB).unwrap()); + assert_eq!(ids(automatic(&s, &other, false)), [1, 2, 3, 4], "other data"); + s.lens_tried_by.0 += 1; + assert_eq!(ids(automatic(&s, &db, false)), [1, 2, 3, 4], "other rules"); + drop(s); + std::fs::remove_dir_all(&dir).unwrap(); +} + fn with_lens(mut p: Photo, l: Option, on: bool) -> Photo { p.embedded_lens = l.map(Box::new); let mut d = (*p.develop).clone(); diff --git a/crates/lensdb/src/lib.rs b/crates/lensdb/src/lib.rs index dfdd769d7b2..16779a0e79e 100644 --- a/crates/lensdb/src/lib.rs +++ b/crates/lensdb/src/lib.rs @@ -20,6 +20,7 @@ pub mod model; mod xml; +use std::hash::{Hash, Hasher}; use std::path::Path; use lightcraft_develop::{EmbeddedLens, EmbeddedVignette, EmbeddedWarp}; @@ -119,6 +120,8 @@ pub struct Shot { pub struct LensDb { pub cameras: Vec, pub lenses: Vec, + /// Another one when the data read is another (a hash of the files' text). + pub revision: u64, } impl LensDb { @@ -154,12 +157,15 @@ impl LensDb { let cameras = root.children("camera").filter_map(camera).collect(); let mut budget = MAX_PROFILE_COPY_BYTES; let lenses = root.children("lens").flat_map(|n| lens(n, &mut budget)).collect(); - Ok(LensDb { cameras, lenses }) + let mut hasher = std::hash::DefaultHasher::new(); + xml.hash(&mut hasher); + Ok(LensDb { cameras, lenses, revision: hasher.finish() }) } pub fn extend(&mut self, other: LensDb) { self.cameras.extend(other.cameras); self.lenses.extend(other.lenses); + self.revision = self.revision.rotate_left(1) ^ other.revision; } pub fn is_empty(&self) -> bool { @@ -195,6 +201,24 @@ impl LensDb { self.best_lens(lens_make, name, camera, |l| l.names_exactly(name)) } + /// The profile of `camera`'s built-in lens, for a file that names no lens. `spec` is the lens text the file does + /// have, a [`spec_name`] ("8.8-36.8mm f/1.8-2.8") or nothing: with several profiles on the camera's mount (the + /// lens alone, the lens with a converter) its focal range picks one, and without it only a sole profile is taken. + /// A profile named by focal length ("18-46mm f/3.5-6.4") must have the words of `spec`, whole. + /// Profiles that fit the focal range equally well are ambiguous, and none is taken, nor is a profile whose mount + /// is not exactly the camera's, case included. `None` for a body whose lens can be changed, since any lens of its + /// mount could be on it: the database starts the mount name of a camera with a fixed lens with a lower-case letter + /// ("canonG7X"), a body's with a capital ("Canon EF"), see . + pub fn find_built_in_lens(&self, spec: &str, camera: &Camera) -> Option<&Profile> { + if !camera.mount.starts_with(char::is_lowercase) { + return None; + } + let spec_words = words(spec); + let names_spec = |model: &String| spec_words.is_empty() || words(model).windows(spec_words.len()).any(|w| w == spec_words); + let eligible = |l: &Profile| l.mounts.contains(&camera.mount) && (!l.named_by_focal_length() || l.models.iter().any(names_spec)); + self.fixed_lens_match(&tokens(spec), eligible).filter(|&(_, unique)| unique).map(|(p, _)| p) + } + fn best_lens(&self, lens_make: Option<&str>, lens_model: &str, camera: Option<&Camera>, eligible: impl Fn(&Profile) -> bool) -> Option<&Profile> { let exif = tokens(lens_model); if exif.is_empty() { @@ -228,24 +252,26 @@ impl LensDb { if cam.mount.is_empty() { return None; } - let cands: Vec<&Profile> = self - .lenses - .iter() - .filter(|l| l.mounts.iter().any(|m| m.eq_ignore_ascii_case(&cam.mount))) - .filter(|l| !l.models.iter().any(|m| tokens(m).iter().any(|t| t == "mm"))) - .collect(); + let eligible = |l: &Profile| l.mounts.iter().any(|m| m.eq_ignore_ascii_case(&cam.mount)) && !l.named_by_focal_length(); + self.fixed_lens_match(exif, eligible).map(|(p, _)| p) + } + + /// The `eligible` profile that best fits the focal range in `exif`, and whether no other profile scored as high. + fn fixed_lens_match(&self, exif: &[String], eligible: impl Fn(&Profile) -> bool) -> Option<(&Profile, bool)> { + let cands: Vec<&Profile> = self.lenses.iter().filter(|l| eligible(l)).collect(); // an interchangeable mount has many lenses; a built-in lens has one or a few profiles if cands.is_empty() || cands.len() > MAX_FIXED_CANDIDATES { return None; } let Some((lo, hi)) = exif_focal_range(exif) else { - return (cands.len() == 1).then(|| cands[0]); + return (cands.len() == 1).then(|| (cands[0], true)); }; let (lo, hi) = (lo * 0.9, hi * 1.1); if !lo.is_finite() || !hi.is_finite() { return None; } let mut best: Option<(f64, &Profile)> = None; + let mut tied = false; for p in cands { let focals: Vec = p.distortion.iter().map(|d| d.0).chain(p.tca.iter().map(|t| t.0)).chain(p.vignetting.iter().map(|v| v.focal)).collect(); @@ -253,11 +279,23 @@ impl LensDb { continue; } let score = focals.iter().filter(|f| (lo..=hi).contains(*f)).count() as f64 / focals.len() as f64; - if score > 0.0 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && p.crop_factor.is_some())) { - best = Some((score, p)); + if score <= 0.0 { + continue; } + match best { + Some((s, _)) if score < s => continue, + // a tie prefers a profile whose calibration crop is known + Some((s, b)) if score == s => { + tied = true; + if b.crop_factor.is_some() || p.crop_factor.is_none() { + continue; + } + } + _ => tied = false, + } + best = Some((score, p)); } - best.map(|(_, p)| p) + best.map(|(_, p)| (p, !tied)) } } @@ -304,6 +342,25 @@ fn read_capped(path: &Path) -> Result { Ok(String::from_utf8_lossy(&bytes).into_owned()) } +/// The [`tokens`] of each word, a range and its "mm" being one word ("C1 - 18 - 46 mm f/3.5" → [c, 1], [], [18, 46, mm], +/// [f, 3.5]). +fn words(s: &str) -> Vec> { + let mut words: Vec = Vec::new(); + let is_number = |s: &str| s.starts_with(|c: char| c.is_ascii_digit()); + for part in s.to_lowercase().split_whitespace() { + let after_dash = part.trim_start_matches('-'); + match words.last_mut().filter(|w| is_number(w.trim_start_matches(['f', '/']))) { + Some(number) + if part.starts_with("mm") || after_dash.is_empty() || is_number(after_dash) && (part.starts_with('-') || number.ends_with('-')) => + { + number.push_str(part) + } + _ => words.push(part.to_string()), + } + } + words.iter().map(|w| tokens(w)).collect() +} + /// Lower-case word tokens; letters and digits are split ("24-105mm" → 24, 105, mm), decimals kept ("2.8"). fn tokens(s: &str) -> Vec { let mut out: Vec = Vec::new(); @@ -535,6 +592,11 @@ impl Profile { !want.is_empty() && self.models.iter().any(|m| tokens(m) == want) } + /// Whether one of the profile's names states a focal length ("18-55mm f/3.5-5.6"), not just a camera. + fn named_by_focal_length(&self) -> bool { + self.models.iter().any(|m| tokens(m).iter().any(|t| t == "mm")) + } + /// Distortion ratio `r_d / r_u` at lensfun radius `r` for `focal` (1 when the profile has none). pub fn distortion_ratio(&self, focal: f64, r: f64) -> f64 { if !self.rectilinear { diff --git a/crates/lensdb/src/tests.rs b/crates/lensdb/src/tests.rs index 2e32f955ecd..e70d0c19903 100644 --- a/crates/lensdb/src/tests.rs +++ b/crates/lensdb/src/tests.rs @@ -457,6 +457,68 @@ fn built_in_lens_matches_by_camera_mount_and_focal_range() { assert_eq!(exif_focal_range(&tokens(&huge)), Some((6.0, 6.0))); } +/// A file that names no lens gets its camera's built-in lens, and only a camera with a fixed lens has one: on a +/// body's mount a lone profile is some lens, not the lens (#3855). +#[test] +fn a_built_in_lens_needs_a_fixed_lens_camera() { + let xml = r#" + TestcamTestcam Compact C1testcamC12.7 + TestcamTC-KTestcam K1 + TestcamTC-01 + TestcamTestcam Compact C1 & compatiblesfixed lens + testcamC12.7 + + OtherlensOtherlens Makro 2/100Testcam K1 + +"#; + let mut db = LensDb::parse(xml).unwrap(); + let cam = |model: &str| db.find_camera("Testcam", model).cloned().unwrap(); + let (compact, body, mountless) = (cam("Testcam Compact C1"), cam("TC-K"), cam("TC-0")); + assert_eq!(db.find_built_in_lens("", &compact).unwrap().mounts, ["testcamC1"]); + assert_eq!(db.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).unwrap().mounts, ["testcamC1"]); + assert!(db.find_built_in_lens("", &body).is_none(), "any lens of the mount could be on a body"); + assert!(db.find_built_in_lens("100mm f/2", &body).is_none()); + assert!(db.find_built_in_lens("", &mountless).is_none()); + let mut cased = db.clone(); + cased.lenses[0].mounts = vec!["TestcamC1".into()]; + assert!(cased.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).is_none(), "mount identity is case sensitive"); + // nor does such a profile make the camera's own ambiguous + cased.lenses.push(db.lenses[0].clone()); + assert_eq!(cased.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).unwrap().mounts, ["testcamC1"]); + // a profile named by focal length has to name the whole specification, whatever number its camera has + for (name, found) in [ + ("Testcam C 1 8.8-36.8 mm f/1.8-2.8", true), + ("Testcam 8.8-36.8mm f/1.8-2.8 & compatibles", true), + ("Testcam 8.8-36.8mm f/1.8-4", false), + ("Testcam 4-8.8-36.8mm f/1.8-2.8", false), + ("Testcam 36.8mm f/1.8-2.8", false), + ("Testcam C1 8.8 - 36.8 mm f/1.8 - 2.8", true), + ("Testcam C1 8.8 - 36.8 mm f/1.8-2.8", true), + ("Testcam C1 - 8.8-36.8mm f/1.8-2.8", true), + ("Testcam 8.8-36.8mm f/1.8-2.8 - compatibles", true), + ("Testcam 4 - 8.8-36.8mm f/1.8-2.8", false), + ("Testcam 4 mm - 8.8-36.8 mm f/1.8-2.8", false), + ] { + let mut named = db.clone(); + named.lenses[0].models = vec![name.into()]; + assert_eq!(named.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).is_some(), found, "{name}"); + assert!(named.find_built_in_lens("", &compact).is_some(), "no specification, one profile: {name}"); + } + // a second profile on the compact's mount (the lens with a converter): the focal range picks, and nothing does without it + let mut converter = db.lenses[0].clone(); + converter.models = vec!["Testcam Compact C1 with tele converter".into()]; + converter.distortion = vec![(62.0, converter.distortion[0].1)]; + db.lenses.push(converter); + assert_eq!(db.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).unwrap().models[0], "Testcam Compact C1 & compatibles"); + assert!(db.find_built_in_lens("", &compact).is_none()); + // a converter calibrated at the lens's own focal lengths fits the range as well: ambiguous, in either order + let n = db.lenses.len(); + db.lenses[n - 1].distortion = db.lenses[0].distortion.clone(); + assert!(db.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).is_none()); + db.lenses.swap(0, n - 1); + assert!(db.find_built_in_lens("8.8-36.8mm f/1.8-2.8", &compact).is_none()); +} + #[test] fn tied_built_in_lens_matches_prefer_a_known_calibration_crop() { let mut db = db(); diff --git a/crates/ui-egui/src/lens_db.rs b/crates/ui-egui/src/lens_db.rs index 8ee309436e6..f7ea7d7dd1f 100644 --- a/crates/ui-egui/src/lens_db.rs +++ b/crates/ui-egui/src/lens_db.rs @@ -132,23 +132,32 @@ fn refresh(app: &mut LightcraftApp) { app.ui.lens_lookup_ids.extend(asked); return; } - let ids = (app.ui.lens_refreshed == Some(key)).then_some(asked); - let again = ids.is_none() && look_up_again(app.ui.lens_refreshed, key); + let automatic = app.ui.lens_refreshed != Some(key); + let again = automatic && look_up_again(app.ui.lens_refreshed, key); app.ui.lens_refreshed = Some(key); let Some(probe) = recheck::file_probe(&app.session) else { return }; let Some(db) = lens_profiles::database() else { return }; - let listed = lens_refresh::missing(&app.session.catalog, &db, ids.as_deref(), again); + let listed = if automatic { + // (what was asked for is looked up after it) + app.ui.lens_lookup_ids = asked; + lens_refresh::automatic(&app.session, &db, again) + } else { + lens_refresh::missing(&app.session.catalog, &db, Some(&asked), false) + }; if listed.is_empty() { return; } let work = move || lens_refresh::probe(&probe, listed); - let done = move |app: &mut LightcraftApp, ctx: &egui::Context, results| { + let done = move |app: &mut LightcraftApp, ctx: &egui::Context, results: lens_refresh::Probed| { // another library, or a database reloaded while the files were read (the probe may have used either): the // next frame looks them up again with the database in use now (asked for here: an idle window draws none) if lookup_key(app) != key { ctx.request_repaint(); return; } + if let Err(e) = lens_refresh::remember_tried(&mut app.session, &db, &results) { + log::warn!("lens profile lookup: {e}"); + } match lens_refresh::apply(&mut app.session, results) { Ok(found) if found.len() == 1 => app.toast(ctx, crate::i18n::tr("1 photo got its lens profile")), Ok(found) if found.len() > 1 => app.toast(ctx, crate::i18n::tr_format!("{n} photos got their lens profile", n = found.len())), diff --git a/docs/lens-profiles.md b/docs/lens-profiles.md index c316178793a..c9c8e7441dd 100644 --- a/docs/lens-profiles.md +++ b/docs/lens-profiles.md @@ -35,9 +35,11 @@ When the database arrives (or changes), every library raw without a profile whos background and gets its profile; a photo still as imported gets the correction switched on, as import would, and an edited one keeps its settings. When a download replaced the database's files, the raws whose profile came from the old database are read again too (they get the new profile, or lose one it no longer gives), and so are raws whose -file named no lens at import. Ticking **Enable Lens Corrections** on a photo without a profile looks it up again -too. `library.refreshLensProfiles` (`all: true` for the wider pass), `lens.downloadDatabase` (which also selects the -downloaded folder) and `lens.databaseStatus` do the same for agents. +file named no lens at import. A raw that names no lens is otherwise read again only once after the database's files or +the way LightCraft finds lenses change, not at every start (a file that couldn't be read then is tried again). Ticking +**Enable Lens Corrections** on a photo without a profile looks it up again too. `library.refreshLensProfiles` (`all: true` for the +wider pass), `lens.downloadDatabase` (which also selects the downloaded folder) and `lens.databaseStatus` do the same +for agents. A database profile is pinned to the photo: every render (fresh decode, cached preview, thumbnail, export) uses the profile the catalog holds, never one a decode looked up in a newer database, and the profile is part of the render @@ -70,13 +72,16 @@ nor a name with a maker in it ("Samyang 85mm f/1.4" for "85mm f/1.4") is taken; files names its profile that way, e.g. a lensfun entry with an extra `24-70mm f/2.8` for the one 24-70 f/2.8 the photographer owns. lensfun's own database has no such names, so it doesn't correct these files. -A fixed-lens camera that records neither a lens model nor a lens specification can use its camera database -entry's mount instead. [Lensfun reserves lowercase initial mount names for fixed-lens cameras](https://lensfun.github.io/manual/latest/el_mount.html). -The existing camera lookup is retained; exactly one lens profile with its case-sensitive mount is accepted. Missing, -uppercase interchangeable, mismatching or ambiguous mounts retain the no-profile fallback. Named lenses and -specification aliases keep their existing lookup rules; an unmatched name/specification does not trigger this -fallback. This identifies an available correction, not evidence that the camera JPEG uses it: calibration still -requires the independent geometry gates described in [Camera preview colour](camera-preview-colour.md). +A fixed-lens camera's file may name no lens (a Canon PowerShot G7 X CR2, a Sony RX100 II ARW). Its lens can't be +changed, and lensfun files the lens's profile under the camera's own mount (`canonG7X`), so such a file gets its +camera's built-in lens. [Lensfun reserves lowercase initial mount names for fixed-lens cameras](https://lensfun.github.io/manual/latest/el_mount.html); +a body's mount starts with a capital (`Canon EF`), and any lens of the mount could have been on it, so its file gets +none. Without a lens specification, exactly one profile with the camera's case-sensitive mount is accepted. With one, +the specification's focal range picks among the mount's profiles (the lens alone, the lens with a converter); a profile +named by focal length (`18-46mm f/3.5-6.4`) must name the same specification. Missing, uppercase, mismatching or +ambiguous mounts get no profile. This identifies an available correction, not evidence that the camera JPEG uses it: +calibration still requires the independent geometry gates described in +[Camera preview colour](camera-preview-colour.md). | Correction | Models | Interpolated over | |---|---|---| @@ -104,8 +109,9 @@ the image centre (lensfun's `
` offsets are not read). Missing or invalid only finite values from 0.05 through 20 are accepted. A calibration inherits the lens's crop factor only when its `cropfactor` attribute is omitted; an explicit invalid override remains unknown. Profiles with an unknown calibration crop factor are not applied. An explicit crop factor of 1 still means full frame. -On exact lookup-score ties, both named and built-in fixed-lens matching prefer a known calibration crop; a higher -match score still wins even when its crop is unknown. +On exact lookup-score ties, matching by the file's lens name prefers a known calibration crop; a higher match score +still wins even when its crop is unknown. Without a lens name, the built-in lens lookup takes no profile on a tie, even +when only one of the tied profiles has a known crop. ## Limits diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 3cccf0a6fbf..d7a1f5bfa81 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -219,7 +219,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-DETAIL-HOTPIXELS | Hot pixel removal | P1 | ✅ | `check:detail.nrOutliers`, `crates/raw/src/hotpixel.rs`, `crates/engine/src/files/load.rs` (`load_bytes_now`), `cmd:app.hotPixelLimit` | Lightroom has no control for this. Here a box under Noise Reduction (raws only), on for newly imported raws and off for edits saved before it existed (issue #1345): single photosites far above all their same-colour neighbours are replaced in the mosaic before demosaicing; a point lit across neighbouring photosites (a star, a spark) is kept. A raw with more than 0.2 % of its photosites to replace (real light kept doesn't count) is left unchanged; Settings ▸ Performance ▸ Hot pixel limit sets the share (test `the_hot_pixel_limit_renders_afresh_only_the_photos_that_remove_hot_pixels`). Switching it decodes the raw again (tests `hot_pixel_box_is_on_for_new_raws_only`, `hot_pixel_box_decodes_the_raw_again`) | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `craft-raw`, `craft-raw`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `craft-raw`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `craft-raw`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`craft-raw`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `craft-raw`, `craft-raw`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `craft-raw`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `craft-raw`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`craft-raw`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; a fixed-lens camera's raw that names no lens (a PowerShot G7 X CR2, a Sony RX100 II ARW) gets its camera's built-in lens, found by the camera's own lower-case mount name (issue #3855); lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*`, `ctl:optics.aiDefringe`, `cmd:aiDefringe.toggle`, `cmd:aiDefringe.models.install`, `crates/denoise/src/defringe.rs`, `docs/ai-defringe.md` | no fringe eyedropper. Beyond Lightroom: AI Defringe, a user-installed network (no model ships) whose correction is cached per photo and applied before develop, with fixed guards (lightness kept, toward grey and the surrounding colour only) | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | @@ -835,6 +835,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-11-05 | minor | LR-EDIT-LENSBLUR: ⬜ → 🟡 (Lens Blur section: Apply, Blur Amount, Boost, focus on the subject or a mask; no depth map yet); LR-MASK-SLIDERS: a Lens Blur block in every mask (selection or outside, Amount, Boost, Transition); KEY-SECTIONS: ⌘6 opens Lens Blur | | 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-30 | patch | LR-BEHAV-TITLEBAR: the search box's padding around its text is the field's, not the title bar's: pressing there no longer moves the window on macOS, and a click there focuses the field (#2807); status counts unchanged | +| 2026-11-06 | minor | LR-EDIT-OPTICS-PROFILE: a fixed-lens camera's raw that names no lens (a PowerShot G7 X CR2: no lens model, no specification) gets its camera's built-in lens from the lens database (#3855); a body with an unnamed lens still gets none; status unchanged (🟡) | | 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-12-03 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V17 renders Apple ProRAW in Lightroom Classic's fitted tone chain (#613, #4196); status unchanged | | 2026-11-07 | minor | LR-EDIT-EFFECTS-GRAIN, LRC-DEV-PROCESS: process V7 takes film grain to crystal layers ([grain.md](grain.md)); V1 to V6 keep value noise | diff --git a/docs/whats-new.md b/docs/whats-new.md index 39d5cc7e927..e10de20c1ce 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -21,6 +21,12 @@ three quarters, where it used to cover 90 % and more, and a slow stroke covers the same as a fast one (issue #4045). New photos (and Reset) get it; photos you already edited keep their brushes until Photo ▸ Update to Current Process. +### Lens profiles for compact cameras that name no lens +- Raws from compact cameras that record no lens name, such as the Canon PowerShot G7 X or the Sony RX100 II, now get + their lens profile from the lens database (issue #3855). The lens is built in, so the camera is enough to find it. + Photos already in the library pick it up when Enable Lens Corrections is ticked or the database is downloaded. A + camera body with an unnamed lens still gets no profile, since any lens could have been on it. + ## 2026-10-31 ### Filter for unrated photos