rosier 0.5.0

A fast picture and video viewer for large folders
//! What a camera wrote into a picture: when it was taken, for sorting.
//!
//! Read with kamadak-exif, which finds the Exif block in JPEG, TIFF (and
//! the TIFF-based RAW files), HEIF, PNG and WebP. Only the header is read.

use std::path::Path;

use exif::{In, Reader, Tag, Value};

/// When the picture at `path` was taken, as seconds since 1970 counted on
/// the camera's clock (time zones are not known for most photos, so this
/// only orders pictures). None when it has no such date.
pub fn taken(path: &Path) -> Option<i64> {
    let file = std::fs::File::open(path).ok()?;
    let exif = Reader::new().read_from_container(&mut std::io::BufReader::new(file)).ok()?;
    [Tag::DateTimeOriginal, Tag::DateTimeDigitized, Tag::DateTime]
        .into_iter()
        .find_map(|tag| match &exif.get_field(tag, In::PRIMARY)?.value {
            Value::Ascii(v) => v.first().and_then(|s| exif::DateTime::from_ascii(s).ok()),
            _ => None,
        })
        .filter(|d| d.year >= 1900 && d.month >= 1 && d.day >= 1)
        .map(|d| {
            let days = days_from_civil(i64::from(d.year), i64::from(d.month), i64::from(d.day));
            days * 86_400 + i64::from(d.hour) * 3600 + i64::from(d.minute) * 60 + i64::from(d.second)
        })
}

/// What the info panel shows about a photo, each line ready to print.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Info {
    /// Maker and model, e.g. "Canon EOS 5DS R".
    pub camera: Option<String>,
    pub lens: Option<String>,
    /// Aperture, shutter speed, ISO and focal length, e.g.
    /// "f/8 · 1/250 s · ISO 100 · 24 mm".
    pub exposure: Option<String>,
    /// When it was taken, "2016-02-03 10:33".
    pub taken: Option<String>,
}

/// Reads the panel's lines from the picture at `path`; empty when it has
/// no Exif.
pub fn info(path: &Path) -> Info {
    let Some(exif) = std::fs::File::open(path)
        .ok()
        .and_then(|f| Reader::new().read_from_container(&mut std::io::BufReader::new(f)).ok())
    else {
        return Info::default();
    };
    let text = |tag| {
        let f = exif.get_field(tag, In::PRIMARY)?;
        match &f.value {
            Value::Ascii(v) => {
                let s = String::from_utf8_lossy(v.first()?)
                    .trim_matches(|c: char| c == '\0' || c.is_whitespace())
                    .to_string();
                (!s.is_empty()).then_some(s)
            }
            _ => None,
        }
    };
    let rational = |tag| match &exif.get_field(tag, In::PRIMARY)?.value {
        Value::Rational(v) => v.first().filter(|r| r.denom != 0).map(|r| (r.num, r.denom)),
        _ => None,
    };
    let make = text(Tag::Make);
    let camera = match (make, text(Tag::Model)) {
        // Models often repeat the maker ("Canon EOS 5DS R").
        (Some(mk), Some(md))
            if md.to_lowercase().starts_with(&mk.split_whitespace().next().unwrap_or_default().to_lowercase()) =>
        {
            Some(md)
        }
        (Some(mk), Some(md)) => Some(format!("{mk} {md}")),
        (mk, md) => mk.or(md),
    };
    let mut parts = Vec::new();
    if let Some((n, d)) = rational(Tag::FNumber) {
        parts.push(format!("f/{}", trim(n as f64 / d as f64)));
    }
    if let Some((n, d)) = rational(Tag::ExposureTime) {
        let secs = n as f64 / d as f64;
        parts.push(if secs >= 1.0 || n == 0 {
            format!("{} s", trim(secs))
        } else {
            format!("1/{} s", (1.0 / secs).round() as u64)
        });
    }
    if let Some(iso) = exif.get_field(Tag::PhotographicSensitivity, In::PRIMARY).and_then(|f| f.value.get_uint(0)) {
        parts.push(format!("ISO {iso}"));
    }
    if let Some((n, d)) = rational(Tag::FocalLength) {
        parts.push(format!("{} mm", trim(n as f64 / d as f64)));
    }
    let taken = [Tag::DateTimeOriginal, Tag::DateTimeDigitized, Tag::DateTime].into_iter().find_map(|tag| match &exif
        .get_field(tag, In::PRIMARY)?
        .value
    {
        Value::Ascii(v) => v.first().and_then(|s| exif::DateTime::from_ascii(s).ok()),
        _ => None,
    });
    Info {
        camera,
        lens: text(Tag::LensModel),
        exposure: (!parts.is_empty()).then(|| parts.join(" · ")),
        taken: taken.map(|d| format!("{:04}-{:02}-{:02} {:02}:{:02}", d.year, d.month, d.day, d.hour, d.minute)),
    }
}

/// 2.8 stays 2.8, 8.0 prints as 8.
fn trim(v: f64) -> String {
    let s = format!("{:.1}", v);
    s.strip_suffix(".0").map(str::to_string).unwrap_or(s)
}

/// Days from 1970-01-01 to the given date (proleptic Gregorian), after
/// Howard Hinnant's `days_from_civil`.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = y.div_euclid(400);
    let yoe = y - era * 400;
    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    #[test]
    fn numbers_print_without_a_trailing_zero() {
        assert_eq!((trim(8.0), trim(2.8), trim(5.6)), ("8".into(), "2.8".into(), "5.6".into()));
    }

    #[test]
    fn days_from_civil_matches_known_dates() {
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(days_from_civil(2000, 3, 1), 11_017);
        assert_eq!(days_from_civil(2016, 2, 29), 16_860);
        assert_eq!(days_from_civil(1969, 12, 31), -1);
    }

    /// A JPEG with an Exif block holding DateTimeOriginal.
    pub fn jpeg_taken_at(stamp: &str) -> Vec<u8> {
        // TIFF header (little endian), IFD0 with one entry pointing at the
        // Exif IFD, which holds DateTimeOriginal (ASCII, 20 bytes).
        let mut tiff = Vec::new();
        tiff.extend_from_slice(b"II*\0");
        tiff.extend_from_slice(&8u32.to_le_bytes());
        // IFD0 at 8: 1 entry, ExifIFDPointer (0x8769, LONG) -> 26.
        tiff.extend_from_slice(&1u16.to_le_bytes());
        tiff.extend_from_slice(&0x8769u16.to_le_bytes());
        tiff.extend_from_slice(&4u16.to_le_bytes());
        tiff.extend_from_slice(&1u32.to_le_bytes());
        tiff.extend_from_slice(&26u32.to_le_bytes());
        tiff.extend_from_slice(&0u32.to_le_bytes());
        // Exif IFD at 26: 1 entry, DateTimeOriginal (0x9003, ASCII, 20) -> 44.
        tiff.extend_from_slice(&1u16.to_le_bytes());
        tiff.extend_from_slice(&0x9003u16.to_le_bytes());
        tiff.extend_from_slice(&2u16.to_le_bytes());
        tiff.extend_from_slice(&20u32.to_le_bytes());
        tiff.extend_from_slice(&44u32.to_le_bytes());
        tiff.extend_from_slice(&0u32.to_le_bytes());
        let mut s = stamp.as_bytes().to_vec();
        s.resize(20, 0);
        tiff.extend_from_slice(&s);
        let mut app1 = b"Exif\0\0".to_vec();
        app1.extend_from_slice(&tiff);
        // A tiny real JPEG, with the APP1 segment put right after SOI.
        let mut img = Vec::new();
        image::RgbImage::from_pixel(8, 8, image::Rgb([200, 100, 50]))
            .write_to(&mut std::io::Cursor::new(&mut img), image::ImageFormat::Jpeg)
            .unwrap();
        let mut out = img[..2].to_vec();
        out.extend_from_slice(&[0xFF, 0xE1]);
        out.extend_from_slice(&((app1.len() + 2) as u16).to_be_bytes());
        out.extend_from_slice(&app1);
        out.extend_from_slice(&img[2..]);
        out
    }

    #[test]
    fn reads_the_date_a_photo_was_taken() {
        let dir = std::env::temp_dir().join(format!("rosier-exif-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let with = dir.join("with.jpg");
        std::fs::write(&with, jpeg_taken_at("2016:02:03 10:33:36")).unwrap();
        assert_eq!(taken(&with), Some(days_from_civil(2016, 2, 3) * 86_400 + 10 * 3600 + 33 * 60 + 36));
        let without = dir.join("without.jpg");
        image::RgbImage::new(4, 4).save(&without).unwrap();
        assert_eq!(taken(&without), None);
        assert_eq!(taken(&dir.join("missing.jpg")), None);
        let i = info(&with);
        assert_eq!(i.taken.as_deref(), Some("2016-02-03 10:33"));
        assert_eq!((i.camera, i.exposure), (None, None), "only what the file has");
        assert_eq!(info(&without), Info::default());
        let _ = std::fs::remove_dir_all(&dir);
    }
}