Skip to content

Commit f30dd5e

Browse files
authored
Merge pull request storytold#2676 from r3d42-git/r3d/upstream-crop-factor-pr
LR-EDIT-OPTICS-PROFILE: preserve unknown crop factors in lens profiles
2 parents ac55490 + be6a900 commit f30dd5e

4 files changed

Lines changed: 227 additions & 17 deletions

File tree

‎crates/engine/src/lens_profiles.rs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ pub fn lookup(db: &LensDb, m: &lightcraft_meta::Metadata, w: f64, h: f64, orient
4949
db.find_lens_named(m.lens_make.as_deref(), &name, camera)?
5050
}
5151
};
52-
let crop = frame_crop_factor(camera.map(|c| c.crop_factor), focal, m.focal_length_35mm);
52+
let crop = frame_crop_factor(camera.and_then(|c| c.crop_factor), focal, m.focal_length_35mm);
5353
let shot = Shot { focal, aperture: m.f_number, distance: None, crop_factor: crop, width: w, height: h };
5454
let corr = lens.correction(&shot)?;
5555
Some(lightcraft_pipeline::optics::reorient_lens(&corr, orientation, w, h))
@@ -177,6 +177,32 @@ mod tests {
177177
assert_eq!(frame_crop_factor(Some(1.0), 0.0, Some(105.0)), Some(1.0), "a hostile focal length is ignored");
178178
}
179179

180+
#[test]
181+
fn unknown_camera_crop_uses_exif_equivalent_without_full_frame_assumption() {
182+
for crop in [
183+
"",
184+
"<cropfactor/>",
185+
"<cropfactor>bad</cropfactor>",
186+
"<cropfactor>NaN</cropfactor>",
187+
"<cropfactor>inf</cropfactor>",
188+
"<cropfactor>0.049</cropfactor>",
189+
"<cropfactor>21</cropfactor>",
190+
] {
191+
let xml = DB.replacen("<cropfactor>1.5</cropfactor>", crop, 1).replace("-0.03", "-0.003").replace("-0.4", "-0.04");
192+
let db = LensDb::parse(&xml).unwrap();
193+
// A below-1 crop exposes the old synthetic 1.0 body: the 10% crop-mode policy would keep it.
194+
let m = lightcraft_meta::Metadata { focal_length_35mm: Some(17.1), ..meta() };
195+
let expected = db.lenses[0]
196+
.correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: Some(17.1 / 18.0), width: 6000.0, height: 4000.0 })
197+
.unwrap();
198+
assert_eq!(lookup(&db, &m, 6000.0, 4000.0, Orientation::Normal).unwrap(), expected, "{crop}");
199+
let fallback = db.lenses[0]
200+
.correction(&Shot { focal: 18.0, aperture: Some(3.5), distance: None, crop_factor: None, width: 6000.0, height: 4000.0 })
201+
.unwrap();
202+
assert_eq!(lookup(&db, &meta(), 6000.0, 4000.0, Orientation::Normal).unwrap(), fallback, "no equivalent: {crop}");
203+
}
204+
}
205+
180206
/// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry
181207
/// stage with straight lines.
182208
#[test]

‎crates/lensdb/src/lib.rs‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ pub struct Camera {
6565
pub maker: String,
6666
pub model: String,
6767
pub mount: String,
68-
pub crop_factor: f64,
68+
/// Sensor crop relative to 35 mm; missing or invalid XML remains unknown.
69+
pub crop_factor: Option<f64>,
6970
}
7071

7172
/// One calibrated vignetting point.
@@ -85,8 +86,8 @@ pub struct Profile {
8586
/// Every name the lens goes by (EXIF variants, translations).
8687
pub models: Vec<String>,
8788
pub mounts: Vec<String>,
88-
/// Crop factor of the camera the calibration was made on.
89-
pub crop_factor: f64,
89+
/// Crop factor of the calibration frame; missing or invalid XML remains unknown.
90+
pub crop_factor: Option<f64>,
9091
/// Long / short side of the calibration frame.
9192
pub aspect_ratio: f64,
9293
/// False for fisheye and other non-rectilinear projections: distortion is then not applied.
@@ -211,7 +212,7 @@ impl LensDb {
211212
{
212213
score *= 0.8;
213214
}
214-
if score >= 0.6 && best.is_none_or(|(s, _)| score > s) {
215+
if score >= 0.6 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && lens.crop_factor.is_some())) {
215216
best = Some((score, lens));
216217
}
217218
}
@@ -250,7 +251,7 @@ impl LensDb {
250251
continue;
251252
}
252253
let score = focals.iter().filter(|f| (lo..=hi).contains(*f)).count() as f64 / focals.len() as f64;
253-
if score > 0.0 && best.is_none_or(|(s, _)| score > s) {
254+
if score > 0.0 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && p.crop_factor.is_some())) {
254255
best = Some((score, p));
255256
}
256257
}
@@ -386,7 +387,7 @@ fn camera(n: &xml::Node) -> Option<Camera> {
386387
maker: n.kid_text("maker")?.to_string(),
387388
model: n.kid_text("model")?.to_string(),
388389
mount: n.kid_text("mount").unwrap_or_default().to_string(),
389-
crop_factor: crop_of(n.kid_text("cropfactor")).unwrap_or(1.0),
390+
crop_factor: crop_of(n.kid_text("cropfactor")),
390391
})
391392
}
392393

@@ -415,7 +416,7 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec<Profile> {
415416
if models.is_empty() {
416417
return Vec::new();
417418
}
418-
let crop = crop_of(n.kid_text("cropfactor")).unwrap_or(1.0);
419+
let crop = crop_of(n.kid_text("cropfactor"));
419420
let aspect = aspect_of(n.kid_text("aspect-ratio")).unwrap_or(1.5);
420421
let rectilinear = n.kid_text("type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear"));
421422
let mounts = n.kids("mount").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect::<Vec<_>>();
@@ -434,7 +435,11 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec<Profile> {
434435
maker: String::new(),
435436
models: Vec::new(),
436437
mounts: Vec::new(),
437-
crop_factor: crop_of(cal.attr("cropfactor")).unwrap_or(crop),
438+
// Only an omitted override inherits; an explicit invalid value remains unknown.
439+
crop_factor: match cal.attr("cropfactor") {
440+
Some(value) => crop_of(Some(value)),
441+
None => crop,
442+
},
438443
aspect_ratio: aspect_of(cal.attr("aspect-ratio")).unwrap_or(aspect),
439444
rectilinear,
440445
distortion: Vec::new(),
@@ -570,14 +575,16 @@ impl Profile {
570575
/// The correction for `shot`, as the DNG opcode polynomials the pipeline applies, centred on the image.
571576
/// Distortion and TCA are combined per plane (R, G, B); a model the polynomial can't follow closely
572577
/// ([`MAX_WARP_ERROR`], [`MAX_VIGNETTE_ERROR`]) or that would fold the image is left out.
578+
/// An unknown or invalid calibration crop factor cannot be converted.
573579
pub fn correction(&self, shot: &Shot) -> Option<EmbeddedLens> {
574580
let (w, h) = (shot.width, shot.height);
575581
if !(w >= 2.0 && h >= 2.0 && w.is_finite() && h.is_finite() && shot.focal.is_finite() && shot.focal > 0.0) {
576582
return None;
577583
}
578-
let cam = shot.crop_factor.filter(|c| c.is_finite() && *c > 0.0).unwrap_or(self.crop_factor);
584+
let calibration_crop = self.crop_factor.filter(|c| c.is_finite() && (0.05..=20.0).contains(c))?;
585+
let cam = shot.crop_factor.filter(|c| c.is_finite() && *c > 0.0).unwrap_or(calibration_crop);
579586
// DNG radius (1 = image half diagonal) → lensfun radii
580-
let to_vig = self.crop_factor / cam;
587+
let to_vig = calibration_crop / cam;
581588
let to_dist = to_vig * (1.0 + self.aspect_ratio * self.aspect_ratio).sqrt();
582589
let center = Point::new(0.5, 0.5);
583590
let radius = w.hypot(h) / 2.0 / w.max(h);

‎crates/lensdb/src/tests.rs‎

Lines changed: 176 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const DB: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
3636
<maker>Testcam</maker>
3737
<model>Testcam 50mm f/1.8</model>
3838
<mount>Other Mount</mount>
39+
<cropfactor>1</cropfactor>
3940
<calibration>
4041
<distortion model="poly5" focal="50" k1="-0.02" k2="0.0003" />
4142
</calibration>
@@ -44,6 +45,7 @@ const DB: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
4445
<maker>Fishco</maker>
4546
<model>Fishco 8mm f/3.5 Fisheye</model>
4647
<type>equisolid</type>
48+
<cropfactor>1</cropfactor>
4749
<calibration>
4850
<distortion model="poly3" focal="8" k1="0.5" />
4951
</calibration>
@@ -101,8 +103,8 @@ fn malformed_documents_are_errors_not_panics() {
101103
#[test]
102104
fn finds_cameras_by_exif_strings() {
103105
let db = db();
104-
assert_eq!(db.find_camera("TESTCAM CORPORATION", "TC-1").unwrap().crop_factor, 1.5);
105-
assert_eq!(db.find_camera("Testcam", "tc-ff").unwrap().crop_factor, 1.0);
106+
assert_eq!(db.find_camera("TESTCAM CORPORATION", "TC-1").unwrap().crop_factor, Some(1.5));
107+
assert_eq!(db.find_camera("Testcam", "tc-ff").unwrap().crop_factor, Some(1.0));
106108
assert!(db.find_camera("Testcam", "TC-2").is_none());
107109
assert!(db.find_camera("Other", "TC-1").is_none());
108110
}
@@ -294,6 +296,140 @@ fn a_named_profile_is_found_behind_a_tie() {
294296
assert!(db.find_lens_named(None, "70-200mm f/4", None).is_none());
295297
}
296298

299+
fn crop_xml(parent: &str, calibration: &str) -> String {
300+
format!(
301+
r#"<lensdatabase><lens><maker>Test</maker><model>Test 50mm</model>{parent}
302+
<calibration {calibration}><distortion model="poly3" focal="50" k1="-0.01" /></calibration>
303+
</lens></lensdatabase>"#
304+
)
305+
}
306+
307+
#[test]
308+
fn tied_lens_matches_prefer_a_known_calibration_crop() {
309+
let name = spec_name([50.0, 50.0, 1.8, 1.8]);
310+
for (parent, unknown, known) in [
311+
("", "", r#"cropfactor="1""#),
312+
("<cropfactor>bad</cropfactor>", "", r#"cropfactor="1""#),
313+
("<cropfactor>1</cropfactor>", r#"cropfactor="bad""#, ""),
314+
("<cropfactor>1</cropfactor>", r#"cropfactor="bad""#, r#"cropfactor="1""#),
315+
] {
316+
let calibration = |attributes: &str| format!(r#"<calibration {attributes}><distortion model="poly3" focal="50" k1="-0.01" /></calibration>"#);
317+
for (first, second) in [(unknown, known), (known, unknown)] {
318+
let xml = format!(
319+
"<lensdatabase><lens><maker>Test</maker><model>{name}</model>{parent}{}{}</lens></lensdatabase>",
320+
calibration(first),
321+
calibration(second),
322+
);
323+
let db = LensDb::parse(&xml).unwrap();
324+
assert_eq!(db.lenses.len(), 2);
325+
assert_eq!(db.lenses.iter().filter(|p| p.crop_factor.is_none()).count(), 1);
326+
for profile in [db.find_lens(None, &name, None), db.find_lens_named(None, &name, None)] {
327+
let profile = profile.unwrap();
328+
assert_eq!(profile.crop_factor, Some(1.0), "{parent}: {first}, {second}");
329+
assert!(profile.correction(&shot(50.0)).is_some());
330+
}
331+
}
332+
}
333+
}
334+
335+
#[test]
336+
fn a_higher_lens_score_still_wins_with_unknown_crop() {
337+
let mut db = db();
338+
let camera = db.cameras[0].clone();
339+
let mut unknown = db.lenses[0].clone();
340+
unknown.crop_factor = None;
341+
let mut known = unknown.clone();
342+
known.crop_factor = Some(1.0);
343+
known.mounts = vec!["Other Mount".into()];
344+
let name = unknown.models[0].clone();
345+
for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] {
346+
db.lenses = lenses;
347+
for profile in [db.find_lens(None, &name, Some(&camera)), db.find_lens_named(None, &name, Some(&camera))] {
348+
assert_eq!(profile.unwrap().crop_factor, None, "the better mount match outranks crop availability");
349+
}
350+
}
351+
}
352+
353+
#[test]
354+
fn unknown_calibration_crop_is_not_assumed_full_frame() {
355+
for parent in [
356+
"",
357+
"<cropfactor/>",
358+
"<cropfactor>bad</cropfactor>",
359+
"<cropfactor>NaN</cropfactor>",
360+
"<cropfactor>inf</cropfactor>",
361+
"<cropfactor>0</cropfactor>",
362+
"<cropfactor>-1</cropfactor>",
363+
"<cropfactor>0.049</cropfactor>",
364+
"<cropfactor>21</cropfactor>",
365+
] {
366+
let db = LensDb::parse(&crop_xml(parent, "")).unwrap();
367+
assert_eq!(db.lenses[0].crop_factor, None, "{parent}");
368+
assert!(db.lenses[0].correction(&shot(50.0)).is_none(), "unknown calibration crop: {parent}");
369+
}
370+
}
371+
372+
#[test]
373+
fn invalid_calibration_override_does_not_inherit_parent_crop() {
374+
for value in ["", "bad", "NaN", "inf", "0", "-1", "0.049", "21"] {
375+
let db = LensDb::parse(&crop_xml("<cropfactor>1.5</cropfactor>", &format!(r#"cropfactor="{value}""#))).unwrap();
376+
assert_eq!(db.lenses[0].crop_factor, None, "{value}");
377+
assert!(db.lenses[0].correction(&shot(50.0)).is_none(), "invalid calibration override: {value}");
378+
}
379+
}
380+
381+
#[test]
382+
fn calibration_crop_inherits_only_when_omitted_and_accepts_valid_overrides() {
383+
let inherited = LensDb::parse(&crop_xml("<cropfactor>1.5</cropfactor>", "")).unwrap();
384+
assert_eq!(inherited.lenses[0].crop_factor, Some(1.5));
385+
assert!(inherited.lenses[0].correction(&shot(50.0)).is_some());
386+
for parent in ["", "<cropfactor>bad</cropfactor>", "<cropfactor>1.5</cropfactor>"] {
387+
for value in ["0.05", "1", "2", "20"] {
388+
let db = LensDb::parse(&crop_xml(parent, &format!(r#"cropfactor="{value}""#))).unwrap();
389+
assert_eq!(db.lenses[0].crop_factor, value.parse().ok());
390+
// With no shot crop the valid calibration supplies the scale, even at the range boundaries.
391+
assert!(db.lenses[0].correction(&Shot { crop_factor: None, ..shot(50.0) }).is_some());
392+
}
393+
}
394+
}
395+
396+
#[test]
397+
fn camera_crop_preserves_unknown_and_explicit_full_frame() {
398+
for (crop, expected) in [
399+
("", None),
400+
("bad", None),
401+
("NaN", None),
402+
("inf", None),
403+
("0", None),
404+
("-1", None),
405+
("0.049", None),
406+
("21", None),
407+
("0.05", Some(0.05)),
408+
("1", Some(1.0)),
409+
("20", Some(20.0)),
410+
] {
411+
let xml = format!(r#"<lensdatabase><camera><maker>Test</maker><model>Body</model><cropfactor>{crop}</cropfactor></camera></lensdatabase>"#);
412+
let db = LensDb::parse(&xml).unwrap();
413+
assert_eq!(db.cameras[0].crop_factor, expected, "{crop}");
414+
}
415+
let db = LensDb::parse("<lensdatabase><camera><maker>Test</maker><model>Body</model></camera></lensdatabase>").unwrap();
416+
assert_eq!(db.cameras[0].crop_factor, None);
417+
}
418+
419+
#[test]
420+
fn direct_profile_api_rejects_invalid_calibration_and_preserves_shot_fallback() {
421+
let mut profile = db().lenses[0].clone();
422+
for crop in [None, Some(f64::NAN), Some(f64::INFINITY), Some(0.0), Some(-1.0), Some(0.049), Some(21.0)] {
423+
profile.crop_factor = crop;
424+
assert!(profile.correction(&shot(24.0)).is_none(), "{crop:?}");
425+
}
426+
profile.crop_factor = Some(1.0);
427+
let expected = profile.correction(&shot(24.0)).unwrap();
428+
for crop in [None, Some(f64::NAN), Some(f64::INFINITY), Some(0.0), Some(-1.0)] {
429+
assert_eq!(profile.correction(&Shot { crop_factor: crop, ..shot(24.0) }).unwrap(), expected);
430+
}
431+
}
432+
297433
#[test]
298434
fn built_in_lens_matches_by_camera_mount_and_focal_range() {
299435
let xml = r#"<lensdatabase>
@@ -320,6 +456,42 @@ fn built_in_lens_matches_by_camera_mount_and_focal_range() {
320456
assert_eq!(exif_focal_range(&tokens(&huge)), Some((6.0, 6.0)));
321457
}
322458

459+
#[test]
460+
fn tied_built_in_lens_matches_prefer_a_known_calibration_crop() {
461+
let mut db = db();
462+
let cam = db.cameras[0].clone();
463+
let mut unknown = db.lenses[0].clone();
464+
unknown.models = vec!["Testcam Compact".into()];
465+
unknown.crop_factor = None;
466+
let mut known = unknown.clone();
467+
known.crop_factor = Some(1.5);
468+
for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] {
469+
db.lenses = lenses;
470+
let lens = db.find_lens(None, "24-70 mm f/2.8", Some(&cam)).unwrap();
471+
assert_eq!(lens.crop_factor, Some(1.5), "an exact focal-range score tie prefers the known crop in either order");
472+
assert!(lens.correction(&shot(24.0)).is_some());
473+
}
474+
}
475+
476+
#[test]
477+
fn a_higher_built_in_lens_score_still_wins_with_unknown_crop() {
478+
let mut db = db();
479+
let cam = db.cameras[0].clone();
480+
let mut unknown = db.lenses[0].clone();
481+
unknown.models = vec!["Testcam Compact".into()];
482+
unknown.crop_factor = None;
483+
unknown.tca.clear();
484+
unknown.vignetting.clear();
485+
let mut known = unknown.clone();
486+
known.crop_factor = Some(1.5);
487+
known.distortion[1].0 = 100.0;
488+
for lenses in [vec![unknown.clone(), known.clone()], vec![known, unknown]] {
489+
db.lenses = lenses;
490+
let lens = db.find_lens(None, "24-70 mm f/2.8", Some(&cam)).unwrap();
491+
assert_eq!(lens.crop_factor, None, "the higher focal-range score remains the primary criterion in either order");
492+
}
493+
}
494+
323495
/// A hand-edited or corrupt database may carry any number: infinities, NaN, enormous or negative
324496
/// coefficients, absurd crop factors and aspect ratios. Whatever loads must give corrections that
325497
/// are `None` or entirely finite, for any shot including nonsense ones; names of any shape find
@@ -334,10 +506,10 @@ fn hostile_numbers_give_finite_corrections_or_none() {
334506
r#"<lens><maker>M</maker><model>M 1</model><cropfactor>{v}</cropfactor><aspect-ratio>{v}</aspect-ratio><calibration><distortion model="poly3" focal="24" k1="0.01"/><vignetting model="pa" focal="24" aperture="2.8" k1="-0.3"/></calibration></lens>"#
335507
),
336508
format!(
337-
r#"<lens><maker>M</maker><model>M 1</model><calibration cropfactor="{v}" aspect-ratio="{v}"><distortion model="ptlens" focal="24" a="{v}" b="{v}" c="{v}"/><tca model="poly3" focal="24" vr="{v}" vb="{v}" cr="{v}" cb="{v}" br="{v}" bb="{v}"/></calibration></lens>"#
509+
r#"<lens><maker>M</maker><model>M 1</model><calibration cropfactor="1" aspect-ratio="{v}"><distortion model="ptlens" focal="24" a="{v}" b="{v}" c="{v}"/><tca model="poly3" focal="24" vr="{v}" vb="{v}" cr="{v}" cb="{v}" br="{v}" bb="{v}"/></calibration></lens>"#
338510
),
339511
format!(
340-
r#"<lens><maker>M</maker><model>M 1</model><calibration><distortion model="poly5" focal="{v}" k1="{v}" k2="{v}"/><distortion model="poly3" focal="50" k1="{v}"/><vignetting model="pa" focal="{v}" aperture="{v}" distance="{v}" k1="{v}" k2="{v}" k3="{v}"/><tca model="linear" focal="{v}" kr="{v}" kb="{v}"/></calibration></lens>"#
512+
r#"<lens><maker>M</maker><model>M 1</model><cropfactor>1</cropfactor><calibration><distortion model="poly5" focal="{v}" k1="{v}" k2="{v}"/><distortion model="poly3" focal="50" k1="{v}"/><vignetting model="pa" focal="{v}" aperture="{v}" distance="{v}" k1="{v}" k2="{v}" k3="{v}"/><tca model="linear" focal="{v}" kr="{v}" kb="{v}"/></calibration></lens>"#
341513
),
342514
] {
343515
let Ok(db) = LensDb::parse(&format!("<lensdatabase>{xml}</lensdatabase>")) else { continue };

‎docs/lens-profiles.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ changes.
1717
## What is applied
1818

1919
The lens is identified from EXIF: camera make / model (for the mount and crop factor; the 35 mm equivalent focal
20-
length is used when the camera isn't listed) and the lens model string. Lens names match on their words; every
20+
length is used when the camera isn't listed or its crop factor is unknown) and the lens model string. Lens names match on their words; every
2121
number (focal lengths, apertures) in the database name must appear in the EXIF name, and the lens maker must agree
2222
when the file names one.
2323

@@ -44,7 +44,12 @@ half diagonal, or that would fold the image, is not applied.
4444

4545
Normalisation follows lensfun's documentation: distortion and TCA radii are 1 at half the shorter side of the
4646
calibration frame (its `cropfactor` and `aspect-ratio`), vignetting radii 1 at its corner; the optical centre is
47-
the image centre (lensfun's `<center>` offsets are not read).
47+
the image centre (lensfun's `<center>` offsets are not read). Missing or invalid crop factors remain unknown;
48+
only finite values from 0.05 through 20 are accepted. A calibration inherits the lens's crop factor only when its
49+
`cropfactor` attribute is omitted; an explicit invalid override remains unknown. Profiles with an unknown
50+
calibration crop factor are not applied. An explicit crop factor of 1 still means full frame.
51+
On exact lookup-score ties, both named and built-in fixed-lens matching prefer a known calibration crop; a higher
52+
match score still wins even when its crop is unknown.
4853

4954
## Limits
5055

0 commit comments

Comments
 (0)