Files
craft-libs/crates/metadata/src/gpx.rs
T
+10 8d3f245d2a craft-metadata: validation and location fixes ported from open LightCraft pull requests (#1042)
* craft-metadata: EXIF, IPTC-IIM, XMP and GPX from LightCraft

lightcraft-meta at 5b61ce1e, as one crate with a module per format: exif
(read, write, maker-note lens, focus point, tag listing), iptc, xmp (parse,
write, merge), gpx, and the JPEG, PNG, WebP, TIFF, RAF and CR3 containers.
They share Metadata, DateTime, Gps and Orientation.

Changed in the move:
- TIFF comes from craft-tiff; Point, Rect and Orientation are the crate's own.
- The app namespace is a parameter: parse_xmp_with, write_xmp_with and
  MergeRules::namespaces take it, and XmpData no longer has lc_settings.
- The HEIF, PSD and MRW readers stay out, since craft-heif, craft-psd and
  craft-raw read those containers; from_embedded takes the blocks they find.

* craft-metadata: a RW2 reads ISO and the rest of its Exif from the JpgFromRaw

A RW2's own Exif IFD is a short subset. What it lacks is filled from the Exif
of the embedded JpgFromRaw, then from the ISO tags of the Panasonic IFD0
(0x0017, 0x0037), each only in its recorded field type. 65535 in a SHORT
ISOSpeedRatings is the overflow marker and states no ISO. The private tags
are read only in a RW2 stream, under the caller's parse options.

Ported from storytold/lightcraft#3518.

* craft-metadata: the Exif rating is written, and 65535 reads as rejected

write_exif writes Rating (0x4746), with 0xFFFF for a rejected photo, and
from_tiff reads 65535 as -1 instead of clamping it to 5.

Ported from storytold/lightcraft#1995.

* 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.

* craft-metadata: JPEG XL containers give their Exif and xml boxes

The first Exif and xml box of a JPEG XL container, plain or Brotli-wrapped
in brob, honouring the Exif box's TIFF header offset. A brob payload is
capped at 32 MiB. A bare codestream has no metadata.

Ported from storytold/lightcraft#3756.

* craft-metadata: XMP Resource structs flatten their attribute fields

A property with rdf:parseType="Resource" may give its fields as attributes
as well as child elements. Only the children were flattened into
XmpData::properties; the attributes now are too, as for a nested
rdf:Description.

Ported from storytold/lightcraft#1226 (the XMP part).

* craft-metadata: a capture date of just a year or a month stays as stated

XMP dates may stop at the year (1983) or the month (1983-04). DateTime now
has a DatePrecision; such a date writes back to XMP as stated and only in
photoshop:DateCreated, and write_exif leaves it out, since an Exif date
cannot say it.

Ported from storytold/lightcraft#3502.

* craft-metadata: Fujifilm in-camera recipes from the maker note

fuji module: the film simulation and the rest of the in-camera recipe (grain,
colour chrome, tone, dynamic range, white balance and its shift, sharpness,
noise reduction, clarity) from a Fujifilm maker note. recipe_from_exif,
recipe_from_bytes (TIFF, JPEG, RAF) and read_recipe_file, which reads only
as far as the metadata. from_embedded fills Metadata::fuji_recipe and
file_tag_rows lists the recipe under Fujifilm.

Ported from storytold/lightcraft#1209.

* craft-metadata: the linear-time scan test compares times, not a fixed bound

The test asserted that 200 000 attributes scan in under 5 s, which failed on
a loaded machine. It now scans 25 000 and 100 000 attributes, takes the best
of three runs of each, and asserts that four times the attributes take less
than ten times as long. Linear scans give about 4; a quadratic duplicate
check gave 18.6 and fails.

* craft-metadata: interleave the linear-time scan test's runs

The best-of-three ratio still failed once under load. The test now alternates
five runs of 50 000 and 200 000 attributes and compares the fastest of each,
so a burst of load slows both sizes. Six runs at load average 55 gave ratios
of 3.9 to 5.4 against the bound of 10.

* craft-metadata: XmpData::toolkit, the x:xmptk of the packet

The name of the program that wrote a packet, from x:xmptk on x:xmpmeta (or
x:xaptk on the older x:xapmeta), whatever prefix the packet binds to
adobe:ns:meta/. write_xmp_with writes XmpWrite::toolkit there, and the test
reads it back, escaped characters included.

* craft-metadata: mpf, the Multi-Picture index of a JPEG

mpf::images lists the images an APP2 MPF index (CIPA DC-007) puts after the
primary image, with their file offsets; the index is read with craft-tiff,
in either byte order, up to 16 entries. mpf::write inserts an index after
the primary's leading APPn segments and appends the other images, with the
primary listed as the representative baseline image: the layout LightCraft's
gain map JPEG writer uses, for any number of images. mpf::markers lists the
marker segments before the first scan, for APPn payloads such as ISO 21496-1
gain map metadata.

* craft-metadata: edit, byte-preserving Exif and XMP edits from PhotoCraft

PhotoCraft's orientation, resolution and Exif colour-space code (codecs
orientation.rs without the pixel transforms, resolution.rs, exif_color.rs),
at photocraft f1b5e7d72, as the edit module:

- upright_exif and upright_xmp set Orientation to 1 in place, in the entry's
  own type and width, every well-formed duplicate included.
- exif_with_resolution and xmp_with_resolution set the resolution in place
  and remove entries that cannot be rewritten; the _adding_missing variant
  appends a new IFD0 when there are none.
- export_exif and export_xmp do both and drop the source Exif thumbnail,
  with the overlap scan bounded.
- exif_orientation, exif_resolution, xmp_resolution, photoshop_resolution,
  exif_color_space and resolution read the same values with the editors'
  rules (first entry wins, SHORT or LONG only, BigTIFF accepted).

The tests that call these functions directly move with them (the codec
round trips stay in PhotoCraft): the orientation, resolution, thumbnail and
compaction tests, the comparison-counting complexity test and the colour
space tests.

* craft-metadata: exif_with_pixel_size, the written size in PixelX/YDimension

A camera records its sensor's size in the Exif IFD's PixelXDimension and
PixelYDimension, which after a crop, resize or rotation names a size the
exported file does not have. exif_with_pixel_size rewrites each one that
holds one SHORT or LONG, in place and as a LONG, in classic and BigTIFF
blocks, with the JPEG Exif prefix kept.

Ported from storytold/photocraft#12407 (the format part).

* craft-metadata: an ISO 8601 clock needs two-digit hours and minutes

Ported from storytold/lightcraft#3523.

* craft-metadata: a UTC offset needs a two-digit minute field

Ported from storytold/lightcraft#3467.

* craft-metadata: tiff:Orientation is read only as an integral code 1 to 8

A fractional or out-of-range value stays a raw property and does not
become the photo's orientation.

Ported from storytold/lightcraft#3495.

* craft-metadata: an XMP ISO is read only when it is a whole number in range

A fractional, non-positive or out-of-range ISO is not truncated or
saturated into one; the next candidate property is tried instead.

Ported from storytold/lightcraft#3633.

* craft-metadata: XMP pixel dimensions are read only as exact whole numbers

A malformed, fractional, negative or out-of-range tiff:ImageWidth or
ImageLength is no longer truncated or saturated, and lets the exif:Pixel
dimension take its place. Numbers are compared as exact decimal digits, so
wide rationals stay exact. The ISO reader now uses the same exact reader
(both PRs added one).

Ported from storytold/lightcraft#3690.

* craft-metadata: XMP GPS minutes and seconds must be under 60; tell when a read was cut short

A coordinate such as 45,60N is no longer normalised to a plausible point;
the raw property stays. XmpData::properties_truncated says the flattened
property map ran past its key budget, Embedded::chunk_walk_incomplete says a
PNG or WebP chunk walk stopped early, and jpeg_segments_with_all_xmp returns
every ordinary XMP packet of a JPEG, so a caller that must prove a file
carries no location can refuse what it could not inspect.

Ported from storytold/lightcraft#3054.

* craft-metadata: IPTC Time Created counts only when it is a whole, valid time

A date with a six-digit clock and no zone stays date-only; HHMMSS±HHMM
carries an offset; clocks and offsets are range-checked. A partial offset,
extra digits, a leap second or trailing text no longer becomes a capture
time, so it cannot block valid XMP or Exif.

Ported from storytold/lightcraft#3448.

* craft-metadata: test hostile XMP attribute references

The one-pass reference scan (entity_end) already covers the bug that
storytold/lightcraft#3007 fixed another way; its test is added here and
passes on this implementation: unknown, unterminated and far-away
references stay verbatim, a value of a million ampersands or of a million
zeros is read once, and multi-byte text around a reference stays whole.

Test from storytold/lightcraft#3007.

* craft-metadata: parse_gps_position; an XMP coordinate's sign comes from its letter

parse_gps_position reads an exif:GPSLatitude and GPSLongitude pair and
checks both axes. A negative degree, minute or second part, or a letter of
the other axis (10,30E as a latitude), is malformed; the letter may be
either case.

Ported from storytold/lightcraft#2088 (the format part).

* craft-metadata: bound the XMP namespace declarations in scope; merge into an empty rdf:RDF

Prefix lookup scans every declaration in scope, so one start tag with
thousands of xmlns declarations made parsing and merging quadratic. More
than 512 declarations in scope is now TooComplex, in parse_xmp and in
merge_xmp's scan. merge_xmp also opens a self-closing <rdf:RDF/> around the
new description instead of failing.

Ported from storytold/lightcraft#3696.

* craft-metadata: XmpData::has_location_metadata, every embedded XMP location

has_location_metadata answers whether a packet names any Exif GPS property or
a non-blank place (IPTC Core location fields, photoshop City/State/Country,
IPTC Extension LocationShown and LocationCreated with a place or coordinates),
including inside array items and repeated structs that the flattened map and
the structured values keep only once (XmpData::names_location, from the parsed
tree). The IPTC Extension namespace is now canonicalised and written.
extended_xmp_guid reports the announced Extended XMP GUID. A caller that must
prove a file has no location checks properties_truncated first.

The source also listed LightCraft's own lc:location; a caller with its own
namespace checks that itself.

Ported from storytold/lightcraft#4121 (the format part).

* craft-metadata: is_lens_spec_name, the inverse check of lens_spec_name

Whether a lens name has the '<focal> mm f/<aperture>' shape lens_spec_name
writes, so a caller can tell a made-up name from a camera's. The test is new.

Ported from storytold/lightcraft#2644 (the format part).

* craft-metadata: Sony focus points for 44 bodies

SONY_MODELS grows from the alpha 1 and A7S III to the 44 bodies whose focus
tags were checked on the public raw.pixls.us samples against ExifTool's
reading; bodies whose 0x201b is not the focus mode stay out. This also covers
the ILCE-6400 and ILCE-7M3 that storytold/lightcraft#3109 adds.

Ported from storytold/lightcraft#1891 (the focus part).

* craft-metadata: GPX points say which track they are on; tracks keep their names

TrackPoint::track counts the <trk> a point came from, Tracklog::names holds
each track's <name> (trimmed, at most 200 characters), and only_track gives
one track's points, so a map can draw a file's tracks apart and tag from one.
At most 10 000 tracks per file (TooComplex past that); a non-finite elevation
is dropped.

Ported from storytold/lightcraft#921 (the GPX part; #916 carries the same).

* craft-metadata: test that from_embedded keeps the EXIF, IPTC, XMP precedence

storytold/lightcraft#2211 adds the same function as extract_embedded; this
crate already has it as from_embedded. Its tests are added: EXIF camera
fields stay, IPTC fills gaps, XMP overrides the user fields, and damaged
blocks read as nothing.

Tests from storytold/lightcraft#2211.

* craft-metadata: the XMP writer keeps a carriage return as &#13;

XML end-of-line handling turns a literal CR into a line feed when a packet is
read, so text with one did not round-trip through other readers. Element
text now writes it as a character reference.

Ported from storytold/lightcraft#4119 (the writer fix only; that PR also
moves LightCraft to quick-xml 0.42, which this crate does not take here, as
craft-xml uses 0.41).

* craft-metadata: README rows for the ported validation and location checks

---------

Co-authored-by: radialmonster <radial@gmail.com>
Co-authored-by: Sebastian Berschneider <berschi@gmail.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Michael Anderson <1427851+endthestart@users.noreply.github.com>
Co-authored-by: Ilya Dorman <ilya@codeforhumans.dev>
Co-authored-by: Clyde C Brown <clyde.c.brown@pm.me>
Co-authored-by: MohammadTeimori <teimori.mohammad@gmail.com>
Co-authored-by: vangel76 <vangel1976@googlemail.com>
Co-authored-by: Max Mittelstädt <62167861+TheGalitube@users.noreply.github.com>
Co-authored-by: NetterSilver <133535268+Silvertree2010@users.noreply.github.com>
Co-authored-by: ronibalthazar <61232335+ronibalthazar@users.noreply.github.com>
Co-authored-by: Andrew Frahn <andrew@emmertex.com>
Co-authored-by: jkalkstein <76634771+jkalkstein@users.noreply.github.com>
Co-authored-by: d-rouge <d-rouge@users.noreply.github.com>
Co-authored-by: espoon <espoon@users.noreply.github.com>
Co-authored-by: Yoann Laissus <yoann.laissus@gmail.com>
Co-authored-by: Jason Baldwin <33934381+bitshiftza@users.noreply.github.com>
Co-authored-by: ingolfteetz <iteetz@me.com>
Co-authored-by: smi-leonivkovic <leon.ivkovic@smi-digital.com>
2026-11-11 21:03:44 -05:00

579 lines
25 KiB
Rust

//! GPS track logs in GPX 1.0 / 1.1 (the open GPS Exchange Format, <https://www.topografix.com/gpx.asp>):
//! the timed track points of every `<trk>`, and the position at any moment for geotagging photos.
//!
//! What we use from the format: `<trk>` → `<trkseg>` → `<trkpt lat=… lon=…>` with optional `<ele>`
//! (metres) and `<time>` (an `xsd:dateTime`, UTC per the schema — a time without a zone is read as
//! UTC). Points without a time can't be matched to a photo and are left out; waypoints (`<wpt>`) and
//! routes (`<rte>`) carry no timeline and are ignored. The schema defines a track segment as one
//! continuous span of logging, so positions are only interpolated *within* a segment, never across
//! the gap where reception was lost or the logger was off.
//!
//! Each point also records which `<trk>` it came from ([`TrackPoint::track`], with the tracks'
//! `<name>`s in [`Tracklog::names`]), so a map can draw the tracks of a file apart and tag from
//! one of them ([`Tracklog::only_track`]).
use quick_xml::events::Event;
use crate::{DateTime, Gps};
/// Nesting / size limits (a track log is flat; these only stop hostile input).
const MAX_DEPTH: usize = 64;
const MAX_POINTS: usize = 5_000_000;
/// Most tracks (`<trk>`) in one file.
const MAX_TRACKS: usize = 10_000;
/// Longest track name kept (characters); the rest is cut.
const MAX_NAME_CHARS: usize = 200;
/// One timed point of a track.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TrackPoint {
/// Seconds since 1970-01-01T00:00:00Z (fractional when the log has sub-second times).
pub time: f64,
pub latitude: f64,
pub longitude: f64,
/// Metres above sea level.
pub elevation: Option<f64>,
/// Track segment number, counted across the whole file (continuous logging spans).
pub segment: u32,
/// The `<trk>` it belongs to, counted from 0 in file order.
pub track: u32,
}
/// How a position was found by [`Tracklog::locate`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Match {
/// The time falls between two points of the same segment: linear interpolation.
Interpolated,
/// The nearest point (at a segment's start or end, or across a gap).
Nearest,
}
/// The timed points of a GPX file, sorted by time.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Tracklog {
pub points: Vec<TrackPoint>,
/// Tracks (`<trk>`) in the file.
pub tracks: usize,
/// Each track's `<name>` (empty when it has none), in file order: `names.len() == tracks`.
pub names: Vec<String>,
/// Track points without a usable time (left out of `points`).
pub untimed: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub enum GpxError {
Xml(String),
/// Not a GPX document (no `<gpx>` root).
NotGpx,
/// Nesting / size limits exceeded.
TooComplex,
}
impl std::fmt::Display for GpxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GpxError::Xml(e) => write!(f, "malformed GPX: {e}"),
GpxError::NotGpx => f.write_str("not a GPX file (no <gpx> element)"),
GpxError::TooComplex => f.write_str("GPX file too large or too deeply nested"),
}
}
}
impl std::error::Error for GpxError {}
/// Local name of a possibly prefixed XML name (`gpx:trkpt` → `trkpt`).
fn local(name: &[u8]) -> &[u8] {
name.rsplit(|&b| b == b':').next().unwrap_or(name)
}
/// An `xsd:dateTime` as seconds since the Unix epoch; no zone = UTC (the GPX schema's convention).
fn parse_time(s: &str) -> Option<f64> {
let mut d = DateTime::parse_iso(s)?;
// a bare date (no time of day) is too coarse to place a photo
if !s.contains('T') {
return None;
}
d.offset_minutes.get_or_insert(0);
Some(d.unix_seconds() as f64 + d.millis as f64 / 1000.0)
}
#[derive(Default)]
struct Pending {
lat: Option<f64>,
lon: Option<f64>,
ele: Option<f64>,
time: Option<f64>,
}
/// Parse a GPX document.
pub fn parse_gpx(s: &str) -> Result<Tracklog, GpxError> {
let mut reader = quick_xml::Reader::from_str(s);
// Mismatched end tags must be rejected; otherwise the path stack can
// attribute a point's time or segment to the wrong enclosing element.
reader.config_mut().check_end_names = true;
let mut path: Vec<Vec<u8>> = Vec::new();
let mut seen_gpx = false;
let mut seen_root = false;
let mut log = Tracklog::default();
let mut segment: u32 = 0;
let mut pt: Option<Pending> = None;
let mut text = String::new();
loop {
let ev = reader.read_event().map_err(|e| GpxError::Xml(e.to_string()))?;
match ev {
Event::Start(ref e) | Event::Empty(ref e) => {
let name = local(e.name().as_ref()).to_vec();
let parent = path.last().map(Vec::as_slice);
if path.is_empty() {
if seen_root {
return Err(GpxError::Xml("multiple document elements".into()));
}
seen_root = true;
}
match name.as_slice() {
b"gpx" if path.is_empty() => seen_gpx = true,
b"trk" if parent == Some(b"gpx") => {
if log.tracks >= MAX_TRACKS {
return Err(GpxError::TooComplex);
}
log.tracks += 1;
log.names.push(String::new());
}
b"trkseg" if parent == Some(b"trk") && log.points.last().is_some_and(|p| p.segment == segment) => segment += 1,
b"trkpt" if parent == Some(b"trkseg") => {
let mut p = Pending::default();
for a in e.attributes().with_checks(false).flatten() {
match local(a.key.as_ref()) {
b"lat" => {
let v = a
.decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder())
.map_err(|e| GpxError::Xml(e.to_string()))?;
p.lat = v.trim().parse().ok();
}
b"lon" => {
let v = a
.decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder())
.map_err(|e| GpxError::Xml(e.to_string()))?;
p.lon = v.trim().parse().ok();
}
_ => {}
}
}
pt = Some(p);
}
_ => {}
}
text.clear();
if matches!(ev, Event::Start(_)) {
if path.len() >= MAX_DEPTH {
return Err(GpxError::TooComplex);
}
path.push(name);
} else if name == b"trkpt" {
finish_point(&mut log, pt.take(), segment)?;
}
}
Event::Text(t) => text.push_str(&t.decode().map_err(|e| GpxError::Xml(e.to_string()))?),
Event::CData(t) => text.push_str(&String::from_utf8_lossy(&t)),
Event::GeneralRef(r) => {
if let Some(c) = r.resolve_char_ref().map_err(|e| GpxError::Xml(e.to_string()))? {
text.push(c);
} else {
let name = r.decode().map_err(|e| GpxError::Xml(e.to_string()))?;
let entity = format!("&{name};");
let value = quick_xml::escape::unescape(&entity).map_err(|e| GpxError::Xml(e.to_string()))?;
text.push_str(value.as_ref());
}
}
Event::End(_) => {
let Some(name) = path.pop() else { continue };
let parent = path.last().map(Vec::as_slice);
match name.as_slice() {
b"ele" if parent == Some(b"trkpt") => {
if let Some(p) = pt.as_mut() {
p.ele = text.trim().parse().ok().filter(|v: &f64| v.is_finite());
}
}
b"time" if parent == Some(b"trkpt") => {
if let Some(p) = pt.as_mut() {
p.time = parse_time(text.trim());
}
}
b"trkpt" => finish_point(&mut log, pt.take(), segment)?,
b"name" if parent == Some(b"trk") => {
if let Some(n) = log.names.last_mut() {
*n = text.trim().chars().take(MAX_NAME_CHARS).collect();
}
}
_ => {}
}
text.clear();
}
Event::Eof => break,
_ => {}
}
}
if !seen_gpx {
return Err(GpxError::NotGpx);
}
if !path.is_empty() {
return Err(GpxError::Xml("unclosed GPX elements".into()));
}
// stable: points logged at the same second keep their file order
log.points.sort_by(|a, b| a.time.total_cmp(&b.time));
Ok(log)
}
fn finish_point(log: &mut Tracklog, p: Option<Pending>, segment: u32) -> Result<(), GpxError> {
let Some(p) = p else { return Ok(()) };
let (Some(lat), Some(lon)) = (p.lat, p.lon) else { return Ok(()) };
if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
return Ok(());
}
let Some(time) = p.time else {
log.untimed += 1;
return Ok(());
};
if log.points.len() >= MAX_POINTS {
return Err(GpxError::TooComplex);
}
let track = u32::try_from(log.tracks.saturating_sub(1)).unwrap_or(u32::MAX);
let elevation = p.ele.filter(|e| e.is_finite());
log.points.push(TrackPoint { time, latitude: lat, longitude: lon, elevation, segment, track });
Ok(())
}
impl Tracklog {
/// First and last point times (seconds since the epoch, UTC).
pub fn span(&self) -> Option<(f64, f64)> {
Some((self.points.first()?.time, self.points.last()?.time))
}
/// The points of track `index` alone (its segments as they were), or `None` when there is no
/// such track.
pub fn only_track(&self, index: usize) -> Option<Tracklog> {
if index >= self.tracks {
return None;
}
let points = self.points.iter().filter(|p| usize::try_from(p.track).ok() == Some(index)).copied().collect();
Some(Tracklog { points, tracks: 1, names: vec![self.names.get(index).cloned().unwrap_or_default()], untimed: 0 })
}
/// Where the logger was at `time` (seconds since the epoch, UTC).
///
/// Between two points of the same segment that are at most `max_gap` seconds apart, the position
/// is interpolated linearly in time. Otherwise the nearest point counts if it is within `max_gap`
/// seconds; beyond that there is no position (the photo was taken while nothing was logged).
pub fn locate(&self, time: f64, max_gap: f64) -> Option<(Gps, Match)> {
let pts = &self.points;
if pts.is_empty() || !time.is_finite() {
return None;
}
let i = pts.partition_point(|p| p.time < time);
let next = pts.get(i);
let prev = i.checked_sub(1).and_then(|j| pts.get(j));
if let Some(n) = next
&& n.time == time
{
return Some((gps(n), Match::Interpolated));
}
if let (Some(a), Some(b)) = (prev, next)
&& a.segment == b.segment
&& b.time - a.time <= max_gap
{
let t = (time - a.time) / (b.time - a.time);
return Some((lerp(a, b, t), Match::Interpolated));
}
let near = match (prev, next) {
(Some(a), Some(b)) => {
if time - a.time <= b.time - time {
a
} else {
b
}
}
(Some(a), None) => a,
(None, Some(b)) => b,
(None, None) => return None,
};
((near.time - time).abs() <= max_gap).then(|| (gps(near), Match::Nearest))
}
}
fn gps(p: &TrackPoint) -> Gps {
Gps { latitude: p.latitude, longitude: p.longitude, altitude: p.elevation }
}
/// Linear interpolation, taking the short way across the ±180° meridian.
fn lerp(a: &TrackPoint, b: &TrackPoint, t: f64) -> Gps {
let mut dlon = b.longitude - a.longitude;
if dlon > 180.0 {
dlon -= 360.0;
} else if dlon < -180.0 {
dlon += 360.0;
}
let mut lon = a.longitude + dlon * t;
if lon > 180.0 {
lon -= 360.0;
} else if lon < -180.0 {
lon += 360.0;
}
let altitude = match (a.elevation, b.elevation) {
(Some(x), Some(y)) => Some(x + (y - x) * t),
(x, y) => x.or(y),
};
Gps { latitude: a.latitude + (b.latitude - a.latitude) * t, longitude: lon, altitude }
}
#[cfg(test)]
mod tests {
use super::*;
const LOG: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
<wpt lat="1.0" lon="1.0"><time>2026-05-01T10:00:30Z</time></wpt>
<trk><name>Walk</name>
<trkseg>
<trkpt lat="46.0000" lon="7.0000"><ele>1600</ele><time>2026-05-01T10:00:00Z</time></trkpt>
<trkpt lat="46.0010" lon="7.0020"><ele>1610</ele><time>2026-05-01T10:01:00Z</time></trkpt>
<trkpt lat="46.0020" lon="7.0040"><time>2026-05-01T10:02:00.500Z</time></trkpt>
<trkpt lat="46.5" lon="7.5"/>
</trkseg>
<trkseg>
<trkpt lat="47.0000" lon="8.0000"><time>2026-05-01T12:00:00Z</time></trkpt>
<trkpt lat="47.0010" lon="8.0010"><time>2026-05-01T12:00:10+00:00</time></trkpt>
</trkseg>
</trk>
</gpx>"#;
fn t(s: &str) -> f64 {
parse_time(s).unwrap()
}
#[test]
fn parses_timed_track_points() {
let log = parse_gpx(LOG).unwrap();
assert_eq!(log.tracks, 1);
assert_eq!(log.points.len(), 5, "waypoints and the untimed point are left out");
assert_eq!(log.untimed, 1);
assert_eq!(log.points[0].elevation, Some(1600.0));
assert_eq!(log.points[2].time, t("2026-05-01T10:02:00Z") + 0.5);
assert_eq!((log.points[0].segment, log.points[2].segment, log.points[3].segment), (0, 0, 1));
assert_eq!(log.span(), Some((t("2026-05-01T10:00:00Z"), t("2026-05-01T12:00:10Z"))));
// 2026-05-01T10:00:00Z
assert_eq!(log.points[0].time, 1_777_629_600.0);
}
#[test]
fn malformed_iso_time_is_untimed_and_cannot_match_midnight() {
let source = r#"<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg>
<trkpt lat="45" lon="7"><time>2026-01-01T</time></trkpt>
<trkpt lat="46" lon="8"><time>2026-01-01T01:00:00Z</time></trkpt>
</trkseg></trk></gpx>"#;
let log = parse_gpx(source).unwrap();
assert_eq!(log.untimed, 1);
assert_eq!(log.points.len(), 1);
assert_eq!((log.points[0].latitude, log.points[0].longitude), (46.0, 8.0));
assert!(log.locate(t("2026-01-01T00:00:00Z"), 0.0).is_none());
}
#[test]
fn interpolates_within_a_segment() {
let log = parse_gpx(LOG).unwrap();
let (g, m) = log.locate(t("2026-05-01T10:00:30Z"), 300.0).unwrap();
assert_eq!(m, Match::Interpolated);
assert!((g.latitude - 46.0005).abs() < 1e-9 && (g.longitude - 7.0010).abs() < 1e-9, "{g:?}");
assert_eq!(g.altitude, Some(1605.0));
// exactly on a point
let (g, _) = log.locate(t("2026-05-01T10:01:00Z"), 300.0).unwrap();
assert_eq!((g.latitude, g.longitude), (46.0010, 7.0020));
}
#[test]
fn never_interpolates_across_segments() {
let log = parse_gpx(LOG).unwrap();
// between the segments (10:02 … 12:00): only near either end
let (g, m) = log.locate(t("2026-05-01T10:04:00Z"), 300.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 46.0020));
let (g, m) = log.locate(t("2026-05-01T11:58:00Z"), 300.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 47.0));
assert!(log.locate(t("2026-05-01T11:00:00Z"), 300.0).is_none(), "an hour from any point");
// before the first and after the last point
assert!(log.locate(t("2026-05-01T09:59:00Z"), 300.0).is_some());
assert!(log.locate(t("2026-05-01T09:50:00Z"), 300.0).is_none());
assert!(log.locate(t("2026-05-01T12:10:00Z"), 300.0).is_none());
}
#[test]
fn max_gap_limits_interpolation() {
let log = parse_gpx(LOG).unwrap();
// the points are 60 s apart: with a 20 s limit, only the nearest point within 20 s counts
assert!(log.locate(t("2026-05-01T10:00:30Z"), 20.0).is_none());
let (g, m) = log.locate(t("2026-05-01T10:00:50Z"), 20.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 46.0010));
}
#[test]
fn gpx_1_0_prefixes_and_zones() {
let s = r#"<gpx:gpx version="1.0" xmlns:gpx="http://www.topografix.com/GPX/1/0"><gpx:trk><gpx:trkseg>
<gpx:trkpt lat="-33.9" lon="151.2"><gpx:time>2026-01-02T10:00:00+11:00</gpx:time></gpx:trkpt>
<gpx:trkpt lat="-33.8" lon="151.3"><gpx:time>2026-01-01T23:01:00</gpx:time></gpx:trkpt>
</gpx:trkseg></gpx:trk></gpx:gpx>"#;
let log = parse_gpx(s).unwrap();
assert_eq!(log.points.len(), 2);
// +11:00 is converted to UTC; no zone = UTC
assert_eq!(log.points[1].time - log.points[0].time, 60.0);
}
fn point_document(lat: &str, lon: &str, ele: &str, time: &str) -> String {
format!(
r#"<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg><trkpt lat="{lat}" lon="{lon}"><ele>{ele}</ele><time>{time}</time></trkpt></trkseg></trk></gpx>"#
)
}
#[test]
fn character_reference_elevation_is_not_truncated() {
let log = parse_gpx(&point_document("45", "7", "1&#50;3", "2026-01-01T00:00:00Z")).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), Some(123.0));
}
#[test]
fn character_reference_latitude_is_not_dropped() {
let log = parse_gpx(&point_document("4&#53;", "7&#x2E;5", "123", "2026-01-01T00:00:00Z")).unwrap();
let point = log.points.first().copied();
assert_eq!(log.points.len(), 1);
assert_eq!(point.map(|p| (p.latitude, p.longitude)), Some((45.0, 7.5)));
}
#[test]
fn character_reference_time_is_not_shifted() {
let encoded = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:&#51;0Z")).unwrap();
let plain = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:30Z")).unwrap();
assert_eq!(encoded.points.first().map(|p| p.time), plain.points.first().map(|p| p.time));
assert_eq!(encoded.points.first().map(|p| p.time), Some(1_767_225_630.0));
}
#[test]
fn predefined_entities_are_decoded_once_and_cdata_stays_literal() {
let with_predefined_entity = point_document("45", "7", "1&amp;23", "2026-01-01T00:00:00Z");
let log = parse_gpx(&with_predefined_entity).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), None);
let cdata = point_document("45", "7", "<![CDATA[1&#50;3]]>", "2026-01-01T00:00:00Z");
let log = parse_gpx(&cdata).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), None);
}
#[test]
fn unknown_and_malformed_character_references_are_rejected() {
let unknown = point_document("45", "7", "&undeclared;", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&unknown), Err(GpxError::Xml(_))));
let malformed = point_document("45", "7", "&#xZZ;", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&malformed), Err(GpxError::Xml(_))));
let unknown_attribute = point_document("4&undeclared;", "7", "123", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&unknown_attribute), Err(GpxError::Xml(_))));
let malformed_attribute = point_document("&#xZZ;", "7", "123", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&malformed_attribute), Err(GpxError::Xml(_))));
}
#[test]
fn non_finite_elevation_is_dropped() {
for ele in ["inf", "-inf", "NaN", "infinity"] {
let s = format!(
r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><ele>{ele}</ele><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>"#
);
let log = parse_gpx(&s).unwrap();
assert_eq!(log.points.len(), 1, "{ele}");
assert_eq!(log.points[0].elevation, None, "{ele}");
}
}
#[test]
fn interpolation_across_the_antimeridian() {
let a = TrackPoint { time: 0.0, latitude: 0.0, longitude: 179.0, elevation: None, segment: 0, track: 0 };
let b = TrackPoint { time: 10.0, latitude: 0.0, longitude: -179.0, elevation: None, segment: 0, track: 0 };
let g = lerp(&a, &b, 0.75);
assert!((g.longitude - -179.5).abs() < 1e-9, "{g:?}");
}
#[test]
fn rejects_multiple_document_roots() {
assert!(matches!(parse_gpx("<gpx/><gpx/>"), Err(GpxError::Xml(_))));
}
#[test]
fn rejects_non_gpx_and_bad_input() {
assert_eq!(parse_gpx("<kml><Document/></kml>"), Err(GpxError::NotGpx));
assert!(parse_gpx("").is_err());
// A partial logger write must not be mistaken for a complete track,
// even if it contains a valid timed point.
let point = r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk>"#;
assert!(matches!(parse_gpx(point), Err(GpxError::Xml(_))));
let wrong_close = r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><time>2026-01-01T00:00:00Z</time></trkpt></trk></trkseg></gpx>"#;
assert!(matches!(parse_gpx(wrong_close), Err(GpxError::Xml(_))));
assert!(
parse_gpx("<gpx><trk><trkseg><trkpt lat=\"x\" lon=\"1\"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>")
.unwrap()
.points
.is_empty()
);
let deep = "<gpx>".to_string() + &"<a>".repeat(100);
assert_eq!(parse_gpx(&deep), Err(GpxError::TooComplex));
let many = "<gpx>".to_string() + &"<trk/>".repeat(MAX_TRACKS + 1) + "</gpx>";
assert_eq!(parse_gpx(&many), Err(GpxError::TooComplex));
}
#[test]
fn tracks_are_told_apart_with_their_names() {
let s = r#"<gpx version="1.1"><trk><name> Morning </name><trkseg>
<trkpt lat="1" lon="1"><time>2026-01-01T10:00:00Z</time></trkpt>
<trkpt lat="1.1" lon="1.1"><time>2026-01-01T10:01:00Z</time></trkpt>
</trkseg></trk>
<trk><trkseg/></trk>
<trk><trkseg>
<trkpt lat="2" lon="2"><time>2026-01-01T09:00:00Z</time></trkpt>
</trkseg></trk></gpx>"#;
let log = parse_gpx(s).unwrap();
assert_eq!(log.tracks, 3);
assert_eq!(log.names, vec!["Morning".to_string(), String::new(), String::new()]);
// sorted by time: the third track's point comes first
assert_eq!(log.points.iter().map(|p| p.track).collect::<Vec<_>>(), vec![2, 0, 0]);
let first = log.only_track(0).unwrap();
assert_eq!((first.points.len(), first.tracks, first.names[0].as_str()), (2, 1, "Morning"));
assert!(log.only_track(1).unwrap().points.is_empty(), "an empty track");
assert!(log.only_track(3).is_none());
// a different track is a different segment: never interpolated across
assert_ne!(log.points[0].segment, log.points[1].segment);
}
#[test]
fn hostile_points_are_left_out() {
let s = r#"<gpx><trk><name>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</name><trkseg>
<trkpt lat="NaN" lon="1"><time>2026-01-01T10:00:00Z</time></trkpt>
<trkpt lat="1" lon="inf"><time>2026-01-01T10:00:01Z</time></trkpt>
<trkpt lat="91" lon="1"><time>2026-01-01T10:00:02Z</time></trkpt>
<trkpt lat="1" lon="-180.5"><time>2026-01-01T10:00:03Z</time></trkpt>
<trkpt lat="90" lon="180"><ele>NaN</ele><time>2026-01-01T10:00:04Z</time></trkpt>
<trkpt lat="-90" lon="-180"><time>not a time</time></trkpt>
<trkpt lat="5" lon="5"><time>2026-01-01T10:00:05Z</time></trkpt>
<trkpt lat="6" lon="6"><time>2026-01-01T09:00:00Z</time></trkpt>
</trkseg></trk></gpx>"#;
let log = parse_gpx(s).unwrap();
assert_eq!(log.points.len(), 3, "{:?}", log.points);
assert_eq!(log.untimed, 1);
assert!(log.points.iter().all(|p| p.latitude.is_finite() && p.longitude.is_finite()));
assert_eq!((log.points[1].latitude, log.points[1].elevation), (90.0, None), "a NaN elevation is no elevation");
// out of order in the file, in order in the log
assert_eq!((log.points[0].latitude, log.points[2].latitude), (6.0, 5.0));
assert_eq!(log.names[0].chars().count(), MAX_NAME_CHARS);
// a single point: located at its own time only (within the gap)
let one = parse_gpx(r#"<gpx><trk><trkseg><trkpt lat="1" lon="2"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>"#).unwrap();
assert_eq!(one.span(), Some((one.points[0].time, one.points[0].time)));
assert!(one.locate(one.points[0].time + 10.0, 60.0).is_some());
assert!(one.locate(f64::NAN, 60.0).is_none());
}
}