Skip to content
Open
55 changes: 47 additions & 8 deletions crates/engine/src/cmd/lens_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProbeInfo, String>)>;

/// 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<String>,
}

/// 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<Missing> {
// a photo and its virtual copies list the photo once, in library order
Expand All @@ -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),
Comment thread
DonPavlov marked this conversation as resolved.
Resolved
Comment thread
DonPavlov marked this conversation as resolved.
Resolved
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<Missing> {
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
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// 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<Missing>) -> Vec<(Missing, std::result::Result<ProbeInfo, String>)> {
let paths: Vec<String> = list.iter().map(|x| x.path.clone()).collect();
Expand Down
135 changes: 114 additions & 21 deletions crates/engine/src/lens_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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))
Comment thread
DonPavlov marked this conversation as resolved.
Resolved
}

/// 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<String> {
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) })
}
Expand Down Expand Up @@ -230,35 +252,23 @@ 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<EmbeddedLens> {
let focal = m.focal_length.filter(|f| f.is_finite() && *f > 0.0)?;
let camera = db.find_camera(m.make.as_deref().unwrap_or_default(), m.model.as_deref().unwrap_or_default());
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?))?
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
None => db.find_built_in_lens("", camera?)?,
},
};
let crop = frame_crop_factor(camera.and_then(|c| c.crop_factor), focal, m.focal_length_35mm);
Expand Down Expand Up @@ -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");
}
Expand Down Expand Up @@ -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#"<lensdatabase>
<camera><maker>Testcam</maker><model>Testcam Compact C1</model><mount>testcamC1</mount><cropfactor>2.7</cropfactor></camera>
<camera><maker>Testcam</maker><model>TC-1</model><mount>T</mount><cropfactor>1.5</cropfactor></camera>
<lens><maker>Testcam</maker><model>Testcam Compact C1 &amp; compatibles</model><model lang="en">fixed lens</model>
<mount>testcamC1</mount><cropfactor>2.7</cropfactor>
<calibration>
<distortion model="poly3" focal="8.8" k1="-0.03" />
<distortion model="poly3" focal="36.8" k1="0.004" />
</calibration>
</lens>
<lens><maker>Testcam</maker><model>Testcam 18-55mm f/3.5-5.6</model><mount>T</mount><cropfactor>1.5</cropfactor>
<calibration><distortion model="poly3" focal="18" k1="-0.03" /></calibration>
</lens></lensdatabase>"#;
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#"<lens><maker>Testcam</maker><model>Testcam Compact C1 with tele converter</model><mount>testcamC1</mount>
<cropfactor>2.7</cropfactor><calibration><distortion model="poly3" focal="62" k1="0.01" /></calibration></lens></lensdatabase>"#;
let two = LensDb::parse(&COMPACT.replace("</lensdatabase>", 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#"<lensdatabase>
<camera><maker>Sony</maker><model>DSC-RX100M2</model><mount>sonyRX100II</mount><cropfactor>2.73</cropfactor></camera>
<lens><maker>Sony</maker><model>DSC-RX100 II &amp; compatibles</model><mount>sonyRX100II</mount><cropfactor>2.73</cropfactor>
<calibration>
<distortion model="poly3" focal="10.4" k1="-0.02" />
<distortion model="poly3" focal="37.1" k1="0.003" />
</calibration>
</lens></lensdatabase>"#;
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.
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PhotoId, Option<String>>,
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.
Expand Down Expand Up @@ -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"))]
Expand Down
7 changes: 7 additions & 0 deletions crates/engine/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<serde_json::Value>,
/// [`Session::lens_tried`].
lens_tried: std::collections::BTreeMap<lightcraft_catalog::PhotoId, Option<String>>,
lens_tried_by: (u32, u64),
}

fn presets_json(s: &Session) -> String {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(()) };
Expand Down
Loading