Skip to main content

capsule_core/exif/
extract.rs

1use std::io::{BufRead, Cursor, Read, Seek, SeekFrom};
2
3use exif::{DateTime as ExifDateTime, In, Reader, Tag, Value};
4use jiff::civil;
5
6#[derive(Debug, Clone, PartialEq, Default)]
7pub struct ExifExtract {
8    pub date_time_original: Option<civil::DateTime>,
9    pub offset_time_original: Option<String>, // e.g. "+09:00"
10    pub gps_lat: Option<f64>,
11    pub gps_lon: Option<f64>,
12    pub make: Option<String>,
13    pub model: Option<String>,
14    pub width: Option<u32>,
15    pub height: Option<u32>,
16    pub duration_ms: Option<u64>, // For video; not from EXIF — always None from this extractor
17    pub content_identifier: Option<String>, // Apple Live Photo UUID
18}
19
20/// Extract the EXIF fields Capsule indexes from a file's bytes.
21///
22/// The in-memory form of [`extract_exif_from_reader`]; see it for the contract.
23pub fn extract_exif_from_bytes(bytes: &[u8]) -> ExifExtract {
24    extract_exif_from_reader(&mut Cursor::new(bytes))
25}
26
27/// Extract the EXIF fields Capsule indexes from a seekable reader over a file's contents.
28///
29/// Generic over the reader so opening the file stays the caller's business (`capsule-library`
30/// hands a buffered file handle here). Contents that are not an EXIF container yield an
31/// all-`None` extract rather than an error — a file without EXIF is ordinary, not a failure — and
32/// are read only as far as the container sniff needs, so a large non-EXIF original is never held
33/// whole. Only an EXIF container is rewound and read to its end, for the Live Photo content
34/// identifier; a read failure there leaves that one field `None`.
35pub fn extract_exif_from_reader<R: BufRead + Seek>(reader: &mut R) -> ExifExtract {
36    let Ok(exif) = Reader::new().read_from_container(reader) else {
37        // Not a valid EXIF container — return all-None result
38        return ExifExtract {
39            date_time_original: None,
40            offset_time_original: None,
41            gps_lat: None,
42            gps_lon: None,
43            make: None,
44            model: None,
45            width: None,
46            height: None,
47            duration_ms: None,
48            content_identifier: None,
49        };
50    };
51
52    // DateTimeOriginal.
53    //
54    // Parsed from the **raw ASCII value**, never from `display_value()`. The EXIF wire format is
55    // `YYYY:MM:DD HH:MM:SS` (colons throughout), but kamadak-exif's `Display` deliberately
56    // reformats it to `YYYY-MM-DD HH:MM:SS` (`tiff.rs`'s `impl fmt::Display for DateTime`). This
57    // code previously applied the wire pattern `%Y:%m:%d %H:%M:%S` to the display string, so the
58    // parse could never succeed and `date_time_original` was **always** `None` for well-formed
59    // EXIF — which silently made every import fall back to `Timestamp::now()`, stamping and
60    // bucketing photos by import time instead of capture time.
61    //
62    // `ExifDateTime::from_ascii` is the crate's own parser for the wire format. It also rejects
63    // the all-blank value the spec allows, which a `strptime` on the raw bytes would not.
64    let date_time_original = exif
65        .get_field(Tag::DateTimeOriginal, In::PRIMARY)
66        .and_then(|field| match &field.value {
67            Value::Ascii(values) => values.first().map(Vec::as_slice),
68            _ => None,
69        })
70        .and_then(|raw| ExifDateTime::from_ascii(raw).ok())
71        .and_then(|dt| {
72            civil::DateTime::new(
73                i16::try_from(dt.year).ok()?,
74                i8::try_from(dt.month).ok()?,
75                i8::try_from(dt.day).ok()?,
76                i8::try_from(dt.hour).ok()?,
77                i8::try_from(dt.minute).ok()?,
78                i8::try_from(dt.second).ok()?,
79                0,
80            )
81            .ok()
82        });
83
84    // OffsetTimeOriginal
85    let offset_time_original = exif
86        .get_field(Tag::OffsetTimeOriginal, In::PRIMARY)
87        .map(|field| field.display_value().to_string())
88        .map(|s| {
89            // kamadak-exif may add surrounding quotes; strip them
90            let s = s.trim();
91            if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
92                s[1..s.len() - 1].to_string()
93            } else {
94                s.to_string()
95            }
96        });
97
98    // GPS Latitude
99    let gps_lat_decimal = exif
100        .get_field(Tag::GPSLatitude, In::PRIMARY)
101        .and_then(|field| {
102            if let Value::Rational(ref rationals) = field.value {
103                if rationals.len() >= 3 {
104                    let deg = rationals[0].to_f64();
105                    let min = rationals[1].to_f64();
106                    let sec = rationals[2].to_f64();
107                    Some(deg + min / 60.0 + sec / 3600.0)
108                } else {
109                    None
110                }
111            } else {
112                None
113            }
114        });
115
116    let gps_lat = gps_lat_decimal.map(|decimal| {
117        let ref_str = exif
118            .get_field(Tag::GPSLatitudeRef, In::PRIMARY)
119            .map(|f| f.display_value().to_string())
120            .unwrap_or_default();
121        if ref_str.to_uppercase().contains('S') {
122            -decimal
123        } else {
124            decimal
125        }
126    });
127
128    // GPS Longitude
129    let gps_lon_decimal = exif
130        .get_field(Tag::GPSLongitude, In::PRIMARY)
131        .and_then(|field| {
132            if let Value::Rational(ref rationals) = field.value {
133                if rationals.len() >= 3 {
134                    let deg = rationals[0].to_f64();
135                    let min = rationals[1].to_f64();
136                    let sec = rationals[2].to_f64();
137                    Some(deg + min / 60.0 + sec / 3600.0)
138                } else {
139                    None
140                }
141            } else {
142                None
143            }
144        });
145
146    let gps_lon = gps_lon_decimal.map(|decimal| {
147        let ref_str = exif
148            .get_field(Tag::GPSLongitudeRef, In::PRIMARY)
149            .map(|f| f.display_value().to_string())
150            .unwrap_or_default();
151        if ref_str.to_uppercase().contains('W') {
152            -decimal
153        } else {
154            decimal
155        }
156    });
157
158    // Make
159    let make = exif
160        .get_field(Tag::Make, In::PRIMARY)
161        .map(|field| field.display_value().to_string())
162        .map(|s| strip_quotes(&s));
163
164    // Model
165    let model = exif
166        .get_field(Tag::Model, In::PRIMARY)
167        .map(|field| field.display_value().to_string())
168        .map(|s| strip_quotes(&s));
169
170    // Width (PixelXDimension)
171    let width = exif
172        .get_field(Tag::PixelXDimension, In::PRIMARY)
173        .and_then(|field| match field.value {
174            Value::Long(ref v) if !v.is_empty() => Some(v[0]),
175            Value::Short(ref v) if !v.is_empty() => Some(u32::from(v[0])),
176            _ => None,
177        });
178
179    // Height (PixelYDimension)
180    let height = exif
181        .get_field(Tag::PixelYDimension, In::PRIMARY)
182        .and_then(|field| match field.value {
183            Value::Long(ref v) if !v.is_empty() => Some(v[0]),
184            Value::Short(ref v) if !v.is_empty() => Some(u32::from(v[0])),
185            _ => None,
186        });
187
188    // content_identifier — Apple Live Photo UUID (byte search)
189    let content_identifier =
190        read_whole(reader).and_then(|bytes| extract_content_identifier(&bytes));
191
192    ExifExtract {
193        date_time_original,
194        offset_time_original,
195        gps_lat,
196        gps_lon,
197        make,
198        model,
199        width,
200        height,
201        duration_ms: None,
202        content_identifier,
203    }
204}
205
206fn strip_quotes(s: &str) -> String {
207    let s = s.trim();
208    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
209        s[1..s.len() - 1].to_string()
210    } else {
211        s.to_string()
212    }
213}
214
215/// The reader's whole contents from the start, or `None` if rewinding or reading fails.
216fn read_whole<R: Read + Seek>(reader: &mut R) -> Option<Vec<u8>> {
217    reader.seek(SeekFrom::Start(0)).ok()?;
218    let mut bytes = Vec::new();
219    reader.read_to_end(&mut bytes).ok()?;
220    Some(bytes)
221}
222
223fn extract_content_identifier(bytes: &[u8]) -> Option<String> {
224    let marker = b"com.apple.quicktime.content.identifier";
225    let pos = bytes.windows(marker.len()).position(|w| w == marker)?;
226    // After the marker, find a UUID-like string (36 chars: 8-4-4-4-12 hex with hyphens)
227    let after = &bytes[pos + marker.len()..];
228    // Scan for UUID pattern in the next 200 bytes
229    let search_region = &after[..after.len().min(200)];
230    let s = std::str::from_utf8(search_region).ok()?;
231    find_uuid_in_str(s)
232}
233
234fn find_uuid_in_str(s: &str) -> Option<String> {
235    // Simple scan: find 8-4-4-4-12 hex pattern
236    for start in 0..s.len().saturating_sub(36) {
237        let candidate = &s[start..start + 36];
238        if is_uuid_format(candidate) {
239            return Some(candidate.to_ascii_lowercase());
240        }
241    }
242    None
243}
244
245fn is_uuid_format(s: &str) -> bool {
246    let bytes = s.as_bytes();
247    if bytes.len() != 36 {
248        return false;
249    }
250    let expected_hyphens = [8, 13, 18, 23];
251    for (i, &b) in bytes.iter().enumerate() {
252        if expected_hyphens.contains(&i) {
253            if b != b'-' {
254                return false;
255            }
256        } else if !b.is_ascii_hexdigit() {
257            return false;
258        }
259    }
260    true
261}
262
263#[cfg(test)]
264mod tests;