craft-metadata: one shutter-speed formatter, exact to four digits

format_exposure_time shows a duration within 0.1% of 1/n second as 1/n and
anything else to four significant digits, so 0.3 s, 1/2.8 s and 0.625 s are
no longer rounded to a reciprocal or one decimal. Metadata::exposure_display
and the ExposureTime tag row both use it.

Ported from storytold/lightcraft#1692.
This commit is contained in:
FredApps
2026-11-11 23:43:34 +00:00
committed by Dylan M. Taylor
parent 554951d2b9
commit 758a16b538
3 changed files with 108 additions and 13 deletions
+10
View File
@@ -1105,4 +1105,14 @@ mod write_tests {
assert!((1.0 / got - den).abs() < 0.5, "1/{den} s came back as 1/{}", 1.0 / got);
}
}
#[test]
fn written_shutter_speeds_show_as_the_same_reciprocal() {
// the exact time is what export writes, and it reads back as the text shown
for (t, want) in [(1.0 / 3.0, "1/3"), (1.0 / 250.0, "1/250"), (1.0 / 12_800.0, "1/12800"), (0.3, "0.3"), (1.0 / 2.8, "0.3571")] {
let back = read_exif(&write_exif(&Metadata { exposure_time: Some(t), ..Default::default() }));
let got = back.exposure_time.unwrap();
assert_eq!(crate::format_exposure_time(got).as_deref(), Some(want), "{t} came back as {got}");
}
}
}
+72 -12
View File
@@ -162,6 +162,29 @@ macro_rules! overlay {
($self:ident, $o:ident, $($f:ident),*) => { $( if $o.$f.is_some() { $self.$f = $o.$f.clone(); } )* };
}
/// How far (relative) a duration may be from an exact `1/n` second and still be shown as `1/n`:
/// absorbs decimal EXIF rationals such as `3333/10000` for 1/3 s without turning 0.3 s or
/// 1/2.8 s into a reciprocal they aren't.
pub const RECIPROCAL_TOLERANCE: f64 = 1e-3;
/// The one shutter-speed formatter for display (catalog `shutter`, Info panel, All Metadata):
/// a near-exact `1/n` second as `1/n` (`1/3`, `1/250`), anything else rounded to four
/// significant digits with trailing zeros dropped (`0.3`, `0.3571`, `2.5`, `30`). Display only:
/// export writes the exact duration. `None` for a time that isn't positive and finite.
pub fn format_exposure_time(t: f64) -> Option<String> {
if !t.is_finite() || t <= 0.0 {
return None;
}
let n = (1.0 / t).round();
if n >= 2.0 && n.is_finite() && (1.0 / (n * t) - 1.0).abs() <= RECIPROCAL_TOLERANCE {
return Some(format!("1/{n}"));
}
// four significant digits; whole seconds never lose digits
let decimals = (3 - t.log10().floor() as i32).max(0) as usize;
let text = format!("{t:.decimals$}");
Some(if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.').to_string() } else { text })
}
impl Metadata {
/// Fill every empty field of `self` from `other`.
pub fn fill_missing(&mut self, other: &Metadata) {
@@ -245,19 +268,10 @@ impl Metadata {
}
}
/// Exposure time formatted like cameras show it: `1/250`, `0.5`, `2″`.
/// Exposure time formatted like cameras show it: `1/250`, `0.3571`, `2.5″` (see [`format_exposure_time`]).
pub fn exposure_display(&self) -> Option<String> {
let t = self.exposure_time?;
if t.is_nan() || t <= 0.0 {
return None;
}
Some(if t < 0.3 {
format!("1/{}", (1.0 / t).round())
} else if t < 1.0 {
format!("{}", (t * 10.0).round() / 10.0)
} else {
format!("{}″", (t * 10.0).round() / 10.0)
})
format_exposure_time(t).map(|text| if t >= 1.0 { format!("{text}″") } else { text })
}
/// Human name of the metering mode.
@@ -386,12 +400,58 @@ mod tests {
assert_eq!(parse_number("inf"), None);
}
#[test]
fn exposure_time_formats_reciprocals_and_significant_digits() {
for (t, want) in [
(1.0 / 3.0, "1/3"),
(1.0 / 250.0, "1/250"),
(1.0 / 8000.0, "1/8000"),
(0.5, "1/2"),
(0.3, "0.3"),
(0.4, "0.4"),
(1.0 / 2.8, "0.3571"),
(0.625, "0.625"),
(0.003, "0.003"),
(1.0, "1"),
(1.3, "1.3"),
(2.5, "2.5"),
(30.0, "30"),
(9.99996, "10"),
(1800.0, "1800"),
] {
assert_eq!(format_exposure_time(t).as_deref(), Some(want), "{t}");
}
for t in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert_eq!(format_exposure_time(t), None, "{t}");
}
}
#[test]
fn exposure_time_reciprocal_tolerance() {
// a camera's decimal rational for 1/3 s, and times just inside the tolerance either side
assert_eq!(format_exposure_time(3333.0 / 10000.0).as_deref(), Some("1/3"));
// a microsecond-level rational error still reads as 1/8000; above ~1/1000 s every time is
// within the tolerance of some 1/n, which is how cameras show those speeds anyway
assert_eq!(format_exposure_time(1.0 / 8000.0 * (1.0 + 1e-5)).as_deref(), Some("1/8000"));
for n in [3.0, 10.0, 250.0] {
let inside = 0.9 * RECIPROCAL_TOLERANCE;
let outside = 1.1 * RECIPROCAL_TOLERANCE;
let want = format!("1/{n}");
assert_eq!(format_exposure_time(1.0 / n * (1.0 + inside)).as_deref(), Some(want.as_str()), "{n} +inside");
assert_eq!(format_exposure_time(1.0 / n * (1.0 - inside)).as_deref(), Some(want.as_str()), "{n} -inside");
assert_ne!(format_exposure_time(1.0 / n * (1.0 + outside)).as_deref(), Some(want.as_str()), "{n} +outside");
assert_ne!(format_exposure_time(1.0 / n * (1.0 - outside)).as_deref(), Some(want.as_str()), "{n} -outside");
}
}
#[test]
fn exposure_display() {
let mut m = Metadata { exposure_time: Some(1.0 / 250.0), ..Default::default() };
assert_eq!(m.exposure_display().as_deref(), Some("1/250"));
m.exposure_time = Some(0.5);
assert_eq!(m.exposure_display().as_deref(), Some("0.5"));
assert_eq!(m.exposure_display().as_deref(), Some("1/2"));
m.exposure_time = Some(0.3);
assert_eq!(m.exposure_display().as_deref(), Some("0.3"));
m.exposure_time = Some(2.0);
assert_eq!(m.exposure_display().as_deref(), Some("2″"));
m.exposure_time = Some(0.0);
+26 -1
View File
@@ -250,7 +250,10 @@ fn value_text(group: &str, tag: u16, v: &Value) -> String {
// exposure time as a fraction of a second
let (n, d) = a[0];
let s = n as f64 / d as f64;
if s >= 1.0 || n == 0 { format!("{} s", rational(n as f64, d as f64)) } else { format!("1/{} s", (1.0 / s).round()) }
match crate::format_exposure_time(s) {
Some(text) => format!("{text} s"),
None => format!("{} s", rational(n as f64, d as f64)),
}
}
Value::Rational(a) if tag == 0x829d && group != "GPS" && a.len() == 1 => format!("f/{}", rational(a[0].0 as f64, a[0].1 as f64)),
Value::Rational(a) if tag == 0x920a && group != "GPS" && a.len() == 1 => format!("{} mm", rational(a[0].0 as f64, a[0].1 as f64)),
@@ -380,6 +383,28 @@ pub fn file_tag_rows(bytes: &[u8]) -> Vec<TagRow> {
#[cfg(test)]
mod tests {
#[test]
fn exposure_rows_do_not_round_third_stop_times() {
for (n, d, expected) in [
(3, 10, "0.3 s"),
(4, 10, "0.4 s"),
(6, 10, "0.6 s"),
(8, 10, "0.8 s"),
(13, 10, "1.3 s"),
(16, 10, "1.6 s"),
(25, 10, "2.5 s"),
(32, 10, "3.2 s"),
(5, 8, "0.625 s"),
(1, 3, "1/3 s"),
(10, 28, "0.3571 s"),
(1, 250, "1/250 s"),
(1, 8000, "1/8000 s"),
(30, 1, "30 s"),
] {
assert_eq!(value_text("EXIF", 0x829a, &Value::Rational(vec![(n, d)])), expected);
}
}
use super::*;
#[test]