diff --git a/README.md b/README.md index 0fe957a..68239bf 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,9 @@ Header (big-endian): ## Coverage -831 formats (the 849 that exist at fileformat.vpscoder.com — "860" is the -max task number; 11 numbers have no published page). The format table is +850 formats (the 849 that exist at fileformat.vpscoder.com — "860" is the +max task number; 11 numbers have no published page — plus WebP, added as +task 861, which has no published page). The format table is derived from the C/C++ reference code for each format (see `tools/all_formats.cpp`, 833 code blocks from 831 tasks) plus a curated magic table and hand overrides for well-known container formats @@ -50,20 +51,73 @@ with no C/C++ code at all (108, 151, 172, 233, 300, 312, 345, 369, 398, 408, 532, 623, 671, 720, 741, 757, 793, 794) are `nocode`/`nocode-text` unless a hand override exists for them (300 ICE and 398 MKA have overrides). +## Geotagging + +After the header table, `sfile` prints a `Geotagging:` section for the +formats where GPS location genuinely exists, decoding it from the +container's own metadata (never invented). Latitude/longitude are decimal +degrees (with the DMS form in parentheses), altitude is metres above (or +below) sea level, datum defaults to WGS-84 (EPSG:4326), and the timestamp +is normalised to ISO `YYYY-MM-DD HH:MM:SS` UTC. + +| format | task(s) | source decoded | +|---|---|---| +| JPEG, TIFF, CR2, NEF, DNG | 331/332, 730, 109, 445, 144 | EXIF GPS IFD via IFD0 tag 0x8825 (EXIF 2.32: 0x0000 version, 0x0001/0x0002 lat ref/value, 0x0003/0x0004 lon, 0x0005/0x0006 alt ref/value, 0x0007 timestamp, 0x0012 datum, 0x001D datestamp; RATIONAL[3] DMS) | +| GeoTIFF | 257 | ModelTiepointTag 33922 / ModelTransformationTag 34264 + GeoKeyDirectoryTag 34735 (GeoKey 2048 = 4326 WGS 84) | +| PNG | 564 | `eXIf` chunk (raw TIFF) and XMP in `iTXt` keyword `XML:com.adobe.xmp` | +| WebP | 861 | `EXIF` and `XMP ` chunks (WebP has no blog task; added as 861 — see `tools/overrides.json`) | +| HEIC / HEIF / AVIF | 286, 287, 48 | Exif item in `meta` via `iinf`/`iloc`; XMP as a mime item (`item_type` "mime", content type `application/rdf+xml`) | +| MP4 / MOV / M4V / F4V / M4A | 415, 412, 373, 207, 370 | `moov/udta` (c)xyz atom (ISO 6709 string; canonical QuickTime text layout `[u16 size][u16 lang]text`, bare strings also accepted), `moov/udta/meta` key `com.apple.quicktime.location.ISO6709` (keys/ilst), XMP in `udta/XMP_` and in a top-level `uuid` box (UUID BE7ACFCB-97A9-42E8-9C71-999491E3AFAC — the layout exiftool itself writes) | +| 3GP / 3G2 | 4, 3 | `moov/udta` loci box (3GPP TS 26.244: signed 16.16 fixed-point lon/lat/alt) | +| CR3 | 110 | GPS IFD in the CMT4 box inside `moov/uuid` (Canon); XMP via the CTBO table entry 1 | +| EXR | 199 | header attributes `longitude` / `latitude` / `altitude` (float32, degrees E/N, metres) | +| JP2 | 329 | XMP in the `uuid` box (UUID BE7ACFCB-97A9-42E8-9C71-999491E3AFAC) or an `xml ` box | +| PSD | 575 | EXIF in image resource 1058 (0x0422), XMP in resource 1060 (0x0424) | +| MKV / WebM | 399, 805 | XMP attachment only (no native GPS field exists) | +| AVI / DIVX | 47, 140 | XMP in the `_PMX` chunk only (no native GPS field exists) | + +Deliberately **not** decoded: raw `.j2k` codestreams (no metadata), +MKV free-text `RECORDING_LOCATION` / `LOCATION` tags and AVI RIFF INFO +chunks (free text, not coordinates — a test fixture proves they are not +reported as GPS), WAV iXML LOCATION, JPEG XL Exif boxes. XMP coordinates +are accepted in DMS (`37,46,29.64N`), decimal-minutes (`37,46.494N`), +and bare-decimal forms. + +Implementation is a dedicated pass in `src/geotag.c` / `src/geotag.h` +(dispatched from `main()` by task number — the fixed-offset header table +cannot express variable-offset metadata). A library entry point +`geotag_scan(path, task, out, max_results)` is declared in `geotag.h`; +the printed field names (`source:`, `gps_latitude:`, `gps_longitude:`, +`gps_altitude_m:`, `gps_datum:`, `gps_datetime_utc:`, `none found +(searched...)`) are the stable output contract — other tools parse them. + +Tests: `tests/geotag/make_geotag_tests.py` builds 26 fixtures with known +values (lat 37.7749 N, lon 122.4194 W, alt 10 m; MP4 keys/ilst uses the +published worked example, alt 30 m) plus two negative fixtures, and +`tests/geotag/run_geotag_tests.py` asserts sfile round-trips them +(26 PASS). Fixtures were cross-checked against exiftool 13.50, which +independently reads the same values from every fixture it supports +(including the real-world layouts: QuickTime text-prefixed (c)xyz, +`moov/udta/meta` with an `hdlr` child, HEIC mime content-type, EXR magic +`76 2F 31 01`, CR3 CMT4). Real files written by exiftool (JPEG EXIF, +MP4 XMP uuid) and ffmpeg (MP4 `loci` box — ffmpeg writes `location` +metadata as loci, not (c)xyz) were also decoded and agree. + ## Testing `tests/run_tests.py` runs `sfile` on every sample in `samples/` (one real sample file per format, collected from the task pages' download links or by web search) and records PASS / PARTIAL / FAIL / NO SAMPLE in -`tests/results.json`. Latest run (Nov 25, 2026, after the PARTIAL round -that triaged all 136 partials and converted 39 to PASS): +`tests/results.json`. Latest run (Dec 2, 2026, after the geotagging +round; counts unchanged from the Nov 25 PARTIAL round except NO SAMPLE +104 -> 105 for the new WebP task): | result | count | meaning | |---|---|---| | PASS | 650 | identified and header decoded | | PARTIAL | 97 | identified, no fixed header layout exists (see below) | | FAIL | 2 | the 2 unresolvable duplicates 312 (.INI) = 311 and 520 (.PBO) = 519 | -| NO SAMPLE | 104 | no real sample file found yet (of 853 tasks counted by the harness, which includes 4 task numbers with no published page: 202, 214, 292, 389) | +| NO SAMPLE | 105 | no real sample file found yet (of 854 tasks counted by the harness, which includes 4 task numbers with no published page: 202, 214, 292, 389, plus WebP task 861) | ### The PARTIAL tail (97) — why no layout exists diff --git a/src/formats.h b/src/formats.h index 5561e6b..a3004ea 100644 --- a/src/formats.h +++ b/src/formats.h @@ -4990,6 +4990,11 @@ static const SField fmt_860_fields[] = { { "magic", 0, 4, FK_BYTES }, { "frame_header", 4, 1, FK_U8 }, }; +static const SField fmt_861_fields[] = { + { "signature", 0, 4, FK_ASCII }, + { "file_size", 4, 4, FK_U32 }, + { "form_type", 8, 4, FK_ASCII }, +}; static const SFormat sfile_formats[] = { { 1, ".3DS", "Three DS", "\x4d\x4d", 2, 0, fmt_1_fields, 2, FMT_BINARY, 0 }, @@ -5841,6 +5846,7 @@ static const SFormat sfile_formats[] = { { 858, ".ZRX", "ZRX file", "", 0, 0, NULL, 0, FMT_TEXT, 0 }, { 859, ".ZS", "ZS file", "\xab\x5a\x53\x66\x69\x4c\x65\x01", 8, 0, fmt_859_fields, 9, FMT_BINARY, 0 }, { 860, ".ZST", "Zstandard archive", "\x28\xb5\x2f\xfd", 4, 0, fmt_860_fields, 2, FMT_BINARY, 0 }, + { 861, ".WEBP", "WebP image", "\x52\x49\x46\x46", 4, 0, fmt_861_fields, 3, FMT_BINARY, 0 }, }; -static const int sfile_nformats = 849; +static const int sfile_nformats = 850; #endif diff --git a/src/formats.json b/src/formats.json index 3e6001a..efefa3e 100644 --- a/src/formats.json +++ b/src/formats.json @@ -33849,6 +33849,36 @@ "notes": "curated-magic", "task": 860 }, + "861": { + "derivation": "override", + "endian": "le", + "ext": ".WEBP", + "fields": [ + { + "kind": "ascii", + "name": "signature", + "offset": 0, + "size": 4 + }, + { + "kind": "u32", + "name": "file_size", + "offset": 4, + "size": 4 + }, + { + "kind": "ascii", + "name": "form_type", + "offset": 8, + "size": 4 + } + ], + "magic": "52494646", + "magic_off": 0, + "name": "WebP image", + "notes": "No blog task: WebP is not among the 860 fileformat.vpscoder.com tasks (task 861 assigned here for sfile coverage). RIFF container, form type WEBP (RFC 9649). EXIF in an EXIF chunk, XMP in an XMP chunk; see src/geotag.c.", + "task": 861 + }, "87": { "derivation": "unknown", "endian": "le", diff --git a/src/geotag.c b/src/geotag.c new file mode 100644 index 0000000..71b7ca6 --- /dev/null +++ b/src/geotag.c @@ -0,0 +1,1627 @@ +/* geotag.c -- GPS/geotagging decode for sfile. + * + * sfile's generic engine (sfile.c) dumps fixed-offset header fields from + * the generated table. Geotagging cannot live in that table: the location + * sits at a variable offset inside a container (an EXIF APP1 segment, a + * PNG chunk, a QuickTime atom, ...), so this file walks the real container + * structures and reports latitude, longitude, altitude and datum. + * + * Sources, grounded in the authoritative specs (tag numbers verified + * against CIPA DC-008 / EXIF 2.32 tag tables and exiftool 13.50 output): + * + * JPEG / TIFF / PNG / WebP / HEIC / HEIF / AVIF -- EXIF GPS IFD + * (CIPA DC-008-2019, EXIF 2.32). GPS IFD reached via IFD0 tag 0x8825 + * (GPSInfo). Tags: GPSVersionID 0x0000 (BYTE[4]), GPSLatitudeRef + * 0x0001 (ASCII "N"/"S"), GPSLatitude 0x0002 (RATIONAL[3] DMS), + * GPSLongitudeRef 0x0003 (ASCII "E"/"W"), GPSLongitude 0x0004 + * (RATIONAL[3] DMS), GPSAltitudeRef 0x0005 (BYTE 0=above/1=below sea + * level), GPSAltitude 0x0006 (RATIONAL, metres), GPSTimeStamp 0x0007 + * (RATIONAL[3] UTC h/m/s), GPSMapDatum 0x0012 (ASCII, "WGS-84"), + * GPSDateStamp 0x001D (ASCII "YYYY:MM:DD"). + * Carriers: JPEG APP1 segment (marker 0xFFE1, "Exif\0\0" prefix); + * TIFF natively (IFD0 at the offset in the header); PNG eXIf chunk + * (raw TIFF header, PNG spec 2017); WebP EXIF chunk (raw TIFF + * header, RFC 9649 section 2.7.1.5); HEIF/AVIF meta box item of type + * "Exif" located via iinf/iloc (ISO/IEC 23008-12 HEIF). + * JPEG / PNG / WebP / MP4 / MOV / MKV / AVI -- XMP (ISO 16684-1) + * exif:GPSLatitude / exif:GPSLongitude ("DD,MM,SSk" or decimal + * degrees) and exif:GPSAltitude. Carriers: JPEG APP1 XMP packet, + * PNG iTXt chunk "XML:com.adobe.xmp", WebP XMP chunk, MP4/MOV + * moov/udta/XMP_ box, MKV AttachedFile with an .xmp name, AVI _PMX + * chunk. + * MP4 / MOV -- QuickTime location (ISO 6709 string "+lat+lon+alt/"): + * moov/udta/meta keys entry "com.apple.quicktime.location.ISO6709" + * (the real-world location; moov/meta is also scanned), and an + * XMP packet in a top-level uuid box (UUID BE7ACFCB-97A9-42E8-...) + * (mdta namespace, value in the parallel ilst/data atom) and the + * legacy moov/udta (c)xyz atom (0xA978797A), whose payload is the + * same ISO 6709 string. + * MKV / WebM -- Matroska has NO standard GPS field (CELLAR tags draft + * section 4.12 defines only free-text RECORDING_LOCATION / + * COMPOSITION_LOCATION). The only real mechanism is an XMP packet + * carried as an attachment (or sidecar). The de-facto ffmpeg + * "LOCATION" TagString is deliberately NOT decoded: it is not a + * Matroska-standard field. + + * AVI -- RIFF INFO has no GPS field, and AVI has no EXIF carrier. + * The only real mechanism is the XMP packet in the _PMX chunk + * (written by Adobe tools). + * + * 3GP / 3G2 -- the loci box in moov/udta (3GPP TS 26.244 table 8.10): + * language, place name, role, then longitude/latitude/altitude as + * signed 16.16 fixed-point degrees/metres. + * CR3 -- GPS IFD in the CMT4 box (a complete TIFF structure whose + * first IFD is the GPS IFD) inside moov/uuid + * 85C0B687-820F-11E0-8111-F4CE462B6A48; XMP via the CTBO table + * entry 1 (Canon, reverse-engineered; exiftool agrees). + * TIFF-based RAW (CR2, NEF, DNG) -- the same GPS IFD via IFD0 0x8825. + * GeoTIFF -- ModelTiepointTag 33922 (or ModelTransformationTag 34264) + * with GeoKeyDirectoryTag 34735; GeographicTypeGeoKey 2048 = 4326 + * (WGS 84) gives lon/lat of the tiepoint. + * EXR -- header attributes longitude/latitude/altitude, float32, + * degrees east of Greenwich / north of the equator, metres above + * sea level (OpenEXR standard attributes). + * JP2 -- XMP in the uuid box UUID BE7ACFCB-97A9-42E8-9C71-999491E3AFAC + * or the xml box; raw .j2k has no metadata. + * PSD -- image resource blocks: EXIF in resource 1058 (0x0422), + * XMP in resource 1060 (0x0424). + + * Deliberately NOT decoded: JPEG XL Exif box, MKV free-text location + * tags (names, not coordinates), AVI INFO chunks, WAV iXML LOCATION + * (audio, out of scope for this pass). + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#include "geotag.h" + +#define GEO_SLURP_CAP (64u << 20) /* 64 MiB: metadata lives near the head */ +#define GEO_PAYLOAD_CAP (4u << 20) /* 4 MiB: single-box payload cap */ +#define GEO_SCAN_CAP (64u << 20) /* 64 MiB: EBML/RIFF scan cap */ + + +static GeoResult geo_results[8]; +static int geo_nresults; +static const char *geo_searched = ""; + +/* ---- small helpers ---- */ +static double dabs(double v) { return v < 0 ? -v : v; } + +static uint16_t g16(const uint8_t *p, int be) { + return be ? (uint16_t)((p[0] << 8) | p[1]) : (uint16_t)(p[0] | (p[1] << 8)); +} +static uint32_t g32(const uint8_t *p, int be) { + if (be) return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | + ((uint32_t)p[2] << 8) | p[3]; + return p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); +} + +/* read a whole file (or its first cap bytes) into memory; NULL on failure */ +static uint8_t *slurp(const char *path, size_t cap, size_t *out_n) { + FILE *fp = fopen(path, "rb"); + if (!fp) return NULL; + uint8_t *buf = malloc(cap ? cap : 1); + if (!buf) { fclose(fp); return NULL; } + size_t n = fread(buf, 1, cap, fp); + fclose(fp); + *out_n = n; + return buf; +} + +/* read [off, off+len) from an open file into a malloc'd buffer; NULL on failure */ +static uint8_t *read_range(FILE *fp, uint64_t off, uint64_t len) { + if (len == 0 || len > GEO_PAYLOAD_CAP) return NULL; + uint8_t *buf = malloc((size_t)len + 1); + if (!buf) return NULL; + if (fseeko(fp, (off_t)off, SEEK_SET) != 0) { free(buf); return NULL; } + if (fread(buf, 1, (size_t)len, fp) != (size_t)len) { free(buf); return NULL; } + buf[len] = 0; + return buf; +} + +static int add_result(const GeoResult *g) { + if (!g->found || geo_nresults >= 8) return 0; + geo_results[geo_nresults++] = *g; + return 1; +} + +static void fmt_dms(double v, int is_lat, char *out, size_t n) { + char h = is_lat ? (v >= 0 ? 'N' : 'S') : (v >= 0 ? 'E' : 'W'); + double a = dabs(v); + int d = (int)a; + double mf = (a - d) * 60.0; + int m = (int)mf; + double s = (mf - m) * 60.0; + snprintf(out, n, "%d\xc2\xb0%d'%05.2f\"%c", d, m, s, h); +} + +static void print_results(void) { + printf("Geotagging:\n"); + if (geo_nresults == 0) { + printf(" none found (searched %s)\n", geo_searched); + return; + } + for (int i = 0; i < geo_nresults; i++) { + const GeoResult *g = &geo_results[i]; + char dms[64]; + printf(" source: %s\n", g->source); + fmt_dms(g->lat, 1, dms, sizeof dms); + printf(" gps_latitude: %.6f (%s)\n", g->lat, dms); + fmt_dms(g->lon, 0, dms, sizeof dms); + printf(" gps_longitude: %.6f (%s)\n", g->lon, dms); + if (g->has_alt) + printf(" gps_altitude_m: %.3f (%s sea level)\n", + g->alt, g->alt_below ? "below" : "above"); + if (g->has_datum) + printf(" gps_datum: %s\n", g->datum); + if (g->has_datetime) + printf(" gps_datetime_utc: %s\n", g->datetime); + } +} + +/* ---- ISO 6709: "+DD.DDDD+DDD.DDDD+AAA.AAA/" (lat, lon, optional alt) ---- */ +static int parse_iso6709(const char *s, const char *source, GeoResult *out) { + double comp[3]; + int ncomp = 0; + const char *p = s; + while (*p && isspace((unsigned char)*p)) p++; + while (*p && *p != '/' && ncomp < 3) { + if (*p != '+' && *p != '-') return 0; + char *end = NULL; + double v = strtod(p, &end); + if (end == p) return 0; + comp[ncomp++] = v; + p = end; + } + if (ncomp < 2) return 0; + if (comp[0] < -90.0 || comp[0] > 90.0) return 0; + if (comp[1] < -180.0 || comp[1] > 180.0) return 0; + memset(out, 0, sizeof *out); + out->found = 1; + snprintf(out->source, sizeof out->source, "%s", source); + out->lat = comp[0]; + out->lon = comp[1]; + if (ncomp >= 3) { out->has_alt = 1; out->alt = comp[2]; out->alt_below = comp[2] < 0; } + snprintf(out->datum, sizeof out->datum, "WGS-84 (ISO 6709 default)"); + out->has_datum = 1; + return 1; +} + +/* ---- TIFF / EXIF GPS IFD (CIPA DC-008, EXIF 2.32) ---- */ +/* TIFF field type sizes, indexed by type 1..13 (0 = invalid). */ +static const uint32_t tiff_type_size[14] = + { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4 }; + +/* Value bytes for one IFD entry, or NULL if out of bounds. + * Values of total size <= 4 live inline at e+8, else at the offset in e+8 + * (relative to the start of the TIFF header). */ +static const uint8_t *tiff_entry_val(const uint8_t *t, size_t len, int be, + const uint8_t *e, uint16_t type, + uint32_t count, uint32_t *nbytes) { + if (type == 0 || type > 13) return NULL; + uint64_t need = (uint64_t)count * tiff_type_size[type]; + if (need > 0x7fffffffu) return NULL; + *nbytes = (uint32_t)need; + if (need <= 4) return e + 8; + uint32_t off = g32(e + 8, be); + if ((uint64_t)off + need > len) return NULL; + return t + off; +} + +static double tiff_rational(const uint8_t *p, int be) { + uint32_t num = g32(p, be), den = g32(p + 4, be); + return den ? (double)num / (double)den : 0.0; +} + +/* Find one entry in the IFD at ifd_off; on success *val points at its value + * bytes, *type / *count describe it. */ +static int tiff_ifd_find(const uint8_t *t, size_t len, int be, uint32_t ifd_off, + uint16_t want, const uint8_t **val, uint16_t *type, + uint32_t *count) { + if (ifd_off + 2 > len) return 0; + uint16_t n = g16(t + ifd_off, be); + if (ifd_off + 2 + (uint32_t)n * 12 > len) return 0; + for (uint16_t i = 0; i < n; i++) { + const uint8_t *e = t + ifd_off + 2 + (size_t)i * 12; + if (g16(e, be) != want) continue; + uint16_t ty = g16(e + 2, be); + uint32_t cn = g32(e + 4, be); + uint32_t nb = 0; + const uint8_t *v = tiff_entry_val(t, len, be, e, ty, cn, &nb); + if (!v) return 0; + *val = v; *type = ty; *count = cn; + return 1; + } + return 0; +} + +static double tiff_dms(const uint8_t *v, int be) { + return tiff_rational(v, be) + tiff_rational(v + 8, be) / 60.0 + + tiff_rational(v + 16, be) / 3600.0; +} + +/* Parse the GPS IFD inside TIFF data t[0..len). Returns 1 if a latitude + * and longitude were recovered. */ +/* Forward: the GPS IFD body, defined just below the wrapper. */ +static int parse_tiff_gps_ifd(const uint8_t *t, size_t len, int be, + uint32_t gps_off, const char *source, + GeoResult *out); + +static int parse_tiff_gps(const uint8_t *t, size_t len, const char *source, + GeoResult *out) { + if (len < 8) return 0; + int be; + if (t[0] == 'I' && t[1] == 'I') be = 0; + else if (t[0] == 'M' && t[1] == 'M') be = 1; + else return 0; + if (g16(t + 2, be) != 42) return 0; + uint32_t ifd0 = g32(t + 4, be); + const uint8_t *v = NULL; + uint16_t ty = 0; + uint32_t cn = 0; + /* IFD0 tag 0x8825 GPSInfo: LONG offset of the GPS IFD. */ + if (!tiff_ifd_find(t, len, be, ifd0, 0x8825, &v, &ty, &cn)) return 0; + if (ty != 4 || cn != 1) return 0; + uint32_t gps_off = g32(v, be); + return parse_tiff_gps_ifd(t, len, be, gps_off, source, out); +} + +/* Parse the GPS IFD at gps_off inside TIFF data t[0..len). */ +static int parse_tiff_gps_ifd(const uint8_t *t, size_t len, int be, + uint32_t gps_off, const char *source, + GeoResult *out) { + const uint8_t *v = NULL; + uint16_t ty = 0; + uint32_t cn = 0; + + memset(out, 0, sizeof *out); + char lat_ref = 'N', lon_ref = 'E'; + int have_lat = 0, have_lon = 0; + double lat = 0, lon = 0; + char date[16] = "", time[16] = ""; + + if (tiff_ifd_find(t, len, be, gps_off, 0x0001, &v, &ty, &cn) && cn >= 1) + lat_ref = (char)v[0]; + if (tiff_ifd_find(t, len, be, gps_off, 0x0002, &v, &ty, &cn) && + ty == 5 && cn == 3) { lat = tiff_dms(v, be); have_lat = 1; } + if (tiff_ifd_find(t, len, be, gps_off, 0x0003, &v, &ty, &cn) && cn >= 1) + lon_ref = (char)v[0]; + if (tiff_ifd_find(t, len, be, gps_off, 0x0004, &v, &ty, &cn) && + ty == 5 && cn == 3) { lon = tiff_dms(v, be); have_lon = 1; } + if (!have_lat || !have_lon) return 0; + + out->lat = (lat_ref == 'S' || lat_ref == 's') ? -lat : lat; + out->lon = (lon_ref == 'W' || lon_ref == 'w') ? -lon : lon; + + if (tiff_ifd_find(t, len, be, gps_off, 0x0005, &v, &ty, &cn) && cn >= 1) + out->alt_below = (v[0] == 1); + if (tiff_ifd_find(t, len, be, gps_off, 0x0006, &v, &ty, &cn) && + ty == 5 && cn == 1) { + out->has_alt = 1; + out->alt = tiff_rational(v, be); + if (out->alt_below) out->alt = -out->alt; + } + if (tiff_ifd_find(t, len, be, gps_off, 0x0007, &v, &ty, &cn) && + ty == 5 && cn == 3) + snprintf(time, sizeof time, "%02d:%02d:%02d", + (int)tiff_rational(v, be), (int)tiff_rational(v + 8, be), + (int)tiff_rational(v + 16, be)); + if (tiff_ifd_find(t, len, be, gps_off, 0x0012, &v, &ty, &cn) && cn >= 1) { + size_t m = cn < sizeof out->datum - 1 ? cn : sizeof out->datum - 1; + while (m > 0 && (v[m - 1] == 0 || v[m - 1] == ' ')) m--; + memcpy(out->datum, v, m); + out->datum[m] = 0; + out->has_datum = 1; + } + if (tiff_ifd_find(t, len, be, gps_off, 0x001D, &v, &ty, &cn) && cn >= 10) + memcpy(date, v, 10); + /* EXIF stores the date as YYYY:MM:DD; normalise to ISO YYYY-MM-DD so + the field is machine-parseable (the documented stable output form). */ + if (date[0] && time[0]) + snprintf(out->datetime, sizeof out->datetime, "%.4s-%.2s-%.2s %s", + date, date + 5, date + 8, time); + else if (date[0]) + snprintf(out->datetime, sizeof out->datetime, "%.4s-%.2s-%.2s", + date, date + 5, date + 8); + else if (time[0]) + snprintf(out->datetime, sizeof out->datetime, "%s", time); + if (out->datetime[0]) out->has_datetime = 1; + + out->found = 1; + snprintf(out->source, sizeof out->source, "%s", source); + return 1; +} + +/* Parse a TIFF structure whose FIRST IFD is itself the GPS IFD + * (Canon CR3 CMT4 box: a complete TIFF header holding the GPS IFD). */ +static int parse_tiff_gps_direct(const uint8_t *t, size_t len, + const char *source, GeoResult *out) { + if (len < 8) return 0; + int be; + if (t[0] == 'I' && t[1] == 'I') be = 0; + else if (t[0] == 'M' && t[1] == 'M') be = 1; + else return 0; + if (g16(t + 2, be) != 42) return 0; + return parse_tiff_gps_ifd(t, len, be, g32(t + 4, be), source, out); +} + + +/* ---- XMP (ISO 16684-1): exif:GPSLatitude/Longitude/Altitude ---- */ +/* Extract the value of one XMP property: attribute form + * exif:GPSLatitude="37,46,29.64N" + * or element form 37,46,29.64N. + * Returns 1 on success. */ +static int xmp_prop(const uint8_t *x, size_t len, const char *name, + char *out, size_t out_n) { + size_t nlen = strlen(name); + for (size_t i = 0; i + nlen <= len; i++) { + if (memcmp(x + i, name, nlen) != 0) continue; + size_t j = i + nlen; + /* attribute form: = "..." (possibly with whitespace) */ + size_t k = j; + while (k < len && (x[k] == ' ' || x[k] == '\t' || x[k] == '\n' || + x[k] == '\r')) k++; + if (k < len && x[k] == '=') { + k++; + while (k < len && (x[k] == ' ' || x[k] == '\t')) k++; + if (k < len && (x[k] == '"' || x[k] == '\'')) { + char q = (char)x[k++]; + size_t m = 0; + while (k < len && x[k] != q && m + 1 < out_n) out[m++] = (char)x[k++]; + out[m] = 0; + return m > 0; + } + } + /* element form: >value< */ + if (k < len && x[k] == '>') { + k++; + size_t m = 0; + while (k < len && x[k] != '<' && m + 1 < out_n) out[m++] = (char)x[k++]; + out[m] = 0; + return m > 0; + } + } + return 0; +} + +/* Parse one XMP GPS coordinate value. ExifTool and the XMP spec write + * "DD,MM,SSk" (degrees, minutes, seconds + hemisphere) or the shorter + * "DD,MM.mmmH" (degrees, decimal minutes + hemisphere); a bare decimal + * "DD.DDDD[k]" is also accepted. The hemisphere letter rides on the + * LAST component present, so it is stripped there. */ +static int xmp_coord(const char *s, double *out) { + while (*s && isspace((unsigned char)*s)) s++; + if (strchr(s, ',')) { + char buf[64]; + char *toks[3] = { NULL, NULL, NULL }; + int ntok = 0; + char hemi = 0; + snprintf(buf, sizeof buf, "%s", s); + char *save = NULL; + for (char *tok = strtok_r(buf, ",", &save); + tok && ntok < 3; tok = strtok_r(NULL, ",", &save)) + toks[ntok++] = tok; + if (ntok == 0) return 0; + char *last = toks[ntok - 1]; + size_t L = strlen(last); + if (L > 0 && isalpha((unsigned char)last[L - 1])) { + hemi = last[L - 1]; + last[L - 1] = 0; + } + double d = strtod(toks[0], NULL); + double m = ntok > 1 ? strtod(toks[1], NULL) : 0.0; + double sec = ntok > 2 ? strtod(toks[2], NULL) : 0.0; + double v = d + m / 60.0 + sec / 3600.0; + if (hemi == 'S' || hemi == 's' || hemi == 'W' || hemi == 'w') v = -v; + *out = v; + return 1; + } + /* decimal degrees, optional trailing hemisphere letter */ + char buf[64]; + snprintf(buf, sizeof buf, "%s", s); + size_t L = strlen(buf); + char hemi = 0; + if (L > 0 && isalpha((unsigned char)buf[L - 1])) { + hemi = buf[L - 1]; + buf[L - 1] = 0; + } + char *end = NULL; + double v = strtod(buf, &end); + if (end == buf) return 0; + if (hemi == 'S' || hemi == 's' || hemi == 'W' || hemi == 'w') v = -v; + *out = v; + return 1; +} + + +static int parse_xmp_gps(const uint8_t *x, size_t len, const char *source, + GeoResult *out) { + char lat_s[64], lon_s[64], alt_s[64]; + double lat, lon; + if (!xmp_prop(x, len, "GPSLatitude", lat_s, sizeof lat_s)) return 0; + if (!xmp_prop(x, len, "GPSLongitude", lon_s, sizeof lon_s)) return 0; + if (!xmp_coord(lat_s, &lat)) return 0; + if (!xmp_coord(lon_s, &lon)) return 0; + if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) return 0; + memset(out, 0, sizeof *out); + out->found = 1; + snprintf(out->source, sizeof out->source, "%s", source); + out->lat = lat; + out->lon = lon; + if (xmp_prop(x, len, "GPSAltitude", alt_s, sizeof alt_s)) { + char *slash = strchr(alt_s, '/'); + double a; + if (slash) { + double num = strtod(alt_s, NULL), den = strtod(slash + 1, NULL); + a = den ? num / den : 0.0; + } else { + a = strtod(alt_s, NULL); + } + out->has_alt = 1; + out->alt = a; + out->alt_below = a < 0; + } + return 1; +} + +/* ---- JPEG: marker scan, APP1 Exif + APP1 XMP ---- */ +static void geotag_jpeg(const uint8_t *b, size_t n) { + static const char xmp_hdr[] = "http://ns.adobe.com/xap/1.0/"; + if (n < 4 || b[0] != 0xFF || b[1] != 0xD8) return; + size_t pos = 2; + GeoResult g; + while (pos + 4 <= n) { + if (b[pos] != 0xFF) break; + uint8_t m = b[pos + 1]; + /* standalone markers: no length field */ + if (m == 0x01 || m == 0xD8 || (m >= 0xD0 && m <= 0xD7)) { pos += 2; continue; } + if (m == 0xDA || m == 0xD9) break; /* SOS / EOI: pixels follow */ + uint16_t slen = (uint16_t)((b[pos + 2] << 8) | b[pos + 3]); + if (slen < 2) break; + size_t seg = pos + 4, seglen = slen - 2; + if (seg + seglen > n) break; + if (m == 0xE1) { /* APP1 */ + if (seglen >= 6 && memcmp(b + seg, "Exif\0\0", 6) == 0) { + if (parse_tiff_gps(b + seg + 6, seglen - 6, + "EXIF GPS IFD (JPEG APP1 segment)", &g)) + add_result(&g); + } else if (seglen > sizeof xmp_hdr && + memcmp(b + seg, xmp_hdr, sizeof xmp_hdr - 1) == 0 && + b[seg + sizeof xmp_hdr - 1] == 0) { + size_t xoff = seg + sizeof xmp_hdr; + if (parse_xmp_gps(b + xoff, seglen - sizeof xmp_hdr, + "XMP packet (JPEG APP1 segment)", &g)) + add_result(&g); + } + } + pos = seg + seglen; + } +} + +/* ---- TIFF: the file IS a TIFF header ---- */ +static void geotag_tiff(const uint8_t *b, size_t n) { + GeoResult g; + if (parse_tiff_gps(b, n, "EXIF GPS IFD (TIFF IFD0)", &g)) add_result(&g); +} + +/* ---- PNG: chunk walk, eXIf + iTXt/tEXt XMP ---- */ +static void geotag_png(const uint8_t *b, size_t n) { + static const uint8_t sig[8] = { 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A }; + if (n < 8 || memcmp(b, sig, 8) != 0) return; + size_t pos = 8; + GeoResult g; + while (pos + 8 <= n) { + uint32_t clen = g32(b + pos, 1); + const uint8_t *type = b + pos + 4; + size_t data = pos + 8; + if (data + clen + 4 > n) break; + if (memcmp(type, "eXIf", 4) == 0) { + if (parse_tiff_gps(b + data, clen, "EXIF GPS IFD (PNG eXIf chunk)", &g)) + add_result(&g); + } else if (memcmp(type, "iTXt", 4) == 0 || memcmp(type, "tEXt", 4) == 0) { + /* keyword NUL ... : XMP lives under "XML:com.adobe.xmp" */ + const uint8_t *kw_end = memchr(b + data, 0, clen); + if (kw_end && (size_t)(kw_end - (b + data)) == 17 && + memcmp(b + data, "XML:com.adobe.xmp", 17) == 0) { + const uint8_t *p = kw_end + 1; + if (memcmp(type, "iTXt", 4) == 0) { + /* comp flag, comp method, language NUL, translated NUL */ + if (p + 2 > b + data + clen) { /* malformed */ } + else { + p += 2; + const uint8_t *l = memchr(p, 0, (b + data + clen) - p); + if (l) p = l + 1; + const uint8_t *t2 = memchr(p, 0, (b + data + clen) - p); + if (t2) p = t2 + 1; + if (p < b + data + clen && + parse_xmp_gps(p, (b + data + clen) - p, + "XMP packet (PNG iTXt chunk)", &g)) + add_result(&g); + } + } else if (p < b + data + clen && + parse_xmp_gps(p, (b + data + clen) - p, + "XMP packet (PNG tEXt chunk)", &g)) { + add_result(&g); + } + } + } + if (memcmp(type, "IEND", 4) == 0) break; + pos = data + clen + 4; + } +} + +/* ---- WebP (RFC 9649): RIFF chunk walk, EXIF + XMP chunks ---- */ +static void geotag_webp(const uint8_t *b, size_t n) { + if (n < 12 || memcmp(b, "RIFF", 4) != 0 || memcmp(b + 8, "WEBP", 4) != 0) + return; + size_t pos = 12; + GeoResult g; + while (pos + 8 <= n) { + const uint8_t *type = b + pos; + uint32_t clen = g32(b + pos + 4, 0); + size_t data = pos + 8; + if (data + clen > n) break; + if (memcmp(type, "EXIF", 4) == 0) { + if (parse_tiff_gps(b + data, clen, "EXIF GPS IFD (WebP EXIF chunk)", &g)) + add_result(&g); + } else if (memcmp(type, "XMP ", 4) == 0) { + if (parse_xmp_gps(b + data, clen, "XMP packet (WebP XMP chunk)", &g)) + add_result(&g); + } + pos = data + clen + (clen & 1); /* RIFF chunks are word-aligned */ + } +} + +/* ---- ISO base media file format (HEIC/HEIF/AVIF/MP4/MOV) ---- */ +typedef struct { + uint64_t size; /* total box size including header */ + char type[5]; /* 4-char box type, NUL-terminated */ + uint64_t hdr; /* header length (8, or 16 with largesize) */ + uint64_t start; /* file offset of the box */ +} Box; + +/* Read a box header at pos within [0, end). Returns 0 at EOF/error. */ +static int read_box(FILE *fp, uint64_t pos, uint64_t end, Box *b) { + uint8_t h[16]; + if (pos + 8 > end) return 0; + if (fseeko(fp, (off_t)pos, SEEK_SET) != 0) return 0; + if (fread(h, 1, 8, fp) != 8) return 0; + uint64_t size = g32(h, 1); + memcpy(b->type, h + 4, 4); + b->type[4] = 0; + b->start = pos; + b->hdr = 8; + if (size == 1) { /* largesize */ + if (pos + 16 > end) return 0; + if (fread(h, 1, 8, fp) != 8) return 0; + size = ((uint64_t)g32(h, 1) << 32) | g32(h + 4, 1); + b->hdr = 16; + } else if (size == 0) { /* to end of parent */ + size = end - pos; + } + if (size < b->hdr) return 0; + b->size = size; + return 1; +} + +/* --- HEIF/AVIF: find the "Exif" item via iinf, locate it via iloc --- */ +/* iinf payload (after size+type): version/flags, entry count, infe boxes. + * infe v2+: version/flags, item_ID u16, protection u16, item_type[4], name. */ +static int iinf_exif_id(const uint8_t *d, size_t len, uint16_t *out_id) { + if (len < 6) return 0; + uint8_t ver = d[0]; + uint32_t count = (ver == 0) ? g16(d + 4, 1) : g32(d + 4, 1); + size_t pos = (ver == 0) ? 6 : 8; + for (uint32_t i = 0; i < count && pos + 8 <= len; i++) { + uint32_t sz = g32(d + pos, 1); + if (sz < 8 || pos + sz > len) return 0; + if (memcmp(d + pos + 4, "infe", 4) == 0 && sz >= 16) { + const uint8_t *e = d + pos + 8; + uint8_t ever = e[0]; + uint16_t id = g16(e + 4, 1); + if (ever >= 2) { + if (memcmp(e + 8, "Exif", 4) == 0) { *out_id = id; return 1; } + } else { + /* v0/1 infe has no item_type; match the item name */ + if (memcmp(e + 8, "Exif", 4) == 0) { *out_id = id; return 1; } + } + } + pos += sz; + } + return 0; +} + +/* iinf scan for an XMP mime item (ISO/IEC 23008-12 HEIF). + * infe v2+: version/flags, item_ID u16, protection u16, item_type[4], + * item_name NUL, content_type NUL, content_encoding NUL. Real HEIC + * files carry the MIME type in content_type (item_name is often + * empty); older writers put it in item_name. Match either. + * infe v0/1 has no item_type: match item_name directly. */ +static int iinf_mime_xmp_id(const uint8_t *d, size_t len, uint16_t *out_id) { + if (len < 6) return 0; + uint8_t ver = d[0]; + uint32_t count = (ver == 0) ? g16(d + 4, 1) : g32(d + 4, 1); + size_t pos = (ver == 0) ? 6 : 8; + for (uint32_t i = 0; i < count && pos + 8 <= len; i++) { + uint32_t sz = g32(d + pos, 1); + if (sz < 8 || pos + sz > len) return 0; + if (memcmp(d + pos + 4, "infe", 4) == 0 && sz >= 16) { + const uint8_t *e = d + pos + 8; + const uint8_t *end = d + pos + sz; + if (e[0] < 2) { + /* v0/1: item_ID u16, protection u16, item_name NUL */ + const uint8_t *nm = e + 8; + if (nm + 19 <= end && memcmp(nm, "application/rdf+xml", 19) == 0) { + *out_id = g16(e + 4, 1); + return 1; + } + } else if (sz >= 24 && memcmp(e + 8, "mime", 4) == 0) { + /* v2+: item_name then content_type, both NUL-terminated */ + const uint8_t *f = e + 12; + for (int field = 0; field < 2 && f < end; field++) { + const uint8_t *z = memchr(f, 0, (size_t)(end - f)); + if (!z) break; + if ((size_t)(z - f) == 19 && + memcmp(f, "application/rdf+xml", 19) == 0) { + *out_id = g16(e + 4, 1); + return 1; + } + f = z + 1; + } + } + } + pos += sz; + } + return 0; +} + + +/* iloc payload: version/flags, offset_size|length_size, + * base_offset_size|index_size, item_count, per-item extents. + * Returns the first extent (offset, length) of item_id. */ +static int iloc_extent(const uint8_t *d, size_t len, uint16_t item_id, + uint64_t *off, uint64_t *ln) { + if (len < 6) return 0; + uint8_t ver = d[0]; + int off_sz = (d[4] >> 4) & 0xF, len_sz = d[4] & 0xF; + int base_sz = (d[5] >> 4) & 0xF, idx_sz = d[5] & 0xF; + size_t pos = 6; + uint32_t count = (ver < 2) ? g16(d + pos, 1) : g32(d + pos, 1); + pos += (ver < 2) ? 2 : 4; + for (uint32_t i = 0; i < count; i++) { + uint32_t id = (ver < 2) ? g16(d + pos, 1) : g32(d + pos, 1); + pos += (ver < 2) ? 2 : 4; + if (pos + 2 > len) return 0; + pos += 2; /* data_reference_index */ + uint64_t base = 0; + for (int k = 0; k < base_sz; k++) { + if (pos >= len) return 0; + base = (base << 8) | d[pos++]; + } + if (pos + 2 > len) return 0; + uint16_t ecnt = g16(d + pos, 1); + pos += 2; + for (uint16_t e = 0; e < ecnt; e++) { + pos += idx_sz; /* extent_index (v1+, usually 0) */ + uint64_t eo = 0, el = 0; + for (int k = 0; k < off_sz; k++) { + if (pos >= len) return 0; + eo = (eo << 8) | d[pos++]; + } + for (int k = 0; k < len_sz; k++) { + if (pos >= len) return 0; + el = (el << 8) | d[pos++]; + } + if (id == item_id) { *off = base + eo; *ln = el; return 1; } + } + } + return 0; +} + +static void geotag_heic(FILE *fp, uint64_t fsize) { + uint64_t pos = 0; + Box b; + const uint8_t *iinf = NULL, *iloc = NULL; + size_t iinf_len = 0, iloc_len = 0; + uint8_t *meta = NULL; + size_t meta_len = 0; + while (read_box(fp, pos, fsize, &b)) { + if (strcmp(b.type, "meta") == 0 && b.size > b.hdr + 4) { + free(meta); + meta = read_range(fp, b.start + b.hdr, b.size - b.hdr); + meta_len = meta ? (size_t)(b.size - b.hdr) : 0; + if (meta && meta_len > 4) { + size_t p = 4; /* skip version/flags */ + while (p + 8 <= meta_len) { + uint32_t sz = g32(meta + p, 1); + if (sz < 8 || p + sz > meta_len) break; + if (memcmp(meta + p + 4, "iinf", 4) == 0) { + iinf = meta + p + 8; iinf_len = sz - 8; + } else if (memcmp(meta + p + 4, "iloc", 4) == 0) { + iloc = meta + p + 8; iloc_len = sz - 8; + } + p += sz; + } + } + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= fsize) break; + } + GeoResult g; + uint16_t exif_id = 0; + uint64_t ex_off = 0, ex_len = 0; + int have_exif = 0; + if (iinf && iloc && iinf_exif_id(iinf, iinf_len, &exif_id) && + iloc_extent(iloc, iloc_len, exif_id, &ex_off, &ex_len)) { + uint8_t *ex = read_range(fp, ex_off, ex_len); + if (ex) { + if (parse_tiff_gps(ex, (size_t)ex_len, + "EXIF GPS IFD (HEIF meta Exif item)", &g)) { + add_result(&g); + have_exif = 1; + } + free(ex); + } + } + /* XMP as a mime item (ISO/IEC 23008-12): infe item_type "mime", + * item_name "application/rdf+xml", located via iloc. */ + uint16_t xmp_id = 0; + uint64_t x_off = 0, x_len = 0; + if (iinf && iloc && iinf_mime_xmp_id(iinf, iinf_len, &xmp_id) && + iloc_extent(iloc, iloc_len, xmp_id, &x_off, &x_len)) { + uint8_t *xp = read_range(fp, x_off, x_len); + if (xp) { + if (parse_xmp_gps(xp, (size_t)x_len, + "XMP packet (HEIF meta mime item)", &g)) + add_result(&g); + free(xp); + } + } + + free(meta); + if (have_exif) return; + + /* Fallback: scan the head of the file for an Exif TIFF header + * (covers writers that omit a usable iloc, e.g. an Exif item in + * mdat without item tables). The TIFF magic after the prefix + * validates the hit. */ + size_t n = 0; + uint8_t *buf = NULL; + if (fseeko(fp, 0, SEEK_SET) == 0) { + buf = malloc(GEO_SCAN_CAP); + if (buf) n = fread(buf, 1, GEO_SCAN_CAP, fp); + } + if (buf) { + static const uint8_t exif_hdr[6] = { 'E', 'x', 'i', 'f', 0, 0 }; + const uint8_t *hit = buf; + while ((hit = memmem(hit, n - (size_t)(hit - buf), + exif_hdr, 6)) != NULL) { + const uint8_t *t = hit + 6; + size_t trem = n - (size_t)(t - buf); + if (trem >= 8 && ((t[0] == 'I' && t[1] == 'I') || + (t[0] == 'M' && t[1] == 'M'))) { + if (parse_tiff_gps(t, trem, + "EXIF GPS IFD (HEIF meta Exif item)", &g)) { + add_result(&g); + break; + } + } + hit += 6; + } + free(buf); + } +} + +/* --- MP4/MOV: moov/udta (c)xyz + XMP_, moov/meta keys+ilst --- */ +static void parse_qt_meta(FILE *fp, uint64_t start, uint64_t end, + const char *src) { + if (end <= start || end - start > GEO_PAYLOAD_CAP) return; + uint8_t *m = read_range(fp, start, end - start); + if (!m) return; + size_t len = (size_t)(end - start); + const uint8_t *keys_blob = NULL, *ilst_blob = NULL; + size_t keys_len = 0, ilst_len = 0; + size_t p = 4; /* skip version/flags */ + while (p + 8 <= len) { + uint32_t sz = g32(m + p, 1); + if (sz < 8 || p + sz > len) break; + if (memcmp(m + p + 4, "keys", 4) == 0) { + keys_blob = m + p + 8; keys_len = sz - 8; + } else if (memcmp(m + p + 4, "ilst", 4) == 0) { + ilst_blob = m + p + 8; ilst_len = sz - 8; + } + p += sz; + } + if (!keys_blob || !ilst_blob || keys_len < 8) { free(m); return; } + /* keys: version/flags(4), entry_count u32; entries: size, "mdta", key */ + char keymap[64][64]; + int nkey = 0; + uint32_t kc = g32(keys_blob + 4, 1); + size_t kp = 8; + for (uint32_t i = 0; i < kc && kp + 8 <= keys_len && nkey < 64; i++) { + uint32_t esz = g32(keys_blob + kp, 1); + if (esz < 8 || kp + esz > keys_len) break; + size_t kl = esz - 8; + if (kl > 63) kl = 63; + memcpy(keymap[nkey], keys_blob + kp + 8, kl); + keymap[nkey][kl] = 0; + nkey++; + kp += esz; + } + /* ilst children: size(4), key index u32, then data atom(s) */ + size_t ip = 0; + GeoResult g; + while (ip + 8 <= ilst_len) { + uint32_t sz = g32(ilst_blob + ip, 1); + uint32_t idx = g32(ilst_blob + ip + 4, 1); + if (sz < 8 || ip + sz > ilst_len) break; + if (idx >= 1 && idx <= (uint32_t)nkey && + strcmp(keymap[idx - 1], "com.apple.quicktime.location.ISO6709") == 0) { + size_t dp = ip + 8; + while (dp + 8 <= ip + sz) { + uint32_t dsz = g32(ilst_blob + dp, 1); + if (dsz < 8 || dp + dsz > ip + sz) break; + if (memcmp(ilst_blob + dp + 4, "data", 4) == 0 && dsz >= 16) { + const char *val = (const char *)ilst_blob + dp + 16; + size_t vlen = dsz - 16; + char tmp[256]; + size_t tl = vlen < sizeof tmp - 1 ? vlen : sizeof tmp - 1; + memcpy(tmp, val, tl); + tmp[tl] = 0; + if (parse_iso6709(tmp, src, &g)) + add_result(&g); + break; + } + dp += dsz; + } + } + ip += sz; + } + free(m); +} + +/* Try to parse an ISO 6709 string out of a (c)xyz payload, tolerating + * the QuickTime user-data text layout [u16 size][u16 language]text as + * well as a bare string or a lone 2-byte length prefix. */ +static int parse_xyz_payload(const uint8_t *v, size_t plen, GeoResult *out) { + char tmp[256]; + size_t tl; + tl = plen < sizeof tmp - 1 ? plen : sizeof tmp - 1; + memcpy(tmp, v, tl); + tmp[tl] = 0; + if (parse_iso6709(tmp, "QuickTime location (moov/udta (c)xyz atom)", out)) + return 1; + if (plen >= 4) { + uint16_t L = (uint16_t)((v[0] << 8) | v[1]); + if (L == plen - 4) { + tl = plen - 4 < sizeof tmp - 1 ? plen - 4 : sizeof tmp - 1; + memcpy(tmp, v + 4, tl); + tmp[tl] = 0; + if (parse_iso6709(tmp, "QuickTime location (moov/udta (c)xyz atom)", out)) + return 1; + } + } + if (plen >= 2) { + uint16_t L = (uint16_t)((v[0] << 8) | v[1]); + if (L == plen - 2) { + tl = plen - 2 < sizeof tmp - 1 ? plen - 2 : sizeof tmp - 1; + memcpy(tmp, v + 2, tl); + tmp[tl] = 0; + if (parse_iso6709(tmp, "QuickTime location (moov/udta (c)xyz atom)", out)) + return 1; + } + } + return 0; +} + + +static void walk_udta(FILE *fp, uint64_t start, uint64_t end) { + uint64_t pos = start; + Box b; + GeoResult g; + while (read_box(fp, pos, end, &b)) { + uint64_t payload = b.start + b.hdr; + uint64_t plen = b.size - b.hdr; + if (memcmp(b.type, "\xa9xyz", 4) == 0 && plen > 0 && plen < 512) { + uint8_t *v = read_range(fp, payload, plen); + if (v) { + if (parse_xyz_payload(v, (size_t)plen, &g)) add_result(&g); + free(v); + } + } else if (memcmp(b.type, "loci", 4) == 0 && plen > 0) { + /* 3GPP TS 26.244 table 8.10: FullBox; language u16, name + * NUL-terminated, role u8, longitude/latitude/altitude as + * signed 32-bit 16.16 fixed-point degrees/metres. Out of + * range means unspecified. */ + uint8_t *v = read_range(fp, payload, plen); + if (v) { + size_t q = 4; /* version/flags */ + if (plen > q + 2) { + q += 2; /* language */ + size_t name_end = plen; + if (q + 2 <= plen && ((v[q] == 0xFF && v[q + 1] == 0xFE) || + (v[q] == 0xFE && v[q + 1] == 0xFF))) { + /* UTF-16 name: scan for a double-NUL terminator */ + for (size_t k = q; k + 1 < plen; k += 2) { + if (v[k] == 0 && v[k + 1] == 0) { name_end = k; break; } + } + } else { + const uint8_t *nm = memchr(v + q, 0, plen - q); + if (nm) name_end = (size_t)(nm - v); + } + q = name_end + ((name_end < plen && v[name_end] == 0) ? 1 : 0); + if (q + 13 <= plen) { + q += 1; /* role */ + int32_t lon_f = (int32_t)g32(v + q, 1); q += 4; + int32_t lat_f = (int32_t)g32(v + q, 1); q += 4; + int32_t alt_f = (int32_t)g32(v + q, 1); + double lon = lon_f / 65536.0, lat = lat_f / 65536.0; + if (lon >= -180.0 && lon <= 180.0 && + lat >= -90.0 && lat <= 90.0) { + memset(&g, 0, sizeof g); + g.found = 1; + snprintf(g.source, sizeof g.source, + "3GPP location (moov/udta loci box)"); + g.lat = lat; + g.lon = lon; + g.has_alt = 1; + g.alt = alt_f / 65536.0; + g.alt_below = g.alt < 0; + snprintf(g.datum, sizeof g.datum, + "WGS-84 (3GPP TS 26.244)"); + g.has_datum = 1; + add_result(&g); + } + } + } + free(v); + } + + } else if (memcmp(b.type, "XMP_", 4) == 0 && plen > 0) { + uint8_t *v = read_range(fp, payload, plen); + if (v) { + if (parse_xmp_gps(v, (size_t)plen, + "XMP packet (MP4/MOV udta XMP_ box)", &g)) + add_result(&g); + free(v); + } + } else if (strcmp(b.type, "meta") == 0) { + parse_qt_meta(fp, payload, b.start + b.size, + "QuickTime location (moov/udta/meta com.apple.quicktime.location.ISO6709)"); + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= end) break; + } +} + +static void walk_moov(FILE *fp, uint64_t start, uint64_t end) { + uint64_t pos = start; + Box b; + while (read_box(fp, pos, end, &b)) { + if (strcmp(b.type, "udta") == 0) + walk_udta(fp, b.start + b.hdr, b.start + b.size); + else if (strcmp(b.type, "meta") == 0) + parse_qt_meta(fp, b.start + b.hdr, b.start + b.size, + "QuickTime location (moov/meta com.apple.quicktime.location.ISO6709)"); + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= end) break; + } +} + +static void geotag_mp4(FILE *fp, uint64_t fsize) { + static const uint8_t xmp_uuid[16] = { + 0xBE, 0x7A, 0xCF, 0xCB, 0x97, 0xA9, 0x42, 0xE8, + 0x9C, 0x71, 0x99, 0x94, 0x91, 0xE3, 0xAF, 0xAC }; + uint64_t pos = 0; + Box b; + GeoResult g; + while (read_box(fp, pos, fsize, &b)) { + if (strcmp(b.type, "moov") == 0) + walk_moov(fp, b.start + b.hdr, b.start + b.size); + else if (strcmp(b.type, "uuid") == 0 && b.size - b.hdr > 16) { + /* XMP packet in a top-level uuid box (the layout exiftool + * writes for MP4); UUID then the raw packet. */ + uint8_t *v = read_range(fp, b.start + b.hdr, b.size - b.hdr); + if (v) { + if (memcmp(v, xmp_uuid, 16) == 0 && + parse_xmp_gps(v + 16, (size_t)(b.size - b.hdr - 16), + "XMP packet (MP4/MOV uuid box)", &g)) + add_result(&g); + free(v); + } + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= fsize) break; + } +} + +/* ---- GeoTIFF: tiepoint / transformation + GeoKey directory ---- */ +/* IFD0 tags: 33550 ModelPixelScaleTag (DOUBLE[3]), 33922 ModelTiepointTag + * (DOUBLE[6] per tiepoint: I,J,K,X,Y,Z), 34264 ModelTransformationTag + * (DOUBLE[16] row-major), 34735 GeoKeyDirectoryTag (SHORT[]). GeoKeys: + * 1024 GTModelType (1 projected, 2 geographic), 2048 GeographicType + * GeoKey (4326 = WGS 84). The tiepoint's model X/Y are lon/lat when the + * model CRS is geographic; datum defaults to WGS-84 when no key says + * otherwise. */ +static double g_f64(const uint8_t *p, int be) { + uint64_t u = 0; + if (be) { for (int i = 0; i < 8; i++) u = (u << 8) | p[i]; } + else { for (int i = 7; i >= 0; i--) u = (u << 8) | p[i]; } + double d; + memcpy(&d, &u, 8); + return d; +} + +static int parse_geotiff(const uint8_t *t, size_t len, GeoResult *out) { + if (len < 8) return 0; + int be; + if (t[0] == 'I' && t[1] == 'I') be = 0; + else if (t[0] == 'M' && t[1] == 'M') be = 1; + else return 0; + if (g16(t + 2, be) != 42) return 0; + uint32_t ifd0 = g32(t + 4, be); + const uint8_t *v = NULL; + uint16_t ty = 0; + uint32_t cn = 0; + int geo_key = 4326; /* default: WGS-84 */ + if (tiff_ifd_find(t, len, be, ifd0, 34735, &v, &ty, &cn) && + ty == 3 && cn >= 4) { + uint16_t nkeys = g16(v + 6, be); + for (uint16_t i = 0; i < nkeys; i++) { + const uint8_t *e = v + 8 + (size_t)i * 8; + if (e + 8 > v + (size_t)cn * 2) break; + uint16_t key = g16(e, be), loc = g16(e + 2, be); + uint16_t cnt = g16(e + 4, be), val = g16(e + 6, be); + if (key == 2048 && loc == 0 && cnt == 1) geo_key = val; + } + } + if (geo_key != 4326) return 0; /* only WGS-84 lon/lat supported */ + double lon = 0, lat = 0; + const char *src = NULL; + if (tiff_ifd_find(t, len, be, ifd0, 33922, &v, &ty, &cn) && + ty == 12 && cn >= 6) { + lon = g_f64(v + 24, be); /* first tiepoint: X, Y */ + lat = g_f64(v + 32, be); + src = "GeoTIFF tiepoint (TIFF IFD0)"; + } else if (tiff_ifd_find(t, len, be, ifd0, 34264, &v, &ty, &cn) && + ty == 12 && cn >= 16) { + lon = g_f64(v + 24, be); /* matrix origin: m[3], m[7] */ + lat = g_f64(v + 56, be); + src = "GeoTIFF transformation (TIFF IFD0)"; + } + if (!src) return 0; + if (lon < -180.0 || lon > 180.0 || lat < -90.0 || lat > 90.0) return 0; + memset(out, 0, sizeof *out); + out->found = 1; + snprintf(out->source, sizeof out->source, "%s", src); + out->lat = lat; + out->lon = lon; + snprintf(out->datum, sizeof out->datum, "WGS-84 (EPSG:4326)"); + out->has_datum = 1; + return 1; +} + +/* ---- EXR: header attributes longitude/latitude/altitude (float32) ---- */ +/* OpenEXR header: magic 76 2F 31 01 (the integer 20000630, LE), + * version u32 LE, then attributes + * (name NUL, type NUL, size u32 LE, value) until an empty name byte. + * longitude/latitude are degrees east of Greenwich / north of the + * equator, altitude metres above sea level. */ +static void geotag_exr(const uint8_t *b, size_t n) { + if (n < 8 || b[0] != 0x76 || b[1] != 0x2F || b[2] != 0x31 || b[3] != 0x01) + return; + size_t pos = 8; + double lon = 0, lat = 0, alt = 0; + int have_lon = 0, have_lat = 0, have_alt = 0; + while (pos < n) { + const uint8_t *nm = memchr(b + pos, 0, n - pos); + if (!nm || nm == b + pos) break; /* empty name: end of header */ + size_t nlen = (size_t)(nm - (b + pos)); + const uint8_t *ty = nm + 1; + const uint8_t *ty_end = memchr(ty, 0, n - (size_t)(ty - b)); + if (!ty_end) break; + size_t tlen = (size_t)(ty_end - ty); + size_t vpos = (size_t)(ty_end - b) + 1; + if (vpos + 4 > n) break; + uint32_t sz = g32(b + vpos, 0); + const uint8_t *val = b + vpos + 4; + if (vpos + 4 + sz > n) break; + if (tlen == 5 && memcmp(ty, "float", 5) == 0 && sz == 4) { + float f; + uint32_t u = g32(val, 0); + memcpy(&f, &u, 4); + if (nlen == 9 && memcmp(b + pos, "longitude", 9) == 0) { + lon = f; have_lon = 1; + } else if (nlen == 8 && memcmp(b + pos, "latitude", 8) == 0) { + lat = f; have_lat = 1; + } else if (nlen == 8 && memcmp(b + pos, "altitude", 8) == 0) { + alt = f; have_alt = 1; + } + } + pos = vpos + 4 + sz; + } + if (have_lon && have_lat && lon >= -180.0 && lon <= 180.0 && + lat >= -90.0 && lat <= 90.0) { + GeoResult g; + memset(&g, 0, sizeof g); + g.found = 1; + snprintf(g.source, sizeof g.source, + "EXR header attributes (longitude/latitude/altitude)"); + g.lat = lat; + g.lon = lon; + if (have_alt) { g.has_alt = 1; g.alt = alt; g.alt_below = alt < 0; } + snprintf(g.datum, sizeof g.datum, "WGS-84 (OpenEXR default)"); + g.has_datum = 1; + add_result(&g); + } +} + +/* ---- JP2: XMP in the uuid box (or the xml box) ---- */ +static void geotag_jp2(FILE *fp, uint64_t fsize) { + static const uint8_t xmp_uuid[16] = { + 0xBE, 0x7A, 0xCF, 0xCB, 0x97, 0xA9, 0x42, 0xE8, + 0x9C, 0x71, 0x99, 0x94, 0x91, 0xE3, 0xAF, 0xAC + }; + uint64_t pos = 0; + Box b; + GeoResult g; + while (read_box(fp, pos, fsize, &b)) { + uint64_t payload = b.start + b.hdr, plen = b.size - b.hdr; + if (strcmp(b.type, "uuid") == 0 && plen > 16) { + uint8_t *hdr = read_range(fp, payload, 16); + if (hdr) { + if (memcmp(hdr, xmp_uuid, 16) == 0) { + uint8_t *x = read_range(fp, payload + 16, plen - 16); + if (x) { + if (parse_xmp_gps(x, (size_t)(plen - 16), + "XMP packet (JP2 uuid box)", &g)) + add_result(&g); + free(x); + } + } + free(hdr); + } + } else if (strcmp(b.type, "xml ") == 0 && plen > 0) { + uint8_t *x = read_range(fp, payload, plen); + if (x) { + if (parse_xmp_gps(x, (size_t)plen, "XMP packet (JP2 xml box)", &g)) + add_result(&g); + free(x); + } + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= fsize) break; + } +} + +/* ---- PSD: image resource blocks 1058 (EXIF) / 1060 (XMP) ---- */ +/* PSD header (26 bytes), color mode data, then image resources: each + * block is "8BIM", resource ID u16 BE, Pascal name (padded to even), + * size u32 BE, data (padded to even). */ +static void geotag_psd(const uint8_t *b, size_t n) { + if (n < 26 || memcmp(b, "8BPS", 4) != 0) return; + size_t pos = 26; + if (pos + 4 > n) return; + uint32_t clen = g32(b + pos, 1); + pos += 4; + if (pos + clen > n) return; + pos += clen; /* color mode data */ + if (pos + 4 > n) return; + uint32_t rlen = g32(b + pos, 1); + pos += 4; + size_t rend = pos + rlen; + if (rend > n) rend = n; + GeoResult g; + while (pos + 8 <= rend) { + if (memcmp(b + pos, "8BIM", 4) != 0) break; + uint16_t id = g16(b + pos + 4, 1); + size_t p = pos + 6; + if (p >= rend) break; + uint8_t nlen = b[p++]; + p += nlen; + if ((1u + nlen) % 2 == 1) p += 1; /* Pascal name padded to even */ + if (p + 4 > rend) break; + uint32_t sz = g32(b + p, 1); + p += 4; + if (p + sz > rend) break; + if (id == 0x0422) { + if (parse_tiff_gps(b + p, sz, "EXIF GPS IFD (PSD resource 1058)", &g)) + add_result(&g); + } else if (id == 0x0424) { + if (parse_xmp_gps(b + p, sz, "XMP packet (PSD resource 1060)", &g)) + add_result(&g); + } + pos = p + sz + (sz & 1); + } +} + +/* ---- CR3: CMT4 GPS IFD + CTBO XMP, in the Canon uuid box ---- */ +/* moov/uuid 85C0B687-820F-11E0-8111-F4CE462B6A48 holds Canon boxes. + * CMT4 is a complete little-endian TIFF structure whose first IFD is + * the GPS IFD. CTBO is int32 count, then records of (int32 index, + * int64 offset, int64 size); index 1 is the XMP packet (offsets are + * absolute file offsets). Layout per Laurent Clevy's reverse + * engineering, confirmed against exiftool 13.50's Canon::uuid table. */ +static void walk_canon_uuid(FILE *fp, uint64_t start, uint64_t end) { + uint64_t pos = start; + Box b; + GeoResult g; + while (read_box(fp, pos, end, &b)) { + uint64_t payload = b.start + b.hdr, plen = b.size - b.hdr; + if (strcmp(b.type, "CMT4") == 0 && plen > 0) { + uint8_t *t = read_range(fp, payload, plen); + if (t) { + if (parse_tiff_gps_direct(t, (size_t)plen, + "EXIF GPS IFD (CR3 CMT4 box)", &g)) + add_result(&g); + free(t); + } + } else if (strcmp(b.type, "CTBO") == 0 && plen >= 4) { + uint8_t *t = read_range(fp, payload, plen); + if (t) { + uint32_t cnt = g32(t, 1); + for (uint32_t i = 0; i < cnt; i++) { + size_t off = 4 + (size_t)i * 20; + if (off + 20 > plen) break; + uint32_t idx = g32(t + off, 1); + uint64_t o = ((uint64_t)g32(t + off + 4, 1) << 32) | + g32(t + off + 8, 1); + uint64_t sz = ((uint64_t)g32(t + off + 12, 1) << 32) | + g32(t + off + 16, 1); + if (idx == 1 && sz > 0) { + uint8_t *x = read_range(fp, o, sz); + if (x) { + if (parse_xmp_gps(x, (size_t)sz, + "XMP packet (CR3 CTBO entry 1)", &g)) + add_result(&g); + free(x); + } + break; + } + } + free(t); + } + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= end) break; + } +} + +static void geotag_cr3(FILE *fp, uint64_t fsize) { + static const uint8_t canon_uuid[16] = { + 0x85, 0xC0, 0xB6, 0x87, 0x82, 0x0F, 0x11, 0xE0, + 0x81, 0x11, 0xF4, 0xCE, 0x46, 0x2B, 0x6A, 0x48 + }; + uint64_t pos = 0; + Box b; + while (read_box(fp, pos, fsize, &b)) { + if (strcmp(b.type, "moov") == 0) { + uint64_t mq = b.start + b.hdr, me = b.start + b.size; + Box c; + while (read_box(fp, mq, me, &c)) { + if (strcmp(c.type, "uuid") == 0 && c.size - c.hdr > 16) { + uint64_t payload = c.start + c.hdr; + uint8_t *u = read_range(fp, payload, 16); + if (u) { + if (memcmp(u, canon_uuid, 16) == 0) + walk_canon_uuid(fp, payload + 16, c.start + c.size); + free(u); + } + } + if (c.size == 0) break; + mq = c.start + c.size; + if (mq >= me) break; + } + } + if (b.size == 0) break; + pos = b.start + b.size; + if (pos >= fsize) break; + } +} + +/* ---- Matroska (MKV/WebM): EBML walk, XMP attachment only ---- */ +/* Matroska has NO standard GPS field (CELLAR tags draft section 4.12 + * defines only free-text RECORDING_LOCATION / COMPOSITION_LOCATION). + * The only real location mechanism is an XMP packet carried as an + * attachment (or sidecar). The de-facto ffmpeg "LOCATION" TagString is + * deliberately NOT decoded: it is not a Matroska-standard field. */ +static int ebml_id(FILE *fp, uint64_t pos, uint64_t *id, int *len) { + uint8_t first; + if (fseeko(fp, (off_t)pos, SEEK_SET) != 0) return 0; + if (fread(&first, 1, 1, fp) != 1) return 0; + int lz = 0; + uint8_t m = 0x80; + while (lz < 8 && !(first & m)) { lz++; m >>= 1; } + if (lz >= 4) return 0; /* element IDs are 1..4 bytes */ + int L = lz + 1; + uint64_t v = first; + for (int i = 1; i < L; i++) { + uint8_t c; + if (fread(&c, 1, 1, fp) != 1) return 0; + v = (v << 8) | c; + } + *id = v; + *len = L; + return 1; +} + +static int ebml_size(FILE *fp, uint64_t pos, uint64_t *size, int *len, + int *unknown) { + uint8_t first; + if (fseeko(fp, (off_t)pos, SEEK_SET) != 0) return 0; + if (fread(&first, 1, 1, fp) != 1) return 0; + int lz = 0; + uint8_t m = 0x80; + while (lz < 8 && !(first & m)) { lz++; m >>= 1; } + if (lz >= 8) return 0; + int L = lz + 1; + uint64_t v = first & (uint8_t)(0xFFu >> L); /* strip marker bit */ + for (int i = 1; i < L; i++) { + uint8_t c; + if (fread(&c, 1, 1, fp) != 1) return 0; + v = (v << 8) | c; + } + uint64_t allones = (L == 8) ? ~0ull : ((1ull << (7 * L)) - 1); + *unknown = (v == allones); + *size = v; + *len = L; + return 1; +} + +/* Read one EBML element header at pos; *start / *end delimit its payload + * (unknown size runs to limit). Returns 0 at EOF/error. */ +static int ebml_elem(FILE *fp, uint64_t pos, uint64_t limit, uint64_t *id, + uint64_t *start, uint64_t *end) { + int ilen = 0, slen = 0, unk = 0; + uint64_t sz = 0; + if (!ebml_id(fp, pos, id, &ilen)) return 0; + if (!ebml_size(fp, pos + ilen, &sz, &slen, &unk)) return 0; + *start = pos + ilen + slen; + *end = unk ? limit : *start + sz; + if (*end > limit) *end = limit; + if (*end < *start) return 0; + return 1; +} + +static int scan_mkv_attachments(FILE *fp, uint64_t start, uint64_t end) { + uint64_t pos = start, id = 0, s = 0, e = 0; + GeoResult g; + while (pos < end && ebml_elem(fp, pos, end, &id, &s, &e)) { + if (id == 0x61A7) { /* AttachedFile */ + char fname[256] = ""; + uint8_t *data = NULL; + size_t dlen = 0; + uint64_t fp2 = s, fid = 0, fs = 0, fe = 0; + while (fp2 < e && ebml_elem(fp, fp2, e, &fid, &fs, &fe)) { + if (fid == 0x466E) { /* FileName */ + size_t L = fe - fs < sizeof fname - 1 ? + (size_t)(fe - fs) : sizeof fname - 1; + uint8_t *nm = read_range(fp, fs, L); + if (nm) { memcpy(fname, nm, L); fname[L] = 0; free(nm); } + } else if (fid == 0x465C) { /* FileData */ + if (fe - fs <= GEO_PAYLOAD_CAP) { + data = read_range(fp, fs, fe - fs); + dlen = data ? (size_t)(fe - fs) : 0; + } + } + if (fe <= fp2) break; + fp2 = fe; + } + if (data) { + size_t fl = strlen(fname); + int is_xmp = (fl >= 4 && + strcasecmp(fname + fl - 4, ".xmp") == 0) || + memmem(data, dlen, " 0) return 1; + } + } + if (e <= pos) break; + pos = e; + } + return 0; +} + +static void geotag_mkv(FILE *fp, uint64_t fsize) { + uint64_t limit = fsize < GEO_SCAN_CAP ? fsize : GEO_SCAN_CAP; + uint64_t pos = 0, id = 0, start = 0, end = 0; + while (pos < limit && ebml_elem(fp, pos, limit, &id, &start, &end)) { + if (id == 0x18538067) { /* Segment */ + uint64_t sp = start; + while (sp < end) { + uint64_t cid = 0, cs = 0, ce = 0; + if (!ebml_elem(fp, sp, end, &cid, &cs, &ce)) break; + if (cid == 0x1941A469) { /* Attachments */ + if (scan_mkv_attachments(fp, cs, ce)) return; + } else if (cid == 0x1F43B675) { /* Cluster: no metadata after it */ + break; + } + if (ce <= sp) break; + sp = ce; + } + } + if (end <= pos) break; + pos = end; + } +} + +/* ---- AVI / DIVX: RIFF chunk walk, XMP in the _PMX chunk ---- */ +/* RIFF INFO has no GPS field and AVI has no EXIF carrier; the only real + * mechanism is the XMP packet in the _PMX chunk (Adobe tools). */ +static void walk_riff_range(FILE *fp, uint64_t start, uint64_t end, int depth) { + uint64_t pos = start; + GeoResult g; + while (pos + 8 <= end) { + uint8_t h[8]; + if (fseeko(fp, (off_t)pos, SEEK_SET) != 0) return; + if (fread(h, 1, 8, fp) != 8) return; + uint32_t sz = g32(h + 4, 0); + uint64_t data = pos + 8, cend = data + sz; + if (cend > end) cend = end; + if (memcmp(h, "_PMX", 4) == 0 && sz > 0) { + uint8_t *x = read_range(fp, data, sz); + if (x) { + if (parse_xmp_gps(x, (size_t)sz, "XMP packet (AVI _PMX chunk)", &g)) + add_result(&g); + free(x); + } + } else if (memcmp(h, "LIST", 4) == 0 && sz >= 4 && depth < 4) { + walk_riff_range(fp, data + 4, cend, depth + 1); + } + pos = cend + (sz & 1); /* RIFF chunks are word-aligned */ + } +} + +static void geotag_avi(FILE *fp, uint64_t fsize) { + uint8_t h[12]; + if (fsize < 12) return; + if (fseeko(fp, 0, SEEK_SET) != 0) return; + if (fread(h, 1, 12, fp) != 12) return; + if (memcmp(h, "RIFF", 4) != 0) return; + if (memcmp(h + 8, "AVI ", 4) != 0 && memcmp(h + 8, "AVIX", 4) != 0) return; + uint64_t end = 8 + (uint64_t)g32(h + 4, 0); + if (end > fsize) end = fsize; + if (end > GEO_SCAN_CAP) end = GEO_SCAN_CAP; + walk_riff_range(fp, 12, end, 0); +} + +/* ---- dispatch ---- */ +static int run_scan(const char *path, int task) { + geo_nresults = 0; + size_t n = 0; + uint8_t *buf = NULL; + FILE *fp = NULL; + uint64_t fsize = 0; + switch (task) { + case 331: case 332: /* JPEG */ + geo_searched = "EXIF GPS IFD in JPEG APP1; XMP in JPEG APP1"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_jpeg(buf, n); free(buf); } + break; + case 730: case 257: /* TIFF, GeoTIFF */ + geo_searched = "EXIF GPS IFD (TIFF IFD0); GeoTIFF tiepoint/transformation"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { + GeoResult g; + geotag_tiff(buf, n); + if (parse_geotiff(buf, n, &g)) add_result(&g); + free(buf); + } + break; + case 109: case 445: case 144: /* CR2, NEF, DNG: TIFF-based RAW */ + geo_searched = "EXIF GPS IFD (TIFF IFD0)"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_tiff(buf, n); free(buf); } + break; + case 564: /* PNG */ + geo_searched = "EXIF GPS IFD in PNG eXIf chunk; XMP in PNG iTXt/tEXt chunk"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_png(buf, n); free(buf); } + break; + case 861: /* WebP */ + geo_searched = "EXIF GPS IFD in WebP EXIF chunk; XMP in WebP XMP chunk"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_webp(buf, n); free(buf); } + break; + case 286: case 287: case 48: /* HEIC, HEIF, AVIF */ + geo_searched = "EXIF GPS IFD in HEIF meta Exif item; XMP in HEIF meta mime item"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_heic(fp, fsize); + fclose(fp); + } + break; + case 415: case 412: case 373: case 207: case 370: case 3: case 4: + /* MP4, MOV, M4V, F4V, M4A, 3G2, 3GP */ + geo_searched = "QuickTime location (moov/udta (c)xyz, moov/meta ISO6709 key, 3GPP loci); XMP in moov/udta XMP_"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_mp4(fp, fsize); + fclose(fp); + } + break; + case 110: /* CR3 */ + geo_searched = "EXIF GPS IFD in CR3 CMT4 box; XMP via CR3 CTBO entry 1"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_cr3(fp, fsize); + fclose(fp); + } + break; + case 199: /* EXR */ + geo_searched = "EXR header attributes longitude/latitude/altitude"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_exr(buf, n); free(buf); } + break; + case 329: /* JP2 */ + geo_searched = "XMP in JP2 uuid box / xml box (raw .j2k has no metadata)"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_jp2(fp, fsize); + fclose(fp); + } + break; + case 575: /* PSD */ + geo_searched = "EXIF GPS IFD in PSD resource 1058; XMP in PSD resource 1060"; + buf = slurp(path, GEO_SLURP_CAP, &n); + if (buf) { geotag_psd(buf, n); free(buf); } + break; + case 399: case 805: /* MKV, WebM */ + geo_searched = "XMP packet in MKV attachment (Matroska has no native GPS field)"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_mkv(fp, fsize); + fclose(fp); + } + break; + case 47: case 140: /* AVI, DIVX */ + geo_searched = "XMP packet in AVI _PMX chunk (RIFF INFO has no GPS field)"; + fp = fopen(path, "rb"); + if (fp) { + fseeko(fp, 0, SEEK_END); + fsize = (uint64_t)ftello(fp); + geotag_avi(fp, fsize); + fclose(fp); + } + break; + default: + return -1; /* no geotagging mechanism for this format */ + } + return geo_nresults; +} + +void decode_geotag(const char *path, int task) { + if (run_scan(path, task) < 0) return; + print_results(); +} + +int geotag_scan(const char *path, int task, GeoResult *out, int max_results) { + if (run_scan(path, task) < 0) return -1; + int n = geo_nresults < max_results ? geo_nresults : max_results; + for (int i = 0; i < n; i++) out[i] = geo_results[i]; + return n; +} diff --git a/src/geotag.h b/src/geotag.h new file mode 100644 index 0000000..831c48c --- /dev/null +++ b/src/geotag.h @@ -0,0 +1,41 @@ +/* geotag.h -- GPS/geotagging decode for sfile. + * + * Prints a "Geotagging:" section for formats that carry a real location + * mechanism, and nothing for formats that have none. See geotag.c for the + * per-format sources and the specs each layout is grounded in. + */ +#ifndef SFILE_GEOTAG_H +#define SFILE_GEOTAG_H + +/* One decoded location. `found` is set when latitude/longitude were + * recovered; altitude, datum and datetime are optional (see the + * has_* flags). Public so other sfile tools (stag, sgeo) can reuse + * the decoders without parsing sfile's text output. */ +typedef struct { + int found; + char source[96]; + double lat, lon; + int has_alt; + double alt; + int alt_below; /* GPSAltitudeRef 1 = below sea level */ + char datum[48]; + int has_datum; + char datetime[48]; + int has_datetime; +} GeoResult; + +/* Scan the file at path (identified as task) and fill out[0..max_results) + * with the locations found. Returns the number filled, 0 when the format + * has a mechanism but no location was found, or -1 when the format has + * no geotagging mechanism at all. */ +int geotag_scan(const char *path, int task, GeoResult *out, int max_results); + + +/* Decode and print any GPS location carried by the file at path, whose + * format was identified as task (a task number from formats.h). + * Prints a "Geotagging:" section (coordinates, or a "none found" line + * naming what was searched) for geotag-capable formats; prints nothing + * for formats with no geotagging mechanism. */ +void decode_geotag(const char *path, int task); + +#endif diff --git a/src/sfile.c b/src/sfile.c index 3d99c92..bb8e902 100644 --- a/src/sfile.c +++ b/src/sfile.c @@ -22,6 +22,7 @@ #include #include "formats.h" +#include "geotag.h" #define HDR_WIN 65536 /* header window: how much of the file we read */ #define HEXDUMP_LEN 64 /* bytes shown for unknown / magic-only formats */ @@ -284,6 +285,8 @@ int main(int argc, char **argv) { print_hex(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN); printf("\n"); } + decode_geotag(path, fmt->task); + free(buf); return 0; } diff --git a/tests/geotag/make_geotag_tests.py b/tests/geotag/make_geotag_tests.py new file mode 100644 index 0000000..7b18d09 --- /dev/null +++ b/tests/geotag/make_geotag_tests.py @@ -0,0 +1,439 @@ +#!/usr/bin/env python3 +"""make_geotag_tests.py -- build sfile geotagging test fixtures. + +Every fixture carries KNOWN GPS values so sfile's decoded output can be +checked by round-trip: + latitude 37.7749 N = 37 deg, 46 min, 29.64 s + longitude 122.4194 W = 122 deg, 25 min, 9.84 s + altitude 10 m (30 m in the MP4 keys/ilst fixture, matching the + fileformat.vpscoder.com worked example verbatim) + datum WGS-84, date 2026-12-01, time 12:34:56 UTC + +Tag numbers follow EXIF 2.32 (CIPA DC-008): GPS IFD via IFD0 tag 0x8825; +0x0000 version, 0x0001/0x0002 lat ref/value (RATIONAL[3] DMS), +0x0003/0x0004 lon ref/value, 0x0005/0x0006 alt ref/value, +0x0007 timestamp, 0x0012 datum, 0x001D datestamp. + +Usage: python3 make_geotag_tests.py [outdir] +""" +import os +import struct +import sys +import zlib + +OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__)) + +LAT_DMS = (37, 46, 2964, 100) # 37 + 46/60 + 29.64/3600 = 37.7749 +LON_DMS = (122, 25, 984, 100) # 122 + 25/60 + 9.84/3600 = 122.4194 +ALT_M = 10 + + +def build_ifd(e, entries, base_off): + """entries: (tag, type, count, payload_bytes). Values >4 bytes are + placed after the IFD; returns (ifd_bytes_with_values, end_offset).""" + n = len(entries) + out = bytearray() + out += struct.pack(e + 'H', n) + val_off = base_off + 2 + n * 12 + 4 + val_blob = bytearray() + for tag, typ, count, payload in entries: + out += struct.pack(e + 'HHI', tag, typ, count) + if len(payload) <= 4: + out += payload + b'\x00' * (4 - len(payload)) + else: + out += struct.pack(e + 'I', val_off) + val_blob += payload + val_off += len(payload) + out += struct.pack(e + 'I', 0) + return bytes(out) + bytes(val_blob), val_off + + +def gps_entries(e, alt=ALT_M): + def u32(v): + return struct.pack(e + 'I', v) + def rat(n, d): + return u32(n) + u32(d) + lat = rat(37, 1) + rat(46, 1) + rat(2964, 100) + lon = rat(122, 1) + rat(25, 1) + rat(984, 100) + return [ + (0x0000, 1, 4, bytes([2, 3, 0, 0])), + (0x0001, 2, 2, b'N\x00'), + (0x0002, 5, 3, lat), + (0x0003, 2, 2, b'W\x00'), + (0x0004, 5, 3, lon), + (0x0005, 1, 1, bytes([0])), + (0x0006, 5, 1, rat(alt, 1)), + (0x0007, 5, 3, rat(12, 1) + rat(34, 1) + rat(56, 1)), + (0x0012, 2, 7, b'WGS-84\x00'), + (0x001D, 2, 11, b'2026:12:01\x00'), + ] + + +def build_tiff_gps(be=False, alt=ALT_M): + """Complete TIFF header + IFD0 (GPS pointer) + GPS IFD.""" + e = '>' if be else '<' + u32 = lambda v: struct.pack(e + 'I', v) + gps_ifd, _ = build_ifd(e, gps_entries(e, alt), 26) + hdr = (b'MM\x00*' if be else b'II*\x00') + u32(8) + ifd0 = (struct.pack(e + 'H', 1) + + struct.pack(e + 'HHI', 0x8825, 4, 1) + u32(26) + u32(0)) + return hdr + ifd0 + gps_ifd + + +def build_tiff_gps_direct(be=False, alt=ALT_M): + """TIFF header whose FIRST IFD is itself the GPS IFD (CR3 CMT4).""" + e = '>' if be else '<' + u32 = lambda v: struct.pack(e + 'I', v) + gps_ifd, _ = build_ifd(e, gps_entries(e, alt), 8) + hdr = (b'MM\x00*' if be else b'II*\x00') + u32(8) + return hdr + gps_ifd + + +def build_tiff_nogps(): + """TIFF header + empty IFD0 (no GPS pointer).""" + return b'II*\x00' + struct.pack('\n' + '\n' + ' \n' + ' \n' + ' \n\n' + % (lat_s, lon_s, alt_s)).encode() + + +XMP_DMS = build_xmp("37,46,29.64N", "122,25,9.84W") +XMP_MIN = build_xmp("37,46.494N", "122,25.164W") # exiftool's form, per the blog + + +def build_jpeg(tiff=None, xmp=None): + out = b'\xff\xd8' + if tiff is not None: + app1 = b'Exif\x00\x00' + tiff + out += b'\xff\xe1' + struct.pack('>H', len(app1) + 2) + app1 + if xmp is not None: + x = b'http://ns.adobe.com/xap/1.0/\x00' + xmp + out += b'\xff\xe1' + struct.pack('>H', len(x) + 2) + x + return out + b'\xff\xd9' + + +def png_chunk(typ, data): + return (struct.pack('>I', len(data)) + typ + data + + struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff)) + + +def build_png(tiff=None, xmp=None): + out = b'\x89PNG\r\n\x1a\n' + out += png_chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0)) + if tiff is not None: + out += png_chunk(b'eXIf', tiff) + if xmp is not None: + out += png_chunk(b'iTXt', + b'XML:com.adobe.xmp\x00\x00\x00\x00\x00' + xmp) + out += png_chunk(b'IDAT', zlib.compress(b'\x00\x00\x00\x00')) + out += png_chunk(b'IEND', b'') + return out + + +def riff_chunk(typ, data): + out = typ + struct.pack('I', 8 + len(payload)) + typ + payload + + +def build_heic(tiff=None, xmp=None): + """HEIC: ftyp + meta (hdlr, iinf, iloc) + mdat holding the item.""" + ftyp = bmff_box(b'ftyp', b'heic\x00\x00\x00\x00heic') + hdlr = bmff_box(b'hdlr', b'\x00\x00\x00\x00' + b'\x00\x00\x00\x00' + + b'pict' + b'\x00' * 12 + b'\x00') + item_data = tiff if tiff is not None else xmp + if tiff is not None: + infe = bmff_box(b'infe', b'\x02\x00\x00\x00' + + struct.pack('>HH', 1, 0) + b'Exif' + b'\x00') + else: + # infe v2 mime item: item_name (empty), content_type, content_encoding + infe = bmff_box(b'infe', b'\x02\x00\x00\x00' + + struct.pack('>HH', 2, 0) + b'mime' + + b'\x00' + b'application/rdf+xml\x00' + b'\x00') + iinf = bmff_box(b'iinf', b'\x00\x00\x00\x00' + struct.pack('>H', 1) + infe) + # iloc v0, offset/length sizes 4, base/index 0; extent offset patched below + item_id = 1 if tiff is not None else 2 + iloc_payload = (b'\x00\x00\x00\x00' + b'\x44\x00' + struct.pack('>H', 1) + + struct.pack('>HHH', item_id, 0, 1) + + struct.pack('>II', 0, len(item_data))) + iloc = bmff_box(b'iloc', iloc_payload) + meta_body = b'\x00\x00\x00\x00' + hdlr + iinf + iloc + meta = bmff_box(b'meta', meta_body) + mdat_off = len(ftyp) + len(meta) + 8 # payload starts after mdat header + # patch the extent offset inside iloc (last 8 bytes of iloc payload: + # extent_offset u32 then extent_length u32) + iloc = iloc[:-8] + struct.pack('>II', mdat_off, len(item_data)) + meta = bmff_box(b'meta', b'\x00\x00\x00\x00' + hdlr + iinf + iloc) + mdat = bmff_box(b'mdat', item_data) + return ftyp + meta + mdat + + +def build_loci(lat=37.7749, lon=-122.4194, alt=10.0, name=b'San Francisco'): + """3GPP TS 26.244 loci box: ver/flags, language, name, role, + lon/lat/alt as signed 16.16 fixed-point, body, notes.""" + def fx(v): + return struct.pack('>i', int(round(v * 65536))) + return (b'\x00\x00\x00\x00' + struct.pack('>H', 0x15C7) + name + b'\x00' + + bytes([0]) + fx(lon) + fx(lat) + fx(alt) + b'earth\x00' + b'\x00') + + +def build_mp4(xyz=None, xyz_prefixed=False, keys_iso=None, xmp=None, + loci=None, moov_first=True, brand=b'isom'): + mvhd = bmff_box(b'mvhd', b'\x00' * 100) + udta_children = b'' + if xyz is not None: + payload = xyz.encode() + if xyz_prefixed: + # canonical QuickTime user-data text: [u16 size][u16 lang]text + payload = struct.pack('>HH', len(payload), 0x15C7) + payload + udta_children += bmff_box(b'\xa9xyz', payload) + if loci is not None: + udta_children += bmff_box(b'loci', loci) + if xmp is not None: + udta_children += bmff_box(b'XMP_', xmp) + meta = b'' + if keys_iso is not None: + key = b'com.apple.quicktime.location.ISO6709' + keys_entry = struct.pack('>I', 8 + len(key)) + b'mdta' + key + keys = bmff_box(b'keys', b'\x00\x00\x00\x00' + struct.pack('>I', 1) + + keys_entry) + data = (struct.pack('>I', 16 + len(keys_iso)) + b'data' + + struct.pack('>II', 1, 0) + keys_iso.encode()) + ilst_entry = struct.pack('>I', 8 + len(data)) + struct.pack('>I', 1) + data + ilst = bmff_box(b'ilst', ilst_entry) + # meta lives inside udta in the wild (ffmpeg/exiftool), with an + # hdlr 'mdir' child; exiftool ignores a moov-level meta entirely. + hdlr = bmff_box(b'hdlr', b'\x00\x00\x00\x00' + b'\x00\x00\x00\x00' + + b'mdir' + b'\x00' * 12 + b'\x00') + meta = bmff_box(b'meta', b'\x00\x00\x00\x00' + hdlr + keys + ilst) + udta_children += meta + udta = bmff_box(b'udta', udta_children) if udta_children else b'' + moov = bmff_box(b'moov', mvhd + udta) + ftyp = bmff_box(b'ftyp', brand + b'\x00\x00\x00\x00' + brand) + mdat = bmff_box(b'mdat', b'\x00' * 64) + return ftyp + moov + mdat if moov_first else ftyp + mdat + moov + + +# ---- EBML (Matroska) ---- +def vint_size(n): + if n < 128: + return bytes([0x80 | n]) + if n < 16384: + return bytes([0x40 | (n >> 8), n & 0xFF]) + raise ValueError("size too big for test fixture") + + +def ebml_elem(eid, payload): + return eid + vint_size(len(payload)) + payload + + +def build_mp4_uuid_xmp(xmp): + """ftyp + moov (mvhd only) + uuid box: XMP UUID + raw XMP packet.""" + ftyp = bmff_box(b'ftyp', b'isom\x00\x00\x00\x00isom') + moov = bmff_box(b'moov', bmff_box(b'mvhd', b'\x00' * 100)) + uuid = bmff_box(b'uuid', bytes.fromhex('be7acfcb97a942e89c71999491e3afac') + xmp) + return ftyp + moov + uuid + + +def build_mkv(xmp=None, with_recording_location=False): + def u8_elem(eid, v): + return ebml_elem(eid, bytes([v])) + def str_elem(eid, s): + return ebml_elem(eid, s if isinstance(s, bytes) else s.encode()) + ebml = ebml_elem(b'\x1a\x45\xdf\xa3', + u8_elem(b'\x42\x86', 1) + u8_elem(b'\x42\xf7', 1) + + str_elem(b'\x42\x82', b'matroska') + u8_elem(b'\x42\x87', 1)) + seg_children = b'' + if with_recording_location: + tag = ebml_elem(b'\x73\x73', ebml_elem( + b'\x67\xc8', + str_elem(b'\x45\xa3', b'RECORDING_LOCATION') + + str_elem(b'\x44\x87', b'San Francisco'))) + seg_children += ebml_elem(b'\x12\x54\xc3\x67', tag) + if xmp is not None: + att = ebml_elem(b'\x61\xa7', + str_elem(b'\x46\x6e', b'gps.xmp') + + str_elem(b'\x46\x60', b'application/rdf+xml') + + ebml_elem(b'\x46\x5c', xmp)) + seg_children += ebml_elem(b'\x19\x41\xa4\x69', att) + segment = b'\x18\x53\x80\x67' + b'\xff' + seg_children # unknown size + return ebml + segment + + +def build_avi(xmp=None): + avih = b'avih' + struct.pack('I', 2) + + struct.pack('>IQQ', 1, xmp_off, len(xmp)) + + struct.pack('>IQQ', 3, mdat_off, 64)) + ctbo = bmff_box(b'CTBO', ctbo_body) + uuid_inner = cmt4 + ctbo + uuid = bmff_box(b'uuid', uuid_body + uuid_inner) + moov = bmff_box(b'moov', uuid) + assert len(moov) == len(ftyp) * 0 + len(bmff_box(b'moov', uuid)), "size drift" + return ftyp + moov + mdat + xmp + + +def build_exr(lon=-122.4194, lat=37.7749, alt=10.0): + out = b'\x76\x2f\x31\x01' + struct.pack('H', 1) + b'\x00' * 6 + + struct.pack('>HIIHH', 1, 1, 1, 8, 3)) + def res_block(rid, data, name=b''): + blk = b'8BIM' + struct.pack('>H', rid) + blk += bytes([len(name)]) + name + if (1 + len(name)) % 2 == 1: + blk += b'\x00' + blk += struct.pack('>I', len(data)) + data + if len(data) % 2 == 1: + blk += b'\x00' + return blk + resources = res_block(0x0422, tiff) + res_block(0x0424, xmp) + return hdr + struct.pack('>I', 0) + struct.pack('>I', len(resources)) + resources + + +def build_geotiff(): + """Big-endian TIFF with GeoKeys 2048=4326 + tiepoint lon/lat.""" + e = '>' + def u16(v): + return struct.pack(e + 'H', v) + def u32(v): + return struct.pack(e + 'I', v) + def f64(v): + return struct.pack(e + 'd', v) + scale = f64(1.0) + f64(1.0) + f64(0.0) + tiepoint = f64(0.0) + f64(0.0) + f64(0.0) + f64(-122.4194) + f64(37.7749) + f64(0.0) + geokeys = (u16(1) + u16(1) + u16(1) + u16(1) + + u16(2048) + u16(0) + u16(1) + u16(4326)) + entries = [ + (33550, 12, 3, scale), + (33922, 12, 6, tiepoint), + (34735, 3, 8, geokeys), + ] + ifd0, _ = build_ifd(e, entries, 8) + hdr = b'MM\x00*' + u32(8) + return hdr + ifd0 + + +def main(): + os.makedirs(OUT, exist_ok=True) + tiff_le = build_tiff_gps(be=False) + tiff_be = build_tiff_gps(be=True) + fixtures = { + 'test-gps.jpg': build_jpeg(tiff_le), + 'test-gps-be.jpg': build_jpeg(tiff_be), + 'test-gps.tiff': tiff_le, + 'test-gps-be.tiff': tiff_be, + 'test-gps.dng': tiff_le, + 'test-gps.png': build_png(tiff_le), + 'test-gps-xmp.png': build_png(xmp=XMP_MIN), + 'test-gps.webp': build_webp(tiff_le), + 'test-gps-xmp.webp': build_webp(xmp=XMP_DMS), + 'test-gps.heic': build_heic(tiff_le), + 'test-gps-xmp.heic': build_heic(xmp=XMP_DMS), + 'test-gps.mp4': build_mp4(xyz='+37.7749-122.4194+010.000/', + xyz_prefixed=True, + keys_iso='+37.7749-122.4194+030.000/'), + 'test-gps-moov-end.mp4': build_mp4(xyz='+37.7749-122.4194+010.000/', + moov_first=False), + 'test-gps.mov': build_mp4(xyz='+37.7749-122.4194+010.000/', + xyz_prefixed=True, brand=b'qt '), + 'test-gps-3gp.3gp': build_mp4(loci=build_loci(), brand=b'3gp4'), + 'test-gps-xmp.mp4': build_mp4(xmp=XMP_DMS), + 'test-gps-xmp-uuid.mp4': build_mp4_uuid_xmp(XMP_DMS), + 'test-gps.mkv': build_mkv(xmp=XMP_MIN), + 'test-gps.avi': build_avi(xmp=XMP_DMS), + 'test-gps.cr3': build_cr3(build_tiff_gps_direct(), XMP_DMS), + 'test-gps.exr': build_exr(), + 'test-gps.jp2': build_jp2(XMP_DMS), + 'test-gps.psd': build_psd(tiff_le, XMP_DMS), + 'test-gps.geotiff': build_geotiff(), + 'test-gps-no-gps.jpg': build_jpeg(build_tiff_nogps()), + 'test-gps-no-gps.mkv': build_mkv(with_recording_location=True), + } + for name, data in fixtures.items(): + path = os.path.join(OUT, name) + with open(path, 'wb') as fh: + fh.write(data) + print('wrote %s (%d bytes)' % (path, len(data))) + + +if __name__ == '__main__': + main() diff --git a/tests/geotag/run_geotag_tests.py b/tests/geotag/run_geotag_tests.py new file mode 100644 index 0000000..a8ea680 --- /dev/null +++ b/tests/geotag/run_geotag_tests.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""run_geotag_tests.py -- round-trip checks for sfile's geotagging decoder. + +For each fixture in tests/geotag/ (built by make_geotag_tests.py), run +./sfile on it and assert the known GPS values appear in the Geotagging +section. Exit non-zero if any check fails. + +Usage: python3 run_geotag_tests.py [sfile_binary] [fixtures_dir] +""" +import os +import subprocess +import sys + +SFILE = sys.argv[1] if len(sys.argv) > 1 else "./sfile" +FIX = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__)) + +LAT = "gps_latitude: 37.774900" +LON = "gps_longitude: -122.419400" +ALT10 = "gps_altitude_m: 10.000 (above sea level)" +DATUM = "gps_datum: WGS-84" +WHEN = "gps_datetime_utc: 2026-12-01 12:34:56" +NONE = "none found" + +CASES = { + 'test-gps.jpg': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (JPEG APP1 segment)"], + 'test-gps-be.jpg': [LAT, LON, ALT10, DATUM, WHEN], + 'test-gps.tiff': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (TIFF IFD0)"], + 'test-gps-be.tiff': [LAT, LON, ALT10, DATUM, WHEN], + 'test-gps.dng': [LAT, LON, ALT10, DATUM, WHEN], + 'test-gps.png': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (PNG eXIf chunk)"], + 'test-gps-xmp.png': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (PNG iTXt chunk)"], + 'test-gps.webp': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (WebP EXIF chunk)"], + 'test-gps-xmp.webp': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (WebP XMP chunk)"], + 'test-gps.heic': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (HEIF meta Exif item)"], + 'test-gps-xmp.heic': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (HEIF meta mime item)"], + # both QuickTime sources agree on lat/lon; altitudes differ (10 vs 30 m) + 'test-gps.mp4': [LAT, LON, + "gps_altitude_m: 10.000 (above sea level)", + "gps_altitude_m: 30.000 (above sea level)", + "source: QuickTime location (moov/udta (c)xyz atom)", + "source: QuickTime location (moov/udta/meta com.apple.quicktime.location.ISO6709)"], + 'test-gps-moov-end.mp4': [LAT, LON, ALT10, + "source: QuickTime location (moov/udta (c)xyz atom)"], + # canonical QuickTime text layout: [u16 size][u16 lang] + string + 'test-gps.mov': [LAT, LON, ALT10], + # 16.16 fixed point: 37.7749 -> 37.774902, -122.4194 -> -122.419403 + 'test-gps-3gp.3gp': ["gps_latitude: 37.774902", + "gps_longitude: -122.419403", ALT10, + "source: 3GPP location (moov/udta loci box)"], + 'test-gps-xmp.mp4': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (MP4/MOV udta XMP_ box)"], + 'test-gps-xmp-uuid.mp4': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (MP4/MOV uuid box)"], + 'test-gps.mkv': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (MKV attachment)"], + 'test-gps.avi': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (AVI _PMX chunk)"], + 'test-gps.cr3': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (CR3 CMT4 box)", + "source: XMP packet (CR3 CTBO entry 1)"], + # float32: 37.7749 -> 37.774899, -122.4194 -> -122.419403 + 'test-gps.exr': ["gps_latitude: 37.774899", + "gps_longitude: -122.419403", ALT10, + "source: EXR header attributes (longitude/latitude/altitude)"], + 'test-gps.jp2': [LAT, LON, "gps_altitude_m: 10.000", + "source: XMP packet (JP2 uuid box)"], + 'test-gps.psd': [LAT, LON, ALT10, DATUM, WHEN, + "source: EXIF GPS IFD (PSD resource 1058)", + "source: XMP packet (PSD resource 1060)"], + 'test-gps.geotiff': [LAT, LON, "gps_datum: WGS-84 (EPSG:4326)", + "source: GeoTIFF tiepoint (TIFF IFD0)"], + 'test-gps-no-gps.jpg': [NONE], + # free-text RECORDING_LOCATION must NOT be reported as coordinates + 'test-gps-no-gps.mkv': [NONE], +} + + +def main(): + n_pass = n_fail = 0 + failures = [] + for name, wants in sorted(CASES.items()): + path = os.path.join(FIX, name) + if not os.path.exists(path): + print("MISSING fixture %s" % name) + n_fail += 1 + failures.append((name, "fixture missing")) + continue + r = subprocess.run([SFILE, path], capture_output=True, text=True) + out = r.stdout + missing = [w for w in wants if w not in out] + bad = [] + if r.returncode != 0: + bad.append("exit code %d" % r.returncode) + if "Geotagging:" not in out: + bad.append("no Geotagging section") + if missing: + bad.append("missing: %s" % "; ".join(missing)) + # negative cases must not report coordinates + if NONE in wants and ("gps_latitude:" in out or "gps_longitude:" in out): + bad.append("reported coordinates where none exist") + if bad: + n_fail += 1 + failures.append((name, " | ".join(bad))) + print("FAIL %s: %s" % (name, " | ".join(bad))) + else: + n_pass += 1 + print("PASS %s" % name) + print("%d PASS, %d FAIL, %d total" % (n_pass, n_fail, n_pass + n_fail)) + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/geotag/test-gps-3gp.3gp b/tests/geotag/test-gps-3gp.3gp new file mode 100644 index 0000000..427b143 Binary files /dev/null and b/tests/geotag/test-gps-3gp.3gp differ diff --git a/tests/geotag/test-gps-be.jpg b/tests/geotag/test-gps-be.jpg new file mode 100644 index 0000000..4bbbd6c Binary files /dev/null and b/tests/geotag/test-gps-be.jpg differ diff --git a/tests/geotag/test-gps-be.tiff b/tests/geotag/test-gps-be.tiff new file mode 100644 index 0000000..5770b18 Binary files /dev/null and b/tests/geotag/test-gps-be.tiff differ diff --git a/tests/geotag/test-gps-moov-end.mp4 b/tests/geotag/test-gps-moov-end.mp4 new file mode 100644 index 0000000..30399d1 Binary files /dev/null and b/tests/geotag/test-gps-moov-end.mp4 differ diff --git a/tests/geotag/test-gps-no-gps.jpg b/tests/geotag/test-gps-no-gps.jpg new file mode 100644 index 0000000..7b99f74 Binary files /dev/null and b/tests/geotag/test-gps-no-gps.jpg differ diff --git a/tests/geotag/test-gps-no-gps.mkv b/tests/geotag/test-gps-no-gps.mkv new file mode 100644 index 0000000..2db1945 --- /dev/null +++ b/tests/geotag/test-gps-no-gps.mkv @@ -0,0 +1 @@ +Eߣ—B†�B÷�B‚ˆmatroskaB‡�S€gÿTÃg«ss¨gÈ¥E£’RECORDING_LOCATIOND‡�San Francisco \ No newline at end of file diff --git a/tests/geotag/test-gps-xmp-uuid.mp4 b/tests/geotag/test-gps-xmp-uuid.mp4 new file mode 100644 index 0000000..15422dc Binary files /dev/null and b/tests/geotag/test-gps-xmp-uuid.mp4 differ diff --git a/tests/geotag/test-gps-xmp.heic b/tests/geotag/test-gps-xmp.heic new file mode 100644 index 0000000..3627353 Binary files /dev/null and b/tests/geotag/test-gps-xmp.heic differ diff --git a/tests/geotag/test-gps-xmp.mp4 b/tests/geotag/test-gps-xmp.mp4 new file mode 100644 index 0000000..1da1a0b Binary files /dev/null and b/tests/geotag/test-gps-xmp.mp4 differ diff --git a/tests/geotag/test-gps-xmp.png b/tests/geotag/test-gps-xmp.png new file mode 100644 index 0000000..614ec92 Binary files /dev/null and b/tests/geotag/test-gps-xmp.png differ diff --git a/tests/geotag/test-gps-xmp.webp b/tests/geotag/test-gps-xmp.webp new file mode 100644 index 0000000..4fe32be Binary files /dev/null and b/tests/geotag/test-gps-xmp.webp differ diff --git a/tests/geotag/test-gps.avi b/tests/geotag/test-gps.avi new file mode 100644 index 0000000..8f8a59a Binary files /dev/null and b/tests/geotag/test-gps.avi differ diff --git a/tests/geotag/test-gps.cr3 b/tests/geotag/test-gps.cr3 new file mode 100644 index 0000000..a3f8b5d Binary files /dev/null and b/tests/geotag/test-gps.cr3 differ diff --git a/tests/geotag/test-gps.dng b/tests/geotag/test-gps.dng new file mode 100644 index 0000000..94fa1fe Binary files /dev/null and b/tests/geotag/test-gps.dng differ diff --git a/tests/geotag/test-gps.exr b/tests/geotag/test-gps.exr new file mode 100644 index 0000000..aaf5312 Binary files /dev/null and b/tests/geotag/test-gps.exr differ diff --git a/tests/geotag/test-gps.geotiff b/tests/geotag/test-gps.geotiff new file mode 100644 index 0000000..bc82554 Binary files /dev/null and b/tests/geotag/test-gps.geotiff differ diff --git a/tests/geotag/test-gps.heic b/tests/geotag/test-gps.heic new file mode 100644 index 0000000..07ecf23 Binary files /dev/null and b/tests/geotag/test-gps.heic differ diff --git a/tests/geotag/test-gps.jp2 b/tests/geotag/test-gps.jp2 new file mode 100644 index 0000000..7aebeb3 Binary files /dev/null and b/tests/geotag/test-gps.jp2 differ diff --git a/tests/geotag/test-gps.jpg b/tests/geotag/test-gps.jpg new file mode 100644 index 0000000..e8ebb9d Binary files /dev/null and b/tests/geotag/test-gps.jpg differ diff --git a/tests/geotag/test-gps.mkv b/tests/geotag/test-gps.mkv new file mode 100644 index 0000000..d4700f5 --- /dev/null +++ b/tests/geotag/test-gps.mkv @@ -0,0 +1,7 @@ +Eߣ—B†�B÷�B‚ˆmatroskaB‡�S€gÿA¤iA•a§A‘Fn‡gps.xmpF`“application/rdf+xmlF\Am + + + + + + \ No newline at end of file diff --git a/tests/geotag/test-gps.mov b/tests/geotag/test-gps.mov new file mode 100644 index 0000000..461f575 Binary files /dev/null and b/tests/geotag/test-gps.mov differ diff --git a/tests/geotag/test-gps.mp4 b/tests/geotag/test-gps.mp4 new file mode 100644 index 0000000..8f89635 Binary files /dev/null and b/tests/geotag/test-gps.mp4 differ diff --git a/tests/geotag/test-gps.png b/tests/geotag/test-gps.png new file mode 100644 index 0000000..cbfec69 Binary files /dev/null and b/tests/geotag/test-gps.png differ diff --git a/tests/geotag/test-gps.psd b/tests/geotag/test-gps.psd new file mode 100644 index 0000000..b7a6b85 Binary files /dev/null and b/tests/geotag/test-gps.psd differ diff --git a/tests/geotag/test-gps.tiff b/tests/geotag/test-gps.tiff new file mode 100644 index 0000000..94fa1fe Binary files /dev/null and b/tests/geotag/test-gps.tiff differ diff --git a/tests/geotag/test-gps.webp b/tests/geotag/test-gps.webp new file mode 100644 index 0000000..370a652 Binary files /dev/null and b/tests/geotag/test-gps.webp differ diff --git a/tests/results.json b/tests/results.json index 44c7355..d04a1c3 100644 --- a/tests/results.json +++ b/tests/results.json @@ -11120,6 +11120,11 @@ "status": "ok", "task": 860 }, + "861": { + "note": "no sample file on disk", + "result": "no-sample", + "task": 861 + }, "87": { "decoded": false, "exit": 0, diff --git a/tools/overrides.json b/tools/overrides.json index 499be05..7925533 100644 --- a/tools/overrides.json +++ b/tools/overrides.json @@ -7555,6 +7555,34 @@ "magic_off": 0, "name": "Zstandard archive" }, + "861": { + "endian": "le", + "ext": ".WEBP", + "fields": [ + { + "kind": "ascii", + "name": "signature", + "offset": 0, + "size": 4 + }, + { + "kind": "u32", + "name": "file_size", + "offset": 4, + "size": 4 + }, + { + "kind": "ascii", + "name": "form_type", + "offset": 8, + "size": 4 + } + ], + "magic": "52494646", + "magic_off": 0, + "name": "WebP image", + "notes": "No blog task: WebP is not among the 860 fileformat.vpscoder.com tasks (task 861 assigned here for sfile coverage). RIFF container, form type WEBP (RFC 9649). EXIF in an EXIF chunk, XMP in an XMP chunk; see src/geotag.c." + }, "9": { "magic": "213c617263683e0a", "notes": "static libraries are ar archives, like .deb"