Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Remove Rust comments and consolidate API documentation

Neeraj Guptafa634ef6b060
diff --git a/rust/crates/exif/README.md b/rust/crates/exif/README.md
index 8f1eeaafbd..3726d53954 100644
--- a/rust/crates/exif/README.md
+++ b/rust/crates/exif/README.md
@@ -46,6 +46,50 @@ nested XMP annotations need parent/list relationships.
vendor trailer bytes and does not establish playback support. Pairing separate
live-photo files belongs to the caller.
+## API contracts
+
+Dates retain local components: offsets are minutes east of UTC, capture output
+normalizes them to `±HH:MM`, and epoch timestamps use microseconds. Local text
+retains nanoseconds. Unknown offsets stay unknown. Partial dates normalize to
+period-start midnight UTC without inventing an embedded offset; source-specific
+`date_time()` preserves precision without this normalization. Epoch zero is valid.
+
+Capture selection uses the first parseable candidate, in this order:
+
+| Family | Sources |
+| --- | --- |
+| Original | XMP `exif:DateTimeOriginal`, IPTC 2:55/60, EXIF Original, XMP `photoshop:DateCreated` |
+| Digitized | XMP `exif:DateTimeDigitized`, IPTC 2:62/63, EXIF Digitized, XMP `xmp:CreateDate` |
+| Metadata change | XMP `xmp:MetadataDate` |
+| Modified | XMP `tiff:DateTime`, EXIF Modified, XMP `xmp:ModifyDate` |
+
+EXIF families use their own subsecond/offset tags; inline values win. Blank
+auxiliary fields mean unknown; malformed values used for conversion fail.
+`capture_date_time_with()` can resolve the epoch using host timezone/DST rules or
+reject a candidate with `false`. An assumed offset must not replace `offset_time`.
+
+Display size prefers container/EXIF dimensions, then a complete XMP pair.
+Native transforms apply in order. Nonzero HEIF rotation or any mirror suppresses
+EXIF/XMP orientation; otherwise valid EXIF wins over XMP. XMP-only sizes use XMP
+orientation. JPEG XL orientation always wins. Crops must be positive, integral,
+pixel-aligned and in bounds; otherwise size is `None`. Display resampling and
+pixel aspect ratio are excluded. Rotations are counterclockwise quarter turns;
+mirror axes are 0 = vertical, 1 = horizontal; EXIF orientations 5–8 swap axes.
+
+GPS helpers preserve `(0, 0)` and reject invalid/incomplete coordinates. EXIF
+signed D/M/S values supply the sign only when both hemisphere references are
+absent; XMP requires a suffix or reference for each axis. Camera text is trimmed;
+exposure is exact rational seconds, focal length is millimetres, and legacy ISO
+ratings preserve the 65535 sentinel. Text decoding requires an explicit encoding;
+IPTC's declared UTF-8 overrides the fallback. Raw collections retain duplicates;
+`tag()`/`property()` return the first. XMP descriptions prefer the requested
+language, then `x-default`, then the first value. Structured XMP parent indices
+align with properties; node parents identify enclosing structures/list items.
+
+Motion extraction chooses the largest candidate, ending at the next video or
+EOF. Explicit `MotionPhoto` values other than `1` disable detection. Panorama
+means GPano cylindrical/equirectangular projection or EXIF `CustomRendered = 6`.
+
## Limits
`Limits::default()` bounds logical reads to 8 MiB, individual values to 64 KiB,
diff --git a/rust/crates/exif/src/datetime.rs b/rust/crates/exif/src/datetime.rs
index 168854bcf8..88660dcccd 100644
--- a/rust/crates/exif/src/datetime.rs
+++ b/rust/crates/exif/src/datetime.rs
@@ -1,7 +1,6 @@
use crate::{Ifd, Metadata};
use std::fmt;
-/// An EXIF date and its matching subsecond/UTC-offset tags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateTimeKind {
Original,
@@ -9,28 +8,17 @@ pub enum DateTimeKind {
Modified,
}
-/// The metadata field(s) containing one date/time value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateTimeSource {
Exif(DateTimeKind),
- /// Namespace URI and local property name.
Xmp(&'static str, &'static str),
- /// Date and time dataset IDs in IPTC record 2.
Iptc(u8, u8),
}
-
-/// Parsed date components and the smallest calendar unit present in the source.
-/// Omitted components use the start of that period (month/day 1, clock 0).
-/// Precision keeps those defaults distinguishable from explicitly supplied values.
-/// No UTC offset is inferred and parsing allocates no strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateTimeValue {
pub date_time: DateTime,
pub precision: DateTimePrecision,
}
-
-/// Smallest supplied calendar unit. Fractional digits remain in the raw field;
-/// DateTime retains their value up to nanoseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateTimePrecision {
Year,
@@ -39,9 +27,6 @@ pub enum DateTimePrecision {
Minute,
Second,
}
-
-/// A complete photo-local date/time. A missing UTC offset is unknown, not UTC.
-/// Original text and precision remain available through the raw metadata tags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateTime {
pub year: u16,
@@ -50,16 +35,11 @@ pub struct DateTime {
pub hour: u8,
pub minute: u8,
pub second: u8,
- /// Fractional seconds, truncated to nine digits.
pub nanosecond: u32,
- /// Signed minutes east of UTC, including negative sub-hour offsets.
pub offset_minutes: Option<i16>,
}
impl Metadata {
- /// Parse a specific EXIF, XMP or IPTC date without fallback or timezone policy.
- /// Returns None when that field is absent or malformed. XMP fields must be
- /// retained by the chosen read mode; arbitrary properties require Details.
#[inline]
pub fn date_time(&self, source: DateTimeSource) -> Option<DateTimeValue> {
match source {
@@ -73,30 +53,6 @@ impl Metadata {
}
}
}
-
- /// Parse one EXIF date family without selecting a creation-time fallback.
- /// Inline fractions/offsets take precedence over matching auxiliary tags.
- /// Blank auxiliary fields mean unknown; malformed fields used for conversion are rejected.
- ///
- /// ```rust,no_run
- /// # use ente_exif::{DateTime, DateTimeKind, DateTimeSource, Limits, Mode, namespace};
- /// # let mut file = std::fs::File::open("photo.jpg")?;
- /// # let metadata = ente_exif::read(&mut file, Mode::Summary, Limits::default())?;
- /// let original = metadata.exif_date_time(DateTimeKind::Original);
- /// let digitized = metadata.exif_date_time(DateTimeKind::Digitized);
- /// let modified = metadata.exif_date_time(DateTimeKind::Modified);
- /// // Choose the fallback order appropriate to the application.
- /// let capture = original.or(modified);
- /// if let Some(date) = capture {
- /// println!("local: {}-{}-{} {}:{}:{}", date.year, date.month, date.day,
- /// date.hour, date.minute, date.second);
- /// println!("offset minutes: {:?}; epoch µs: {:?}", date.offset_minutes, date.unix_micros());
- /// }
- /// let xmp_created = metadata.date_time(DateTimeSource::Xmp(namespace::XMP, "CreateDate"));
- /// let iptc_created = metadata.date_time(DateTimeSource::Iptc(55, 60));
- /// let strict = DateTime::parse("2024-02-29T12:34:56+05:30");
- /// # Ok::<(), Box<dyn std::error::Error>>(())
- /// ```
pub fn exif_date_time(&self, kind: DateTimeKind) -> Option<DateTime> {
let (ifd, date, subsecond, offset) = match kind {
DateTimeKind::Original => (Ifd::Exif(0), 0x9003, 0x9291, 0x9011),
@@ -123,16 +79,9 @@ impl Metadata {
}
impl DateTime {
- /// Parse a complete EXIF or ISO-style timestamp with optional fraction and offset.
- /// Accepts YYYY:MM:DD HH:MM:SS and YYYY-MM-DD[T or space]HH:MM:SS,
- /// dot/colon fractions, and Z or `±HH[:]?MM` offsets. Partial dates, leap seconds,
- /// impossible calendar dates and named timezones return None.
pub fn parse(value: &str) -> Option<Self> {
parse(value.trim(), Some(""), Some(""))
}
-
- /// Epoch microseconds only when the offset and calendar components are valid.
- /// No device timezone, DST rule, sentinel-date policy or fallback is applied.
pub fn unix_micros(self) -> Option<i64> {
if !self.valid() {
return None;
diff --git a/rust/crates/exif/src/dimensions.rs b/rust/crates/exif/src/dimensions.rs
index 5427c2fb6b..608e9aee10 100644
--- a/rust/crates/exif/src/dimensions.rs
+++ b/rust/crates/exif/src/dimensions.rs
@@ -13,16 +13,10 @@ pub struct CleanAperture {
pub horizontal_offset: Rational,
pub vertical_offset: Rational,
}
-
-/// A primary-image transform. Crops use coordinates after preceding transforms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transform {
- /// Authoritative orientation using EXIF's 1–8 convention (JPEG XL).
- /// Even 1 (normal) overrides EXIF/XMP orientation.
Orientation(u8),
- /// Quarter turns counterclockwise (0–3).
Rotate(u8),
- /// Mirror axis: 0 = vertical axis, 1 = horizontal axis.
Mirror(u8),
Crop(CleanAperture),
}
@@ -31,10 +25,6 @@ impl Dimensions {
pub(crate) fn new(width: u32, height: u32) -> Option<Self> {
(width != 0 && height != 0).then_some(Self { width, height })
}
-
- /// Apply EXIF's width/height swap to stored dimensions, including OS-provided ones.
- /// Orientations 5–8 swap axes. Unknown values leave the pair unchanged.
- /// Do not apply this again to dimensions already oriented by a decoder.
pub fn with_exif_orientation(mut self, orientation: u32) -> Self {
if (5..=8).contains(&orientation) {
std::mem::swap(&mut self.width, &mut self.height);
@@ -44,8 +34,6 @@ impl Dimensions {
}
impl CleanAperture {
- /// Apply an exact pixel crop to dimensions after any preceding transforms.
- /// Returns None unless the crop is positive, integral, aligned and in bounds.
pub fn cropped_dimensions(self, input: Dimensions) -> Option<Dimensions> {
Some(Dimensions {
width: crop_axis(input.width, self.width, self.horizontal_offset)?,
@@ -63,7 +51,6 @@ fn crop_axis(input: u32, size: Rational, offset: Rational) -> Option<u32> {
}
let size = u32::try_from(size.numerator / size.denominator).ok()?;
let spare = i128::from(input.checked_sub(size)?);
- // https://developer.apple.com/documentation/quicktime-file-format/clean_aperture
let denominator = 2 * i128::from(offset.denominator);
let origin = spare * i128::from(offset.denominator) + 2 * i128::from(offset.numerator);
(origin >= 0 && origin <= spare * denominator && origin % denominator == 0).then_some(size)
diff --git a/rust/crates/exif/src/gif.rs b/rust/crates/exif/src/gif.rs
index fe1745f58d..55193e2d09 100644
--- a/rust/crates/exif/src/gif.rs
+++ b/rust/crates/exif/src/gif.rs
@@ -39,7 +39,6 @@ pub(crate) fn read<R: Read + Seek>(
let app = reader.bytes(offset, size)?;
offset += size as u64;
if app == b"XMP DataXMP" {
- // https://github.com/adobe/XMP-Toolkit-SDK/blob/main/docs/XMPSpecificationPart3.pdf
let start = offset;
let mut packet = Vec::new();
loop {
diff --git a/rust/crates/exif/src/iptc.rs b/rust/crates/exif/src/iptc.rs
index 1127f5f25a..a0be460f6b 100644
--- a/rust/crates/exif/src/iptc.rs
+++ b/rust/crates/exif/src/iptc.rs
@@ -10,16 +10,9 @@ pub struct Iptc {
}
impl Metadata {
- /// IPTC caption (2:120), respecting its character-set announcement.
pub fn iptc_caption(&self, fallback: TextEncoding) -> Option<Cow<'_, str>> {
self.iptc_text(2, 120, fallback)
}
-
- /// Decode the first matching IPTC text dataset without trimming it.
- /// Record 1 uses ASCII. Records 2–6 and 8 support the UTF-8 announcement
- /// (ESC % G); other announcements return `None`. The caller's encoding is
- /// used only when no announcement exists. Invalid UTF-8 is not repaired.
- /// Raw datasets, including repeats and unsupported encodings, remain available.
pub fn iptc_text(
&self,
record: u8,
diff --git a/rust/crates/exif/src/jxl.rs b/rust/crates/exif/src/jxl.rs
index 575ac1eda6..9db85927c4 100644
--- a/rust/crates/exif/src/jxl.rs
+++ b/rust/crates/exif/src/jxl.rs
@@ -74,7 +74,6 @@ fn codestream(bytes: &[u8], state: &mut State) -> Result<(), Error> {
if bits.take(16)? != 0x0aff {
return Err(Error::Malformed("JPEG XL signature"));
}
- // https://www.iso.org/standard/85066.html — Annex D.2–D.3.
let div8 = bits.take(1)? != 0;
let height = bits.dimension(div8)?;
let ratio = bits.take(3)?;
@@ -125,7 +124,6 @@ fn compressed<R: Read + Seek>(
}
fn decompress(input: &[u8], state: &mut State) -> Result<Vec<u8>, Error> {
- // https://www.rfc-editor.org/rfc/rfc7932.html#section-9.1
let first = *input.first().ok_or(Error::Malformed("Brotli header"))?;
let window_bits = if first & 1 == 0 {
16
diff --git a/rust/crates/exif/src/lib.rs b/rust/crates/exif/src/lib.rs
index 84d2b316b7..13664ed99a 100644
--- a/rust/crates/exif/src/lib.rs
+++ b/rust/crates/exif/src/lib.rs
@@ -1,4 +1,3 @@
-//! Photo metadata without reading or decoding image pixels.
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
@@ -34,27 +33,9 @@ pub use text::TextEncoding;
pub use xmp::{Property, XmpNode, XmpStructure, namespace};
use std::io::{Read, Seek};
-
-/// Reads from byte zero, leaving the source positioned at the last accessed range.
-/// Metadata errors in a bounded block are reported in `issues`; I/O and resource
-/// limits stop the operation. No-metadata images return an empty successful result.
pub fn read<R: Read + Seek>(source: &mut R, mode: Mode, limits: Limits) -> Result<Metadata, Error> {
read_with_structure(source, mode, limits, None)
}
-
-/// Details plus XMP ancestor/list relationships, for consumers of structured annotations.
-///
-/// ```rust,no_run
-/// # use ente_exif::Limits;
-/// # let mut file = std::fs::File::open("photo.xmp")?;
-/// let structured = ente_exif::read_structured(&mut file, Limits::default())?;
-/// // Includes Details metadata; parents[i] belongs to metadata.xmp[i].
-/// for (property, parent) in structured.metadata.xmp.iter().zip(&structured.xmp.parents) {
-/// println!("{}: {} (parent {parent:?})", property.name, property.value);
-/// }
-/// // Follow XmpNode::parent through structured.xmp.nodes to find region/list owners.
-/// # Ok::<(), Box<dyn std::error::Error>>(())
-/// ```
pub fn read_structured<R: Read + Seek>(
source: &mut R,
limits: Limits,
@@ -133,11 +114,7 @@ fn read_with_structure<R: Read + Seek>(
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
- /// Common capture, camera, location, description, panorama and motion fields.
Summary,
- /// Named standard TIFF tags, secondary IFDs, general XMP/IPTC and PNG text.
- /// Unknown TIFF tags, MakerNotes and pixel/thumbnail references are omitted
- /// with their byte counts. Opaque XMP HDRPlusMakernote is skipped in both modes.
Details,
}
diff --git a/rust/crates/exif/src/metadata.rs b/rust/crates/exif/src/metadata.rs
index c3d8b7eedf..20e35612fb 100644
--- a/rust/crates/exif/src/metadata.rs
+++ b/rust/crates/exif/src/metadata.rs
@@ -6,9 +6,7 @@ use crate::{
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Metadata {
pub format: Format,
- /// Stored primary-image dimensions, before applying any transforms.
pub dimensions: Option<Dimensions>,
- /// Primary-image transforms in application order, independent of EXIF/XMP.
pub transforms: Vec<Transform>,
pub tags: Vec<Tag>,
pub xmp: Vec<Property>,
@@ -31,30 +29,21 @@ pub struct Location {
}
impl Metadata {
- /// Default capture-date selection. See [`photo::capture_date_time`].
pub fn capture_date_time(&self) -> Option<CaptureDateTime> {
photo::capture_date_time(self)
}
-
- /// Default date selection with caller resolution/rejection. See [`photo::capture_date_time_with`].
pub fn capture_date_time_with(
&self,
accept: impl FnMut(&mut CaptureDateTime) -> bool,
) -> Option<CaptureDateTime> {
photo::capture_date_time_with(self, accept)
}
-
- /// Default display-size selection. See [`photo::display_dimensions`].
pub fn display_dimensions(&self) -> Option<Dimensions> {
photo::display_dimensions(self)
}
-
- /// First matching tag. The raw collection preserves duplicates.
pub fn tag(&self, ifd: Ifd, id: u16) -> Option<&Tag> {
self.tags.iter().find(|tag| tag.ifd == ifd && tag.id == id)
}
-
- /// First matching namespace URI/local name. Raw properties preserve duplicates.
pub fn property(&self, namespace: &str, name: &str) -> Option<&str> {
self.xmp
.iter()
@@ -71,14 +60,9 @@ impl Metadata {
.iter()
.filter(move |p| p.namespace == namespace && p.name == name)
}
-
- /// Raw EXIF orientation. Native container/codestream transforms are separate.
pub fn orientation(&self) -> Option<u32> {
self.tag(Ifd::Image(0), 0x112)?.value.unsigned()
}
-
- /// GPano cylindrical/equirectangular projection or EXIF CustomRendered = 6.
- /// Does not infer panoramas from aspect ratio.
pub fn is_panorama(&self) -> bool {
matches!(
self.property(namespace::GPANO, "ProjectionType"),
@@ -88,18 +72,12 @@ impl Metadata {
.and_then(|t| t.value.unsigned())
== Some(6)
}
-
- /// Stored primary-image width, before orientation or cropping.
pub fn width(&self) -> Option<u32> {
self.dimensions.map(|d| d.width)
}
-
- /// Stored primary-image height, before orientation or cropping.
pub fn height(&self) -> Option<u32> {
self.dimensions.map(|d| d.height)
}
-
- /// Dimensions from one XMP namespace/pair, without orientation or source fallback.
pub fn xmp_dimensions(&self) -> Option<Dimensions> {
[
(namespace::TIFF, "ImageWidth", "ImageLength"),
@@ -113,23 +91,15 @@ impl Metadata {
)
})
}
-
- /// EXIF camera make; trimmed and borrowed. Empty values are absent.
pub fn camera_make(&self) -> Option<&str> {
self.text(Ifd::Image(0), 0x10f)
}
-
- /// EXIF camera model; trimmed and borrowed.
pub fn camera_model(&self) -> Option<&str> {
self.text(Ifd::Image(0), 0x110)
}
-
- /// EXIF lens model; trimmed and borrowed.
pub fn lens_model(&self) -> Option<&str> {
self.text(Ifd::Exif(0), 0xa434)
}
-
- /// Exact positive EXIF exposure time in seconds, without display rounding.
pub fn exposure_time(&self) -> Option<Rational> {
let Value::Rational(values) = &self.tag(Ifd::Exif(0), 0x829a)?.value else {
return None;
@@ -139,35 +109,21 @@ impl Metadata {
};
(value.as_f64()? > 0.0).then_some(*value)
}
-
- /// Positive EXIF f-number (for example, 2.8).
pub fn f_number(&self) -> Option<f64> {
self.positive_number(0x829d)
}
-
- /// Positive EXIF focal length in millimetres.
pub fn focal_length(&self) -> Option<f64> {
self.positive_number(0x920a)
}
-
- /// Legacy EXIF sensitivity values (0x8827), including any 65535 sentinel.
- /// Does not infer ISO speed from the newer sensitivity-type/extended tags.
pub fn iso_speed_ratings(&self) -> Option<&[u32]> {
match &self.tag(Ifd::Exif(0), 0x8827)?.value {
Value::Unsigned(values) => Some(values),
_ => None,
}
}
-
- /// EXIF ImageDescription only; no XMP/IPTC precedence or character-set guess.
pub fn exif_description(&self) -> Option<&str> {
self.text(Ifd::Image(0), 0x10e)
}
-
- /// EXIF coordinates only. Preserves (0, 0); source precedence belongs to the caller.
- /// Signed D/M/S components supply the sign only when both references are absent.
- /// Rejects incomplete/out-of-range coordinates, malformed references, non-finite
- /// values and minute/second magnitudes of 60 or more.
pub fn exif_location(&self) -> Option<Location> {
let latitude_ref = self.tag(Ifd::Gps(0), 1);
let longitude_ref = self.tag(Ifd::Gps(0), 3);
@@ -204,22 +160,6 @@ impl Metadata {
coordinate(4, longitude_ref, b'E', b'W')?,
)
}
-
- /// XMP decimal or comma-separated degree/minute/second coordinates.
- /// A suffix or separate hemisphere reference is required for each axis.
- ///
- /// ```rust,no_run
- /// # use ente_exif::{Limits, Mode, namespace};
- /// # let mut file = std::fs::File::open("photo.jpg")?;
- /// let metadata = ente_exif::read(&mut file, Mode::Details, Limits::default())?;
- /// let exif_location = metadata.exif_location();
- /// let xmp_location = metadata.xmp_location();
- /// let description = metadata.xmp_description(Some("en"));
- /// for keyword in metadata.properties(namespace::DC, "subject") {
- /// println!("{}", keyword.value);
- /// }
- /// # Ok::<(), Box<dyn std::error::Error>>(())
- /// ```
pub fn xmp_location(&self) -> Option<Location> {
location(
xmp_coordinate(
@@ -236,9 +176,6 @@ impl Metadata {
)?,
)
}
-
- /// Preferred language, then x-default, then the first XMP description.
- /// IPTC encoding and cross-source caption precedence remain explicit in the caller.
pub fn xmp_description(&self, language: Option<&str>) -> Option<&str> {
let descriptions = || self.properties(namespace::DC, "description");
language
diff --git a/rust/crates/exif/src/motion.rs b/rust/crates/exif/src/motion.rs
index c02aef67ee..35b7add6cc 100644
--- a/rust/crates/exif/src/motion.rs
+++ b/rust/crates/exif/src/motion.rs
@@ -2,13 +2,6 @@ use crate::boxes::box_at;
use crate::read::{Error, Reader, State, be32, le32, range};
use crate::{Format, namespace};
use std::io::{Read, Seek};
-
-/// Half-open extraction range `[start, end)` for appended motion video.
-/// Selects the largest candidate, ending at the next recognized video or EOF;
-/// vendor trailers may be included. Checks `ftyp` and bounded `moov`/`mdat` boxes,
-/// not codec decodability. Detection uses XMP directories/MicroVideo offsets,
-/// HEIF `mpvd`, Samsung SEF or OnePlus JXRS. An explicit MotionPhoto value other
-/// than `1` disables detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VideoRange {
pub start: u64,
@@ -81,7 +74,6 @@ fn xmp_starts(state: &State, len: u64, starts: &mut Vec<u64>) -> Result<(), Erro
.find(|p| p.namespace == namespace::ITEM && p.item == Some(item) && p.name == name)
.map(|p| p.value.as_str())
};
- // https://developer.android.com/media/platform/motion-photo-format
if property("Semantic") == Some("Primary") {
continue;
}
diff --git a/rust/crates/exif/src/photo.rs b/rust/crates/exif/src/photo.rs
index 48bccde71e..c6b435a9fd 100644
--- a/rust/crates/exif/src/photo.rs
+++ b/rust/crates/exif/src/photo.rs
@@ -1,68 +1,18 @@
-//! Default capture-date and display-size policies, built on the public parser API.
-//! Applications can replace these functions with their own source selection,
-//! normalization and decoder rules. Reading metadata does not call this module.
-
use crate::{
DateTime, DateTimeKind, DateTimePrecision, DateTimeSource, Dimensions, Metadata, Transform,
namespace,
};
-/// Resolved capture metadata. Local time and the embedded offset remain separate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureDateTime {
- /// ISO local date/time without a timezone suffix; retains nanosecond precision.
pub date_time: String,
- /// Embedded UTC offset, normalized to ±HH:MM. None means absent, not UTC.
pub offset_time: Option<String>,
- /// Epoch microseconds. None when a full timestamp has no embedded offset.
- /// Date-only inputs use midnight UTC without inventing an embedded offset.
pub timestamp_micros: Option<i64>,
pub source: DateTimeSource,
}
-
-/// First parseable capture date, in this order:
-///
-/// | Family | Sources |
-/// | --- | --- |
-/// | Original | XMP `exif:DateTimeOriginal`, IPTC 2:55/60, EXIF Original, XMP `photoshop:DateCreated` |
-/// | Digitized | XMP `exif:DateTimeDigitized`, IPTC 2:62/63, EXIF Digitized, XMP `xmp:CreateDate` |
-/// | Metadata change | XMP `xmp:MetadataDate` |
-/// | Modified | XMP `tiff:DateTime`, EXIF Modified, XMP `xmp:ModifyDate` |
-///
-/// Year/month/date-only values use the start of that period at midnight UTC,
-/// without inventing an embedded offset. Omitted seconds become zero. Full times
-/// without offsets remain unresolved; no host timezone or sentinel filtering is
-/// assumed. Valid epoch zero and unusual years are preserved.
-///
-/// Local text retains nanoseconds, epoch values retain microseconds, and `Z`
-/// normalizes to `+00:00`. Only the selected candidate's strings are allocated.
-/// Use [`Metadata::date_time`] for source precision without normalization.
pub fn capture_date_time(metadata: &Metadata) -> Option<CaptureDateTime> {
capture_date_time_with(metadata, |_| true)
}
-
-/// Resolve or reject each candidate before choosing the first accepted one.
-/// The callback can fill `timestamp_micros` from a host timezone and reject
-/// application-specific sentinel dates by returning false. An assumed device
-/// offset should not be stored in `offset_time`, which describes the source.
-/// Does not inspect filenames, filesystem timestamps or external sidecars.
-///
-/// ```rust,no_run
-/// # use ente_exif::{Limits, Mode};
-/// # let mut file = std::fs::File::open("photo.jpg")?;
-/// # let metadata = ente_exif::read(&mut file, Mode::Summary, Limits::default())?;
-/// # fn local_timestamp_in_host_timezone(_: &str) -> Option<i64> { None }
-/// let capture = metadata.capture_date_time_with(|candidate| {
-/// if candidate.timestamp_micros.is_none() {
-/// // Supplied by the application: resolve this date in the host's timezone,
-/// // including its daylight-saving rules, rather than using today's offset.
-/// candidate.timestamp_micros = local_timestamp_in_host_timezone(&candidate.date_time);
-/// }
-/// // Returning false skips this candidate and continues through the table.
-/// candidate.timestamp_micros.is_some()
-/// });
-/// # Ok::<(), Box<dyn std::error::Error>>(())
-/// ```
pub fn capture_date_time_with(
metadata: &Metadata,
mut accept: impl FnMut(&mut CaptureDateTime) -> bool,
@@ -119,19 +69,6 @@ pub fn capture_date_time_with(
accept(&mut result).then_some(result)
})
}
-
-/// Final pixel dimensions: container/EXIF size, then a complete XMP pair.
-/// Applies HEIF transforms in order. A nonzero HEIF rotation or any mirror
-/// suppresses EXIF/XMP orientation; otherwise valid EXIF wins over XMP.
-/// Zero HEIF rotation allows EXIF/XMP fallback; mirrors do not swap axes.
-/// JPEG XL's codestream orientation always overrides EXIF/XMP, including normal
-/// orientation. Its dimensions exclude optional intrinsic display resampling.
-/// XMP-only dimensions use XMP orientation only. Missing/invalid orientation
-/// leaves dimensions unchanged. Does not apply transforms to decoded pixels.
-///
-/// Returns `None` for missing dimensions or a crop that is not a positive,
-/// integer, pixel-aligned rectangle within its input image. Pixel aspect
-/// ratio, scaling and decoder-specific rendering policies are not applied.
pub fn display_dimensions(metadata: &Metadata) -> Option<Dimensions> {
let mut dimensions = metadata.dimensions.or_else(|| metadata.xmp_dimensions())?;
let mut oriented = false;
diff --git a/rust/crates/exif/src/read.rs b/rust/crates/exif/src/read.rs
index 252d910d25..c74c7d7a5d 100644
--- a/rust/crates/exif/src/read.rs
+++ b/rust/crates/exif/src/read.rs
@@ -40,20 +40,12 @@ impl From<io::Error> for Error {
Self::Io(e)
}
}
-
-/// Per-read resource budgets; not an exact heap/RSS cap. Retained accounting
-/// excludes allocator capacity, caller buffering and dependency internals.
-/// XML additionally allows at most 64 namespace declarations per element.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
- /// Logical source reads; also sets a separate cumulative expanded-text budget
- /// and the maximum Brotli window size.
pub read_bytes: usize,
- /// Maximum retained value or decompressed text chunk (raw profiles use read_bytes).
pub value_bytes: usize,
pub output_bytes: usize,
pub entries: usize,
- /// TIFF directories per block.
pub directories: usize,
pub depth: usize,
}
@@ -73,7 +65,6 @@ impl Default for Limits {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Statistics {
- /// Logical source bytes, excluding read-ahead inside a caller's BufReader.
pub bytes_read: u64,
pub reads: usize,
}
diff --git a/rust/crates/exif/src/tags.rs b/rust/crates/exif/src/tags.rs
index a635b6e80f..b8e86077a4 100644
--- a/rust/crates/exif/src/tags.rs
+++ b/rust/crates/exif/src/tags.rs
@@ -38,17 +38,12 @@ pub enum Value {
Signed(Vec<i32>),
Rational(Vec<Rational>),
Float(Vec<f64>),
- /// Original bytes, including any TIFF string terminator.
Ascii(Vec<u8>),
Bytes(Vec<u8>),
- /// Opaque/unknown binary fields are described without retaining their payload.
- Omitted {
- bytes: u64,
- },
+ Omitted { bytes: u64 },
}
impl Value {
- /// Reads one finite number without allocating a converted vector.
pub fn number(&self, index: usize) -> Option<f64> {
match self {
Self::Unsigned(v) => v.get(index).map(|n| f64::from(*n)),
@@ -73,19 +68,6 @@ impl Value {
let end = bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len());
std::str::from_utf8(&bytes[..end]).ok()
}
-
- /// Decode a TIFF ASCII field up to its first NUL. Legacy encodings are a
- /// caller-selected compatibility policy; TIFF specifies ASCII.
- /// ASCII and UTF-8 results borrow the original bytes.
- ///
- /// ```rust
- /// use ente_exif::{Metadata, TextEncoding, Value};
- ///
- /// let value = Value::Ascii(b"Caf\xe9\0".to_vec());
- /// assert_eq!(value.text_with(TextEncoding::Latin1).as_deref(), Some("Café"));
- /// let metadata = Metadata::default();
- /// let caption = metadata.iptc_caption(TextEncoding::Windows1252);
- /// ```
pub fn text_with(&self, encoding: TextEncoding) -> Option<Cow<'_, str>> {
let Self::Ascii(bytes) = self else {
return None;
diff --git a/rust/crates/exif/src/text.rs b/rust/crates/exif/src/text.rs
index 58dd5d5d3c..f12c2f0bd6 100644
--- a/rust/crates/exif/src/text.rs
+++ b/rust/crates/exif/src/text.rs
@@ -1,6 +1,4 @@
use std::borrow::Cow;
-
-/// Explicit decoding for metadata bytes. No character-set detection is performed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextEncoding {
Ascii,
@@ -16,7 +14,6 @@ pub(crate) fn decode(bytes: &[u8], encoding: TextEncoding) -> Option<Cow<'_, str
if encoding == TextEncoding::Ascii {
return None;
}
- // https://encoding.spec.whatwg.org/index-windows-1252.txt
const C1: [char; 32] = [
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž',
'\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{9d}',
diff --git a/rust/crates/exif/src/xmp.rs b/rust/crates/exif/src/xmp.rs
index 5c6e55808c..0ef6e5dcdd 100644
--- a/rust/crates/exif/src/xmp.rs
+++ b/rust/crates/exif/src/xmp.rs
@@ -27,14 +27,12 @@ pub struct Property {
pub name: String,
pub value: String,
pub language: Option<String>,
- /// Associates properties from the same RDF list item, preserving item order.
pub item: Option<u32>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct XmpStructure {
pub nodes: Vec<XmpNode>,
- /// One parent-node index per entry in Metadata::xmp.
pub parents: Vec<Option<u32>>,
}
diff --git a/rust/crates/exif/tests/integration/jxl.rs b/rust/crates/exif/tests/integration/jxl.rs
index f0929b3922..33cd013056 100644
--- a/rust/crates/exif/tests/integration/jxl.rs
+++ b/rust/crates/exif/tests/integration/jxl.rs
@@ -366,8 +366,6 @@ fn header(
}
pack(&bits)
}
-
-// https://www.rfc-editor.org/rfc/rfc7932.html#section-9
fn stored_brotli(bytes: &[u8]) -> Vec<u8> {
assert!(!bytes.is_empty() && bytes.len() <= 65536);
let mut bits = Vec::new();