Compare commits

...
10 Commits
Author SHA1 Message Date
Muse 934c336667 sgeo --trip: draw the journey as an ordered polyline with time labels
Reads a stag CSV, orders the geotagged rows by their parsed
timestamp (ISO and EXIF-colon forms sort together), and draws the
trip on an OSM map: blue line with white halo, direction arrowhead
per leg, red marker per stop, MM-DD HH:MM label per timestamped
stop. Rows without a timestamp go last in CSV order; rows without
coordinates are skipped. Reuses sgeo tile/zoom/marker code via
shared fetch_tiles/draw_attribution helpers. Tests: 11/11 in
tests/run_tests.sh (3 new trip cases + tests/check_trip.py).
Docs: docs/trip-path.md.
2026-12-02 09:36:30 +00:00
cnmcdee a2106045a6 json: --json output and libsfile linkable library
- sfile --json: one JSON object per file (JSON Lines) carrying format,
  offsets, decoded fields and geotags when present; default CLI
  output byte-identical (verified against the pre-refactor binary).
- libsfile: src/sfile.h + src/sfile_lib.c expose the decoder
  (sfile_decode_file/mem, sfile_result_to_json, format table
  introspection); make lib builds libsfile.a and libsfile.so.1.1.0,
  make install installs them plus the header.
- tests/test_json.py: JSON parses and matches the text table on the
  same files (make test-json); tests/test_library.c + test_lib.sh:
  static and shared link test (make test-lib).
2026-12-02 09:28:39 +00:00
Muse b21573d47d docs: make works in a fresh clone again now decoders landed (b368998)
Remove the stale caveat that make fails without src/geotag.c.
Plain make builds sfile (and scar); make stag sgeo stays the
minimal build for the geotag tools.
2026-12-02 09:23:36 +00:00
Muse b3689981bc Geotagging decoders: GPS from EXIF/XMP/QuickTime/GeoTIFF/EXR/PSD/CR3 (26 fixtures, 26 PASS)
Dedicated pass in src/geotag.c (dispatched by task number) reporting
latitude/longitude/altitude/datum/datetime for JPEG/TIFF/RAW (EXIF GPS
IFD 0x8825), PNG (eXIf + XMP), WebP (EXIF + XMP, new task 861),
HEIC/HEIF/AVIF (Exif + mime XMP items), MP4/MOV (prefixed (c)xyz,
udta/meta ISO6709 keys, XMP_ and uuid XMP), 3GP loci, CR3 CMT4 + CTBO
XMP, GeoTIFF tiepoint/transformation, EXR float attrs, JP2 uuid XMP,
PSD resources 1058/1060, MKV/AVI XMP only (no native GPS field).
Fixtures in tests/geotag/ cross-checked against exiftool 13.50 and
real files written by exiftool/ffmpeg. Full suite unchanged:
650 PASS / 97 PARTIAL / 2 FAIL / 105 NO SAMPLE.
2026-12-02 09:20:41 +00:00
Muse 3f725687e2 docs: stag/sgeo usage, CSV format, map + attribution, build caveat
- docs/stag-sgeo.md: building (make stag sgeo; make all blocked on
  uncommitted src/geotag.c), sfile lookup order, media-extension scan
  set, CSV columns + empty-coords rule, real stag/sgeo output against
  the decoder build of sfile (SF/Tokyo EXIF GPS), OSM attribution and
  the runtime tile-fetch dependency, test suite (8/8).
- README.md: stag/sgeo section + Layout/Building entries.
2026-12-02 09:18:42 +00:00
Muse 720523151a contract: datetime is ISO YYYY-MM-DD, not EXIF YYYY:MM:DD
Real-file test against the /opt/sfile decoders showed the decoder
normalises EXIF GPSDateStamp to dashes (geotag.c: EXIF stores the
date as YYYY:MM:DD; normalised to ISO YYYY-MM-DD so the field is
machine-parseable). The contract example/table said YYYY:MM:DD.
Fixed the doc, and the fake sfile + expected CSV to match the real
decoder output (the nyc fallback case still exercises the colon
form via GPSDateStamp).
2026-12-02 09:15:06 +00:00
Muse 8f81caa14b tests + contract: fake-sfile harness, tile server, map checks
tests/run_tests.sh: fake sfile on PATH (tests/bin/sfile, canned GPS
values in section + EXIF tag-name forms), a local tile server
(tests/tile_server.py, $SGEO_TILE_BASE) so sgeo tests run offline,
and tests/check_map.py (stdlib PNG decode: marker-cluster count +
attribution plaque). Cases: multi-file CSV byte-for-byte, multi +
single-point maps, no-geotag dir, empty dir, default outfiles.
8 checks, all passing.

docs/geotag-contract.md: the field-name contract between the
decoder (what sfile prints in its Geotagging: section) and the
client parser (section + EXIF tag-name / uniform-table fallback
forms it accepts), incl. first-source-wins, defaults, and ranges.

Note: tests/bin/sfile is force-added -- .gitignore has a bare
sfile rule for the built binary.
2026-12-02 09:15:06 +00:00
Muse 134eaac49e sgeo: plot geotagged files on an OpenStreetMap image
sgeo [dir] [outfile] collects media files, extracts geotags via the
client seam, and plots one red marker per geotagged file on a map
stitched from tile.openstreetmap.org tiles (libcurl at runtime,
libpng stitching). Zoom is computed from the points bounding box
(single point, or coincident points, use zoom 15); the tile count
is capped by zooming out. Attribution (C) OpenStreetMap
contributors is drawn ON the image with a self-contained 5x7 bitmap
font -- no ImageMagick at runtime. $SGEO_TILE_BASE overrides the
tile source (for tests). With no geotagged files sgeo prints a
message to stderr, exits non-zero, and writes no output file.
2026-12-02 09:15:06 +00:00
Muse 7e9657520c stag: scan a directory and tabulate geotags as CSV
stag [dir] [outfile] collects media files (non-recursive), runs sfile
on each via the geotag client seam (src/geotag_client.c, $SFILE/PATH/
alongside-executable lookup) and writes one CSV row per file:
file,format,latitude,longitude,altitude,datum,timestamp,source.
Files with no geotag still get a row, with the geotag fields empty.

Also fixes a typo in the seam that broke the build: strrchr(self, /)
was missing its quotes (must be strrchr(self, /)).

Makefile: new stag target (links geotag_client.c, -lm); all still
builds just sfile.
2026-12-02 09:15:06 +00:00
cnmcdee eac6be4802 scar: file carver built on sfiles format table
Scan a raw disk image for sfiles known magics (831 formats) and carve
out the files: PNG chunk walk, JPEG marker walk, GIF block walk, ZIP
local-header walk + EOCD, PDF %%EOF scan, gzip inflate sizing; next-
header/EOF fallback with a size cap for the rest. Report lists offset,
format, size, confidence and how the end was found.

- src/scar.c, src/footers.h: carver + footer/trailer table
- Makefile: scar target (links -lz), test-scar target, install both
- tests/test_scar.py: synthetic image, 7 files recovered byte-identical
- docs/scar.md: usage, real example output, decisions, limits
2026-12-02 09:12:01 +00:00
65 changed files with 8701 additions and 272 deletions

No files matched your search

+6
View File
@@ -10,3 +10,9 @@ __pycache__/
LOOP_STATUS
loop.log
driver.pid
scar
libsfile.a
libsfile.so
libsfile.so.1
libsfile.so.*
+70 -8
View File
@@ -4,14 +4,60 @@ CFLAGS ?= -O2 -Wall -Wextra -std=c11
PREFIX ?= /usr/local
SRC = src/sfile.c
LIB_SRC = src/sfile_lib.c src/geotag.c
LIB_HDR = src/sfile.h src/geotag.h
LIB_OBJ = sfile_lib.o geotag.o
LIB_A = libsfile.a
LIB_SO = libsfile.so.1.1.0
LIB_SONAME = libsfile.so.1
BIN = sfile
GEN = tools/gen_formats.py
TABLE = src/formats.h src/formats.json
all: $(BIN)
SCAR_SRC = src/scar.c
SCAR_BIN = scar
$(BIN): $(SRC) src/formats.h
$(CC) $(CFLAGS) -o $@ $(SRC)
all: $(BIN) $(SCAR_BIN) lib
$(BIN): $(SRC) $(LIB_OBJ) src/formats.h
$(CC) $(CFLAGS) -o $@ $(SRC) $(LIB_OBJ)
# libsfile — the decode engine as a linkable library (see docs/library.md).
# The CLI links the same objects, so library and CLI results agree.
# geotag.c is part of the library: sfile_decode_file fills the geotag
# fields of sfile_result via geotag_scan().
lib: $(LIB_A) libsfile.so
sfile_lib.o: src/sfile_lib.c $(LIB_HDR) src/formats.h
$(CC) $(CFLAGS) -c -o $@ src/sfile_lib.c
geotag.o: src/geotag.c src/geotag.h
$(CC) $(CFLAGS) -c -o $@ src/geotag.c
$(LIB_A): $(LIB_OBJ)
ar rcs $@ $(LIB_OBJ)
$(LIB_SO): $(LIB_SRC) $(LIB_HDR) src/formats.h
$(CC) $(CFLAGS) -fPIC -shared -Wl,-soname,$(LIB_SONAME) -o $@ $(LIB_SRC)
libsfile.so: $(LIB_SO)
ln -sf $(LIB_SO) $(LIB_SONAME)
ln -sf $(LIB_SONAME) libsfile.so
# scar — file carver built on sfile's format table (src/scar.c).
# Links zlib: gzip members are sized by inflating the stream.
# (The file target below also answers `make scar`.)
$(SCAR_BIN): $(SCAR_SRC) src/formats.h src/footers.h
$(CC) $(CFLAGS) -o $@ $(SCAR_SRC) -lz
# stag / sgeo -- geotag tools. They do NOT link against sfile: they run
# the sfile binary and parse its "Geotagging:" section through the
# client seam in src/geotag_client.c (see docs/geotag-contract.md).
stag: src/stag.c src/geotag_client.c src/geotag_client.h
$(CC) $(CFLAGS) -o $@ src/stag.c src/geotag_client.c -lm
sgeo: src/sgeo.c src/geotag_client.c src/geotag_client.h
$(CC) $(CFLAGS) -o $@ src/sgeo.c src/geotag_client.c -lpng -lcurl -lm
# Regenerate the format table from the collected reference code.
# (Requires tools/all_formats.cpp; overrides live in tools/overrides.json.)
@@ -21,12 +67,28 @@ table: $(GEN) tools/all_formats.cpp
test: $(BIN)
./tests/run_tests.sh
install: $(BIN)
mkdir -p $(PREFIX)/bin
test-json: $(BIN)
python3 tests/test_json.py
test-lib: lib
./tests/test_lib.sh
test-geotag: $(BIN)
python3 tests/geotag/run_geotag_tests.py
test-scar: $(SCAR_BIN)
python3 tests/test_scar.py
install: $(BIN) $(SCAR_BIN) lib
mkdir -p $(PREFIX)/bin $(PREFIX)/lib $(PREFIX)/include
cp $(BIN) $(PREFIX)/bin/
chmod 755 $(PREFIX)/bin/$(BIN)
cp $(SCAR_BIN) $(PREFIX)/bin/
cp $(LIB_A) $(PREFIX)/lib/
cp -P $(LIB_SO) $(LIB_SONAME) libsfile.so $(PREFIX)/lib/
cp $(LIB_HDR) $(PREFIX)/include/
chmod 755 $(PREFIX)/bin/$(BIN) $(PREFIX)/bin/$(SCAR_BIN)
clean:
rm -f $(BIN) *.o
rm -f $(BIN) $(SCAR_BIN) stag sgeo *.o $(LIB_A) $(LIB_SO) $(LIB_SONAME) libsfile.so
.PHONY: all table test install clean
.PHONY: all table test test-json test-lib test-geotag test-scar install clean lib
+187 -13
View File
@@ -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
@@ -129,11 +183,15 @@ samples, gzip files saved as .bson) are deleted, not tested.
**Table-driven, generic engine.** All per-format knowledge lives in the
generated table `src/formats.h` (one entry per format: extension, name,
magic bytes + offset, field list of name/offset/size/kind, endianness).
The engine (`src/sfile.c`) contains no per-format decode logic — it walks
the table, matches magic, and formats the fields. A format is never
"guessed": the decode is derived from the collected reference code, a
published format spec (the hand overrides), or a verified sample file,
and the derivation is recorded per format in `src/formats.json`.
The engine (`src/sfile_lib.c`, shipped as `libsfile` — see below)
contains no per-format decode logic — it walks the table, matches
magic, and formats the fields. The `sfile` CLI (`src/sfile.c`) is a
thin wrapper over the library: it parses arguments and prints the
library's `sfile_result`, as the human table or as JSON. A format is
never "guessed": the decode is derived from the collected reference
code, a published format spec (the hand overrides), or a verified
sample file, and the derivation is recorded per format in
`src/formats.json`.
**Identification order.** Longest magic match wins. Several formats share
a magic (all ZIP-based formats share `PK\x03\x04`; all RIFF formats share
@@ -152,21 +210,66 @@ first line.
## Building
```
make # builds ./sfile (gcc, -O2 -Wall -Wextra, no exotic deps)
make # builds ./sfile and ./scar (gcc, -O2 -Wall -Wextra, no exotic deps)
make lib # builds libsfile.a + libsfile.so.1.1.0 (see below)
make stag sgeo # builds the geotag tools (see below)
make table # regenerate src/formats.h from tools/all_formats.cpp
make test # run the per-format test loop over samples/
make test-json # JSON output tests (parses + matches the text table)
make test-lib # library link test, static and shared
make test-geotag # geotag decoder tests (26 fixtures)
make install # install to /usr/local/bin (PREFIX=... to change)
```
## Usage
```
sfile <file> identify + decode the header
sfile <file>... identify + decode the header (several files OK)
sfile --json <file>... same decode as JSON, one object per file (one per line)
sfile --list list all known formats (task, extension, name)
sfile --help
sfile --version
```
Exit codes: 0 identified, 1 usage error, 2 file unreadable, 3 unknown format.
With several files the worst code wins (unreadable beats unknown).
## JSON output
`sfile --json` prints the same decode as JSON (one compact object per
file, one per line): format, offsets, decoded fields, and `geotags`
when the file carries a location (from `geotag_scan()` — EXIF GPS,
XMP, QuickTime, GeoTIFF, EXR, PSD, CR3). See `docs/json.md` for the
schema and real examples.
```sh
$ sfile --json photo.png
{"file":"photo.png","size":29,"identified":true,"format":{"task":564,"ext":".PNG","name":"PNG image","kind":"binary","endian":"big"},"identified_by":"magic","magic":{"bytes":"89 50 4e 47 0d 0a 1a 0a","offset":0},"header":{"endian":"big","fields":[{"offset":0,"size":8,"name":"signature","type":"bytes","value":"89 50 4e 47 0d 0a 1a 0a"},{"offset":8,"size":4,"name":"ihdr_length","type":"u32","value":13},{"offset":12,"size":4,"name":"ihdr_type","type":"ascii","value":"IHDR"},{"offset":16,"size":4,"name":"width","type":"u32","value":800},{"offset":20,"size":4,"name":"height","type":"u32","value":600},{"offset":24,"size":1,"name":"bit_depth","type":"u8","value":8},{"offset":25,"size":1,"name":"color_type","type":"u8","value":2},{"offset":26,"size":1,"name":"compression","type":"u8","value":0},{"offset":27,"size":1,"name":"filter","type":"u8","value":0},{"offset":28,"size":1,"name":"interlace","type":"u8","value":0}]},"geotags":[]}
```
## Library mode: libsfile
The decode engine is also a linkable C library — `make lib` builds
`libsfile.a` and `libsfile.so.1.1.0`, `make install` puts them in
`$(PREFIX)/lib` with `sfile.h` + `geotag.h` in `$(PREFIX)/include`.
Link it instead of shelling out to the `sfile` binary:
```c
#include "sfile.h"
sfile_result r;
sfile_decode_file("photo.png", &r); /* 0 identified, 2 unreadable, 3 unknown */
printf("%s, task %d, %d fields\n", r.name, r.task, r.nfields);
sfile_free_result(&r);
```
```sh
gcc prog.c -lsfile # shared (after make install)
gcc prog.c libsfile.a # static
```
See `docs/library.md` for the full API, a worked example with real
output, and the tests (`make test-lib`).
## Testing
@@ -194,7 +297,16 @@ values) is fixed in `tools/overrides.json` and the table regenerated.
```
sfile/
src/sfile.c the engine (generic; no per-format code)
src/sfile.c the CLI (thin wrapper over libsfile)
src/sfile.h libsfile public API
src/sfile_lib.c the decode engine (generic; no per-format code)
src/geotag.c geotag decoders (EXIF/XMP/QuickTime/GeoTIFF/EXR/PSD/CR3)
src/geotag.h geotag_scan() / GeoResult API
src/scar.c file carver built on the format table
src/stag.c geotag CSV tabulator (see below)
src/sgeo.c geotag map plotter (see below)
src/geotag_client.c the stag/sgeo <-> sfile seam (runs sfile, parses "Geotagging:")
src/footers.h footer/trailer signatures used by scar
src/formats.h generated format table (do not edit by hand)
src/formats.json the table as JSON (source of truth for tests)
tools/gen_formats.py generator: reference code -> formats.json/.h
@@ -204,10 +316,72 @@ sfile/
tools/get_sample_urls.py extracts sample_urls.json from the raw pages
tools/extract_cpp.py extracts all_formats.cpp from the raw pages
tests/run_tests.py the per-format test loop
tests/run_tests.sh the stag/sgeo test suite (11 checks, fake sfile + local tile server)
tests/test_json.py --json tests: parses + matches the text table (make test-json)
tests/test_lib.sh library link test, static + shared (make test-lib)
tests/test_library.c link-test program (decodes via the public API only)
tests/make_fixtures.py synthetic fixtures shared by the JSON/library tests
tests/test_scar.py synthetic-image test for scar (make test-scar)
tests/results.json latest test results
docs/scar.md scar usage, carving decisions, limits
docs/json.md --json output: schema, geotags, examples
docs/library.md libsfile: API, building, example, tests
docs/stag-sgeo.md stag/sgeo usage, CSV format, map + attribution, network dependency
docs/trip-path.md sgeo --trip: the journey as a polyline with time labels
docs/geotag-contract.md the sfile <-> stag/sgeo geotag seam (what sfile prints, what the client accepts)
samples/ one real sample file per format + manifests
```
## Carving: scar
`scar` recovers deleted files from a raw disk image using the same
format table: it scans for known magics and carves out each file it
finds, with a report (offset, format, size, confidence) — see
`docs/scar.md`.
```
$ make scar
$ scar image.dd # carves into ./carved/, prints a report table
```
See `docs/scar.md` for a full example run (real output), how carving
decisions are made, and the limits.
## Geotags: stag and sgeo
`stag` scans a directory of photos/videos and writes one CSV row per
file (`file,format,latitude,longitude,altitude,datum,timestamp,source`);
every scanned file gets a row, with empty geo fields when no location
was found. `sgeo` plots the geotagged files on an OpenStreetMap image
(one red marker each, attribution baked onto the PNG). `sgeo --trip
geotags.csv` draws the same points as a journey instead: the rows in
timestamp order, connected as a polyline with time labels (see
`docs/trip-path.md`). Both run the
`sfile` binary and parse its `Geotagging:` section — they never parse
containers themselves; the seam is `docs/geotag-contract.md`.
```console
$ make stag sgeo # build the geotag tools
$ stag photos/ # -> geotags.csv in the cwd
$ sgeo photos/ # -> map.png in the cwd (fetches OSM tiles at runtime)
```
Real output (San Francisco + Tokyo EXIF GPS, via the decoder build
of sfile):
```text
file,format,latitude,longitude,altitude,datum,timestamp,source
plain.jpg,JPEG image,,,,,,
sf_real.jpg,JPEG image,37.774929,-122.419418,12.000,WGS-84,2024-05-01 12:34:56,EXIF GPS IFD (JPEG APP1 segment)
tokyo_real.jpg,JPEG image,35.676200,139.650300,,WGS-84,,EXIF GPS IFD (JPEG APP1 segment)
```
`sgeo` needs network access to tile.openstreetmap.org when it runs,
and the `© OpenStreetMap contributors` attribution drawn on the image
must stay there. See `docs/stag-sgeo.md` for the full usage, the CSV
format and the empty-coords rule, the test suite
(`tests/run_tests.sh`, 11/11 pass), and the build caveat.
## Sources
Format reference code: https://fileformat.vpscoder.com (849 task pages).
+119
View File
@@ -0,0 +1,119 @@
# Geotag contract: what sfile prints, what the client parser accepts
Coordination doc for the two sides of the geotag seam:
- **Decoder side** — `src/geotag.c` (`decode_geotag()`), owned by the
geotagging-decoder work. It walks the real container structures
(EXIF GPS IFD, XMP, QuickTime location, GeoTIFF, ...) and prints a
`Geotagging:` section.
- **Client side** — `src/geotag_client.c` (`extract_geotag()`), owned by
the stag/sgeo work. It runs the `sfile` binary, captures stdout, and
parses the section below into a `Geotag`. stag and sgeo never parse
image/video containers themselves.
If the decoder changes what it prints, this doc and the client parser
change together. The client deliberately accepts *more* than the
decoder currently prints (the fallback forms in §3), so older sfile
output keeps working.
## 1. The section format (what the decoder prints)
Printed once per file, after the format header, for every format that
has a geotagging mechanism. One block per location found (up to 8),
each block starting with a `source:` line:
```
Geotagging:
source: EXIF GPS
gps_latitude: 37.774929 (37°46'29.64"N)
gps_longitude: -122.419418 (122°25'9.90"W)
gps_altitude_m: 12.000 (above sea level)
gps_datum: WGS-84
gps_datetime_utc: 2024-05-01 12:34:56
```
Field rules:
| Line | Meaning |
| ---- | ------- |
| `source: <text>` | Where the location came from, e.g. `EXIF GPS`, `XMP`, `QuickTime location`. Starts a new block. |
| `gps_latitude: <decimal> (<DMS>)` | Signed decimal degrees, WGS-84, 6 decimals. The parenthesised DMS display (`37°46'29.64"N`) is display-only; the decimal before it is authoritative. |
| `gps_longitude: <decimal> (<DMS>)` | Same, signed decimal degrees. |
| `gps_altitude_m: <value> (above\|below sea level)` | Metres above sea level, 3 decimals. Only printed when an altitude was recovered. `(below sea level)` means the value is a depth (client negates it). |
| `gps_datum: <text>` | Datum as recorded, usually `WGS-84`. Some sources append a qualifier in parentheses, e.g. `WGS-84 (EPSG:4326)` (GeoTIFF), `WGS-84 (ISO 6709 default)` (QuickTime location), `WGS-84 (OpenEXR default)`. Only printed when known. |
| `gps_datetime_utc: <datetime>` | UTC timestamp, ISO `YYYY-MM-DD HH:MM:SS`. The decoder normalises EXIF dates (`YYYY:MM:DD` as stored) to dashes so the field is machine-parseable. Date only (`YYYY-MM-DD`) when no time was recovered, time only when no date was. Only printed when known. |
No location found (format has a mechanism, but this file carries
none):
```
Geotagging:
none found (searched EXIF GPS IFD in JPEG APP1; XMP in JPEG APP1)
```
The parenthesised text names what was searched; the client ignores
it — absence of coordinates already means "no geotag".
Formats with **no** geotagging mechanism print **no** `Geotagging:`
section at all; the client treats that the same as "none found".
## 2. Client semantics
- **First source wins.** When the decoder prints several blocks, the
client parses the first block only; a second `source:` line stops
parsing. (The decoder prints blocks in its own priority order.)
- **A geotag counts only if both latitude and longitude parse** and
are in range (latitude ±90, longitude ±180); otherwise `found = 0`.
- **Datum** defaults to `WGS-84` when a location was found and no
`gps_datum` line was printed. **Source** defaults to `unknown`
when no `source:` line was seen.
- **Timestamp** is passed through verbatim from `gps_datetime_utc`,
or assembled from the fallback date/time tags (§3).
- **Format name** comes from sfile's `Format:` line
(`Format: NAME (ext) — task N` → `NAME`; `Format: unknown ...` →
`unknown`).
## 3. Fallback forms the client also accepts
The decoder is not the only producer of GPS text: sfile's generic
header dump can also show the raw EXIF GPS tags. The client accepts
those too, so a file whose GPS tags appear in the uniform header
table still yields a geotag. Either of these forms works:
Key: value lines (as printed, or as rows of sfile's uniform table,
`offset size field value...`):
```
GPSLatitude: 37/1, 46/1, 2964/100 GPSLatitudeRef: N
GPSLongitude: 122/1, 25/1, 990/100 GPSLongitudeRef: W
GPSAltitude: 12/1 GPSAltitudeRef: 0
GPSDateStamp: 2024:05:01 GPSTimeStamp: 12/1, 34/1, 56/1
```
Accepted variants:
- **Key matching** is case-insensitive and ignores `_`, space and
`-` in the key, so `GPSLatitude`, `gps_latitude`, `GPS latitude`
and `GPS map datum` all match. `gps_mapdatum` is accepted as an
alias of `gps_datum`; `gps_datetime` as an alias of
`gps_datetime_utc`.
- **Coordinate values** may be a plain decimal (`37.774929`), DMS
rationals (`37/1, 46/1, 2964/100`), or DMS with symbols
(`37°46'29.64"N`). A hemisphere letter in the value (`N`/`S`/
`E`/`W`) applies, but an explicit `...Ref` tag wins over it:
`S`/`W` negate, `N`/`E` keep positive.
- **Altitude** may be a rational (`12/1`) or a decimal; `GPSAltitudeRef`
`1` (or the words `below sea level`) negates it, `0` / `above`
keeps it positive.
- **Timestamp** may come from `gps_datetime_utc` verbatim, or from
`GPSDateStamp` (`YYYY:MM:DD`) plus `GPSTimeStamp` (either
`HH:MM:SS` or rationals `12/1, 34/1, 56/1`).
## 4. What stag/sgeo do with a parsed Geotag
stag writes one CSV row per scanned file with the columns
`file,format,latitude,longitude,altitude,datum,timestamp,source`
(latitude/longitude `%.6f`, altitude `%.3f`, empty when absent).
sgeo plots one marker per file with `found == 1`, at
(latitude, longitude). Both tools get the format name from the same
parsed `Format:` line.
+217
View File
@@ -0,0 +1,217 @@
# sfile --json — machine-readable decode output
`sfile --json <file>...` prints the same decode as the human-readable
table, as JSON: **one compact JSON object per file, one per line**
(JSON Lines). Each line parses on its own; with several files the
output is one object per line, in argument order.
```sh
sfile --json photo.png
sfile --json *.png > decodes.jsonl # one object per file
```
Exit codes are unchanged from the text mode: 0 identified, 1 usage
error, 2 file unreadable, 3 unknown format. With several files the
worst code wins (unreadable beats unknown). An unreadable file still
produces a JSON object on stdout (with `size: null` and an `error`
string); the `perror`-style message also goes to stderr, so stdout
stays pure JSON.
## Example: a PNG header
The CLI emits compact one-line JSON; the object below is the real
output of `sfile --json` on a 29-byte PNG, reformatted for reading:
```json
{
"file": "/tmp/fx/sample.png",
"size": 29,
"identified": true,
"format": {"task": 564, "ext": ".PNG", "name": "PNG image",
"kind": "binary", "endian": "big"},
"identified_by": "magic",
"magic": {"bytes": "89 50 4e 47 0d 0a 1a 0a", "offset": 0},
"header": {
"endian": "big",
"fields": [
{"offset": 0, "size": 8, "name": "signature", "type": "bytes",
"value": "89 50 4e 47 0d 0a 1a 0a"},
{"offset": 8, "size": 4, "name": "ihdr_length", "type": "u32",
"value": 13},
{"offset": 12, "size": 4, "name": "ihdr_type", "type": "ascii",
"value": "IHDR"},
{"offset": 16, "size": 4, "name": "width", "type": "u32",
"value": 800},
{"offset": 20, "size": 4, "name": "height", "type": "u32",
"value": 600},
{"offset": 24, "size": 1, "name": "bit_depth", "type": "u8",
"value": 8},
{"offset": 25, "size": 1, "name": "color_type", "type": "u8",
"value": 2},
{"offset": 26, "size": 1, "name": "compression", "type": "u8",
"value": 0},
{"offset": 27, "size": 1, "name": "filter", "type": "u8",
"value": 0},
{"offset": 28, "size": 1, "name": "interlace", "type": "u8",
"value": 0}
]
},
"geotags": []
}
```
Compare with the text mode on the same file: the field values agree
(`width` 800, `ihdr_type` `"IHDR"`, …) — JSON is a re-encoding of the
same decode, not a second implementation. `tests/test_json.py`
checks this parity on every fixture (`make test-json`).
## Schema
| key | when present | meaning |
|---|---|---|
| `file` | always | path as given on the command line |
| `size` | always | file size in bytes, or `null` when unreadable |
| `identified` | always | `true` when a format was identified |
| `error` | `status != 0` | human-readable reason (`"unknown format (no magic match, no known extension)"`, or the `strerror` text for unreadable files) |
| `format` | identified | `task` (fileformat task number), `ext`, `name`, `kind` (`"binary"` / `"text"` / `"unknown"`), `endian` (`"big"` / `"little"`) |
| `identified_by` | identified | `"magic"` or `"extension"` |
| `magic` | magic present | `bytes` (space-separated lowercase hex), `offset` |
| `other_candidates` | >1 format shares the magic | the other formats' `ext` + `task` (the chosen format excluded) |
| `header` | binary format with a layout | `endian` + `fields[]` |
| `document` | text format | see below |
| `note` | binary format, no layout | `"no header layout derived (derivation: magic-only)"` or `"(derivation: unknown)"` |
| `hexdump` | unknown, or no layout | first 64 bytes, space-separated lowercase hex |
| `geotags` | format has a geotagging mechanism | array of locations (empty when none found); omitted when the format has no mechanism at all |
### Field objects
`{"offset", "size", "name", "type", "value"}` — `offset`/`size` in
bytes, `name` from the format table, `type` one of `u8 u16 u32 u64 i8
i16 i32 i64 f32 f64 ascii bytes`.
`value` is a JSON number for numeric fields (integers exact; floats
at full `%.17g` precision, so a latitude survives the round-trip —
the text table's `%g` shows only 6 significant digits), a JSON string
for `ascii` (unquoted — the text table quotes it: `"IHDR"`) and for
`bytes` (space-separated hex, no trailing space).
A field that runs past the bytes read (empty/truncated file) has
`"value": null` and `"unavailable": "beyond header window / EOF"` —
the same words the text table prints.
### Document objects (text formats)
```json
{"type": "xml", "declaration": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"root_element": "catalog", "version": "2.0"}
{"type": "json", "first_key": "name"}
{"type": "text", "first_line": "Hello, sfile."}
```
Keys that were not found are omitted (a JSON array has just
`{"type": "json"}`; a text file always has `first_line`, possibly
`""`).
### Geotag objects
`geotags` comes from `geotag_scan()` (`src/geotag.c`) — the same
decoders behind the text mode's `Geotagging:` section (EXIF GPS,
XMP, QuickTime/ISO 6709, GeoTIFF, EXR, PSD, CR3, …). Each entry:
```json
{"source": "EXIF GPS IFD (JPEG APP1 segment)",
"latitude": 37.7749, "longitude": -122.41940000000001,
"altitude_m": 10, "datum": "WGS-84",
"datetime_utc": "2026-12-01 12:34:56"}
```
`source`, `latitude`, `longitude` are always present;
`altitude_m`, `datum`, `datetime_utc` only when the decoder found
them. A file can carry several locations (an MP4 with two
QuickTime sources yields two entries). `geotags: []` means the
format has a mechanism but this file carries no location; the key
is omitted entirely when the format has no mechanism. Header
fields merely *named* `latitude`/`longitude` (e.g. SPS track
files, task 678) are decoded as ordinary fields and are **not**
geotags — they do not produce a `geotags` key.
## Example: geotags, shared magic, unknown, unreadable
A JPEG with EXIF GPS (the tail of the real output of
`sfile --json tests/geotag/test-gps.jpg`):
```json
"geotags": [
{
"source": "EXIF GPS IFD (JPEG APP1 segment)",
"latitude": 37.7749,
"longitude": -122.41940000000001,
"altitude_m": 10,
"datum": "WGS-84",
"datetime_utc": "2026-12-01 12:34:56"
}
]
```
The text mode prints the same location as:
```
Geotagging:
source: EXIF GPS IFD (JPEG APP1 segment)
gps_latitude: 37.774900 (37°46'29.64"N)
gps_longitude: -122.419400 (122°25'09.84"W)
gps_altitude_m: 10.000 (above sea level)
gps_datum: WGS-84
gps_datetime_utc: 2026-12-01 12:34:56
```
An MP4 with two QuickTime location sources
(`tests/geotag/test-gps.mp4`) yields two entries — same
coordinates, different altitudes:
```json
"geotags": [
{"source": "QuickTime location (moov/udta (c)xyz atom)",
"latitude": 37.7749, "longitude": -122.4194,
"altitude_m": 10, "datum": "WGS-84 (ISO 6709 default)"},
{"source": "QuickTime location (moov/udta/meta com.apple.quicktime.location.ISO6709)",
"latitude": 37.7749, "longitude": -122.4194,
"altitude_m": 30, "datum": "WGS-84 (ISO 6709 default)"}
]
```
An XML file shares its `<?xml` magic with 47 other formats, so the
chosen format's disambiguation is recorded:
```json
{"file": "/tmp/fx/doc.xml", "size": 80, "identified": true,
"format": {"task": 839, "ext": ".XML", "name": "XML", "kind": "text", "endian": "little"},
"identified_by": "magic", "magic": {"bytes": "3c 3f 78 6d 6c", "offset": 0},
"other_candidates": [{"ext": ".POM", "task": 565}, {"ext": ".KML", "task": 341},
{"ext": ".GPX", "task": 266}],
"document": {"type": "xml", "declaration": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"root_element": "catalog", "version": "2.0"}}
```
(`other_candidates` above is abridged — the real output lists all 47.)
Unknown and unreadable files (exit 3 and 2):
```json
{"file": "/tmp/fx/mystery.zzz", "size": 64, "identified": false,
"error": "unknown format (no magic match, no known extension)",
"hexdump": "01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40"}
{"file": "/tmp/fx/does-not-exist.bin", "size": null, "identified": false,
"error": "No such file or directory"}
```
## Tests
`tests/test_json.py` (`make test-json`) builds synthetic fixtures
(PNG, SPS, JSON, XML, text, unknown, empty PNG, magic-only
WEBM/WAB, missing file) and checks that every `--json` line parses,
carries the same facts as the text output on the same file
(including the `Geotagging:` section vs the `geotags` array), and
exits with the same code. The geotag cases use the real fixtures in
`tests/geotag/` (EXIF GPS JPEG, two-result MP4, no-location JPEG).
Fixture builder: `tests/make_fixtures.py`.
+123
View File
@@ -0,0 +1,123 @@
# libsfile — the sfile decode engine as a C library
The `sfile` CLI is a thin wrapper over `libsfile`: the decode engine
(`src/sfile_lib.c`, public API in `src/sfile.h`) plus the geotag
decoders (`src/geotag.c`, API in `src/geotag.h`). Other tools (stag,
sgeo, scar, …) can link it instead of shelling out to the `sfile`
binary — and get exactly the same results the CLI prints, since the
CLI consumes the same `sfile_result` struct.
## Building
```sh
make lib # libsfile.a + libsfile.so.1.1.0 (+ .so.1/.so links)
make # also builds ./sfile and ./scar
make install # /usr/local/{bin,lib,include} (PREFIX=... to change)
```
`make install` puts `libsfile.a`, `libsfile.so.1.1.0` (plus the
`libsfile.so.1` / `libsfile.so` symlinks) in `$(PREFIX)/lib` and
`sfile.h` + `geotag.h` in `$(PREFIX)/include`. The library is new
in sfile 1.1.0; `sfile_result` is a plain struct with no ABI
stability promise across versions — recompile dependents when
upgrading.
## API (`src/sfile.h`)
| function | what it does |
|---|---|
| `sfile_decode_file(path, res)` | decode a file from disk; returns 0 identified, 2 unreadable, 3 unknown (the CLI exit codes). Also runs `geotag_scan()` for the `geotags` fields. |
| `sfile_decode_mem(buf, n, display_name, fsize, res)` | decode bytes already in memory; same return codes. `display_name` is used for the extension fallback. No geotag scan (no path to scan — call `geotag_scan()` yourself if you have one). |
| `sfile_free_result(res)` | release everything the decode allocated. |
| `sfile_result_to_json(res)` | serialize the result as one compact JSON object (see `docs/json.md`); malloc'd, caller frees. |
| `sfile_format_count()` / `sfile_get_format_info(i, info)` | format-table introspection (powers `sfile --list`). |
| `sfile_field_kind_name(kind)` | `"u8"` / `"u16"` / … / `"ascii"` / `"bytes"`. |
| `geotag_scan(path, task, out, max)` | (`src/geotag.h`) fill `out[]` with the locations found (EXIF GPS, XMP, QuickTime, GeoTIFF, EXR, PSD, CR3); returns the count, 0 when the format has a mechanism but no location, -1 when it has none. |
`sfile_result` carries the path and size, the identified format
(task/ext/name/kind/endian, `identified_by`, magic bytes, the other
formats sharing the magic), the decoded header fields (`offset`,
`size`, `name`, `kind`, `value` formatted exactly as the CLI prints
it, plus a JSON-friendly `raw` and the numeric value), the text
fallback decode (`doc_type` + XML/JSON/first-line strings), the
hex dump for unknown/no-layout files, and the geotags
(`geotags[8]` + `ngeotags` + `geotag_status`, the `geotag_scan()`
return: -1 no mechanism, 0 none found, >0 count).
Ownership: strings pointing into the format table (format name/ext,
field names, candidate exts) are borrowed — do not free them.
Everything else in the struct is owned and freed by
`sfile_free_result()`. Threading: the table walk holds no shared
state, except the geotag scan, which reuses `geotag.c`'s static
result buffer — concurrent `sfile_decode_file()` calls are not
thread-safe; serialize them or use `sfile_decode_mem()`.
## Minimal example
```c
/* minimal.c - decode a file with libsfile and print its format + fields */
#include <stdio.h>
#include "sfile.h"
int main(int argc, char **argv) {
if (argc < 2) return 1;
sfile_result r;
int st = sfile_decode_file(argv[1], &r);
if (st != 0) { printf("cannot decode: %s\n", r.error); sfile_free_result(&r); return st; }
printf("%s (%s), task %d, %d fields\n", r.name, r.ext, r.task, r.nfields);
for (int i = 0; i < r.nfields; i++)
printf(" %s = %s\n", r.fields[i].name, r.fields[i].value);
if (r.ngeotags > 0)
printf("geotag: %g, %g (%s)\n", r.geotags[0].lat, r.geotags[0].lon,
r.geotags[0].source);
sfile_free_result(&r);
return 0;
}
```
```sh
# shared library
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o minimal minimal.c -L. -lsfile -Wl,-rpath,$PWD
# or static
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o minimal minimal.c libsfile.a
```
Real output (verified against both):
```
$ ./minimal sample.png
PNG image (.PNG), task 564, 10 fields
signature = 89 50 4e 47 0d 0a 1a 0a
ihdr_length = 13
ihdr_type = "IHDR"
width = 800
height = 600
bit_depth = 8
color_type = 2
compression = 0
filter = 0
interlace = 0
$ ./minimal test-gps.jpg
JPEG image (.JPG), task 332, 4 fields
soi = ff d8
marker = ff e1
segment_length = 258
identifier = "Exif"
geotag: 37.7749, -122.419 (EXIF GPS IFD (JPEG APP1 segment))
```
The field values are the CLI's own strings (`"IHDR"` quoted,
bytes as hex), so a program printing them reproduces the CLI's
header table exactly. `tests/test_library.c` is a fuller example
(it also exercises `sfile_decode_mem()` and
`sfile_result_to_json()`).
## Tests
`tests/test_lib.sh` (`make test-lib`) compiles
`tests/test_library.c` against the static library *and* the
shared library, then diffs the field lines each prints against the
`./sfile` CLI's header table on the same files, checks the
`--mem` path, the EXIF GPS geotag (JPEG fixture), and that the
library's own JSON parses and carries the right geotags.
+122
View File
@@ -0,0 +1,122 @@
# scar — file carver
`scar` recovers deleted files from a raw disk image (or any file: a
memory dump, a firmware blob, a corrupted partition image). It scans for
the magic bytes `sfile` knows about — all 831 formats in
`src/formats.h` — and carves out every file it finds, writing each one
to the output directory as `<offset>.<ext>` and printing a report of
what it recovered, where it was, and how sure it is.
```sh
make scar # builds ./scar (needs zlib: gzip is sized by inflate)
scar image.dd # carves into ./carved/
scar -o recovered image.dd # carve into recovered/
scar -m 64m -o out image.dd # cap each carved file at 64 MiB
scar -q image.dd # quiet: report.txt only, no stdout table
```
## Example run
The image below is synthetic — built by `tests/test_scar.py`, which
plants a PNG, a JPEG, a GIF, a ZIP, a PDF and a gzip member at known
offsets in random filler, plus a JPEG truncated by the end of the image
— but the output is the real output of that run:
```
$ scar -o carved /tmp/scar-test/test.img
scar 1.0: /tmp/scar-test/test.img (10531 bytes) — 7 files carved, 2985 bytes total
offset size format ext confidence method file
0 135 PNG image png high png-chunk-walk 0000000000.png
248 1116 JPEG image jpeg high jpeg-marker-walk 0000000248.jpeg
5460 600 GIF image gif high gif-block-walk 0000005460.gif
6060 521 ZIP archive zip high zip-local-walk 0000006060.zip
7358 329 PDF document pdf high pdf-eof-scan 0000007358.pdf
9735 84 gzip archive gz high gzip-inflate 0000009735.gz
10331 200 JPEG image jpeg low eof 0000010331.jpeg
```
The same table is written to `carved/report.txt`. Every recovered file
is byte-identical to the planted original — the test verifies that
(`python3 tests/test_scar.py`, exit 0 on success).
## How carving decisions are made
A header alone is not a file: `scar` has to know where the file ends,
and it works through the methods below in order of preference. The
`method` column says which one was used; `confidence` says how much to
trust it.
| method | confidence | how the end is found |
|---|---|---|
| `png-chunk-walk` | high | Walk the PNG chunks (length + type + data + CRC) until the IEND chunk. First chunk must be IHDR. |
| `jpeg-marker-walk` | high | Walk JPEG markers; SOS scan data is skipped byte-by-byte (FF00 is an escaped literal, FFD0–FFD7 are restart markers) until the EOI marker FFD9. |
| `gif-block-walk` | high | Walk GIF blocks (image descriptors, extensions, sub-blocks) until the 0x3B trailer. |
| `zip-local-walk` | high | Walk the local file headers, then the central directory; the end is the EOCD record + comment. Entries with the data-descriptor flag carry no sizes, so their data is skipped by scanning for the next PK signature. |
| `pdf-eof-scan` | high | Scan for `%%EOF`, consume the trailing newline. |
| `gzip-inflate` | high | Inflate the member (zlib, gzip wrapper); `total_in` at stream end is the member length. Concatenated members are followed. |
| `png-iend-scan` | medium | Chunk walk failed on a damaged PNG; the IEND chunk (type + fixed CRC AE 42 60 82) was found by scanning. |
| `zip-eocd-scan` | medium | Local-header walk failed; the EOCD was found by scanning and validated (central-directory offset + size must land exactly on the EOCD). |
| `next-header` | low | No structure or footer: the file runs until the next recognised header. |
| `eof` | low | No structure, footer, or following header: the file runs to the end of the image (usually a file truncated by the end of the image, like the last JPEG above). |
| `capped` | low | The file ran past `-m` (default 512 MiB) and was cut there. |
Three rules keep the results honest:
1. **A header that fails structural validation is not a file.**
Random data contains magic bytes — a 2-byte gzip magic occurs about
once per 64 KiB — so a candidate is only carved if its structure
checks out (PNG's first chunk is IHDR, JPEG's markers walk, the
gzip stream inflates, …). A failed candidate costs one byte of
scanning, not a bogus file.
2. **The next-header scan never looks inside a file's own structure.**
When a file is truncated, the walk reports how many leading bytes it
validated, and the fallback scan starts after them. This matters
because a file's own data is full of other formats' magics: a JFIF
header contains the byte sequence `00 00 01 00`, which is a real ICO
magic, 13 bytes into every JPEG. Scanning from the file start would
have cut the truncated JPEG in the example above to 13 bytes instead
of the 200 that were really there. A candidate next-header only
counts if it sizes plausibly itself, or has a magic of at least 4
bytes.
3. **Scanning resumes after the carved file, never inside it.** Bytes
inside a recovered file are never re-scanned, so an embedded header
(a JPEG thumbnail in a PNG's metadata, a ZIP stored inside another
file) does not produce a second, bogus carve. The outer file wins.
## Limits
- **Only headers at offset 0 of a format count.** Formats whose magic
sits at a nonzero offset in the file cannot anchor a carve.
- **2-byte magics are only carved for gzip.** Any other format with a
2-byte magic is skipped: in random data it would false-positive every
~64 KiB. (3-byte magics are carved, but only bound a fallback scan if
they size plausibly — see rule 2.)
- **ZIP64 is not walked.** A ZIP whose sizes are 0xFFFFFFFF falls back
to the EOCD scan (medium confidence) instead of the local-header walk.
- **No embedded-file recovery.** A file stored inside another carved
file is not carved separately (rule 3). Run `scar` on the carved file
itself to go one level deeper.
- **Fragmented files are not reassembled.** Like every header carver,
`scar` recovers contiguous runs only; a file whose clusters are
scattered across the image comes back as its first run (low
confidence) or not at all.
- **Low-confidence carves need checking.** A `next-header` / `eof` /
`capped` result means "bytes that start with a known header and run
this far" — open the file (or run `sfile` on it) before trusting it.
- **The image is memory-mapped read-only**, so very large images need
enough virtual address space; the per-file cap (`-m`) bounds output,
not input.
## Exit codes
0 = at least one file carved, 1 = usage error, 2 = image unreadable,
3 = nothing found.
## See also
- `src/scar.c` — the carver (generic engine + six structure walkers).
- `src/footers.h` — the footer/trailer signature table it scans for.
- `tests/test_scar.py` — the synthetic-image test; run with
`make test-scar`.
+247
View File
@@ -0,0 +1,247 @@
# stag / sgeo — geotags as CSV, geotags on a map
`stag` scans a directory of photos and videos and writes one CSV row
per file with whatever location `sfile` recovered from it. `sgeo`
plots the geotagged files from a directory on an OpenStreetMap image.
Both are thin clients over `sfile`: they run the `sfile` binary on
each file and parse the `Geotagging:` section it prints — they never
parse image or video containers themselves. The exact seam — what
`sfile` prints and what the client parser accepts — is
`docs/geotag-contract.md`.
## Building
```console
$ make # builds sfile (and scar)
$ make stag sgeo # builds the geotag tools
```
`stag` needs only libm; `sgeo` links libpng and libcurl
(`-lpng -lcurl -lm`), so the libpng and libcurl development packages
must be installed. Both need a built `sfile` binary at *runtime*, not
at build time (see [Finding sfile](#finding-sfile)).
The geotagging decoders landed Dec 2, 2026 (commit `b368998`), so a
plain `make` works in a fresh clone again (verified Dec 2, 2026).
`make stag sgeo` remains the minimal build for just the geotag tools:
it does not touch `sfile`.
## Finding sfile
`stag`/`sgeo` locate the `sfile` binary in this order:
1. `$SFILE`, if set — it must be executable, otherwise the tool fails
loudly instead of guessing.
2. `sfile` on `PATH`.
3. `sfile` in the same directory as the `stag`/`sgeo` binary.
If no `sfile` can be run, the tool stops with
`stag: cannot run sfile on '...' (set $SFILE or put sfile on PATH)`
and exit code 1.
## What gets scanned
One directory, non-recursive. Only regular files with a media
extension are scanned (case-insensitive), sorted by filename;
dotfiles are skipped:
```text
jpg jpeg png gif webp tif tiff heic heif avif jxl bmp dib
mp4 m4v mov mkv webm avi m2ts mts 3gp 3g2 mpg mpeg wmv flv f4v ogv
```
Everything else is skipped: text files, subdirectories, dotfiles.
Note that a previous `sgeo` run's `map.png` sitting in the same
directory *is* a PNG, so it is scanned and gets an empty row — see
the real example below.
## stag
```console
$ stag [dir] [outfile]
```
`dir` defaults to `.`, `outfile` defaults to `geotags.csv` in the
current directory. Exit code 0 on success, 1 on a usage error, an
unreadable directory, an unwritable outfile, or an un-runnable
`sfile`. A summary goes to stderr, e.g.
`stag: 4 file(s), 2 geotagged -> geotags.csv`.
### CSV format
Header:
```text
file,format,latitude,longitude,altitude,datum,timestamp,source
```
One row per scanned file, in filename order. Fields:
| column | content |
| --- | --- |
| `file` | filename only (no directory); quoted when it contains a comma, quote, or newline |
| `format` | format name from sfile's `Format:` line, e.g. `JPEG image`; `unknown` if sfile could not identify the file |
| `latitude` / `longitude` | signed decimal degrees, 6 decimals; empty when no geotag was found |
| `altitude` | metres above sea level, 3 decimals; empty when no altitude was recovered |
| `datum` | datum as recorded, usually `WGS-84`; defaults to `WGS-84` when a location was found and no datum was printed; empty when no geotag |
| `timestamp` | UTC timestamp from `gps_datetime_utc`, passed through verbatim; empty when unknown |
| `source` | where the location came from, e.g. `EXIF GPS`; `unknown` when no `source:` line was seen; empty when no geotag |
**The empty-coords rule:** every scanned file gets a row, even one
with no location at all. A missing geotag means empty
latitude/longitude/altitude/datum/timestamp/source — never a missing
row, never a zero coordinate. (0, 0) is a real place in the Gulf of
Guinea; an empty field is "not recorded".
### Real example
Two JPEGs with EXIF GPS tags written by exiftool (San Francisco and
Tokyo), one plain JPEG with no GPS, plus the `map.png` from an
earlier `sgeo` run in the same directory — run with the decoder
build of sfile (`SFILE=/opt/sfile/sfile`):
```console
$ SFILE=/opt/sfile/sfile ./stag /tmp/realgeo /tmp/realgeo-fresh.csv
stag: 4 file(s), 2 geotagged -> /tmp/realgeo-fresh.csv
$ cat /tmp/realgeo-fresh.csv
file,format,latitude,longitude,altitude,datum,timestamp,source
plain.jpg,JPEG image,,,,,,
real.png,PNG image,,,,,,
sf_real.jpg,JPEG image,37.774929,-122.419418,12.000,WGS-84,2024-05-01 12:34:56,EXIF GPS IFD (JPEG APP1 segment)
tokyo_real.jpg,JPEG image,35.676200,139.650300,,WGS-84,,EXIF GPS IFD (JPEG APP1 segment)
```
What sfile printed for the San Francisco file (the input stag
parsed — note the ISO timestamp; the decoder normalises EXIF
`YYYY:MM:DD` to dashes, see `docs/geotag-contract.md`):
```text
Geotagging:
source: EXIF GPS IFD (JPEG APP1 segment)
gps_latitude: 37.774929 (37°46'29.74"N)
gps_longitude: -122.419418 (122°25'09.90"W)
gps_altitude_m: 12.000 (above sea level)
gps_datum: WGS-84
gps_datetime_utc: 2024-05-01 12:34:56
```
The synthetic suite (`tests/run_tests.sh`) also covers the fallback
forms the client accepts — raw EXIF GPS tags in sfile's header table
instead of a `Geotagging:` section — where the source defaults to
`unknown` and the timestamp keeps its EXIF colons:
```text
file,format,latitude,longitude,altitude,datum,timestamp,source
PARIS.JPG,JPEG image,48.856600,2.352200,,WGS-84,,EXIF GPS
nyc.jpg,JPEG image,40.712800,-74.006000,10.000,WGS-84,2024:06:15 08:30:00,unknown
plain.jpg,JPEG image,,,,,,
sf.jpg,JPEG image,37.774929,-122.419418,12.000,WGS-84,2024-05-01 12:34:56,EXIF GPS
tokyo.jpg,JPEG image,35.676200,139.650300,,WGS-84,,XMP
```
## sgeo
```console
$ sgeo [dir] [outfile]
```
`dir` defaults to `.`, `outfile` defaults to `map.png` in the
current directory. The map is built from OpenStreetMap raster tiles
fetched at runtime (see [Network dependency](#network-dependency))
and stitched with libpng. The zoom is computed from the points'
bounding box — a single point, or several at the same spot, uses
zoom 15 — and zoomed out until the tile count fits (at most 100
tiles). One red filled circle (radius 7 px) is drawn per geotagged
file. Exit code 0 on success.
### Real example
Same directory as the `stag` example above, against the live tile
server:
```console
$ SFILE=/opt/sfile/sfile ./sgeo /tmp/realgeo /tmp/realgeo-fresh.png
sgeo: 4 file(s), 2 geotagged, zoom 2, 1024x256, 4 tile(s) -> /tmp/realgeo-fresh.png
$ file /tmp/realgeo-fresh.png
/tmp/realgeo-fresh.png: PNG image data, 1024 x 256, 8-bit/color RGB, non-interlaced
```
San Francisco and Tokyo are far apart, so the zoom drops to 2 and
the image is 1024x256 from 4 tiles.
### Trip path
`sgeo --trip <csv> [outfile]` draws the journey a stag CSV records
— the geotagged rows in timestamp order, as a polyline with time
labels — instead of just markers. See `docs/trip-path.md`.
### No geotags
If no file in the directory has a location, `sgeo` prints an error
to stderr, exits 1, and writes **no file**:
```console
$ sgeo /tmp/nogeo /tmp/nogeo.png
sgeo: no geotagged files found in '/tmp/nogeo' -- nothing to plot
$ ls /tmp/nogeo.png
ls: cannot access '/tmp/nogeo.png': No such file or directory
```
### Attribution
The string `© OpenStreetMap contributors` is drawn **on the image
itself** — a white plaque with black text, bottom-left — using a
small self-contained 5x7 bitmap font, so no ImageMagick or other
tool is needed at runtime. The OpenStreetMap tile usage policy
requires this attribution wherever the tiles are shown; because it
is baked into the PNG, the map stays attributed wherever the file
goes. Do not crop it off.
### Network dependency
`sgeo` fetches tiles from `https://tile.openstreetmap.org` **when it
runs** (libcurl); no tiles are bundled with the tool or the repo, and
the User-Agent identifies the tool, per the OSM tile usage policy.
That means `sgeo` needs network access to tile.openstreetmap.org at
runtime — offline it fails on the tile fetch — and it makes one HTTP
request per tile (4 in the example above). `$SGEO_TILE_BASE`
overrides the tile base URL; the tests use it to point at a local
tile server.
## Tests
`tests/run_tests.sh` (run from the repo root) exercises both tools
end to end with a fake `sfile` (`tests/bin/sfile`, canned GPS values
dispatched on filename) and a local tile server
(`tests/tile_server.py`, via `$SGEO_TILE_BASE`), so the suite is
offline. Eleven checks, all passing:
```console
$ ./tests/run_tests.sh
PASS: stag multi-file CSV byte-for-byte
PASS: sgeo multi-file map (4 markers + attribution)
PASS: sgeo single-point map (1 marker)
PASS: stag no-geotag CSV
PASS: sgeo no-geotag: non-zero, message, no file
PASS: stag empty-dir CSV (header only)
PASS: sgeo empty-dir: non-zero, no file
PASS: default outfiles geotags.csv / map.png
PASS: sgeo --trip ordered polyline + time labels
PASS: sgeo --trip single point
PASS: sgeo --trip failures (no geotags, bad header, missing file)
stag/sgeo tests: ALL PASS
```
Cases covered: a multi-file directory (CSV byte-for-byte against
`tests/expected_geotags.csv`, map with 4 markers plus the
attribution plaque), a single point, a no-geotag directory (stag
rows are empty, sgeo fails with no file), an empty directory (stag
header only, sgeo fails with no file), and the default outfiles
(`geotags.csv` / `map.png` in the cwd). The `--trip` cases use a
synthetic CSV (rows out of timestamp order, one EXIF-colon timestamp,
one untimestamped row, one row with no geotag): `tests/check_trip.py`
re-implements the projection and checks the markers land on their
projected points, the blue line follows the timestamp-ordered legs
(and not the file-order hops), and every timestamped marker has a
label plaque. The real-file path against the decoder build of sfile
is shown in the examples above.
+150
View File
@@ -0,0 +1,150 @@
# sgeo --trip: draw the journey as a path on the map
`sgeo --trip <csv> [outfile]` reads a [stag](stag-sgeo.md) CSV and
draws the trip it records: the geotagged rows in timestamp order,
connected as an ordered polyline on an OpenStreetMap image — not just
markers. Each stop gets a red marker, each leg a blue line with a
white halo and an arrowhead showing the direction of travel, and each
timestamped stop a time label (`MM-DD HH:MM`, UTC, as stag printed
it) next to its marker.
## Usage
```console
$ make sgeo
$ stag photos/ # -> geotags.csv in the cwd
$ sgeo --trip geotags.csv # -> trip.png in the cwd
$ sgeo --trip geotags.csv day1.png
```
`outfile` defaults to `trip.png` in the current directory. The map is
built from OpenStreetMap raster tiles fetched at runtime, exactly like
`sgeo`'s directory mode (same zoom choice from the points' bounding
box, same tile budget, same attribution plaque baked onto the image).
`$SGEO_TILE_BASE` overrides the tile base URL; the tests use it to
point at a local tile server. No `sfile` binary is needed: the input
is the CSV itself, so `--trip` works on a CSV made anywhere — by stag,
by hand, or by a spreadsheet — as long as it has stag's columns.
Exit code 0 on success; 1 if the CSV cannot be read, has a bad
header, or has no geotagged rows (no output file is written then),
2 on a usage error.
## CSV input expectations
The header must start with stag's columns:
```text
file,format,latitude,longitude,altitude,datum,timestamp,source
```
Rows are parsed as real CSV (quoted fields, with `""` for a quote
inside, are handled, so filenames containing commas work). Only the
latitude, longitude and timestamp columns matter:
| column | how --trip uses it |
| --- | --- |
| `latitude` / `longitude` | the stop's position; empty means "no geotag" and the row is skipped (the CSV's empty-coords rule) |
| `timestamp` | the stop's time, for ordering and the label; empty means "time unknown" and the stop goes last, in CSV order, with no label |
| the rest | ignored (`file` appears in warnings only) |
A row with garbage coordinates (non-numeric, or latitude outside
±90 / longitude outside ±180) is warned about on stderr and skipped;
the count is reported at the end. A row with fewer than 7 fields is
malformed and skipped the same way.
## Timestamp ordering
Rows are ordered by their timestamp, not by their position in the
file — a CSV in filename order is almost never in time order, and
drawing file order would draw the wrong journey. The timestamp is
parsed, not compared as text, so the two forms stag emits sort
together:
- ISO, as the decoder prints it: `2024-05-01 12:34:56` (or date-only
`2024-05-01`, which labels as `05-01` and sorts at midnight)
- EXIF-colon, as the fallback path passes it through:
`2024:06:15 08:30:00`
(A text comparison would put every `YYYY:MM:DD` row after every
`YYYY-MM-DD` row, whatever the dates — `:` sorts after `-`.) Rows
with equal timestamps, and all rows with no timestamp, keep CSV
order, so the path is deterministic. A time-only value (no date)
cannot be ordered and is treated as no timestamp.
Labels show `MM-DD HH:MM` (date-only: `MM-DD`). The year is omitted:
a trip path fits on one map, and the year is in the CSV. Times are
UTC, as stag prints them.
## What is drawn, in order
1. The legs, in timestamp order: a blue line (radius 2) with a white
halo (radius 4) so the path reads over any tile.
2. One arrowhead per leg, at the leg's midpoint, pointing along the
direction of travel (legs shorter than 80 px get none — the arrow
would touch the markers).
3. One red marker per stop (the same marker as directory mode),
drawn on top of the line.
4. One time label per timestamped stop: a white plaque with black
text, upper-right of the marker, flipped to the left (or below) at
the image edge. Untimestamped stops get a marker but no label.
5. The `© OpenStreetMap contributors` attribution plaque, last, so
it is never covered up.
A single geotagged row draws just its marker and label, like
directory mode with one point.
## Example
Five photos around San Francisco, in the CSV in filename order
(`c.jpg` first, `a.jpg` second — deliberately not time order), one
with no timestamp, one with no geotag at all:
```console
$ cat trip.csv
file,format,latitude,longitude,altitude,datum,timestamp,source
c.jpg,JPEG image,37.784900,-122.379400,,WGS-84,2024-05-01 10:00:00,EXIF GPS
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
d.jpg,JPEG image,37.754900,-122.439400,,WGS-84,2024-05-01 11:00:00,EXIF GPS
b.jpg,JPEG image,37.804900,-122.409400,,WGS-84,2024:05:01 09:00:00,EXIF GPS
e.jpg,JPEG image,37.794900,-122.439400,,WGS-84,,EXIF GPS
plain.jpg,JPEG image,,,,,,
$ sgeo --trip trip.csv trip.png
sgeo: 6 row(s) in 'trip.csv', 5 point(s), 4 with timestamps, zoom 13, 768x768, 9 tile(s) -> trip.png
```
The drawn path is 08:00 (downtown) → 09:00 (Telegraph Hill) →
10:00 (over the Bay) → 11:00 (Castro) → the untimestamped stop
(Presidio Heights) last — not the file's c → a → d → b → e order.
The b.jpg leg proves the mixed-format sort: its EXIF-colon
`2024:05:01 09:00:00` slots between the two ISO timestamps, where a
text sort would have put it after all of them. The same map rendered
against live OSM tiles is the feature image of the follow-up article
on fileformat.vpscoder.com (see the stag/sgeo article there).
## Limits
- A trip crossing the antimeridian (±180°) draws the long way
around the map: the polyline connects the projected points
directly, with no wrap. (Directory mode has the same shape of
limitation for markers at opposite edges.)
- In a dense cluster, time labels can overlap each other or a leg:
labels are placed per-marker with no collision avoidance. Split
the CSV if the labels collide.
- The path is a straight line between consecutive stops
(great-circle segments are not drawn); for a day's photos the
difference is invisible at these zooms.
- Only the first location per file is used: the CSV has one row per
file, so a file with several locations contributes its first
block, as stag records it (see `docs/geotag-contract.md`,
"first source wins").
## Tests
`tests/run_tests.sh` covers `--trip` with a synthetic CSV (the
example above, against the local tile server) plus a single-point
CSV and the failure cases — see `tests/check_trip.py`, which
re-implements the projection and checks the markers land on their
projected points, the blue line follows the timestamp-ordered legs
(and not the file-order hops), and every timestamped marker has a
label plaque. Eleven checks in the suite, all passing.
+79
View File
@@ -0,0 +1,79 @@
/* footers.h — footer / trailer signatures used by scar.
*
* A carver cannot trust a header alone: it has to know where the file
* ENDS. Some formats carry their length up front (PNG chunks, ZIP local
* headers) so the end is computed by walking the structure; the rest end
* at a recognisable trailer, listed here. Two formats have no fixed
* trailer at all and need special handling, noted below:
*
* - gzip: the trailer is just CRC32 + ISIZE (8 bytes, no magic), so the
* end is found by inflating the stream (see gzip_end() in scar.c).
* - GIF: the trailer is a single 0x3B byte, which also appears inside
* image data, so GIF is walked block-by-block instead (gif_end()).
*
* This header is shared data, not code: scar.c does the walking, this
* file only names the byte patterns it looks for.
*/
#ifndef SCAR_FOOTERS_H
#define SCAR_FOOTERS_H
#include <stdint.h>
#include <string.h>
typedef struct {
const char *ext; /* extension, as in sfile's format table */
const char *name; /* what the trailer is */
const uint8_t *sig; /* trailer bytes (NULL when there is no fixed trailer) */
uint32_t len; /* trailer length in bytes */
const char *note; /* how the end is really found */
} ScarFooter;
/* JPEG: End Of Image marker. Found by walking markers, not by scanning,
because 0xFFD9 can also occur inside entropy-coded scan data. */
static const uint8_t FOOT_JPEG_EOI[] = { 0xFF, 0xD9 };
/* PNG: IEND chunk — type "IEND" + its fixed CRC AE 42 60 82.
The chunk walk finds it structurally; this pattern is the fallback
when a chunk header is damaged. */
static const uint8_t FOOT_PNG_IEND[] = { 'I', 'E', 'N', 'D', 0xAE, 0x42, 0x60, 0x82 };
/* GIF: trailer byte 0x3B. Only meaningful after block walking. */
static const uint8_t FOOT_GIF_TRAILER[] = { 0x3B };
/* ZIP: End Of Central Directory record. Walking the local file headers
lands on the central directory; the EOCD then gives the exact end
(record + comment). Validated: cd_offset + cd_size must equal the
EOCD's own offset, which rejects stray PK\x05\x06 bytes in file data. */
static const uint8_t FOOT_ZIP_EOCD[] = { 'P', 'K', 0x05, 0x06 };
/* PDF: "%%EOF" near the end of the file, usually followed by a newline. */
static const uint8_t FOOT_PDF_EOF[] = { '%', '%', 'E', 'O', 'F' };
static const ScarFooter scar_footers[] = {
{ ".JPEG", "EOI marker", FOOT_JPEG_EOI, 2, "marker walk; EOI ends the file" },
{ ".JPG", "EOI marker", FOOT_JPEG_EOI, 2, "marker walk; EOI ends the file" },
{ ".PNG", "IEND chunk", FOOT_PNG_IEND, 8, "chunk walk; IEND chunk ends the file" },
{ ".GIF", "trailer byte 0x3B", FOOT_GIF_TRAILER, 1, "block walk; 0x3B ends the file" },
{ ".ZIP", "EOCD record", FOOT_ZIP_EOCD, 4, "local-header walk, then EOCD + comment" },
{ ".PDF", "%%EOF", FOOT_PDF_EOF, 5, "scan for %%EOF, consume trailing newline" },
{ ".GZ", "(none — CRC+ISIZE)", NULL, 0, "no fixed trailer; end found by inflate" },
};
#define SCAR_NFOOTERS (sizeof(scar_footers) / sizeof(scar_footers[0]))
/* find_bytes: first occurrence of needle in haystack at or after `from`,
or -1. (memmem wrapper; glibc has memmem, this keeps the call sites
readable and the -1 convention uniform.) */
static inline int64_t scar_find_bytes(const uint8_t *hay, uint64_t hay_len,
const uint8_t *needle, uint32_t needle_len,
uint64_t from)
{
if (needle_len == 0 || hay_len < needle_len || from > hay_len - needle_len)
return -1;
const uint8_t *hit = memmem(hay + from, (size_t)(hay_len - from),
needle, needle_len);
if (!hit) return -1;
return (int64_t)(hit - hay);
}
#endif /* SCAR_FOOTERS_H */
+7 -1
View File
@@ -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
+30
View File
@@ -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",
+1627
View File
File diff suppressed because it is too large. Load diff
+41
View File
@@ -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
+556
View File
@@ -0,0 +1,556 @@
/* geotag_client.c -- client side of the stag/sgeo <-> sfile seam.
*
* FIELD-NAME CONTRACT (see docs/geotag-contract.md for the full text):
* stag/sgeo run the `sfile` binary on each file and parse its stdout.
* The decoder prints a "Geotagging:" section; this parser accepts:
*
* source: EXIF GPS
* gps_latitude: 37.774929 (37°46'29.64"N) -- decimal degrees first
* gps_longitude: -122.419418 (122°25'9.90"W)
* gps_altitude_m: 12.000 (above sea level)
* gps_datum: WGS-84
* gps_datetime_utc: 2024:05:01 12:34:56
* none found (searched ...) -- no geotag
*
* and, as a fallback, the EXIF tag-name forms, either as "key: value"
* lines or as rows of sfile's uniform header table:
*
* GPSLatitude: 37/1, 46/1, 2964/100 GPSLatitudeRef: N
* GPSLongitude: 122/1, 25/1, 990/100 GPSLongitudeRef: W
* GPSAltitude: 12/1 GPSAltitudeRef: 0
* GPSDateStamp: 2024:05:01 GPSTimeStamp: 12/1, 34/1, 56/1
*
* DMS rationals plus hemisphere refs are converted to signed decimal
* degrees. Datum is WGS-84 unless the decoder says otherwise. When the
* decoder reports several sources, the FIRST one wins.
*
* This module never parses image/video containers itself -- that is the
* decoder's job, inside sfile.
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "geotag_client.h"
#define GEO_OUT_CAP (1u << 20) /* 1 MiB of sfile output is plenty */
/* ---- locating the sfile binary ---- */
static int path_has_exec(const char *dir, const char *name, char *buf, size_t n) {
if (snprintf(buf, n, "%s/%s", dir, name) >= (int)n) return 0;
return access(buf, X_OK) == 0;
}
int find_sfile(char *buf, size_t n) {
const char *env = getenv("SFILE");
if (env && *env) {
if (access(env, X_OK) == 0) {
snprintf(buf, n, "%s", env);
return 1;
}
return 0; /* $SFILE set but not executable: fail loudly, no guessing */
}
const char *path = getenv("PATH");
if (path && *path) {
char *copy = strdup(path);
if (copy) {
char *save = NULL, *dir;
for (dir = strtok_r(copy, ":", &save); dir;
dir = strtok_r(NULL, ":", &save)) {
if (path_has_exec(*dir ? dir : ".", "sfile", buf, n)) {
free(copy);
return 1;
}
}
free(copy);
}
}
/* alongside this executable (/proc/self/exe, Linux) */
char self[PATH_MAX];
ssize_t m = readlink("/proc/self/exe", self, sizeof self - 1);
if (m > 0) {
self[m] = 0;
char *slash = strrchr(self, '/');
if (slash) {
*slash = 0;
if (path_has_exec(self, "sfile", buf, n)) return 1;
}
}
return 0;
}
/* ---- running sfile ---- */
/* Run sfile on path, capturing stdout. Returns a malloc'd NUL-terminated
* buffer, or NULL if sfile could not be run. The exit status is stored in
* *status_out when non-NULL (sfile exit 3 = unknown format still yields
* usable output, so callers parse the buffer regardless). */
static char *run_sfile(const char *sfile, const char *path, int *status_out) {
int pipefd[2];
if (pipe(pipefd) != 0) return NULL;
pid_t pid = fork();
if (pid < 0) { close(pipefd[0]); close(pipefd[1]); return NULL; }
if (pid == 0) {
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
/* stderr stays the caller's: sfile usage/file errors are its own */
execl(sfile, "sfile", path, (char *)NULL);
_exit(127);
}
close(pipefd[1]);
size_t cap = 65536, len = 0;
char *out = malloc(cap);
if (!out) { close(pipefd[0]); return NULL; }
for (;;) {
if (len + 8192 >= cap) {
if (cap >= GEO_OUT_CAP) break;
cap *= 2;
char *nb = realloc(out, cap);
if (!nb) { free(out); close(pipefd[0]); return NULL; }
out = nb;
}
ssize_t r = read(pipefd[0], out + len, cap - len - 1);
if (r < 0) { if (errno == EINTR) continue; break; }
if (r == 0) break;
len += (size_t)r;
}
close(pipefd[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { }
out[len] = 0;
if (status_out) *status_out = status;
if (WIFEXITED(status) && WEXITSTATUS(status) == 127 && len == 0) {
free(out); /* exec failed: sfile binary unusable */
return NULL;
}
return out;
}
/* ---- value parsing ---- */
static double dabs(double v) { return v < 0 ? -v : v; }
/* "num/den" rational; returns 0 on failure. */
static int parse_rational(const char *s, double *out) {
char *end = NULL;
double num = strtod(s, &end);
if (end == s) return 0;
while (*end && isspace((unsigned char)*end)) end++;
if (*end != '/') { *out = num; return 1; }
const char *d = end + 1;
double den = strtod(d, &end);
if (end == d || den == 0) return 0;
*out = num / den;
return 1;
}
/* Parse one coordinate value into decimal degrees.
* Accepts: plain decimal ("37.774929"), DMS rationals
* ("37/1, 46/1, 2964/100"), DMS with symbols ("37°46'29.64\"N").
* On success returns 1 and sets *hemi to the hemisphere letter found in
* the value itself (N/S/E/W), or 0 if none. */
static int parse_coord_value(const char *s, double *out, char *hemi) {
while (*s && isspace((unsigned char)*s)) s++;
*hemi = 0;
/* A parenthesised DMS display after a decimal ("37.774929 (37°...N)"):
* the decimal before it is authoritative; ignore the rest. */
{
const char *paren = strchr(s, '(');
if (paren) {
char *end = NULL;
double v = strtod(s, &end);
if (end != s && end <= paren) {
/* hemisphere letter, if any, lives after the paren */
const char *q = paren;
while (*q) {
if (*q == 'N' || *q == 'S' || *q == 'E' || *q == 'W' ||
*q == 'n' || *q == 's' || *q == 'e' || *q == 'w')
*hemi = *q;
q++;
}
*out = v;
return 1;
}
}
}
/* DMS rationals: contains '/' and ',' */
if (strchr(s, '/') && strchr(s, ',')) {
double comp[3] = { 0, 0, 0 };
int ncomp = 0;
char buf[128];
snprintf(buf, sizeof buf, "%s", s);
char *save = NULL, *tok;
for (tok = strtok_r(buf, ",", &save); tok && ncomp < 3;
tok = strtok_r(NULL, ",", &save)) {
/* trailing hemisphere letter may ride on the last component */
size_t L = strlen(tok);
while (L > 0 && isspace((unsigned char)tok[L - 1])) tok[--L] = 0;
if (L > 0 && isalpha((unsigned char)tok[L - 1])) {
*hemi = tok[L - 1];
tok[--L] = 0;
}
if (!parse_rational(tok, &comp[ncomp])) return 0;
ncomp++;
}
if (ncomp == 0) return 0;
*out = comp[0] + comp[1] / 60.0 + comp[2] / 3600.0;
return 1;
}
/* DMS with symbols or plain decimal: scan the leading numbers. */
{
double comp[3] = { 0, 0, 0 };
int ncomp = 0;
const char *p = s;
while (*p && ncomp < 3) {
while (*p && !(isdigit((unsigned char)*p) || *p == '-' ||
*p == '+' || *p == '.')) {
if (*p == 'N' || *p == 'S' || *p == 'E' || *p == 'W' ||
*p == 'n' || *p == 's' || *p == 'e' || *p == 'w')
*hemi = *p;
p++;
}
if (!*p) break;
char *end = NULL;
double v = strtod(p, &end);
if (end == p) break;
comp[ncomp++] = v;
p = end;
}
if (ncomp == 0) return 0;
if (ncomp == 1) { *out = comp[0]; return 1; }
*out = comp[0] + comp[1] / 60.0 + comp[2] / 3600.0;
/* a negative degrees part already carries the sign */
if (comp[0] < 0) *out = -dabs(*out);
return 1;
}
}
/* Normalise a key for matching: lowercase, drop '_', ' ', '-'. */
static void norm_key(const char *s, char *out, size_t n) {
size_t m = 0;
for (; *s && m + 1 < n; s++) {
if (*s == '_' || *s == ' ' || *s == '-' || *s == '\t') continue;
out[m++] = (char)tolower((unsigned char)*s);
}
out[m] = 0;
}
static int all_digits(const char *s) {
if (!*s) return 0;
for (; *s; s++) if (!isdigit((unsigned char)*s)) return 0;
return 1;
}
/* ---- output parsing ---- */
typedef struct {
int seen_source; /* a source: line was seen (first block only) */
int done; /* second source: seen: stop parsing geo keys */
int have_lat, have_lon;
double lat, lon;
char lat_hemi, lon_hemi;
char lat_ref, lon_ref;
int have_alt;
double alt;
int alt_below; /* from "(below sea level)" or GPSAltitudeRef 1 */
int have_alt_ref;
char datum[48];
char date[16]; /* YYYY:MM:DD */
char time[16]; /* HH:MM:SS */
char datetime[48]; /* combined, or gps_datetime_utc verbatim */
char source[64];
} GeoParse;
static void apply_key(GeoParse *g, const char *key, const char *val) {
char nk[64];
norm_key(key, nk, sizeof nk);
if (strcmp(nk, "source") == 0) {
if (g->seen_source) { g->done = 1; return; } /* second block: stop */
g->seen_source = 1;
snprintf(g->source, sizeof g->source, "%s", val);
/* trim trailing whitespace */
size_t L = strlen(g->source);
while (L > 0 && isspace((unsigned char)g->source[L - 1]))
g->source[--L] = 0;
return;
}
if (g->done) return;
if (strcmp(nk, "gpslatitude") == 0) {
char h = 0;
double v;
if (parse_coord_value(val, &v, &h)) {
g->lat = v; g->have_lat = 1;
if (h) g->lat_hemi = h;
}
} else if (strcmp(nk, "gpslatituderef") == 0) {
if (*val) g->lat_ref = *val;
} else if (strcmp(nk, "gpslongitude") == 0) {
char h = 0;
double v;
if (parse_coord_value(val, &v, &h)) {
g->lon = v; g->have_lon = 1;
if (h) g->lon_hemi = h;
}
} else if (strcmp(nk, "gpslongituderef") == 0) {
if (*val) g->lon_ref = *val;
} else if (strcmp(nk, "gpsaltitude") == 0 ||
strcmp(nk, "gpsaltitudem") == 0) {
double v;
int ok = 0;
if (strchr(val, '/')) ok = parse_rational(val, &v);
if (!ok) {
char *end = NULL;
v = strtod(val, &end);
ok = (end != val);
}
if (ok) {
g->alt = v; g->have_alt = 1;
if (strstr(val, "below")) g->alt_below = 1;
if (strstr(val, "above")) g->alt_below = 0;
}
} else if (strcmp(nk, "gpsaltituderef") == 0) {
g->have_alt_ref = 1;
if (*val == '1' || strstr(val, "below")) g->alt_below = 1;
else g->alt_below = 0;
} else if (strcmp(nk, "gpsdatum") == 0 || strcmp(nk, "gpsmapdatum") == 0) {
snprintf(g->datum, sizeof g->datum, "%s", val);
size_t L = strlen(g->datum);
while (L > 0 && isspace((unsigned char)g->datum[L - 1]))
g->datum[--L] = 0;
} else if (strcmp(nk, "gpsdatetimeutc") == 0 ||
strcmp(nk, "gpsdatetime") == 0) {
snprintf(g->datetime, sizeof g->datetime, "%s", val);
size_t L = strlen(g->datetime);
while (L > 0 && isspace((unsigned char)g->datetime[L - 1]))
g->datetime[--L] = 0;
} else if (strcmp(nk, "gpsdatestamp") == 0) {
snprintf(g->date, sizeof g->date, "%.10s", val);
} else if (strcmp(nk, "gpstimestamp") == 0) {
/* "HH:MM:SS" or rationals "12/1, 34/1, 56/1" */
if (strchr(val, ':') && !strchr(val, '/')) {
snprintf(g->time, sizeof g->time, "%.8s", val);
} else if (strchr(val, '/')) {
double comp[3] = { 0, 0, 0 };
char buf[64];
snprintf(buf, sizeof buf, "%s", val);
char *save = NULL, *tok;
int n = 0;
for (tok = strtok_r(buf, ",", &save); tok && n < 3;
tok = strtok_r(NULL, ",", &save)) {
if (parse_rational(tok, &comp[n])) n++;
}
if (n == 3)
snprintf(g->time, sizeof g->time, "%02d:%02d:%02d",
(int)comp[0], (int)comp[1], (int)comp[2]);
}
}
}
/* Split one output line into a (key, value) pair, if it looks like one.
* Handles "key: value" lines and uniform-table rows
* (" <offset> <size> <field> <value>"). Returns 1 on success. */
static int split_line(char *line, char **key_out, char **val_out) {
while (*line && isspace((unsigned char)*line)) line++;
if (!*line) return 0;
char *colon = strchr(line, ':');
if (colon) {
/* a "key: value" line -- but not a bare time or a table row whose
* value merely contains a colon; keys have no spaces... except
* "GPS map datum" style keys do. Accept any key up to the colon
* as long as it is short and has no digits at the start. */
if (colon - line < 40 && !isdigit((unsigned char)line[0])) {
*colon = 0;
char *val = colon + 1;
while (*val && isspace((unsigned char)*val)) val++;
/* trim trailing whitespace on the key */
char *k = line + strlen(line);
while (k > line && isspace((unsigned char)k[-1])) *--k = 0;
*key_out = line;
*val_out = val;
return 1;
}
}
/* uniform-table row: offset size field value... */
{
char *save = NULL;
char *t1 = strtok_r(line, " \t", &save);
char *t2 = t1 ? strtok_r(NULL, " \t", &save) : NULL;
char *t3 = t2 ? strtok_r(NULL, " \t", &save) : NULL;
if (t1 && t2 && t3 && all_digits(t1) && all_digits(t2)) {
*key_out = t3;
*val_out = save ? save : (char *)"";
while (**val_out && isspace((unsigned char)**val_out)) (*val_out)++;
return 1;
}
}
return 0;
}
static void finish_geo(const GeoParse *g, Geotag *out) {
memset(out, 0, sizeof *out);
snprintf(out->format, sizeof out->format, "%s", "unknown");
if (!g->have_lat || !g->have_lon) return;
double lat = g->lat, lon = g->lon;
char lr = g->lat_ref ? g->lat_ref : g->lat_hemi;
char orr = g->lon_ref ? g->lon_ref : g->lon_hemi;
if (lr == 'S' || lr == 's') lat = -dabs(lat);
else if (lr == 'N' || lr == 'n') lat = dabs(lat);
if (orr == 'W' || orr == 'w') lon = -dabs(lon);
else if (orr == 'E' || orr == 'e') lon = dabs(lon);
if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) return;
out->found = 1;
out->latitude = lat;
out->longitude = lon;
snprintf(out->source, sizeof out->source, "%s",
g->source[0] ? g->source : "unknown");
if (g->have_alt) {
out->has_altitude = 1;
/* below-sea-level ref/text forces negative; otherwise keep the
* parsed sign (a negative value already means below). */
out->altitude = g->alt_below ? -dabs(g->alt) : g->alt;
}
snprintf(out->datum, sizeof out->datum, "%s",
g->datum[0] ? g->datum : "WGS-84");
if (g->datetime[0])
snprintf(out->timestamp, sizeof out->timestamp, "%s", g->datetime);
else if (g->date[0] && g->time[0])
snprintf(out->timestamp, sizeof out->timestamp, "%s %s", g->date, g->time);
else if (g->date[0])
snprintf(out->timestamp, sizeof out->timestamp, "%s", g->date);
else if (g->time[0])
snprintf(out->timestamp, sizeof out->timestamp, "%s", g->time);
}
int extract_geotag(const char *path, Geotag *out) {
memset(out, 0, sizeof *out);
snprintf(out->format, sizeof out->format, "%s", "unknown");
char sfile[PATH_MAX];
if (!find_sfile(sfile, sizeof sfile)) return -1;
int status = 0;
char *txt = run_sfile(sfile, path, &status);
if (!txt) return -1;
GeoParse g;
memset(&g, 0, sizeof g);
int none_found = 0;
char *save = NULL;
for (char *line = strtok_r(txt, "\n", &save); line;
line = strtok_r(NULL, "\n", &save)) {
/* Format line: "Format: NAME (ext) — task N" / "Format: unknown ..." */
if (strncmp(line, "Format:", 7) == 0) {
const char *v = line + 7;
while (*v && isspace((unsigned char)*v)) v++;
if (strncmp(v, "unknown", 7) == 0) {
snprintf(out->format, sizeof out->format, "%s", "unknown");
} else {
const char *paren = strstr(v, " (");
size_t m = paren ? (size_t)(paren - v) : strlen(v);
if (m >= sizeof out->format) m = sizeof out->format - 1;
memcpy(out->format, v, m);
out->format[m] = 0;
/* trim trailing whitespace */
while (m > 0 && isspace((unsigned char)out->format[m - 1]))
out->format[--m] = 0;
}
continue;
}
if (strstr(line, "none found")) none_found = 1;
char *key = NULL, *val = NULL;
char *copy = line; /* split_line mutates in place; line is ours */
if (split_line(copy, &key, &val))
apply_key(&g, key, val);
}
(void)none_found; /* absence of coordinates already means "no geotag" */
free(txt);
Geotag tmp;
finish_geo(&g, &tmp);
/* keep the parsed format, which finish_geo reset to "unknown" */
char fmt[64];
snprintf(fmt, sizeof fmt, "%s", out->format);
*out = tmp;
snprintf(out->format, sizeof out->format, "%s", fmt);
return 0;
}
/* ---- shared directory scan ---- */
static const char *const media_exts[] = {
"jpg", "jpeg", "png", "gif", "webp", "tif", "tiff",
"heic", "heif", "avif", "jxl", "bmp", "dib",
"mp4", "m4v", "mov", "mkv", "webm", "avi",
"m2ts", "mts", "3gp", "3g2", "mpg", "mpeg", "wmv", "flv", "f4v", "ogv",
NULL
};
int is_media_file(const char *name) {
const char *dot = strrchr(name, '.');
if (!dot || dot == name || !dot[1]) return 0;
const char *ext = dot + 1;
for (int i = 0; media_exts[i]; i++) {
const char *a = ext, *b = media_exts[i];
int eq = 1;
while (*a && *b) {
if (tolower((unsigned char)*a) != *b) { eq = 0; break; }
a++; b++;
}
if (eq && *a == 0 && *b == 0) return 1;
}
return 0;
}
static int cmp_str(const void *a, const void *b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
int collect_media_files(const char *dir, char ***out_names, int *out_n) {
*out_names = NULL;
*out_n = 0;
DIR *d = opendir(dir);
if (!d) return -1;
char **names = NULL;
int n = 0, cap = 0;
struct dirent *e;
while ((e = readdir(d)) != NULL) {
if (e->d_name[0] == '.') continue; /* skip dotfiles, . and .. */
if (!is_media_file(e->d_name)) continue;
char full[PATH_MAX];
if (snprintf(full, sizeof full, "%s/%s", dir, e->d_name) >= (int)sizeof full)
continue;
struct stat st;
if (stat(full, &st) != 0 || !S_ISREG(st.st_mode)) continue;
if (n == cap) {
cap = cap ? cap * 2 : 32;
char **nb = realloc(names, (size_t)cap * sizeof *nb);
if (!nb) break;
names = nb;
}
names[n] = strdup(e->d_name);
if (!names[n]) break;
n++;
}
closedir(d);
if (names) qsort(names, (size_t)n, sizeof *names, cmp_str);
*out_names = names;
*out_n = n;
return 0;
}
void free_media_list(char **names, int n) {
if (!names) return;
for (int i = 0; i < n; i++) free(names[i]);
free(names);
}
+53
View File
@@ -0,0 +1,53 @@
/* geotag_client.h -- client side of the stag/sgeo <-> sfile seam.
*
* stag and sgeo do NOT link against sfile: sfile is a monolithic
* single-file program, so there is no library to link. Instead they run
* the `sfile` binary and parse the "Geotagging:" section it prints.
* See docs/geotag-contract.md for the field-name contract this parser
* accepts (it covers both the section format the decoder prints today
* and the EXIF GPS tag-name / uniform-table forms).
*
* NOTE: this file is deliberately NOT named geotag.h -- src/geotag.h is
* the decoder-side header owned by the geotagging-decoder work in sfile.
* Do not confuse the two: this module consumes sfile output, it never
* parses image/video containers itself.
*/
#ifndef SFILE_GEOTAG_CLIENT_H
#define SFILE_GEOTAG_CLIENT_H
#include <stddef.h>
typedef struct {
int found; /* 1 if a latitude/longitude was recovered */
char source[64]; /* e.g. "EXIF GPS", "XMP", "QuickTime location" */
double latitude; /* signed decimal degrees, WGS-84 */
double longitude; /* signed decimal degrees, WGS-84 */
int has_altitude;
double altitude; /* metres above sea level (negative = below) */
char datum[48]; /* e.g. "WGS-84"; "WGS-84" when found and unset */
char timestamp[48]; /* "YYYY:MM:DD HH:MM:SS" UTC, "YYYY:MM:DD", or "" */
char format[64]; /* format name as reported by sfile, or "unknown" */
} Geotag;
/* Run sfile on path and fill out. Returns 0 on success (out->found tells
* whether a geotag was present; out->format is set whenever sfile ran),
* -1 if sfile could not be run at all. */
int extract_geotag(const char *path, Geotag *out);
/* Locate the sfile binary: $SFILE, then PATH, then alongside the current
* executable. Returns 1 and fills buf, or 0 if not found. */
int find_sfile(char *buf, size_t n);
/* ---- shared directory scan (used by both stag and sgeo) ---- */
/* Is filename (a basename) an image/video file we scan? Extension
* allowlist, case-insensitive. */
int is_media_file(const char *name);
/* Collect sorted basenames of media files in dir (non-recursive).
* Returns 0 on success, -1 if dir cannot be opened. Caller frees the
* list with free_media_list(). */
int collect_media_files(const char *dir, char ***out_names, int *out_n);
void free_media_list(char **names, int n);
#endif
+703
View File
@@ -0,0 +1,703 @@
/* scar — file carver built on sfile's format table.
*
* scar [-o outdir] [-m max-bytes] <image>
*
* Scans a raw disk image (or any file) for the magic bytes sfile knows
* about — all 831 formats in src/formats.h — and carves out the files it
* finds. Each recovered file is written to the output directory as
* <offset>.<ext> (offset = decimal byte offset in the image, zero-padded)
* and listed in a report: offset, format, size, confidence, how the end
* was found, and the output filename. The same report is printed to
* stdout and written to <outdir>/report.txt.
*
* How the end of a file is found, in order of preference:
* 1. Structure walk (high confidence): PNG chunk walk, JPEG marker
* walk, GIF block walk, ZIP local-header walk + EOCD, gzip inflate.
* The walk either lands exactly on the end or fails cleanly.
* 2. Footer scan (medium confidence): the trailer from footers.h is
* searched for (PDF %%EOF, PNG IEND, ZIP EOCD) when the walk fails
* on a damaged file.
* 3. Next-header / EOF fallback (low confidence): the file runs until
* the next recognised header, or the end of the image, capped at
* -m (default 512 MiB). Used for formats with no footer and for
* files truncated by the end of the image. The scan for the next
* header starts after the bytes the structure walk already
* validated as this file's own, and a candidate header only counts
* if it sizes plausibly itself (or has a >= 4 byte magic) — a
* file's own data is full of byte sequences that are somebody
* else's magic (a JFIF header contains the ICO magic 00 00 01 00).
*
* After a file is carved, scanning resumes at its end — bytes inside a
* recovered file are never re-scanned, so an embedded header (a JPEG
* thumbnail inside a PNG's metadata, say) does not produce a second,
* bogus carve. A header that fails structural validation is skipped by
* one byte, so random data that happens to contain magic bytes (a 2-byte
* gzip magic occurs about once per 64 KiB of random data) costs nothing
* but a rejected inflate attempt.
*
* Exit codes: 0 = at least one file carved, 1 = usage error,
* 2 = image unreadable, 3 = nothing found.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <zlib.h>
#include "formats.h"
#include "footers.h"
#define SCAR_VERSION "1.0"
#define DEFAULT_MAX (512ull * 1024 * 1024) /* 512 MiB per carved file */
static const char *prog;
static uint64_t opt_max = DEFAULT_MAX;
static const char *opt_outdir = "carved";
static int opt_quiet = 0;
/* ---- little/big-endian readers ---- */
static uint16_t rd16le(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }
static uint16_t rd16be(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); }
static uint32_t rd32le(const uint8_t *p) {
return p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static uint32_t rd32be(const uint8_t *p) {
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
}
/* Sizer return convention: >= 0 exact size, -1 structurally invalid
(reject the candidate), -2 truncated by end of image (fall back to
next-header/EOF with low confidence). On -2, *consumed (when non-NULL)
is set to how many leading bytes the walk validated as belonging to
this file, so the fallback scan starts after the file's own structure
instead of inside it — a JPEG's APP0 segment, for example, contains
the byte sequence 00 00 01 00, which is a real ICO magic, and scanning
for the next header from the file start would cut a truncated JPEG
short at its own JFIF header. */
enum { SZ_NONE = 0, SZ_PNG, SZ_JPEG, SZ_GIF, SZ_ZIP, SZ_PDF, SZ_GZIP };
static int sizer_for(const SFormat *f)
{
const char *e = f->ext;
if (!e) return SZ_NONE;
if (strcasecmp(e, ".PNG") == 0) return SZ_PNG;
if (strcasecmp(e, ".JPEG") == 0 || strcasecmp(e, ".JPG") == 0) return SZ_JPEG;
if (strcasecmp(e, ".GIF") == 0) return SZ_GIF;
if (strcasecmp(e, ".ZIP") == 0) return SZ_ZIP;
if (strcasecmp(e, ".PDF") == 0) return SZ_PDF;
if (strcasecmp(e, ".GZ") == 0) return SZ_GZIP;
return SZ_NONE;
}
/* ---- first-byte index over the format table ---- */
static const SFormat **idx[256];
static int nidx[256];
static void build_index(void)
{
int cnt[256] = { 0 };
for (int i = 0; i < sfile_nformats; i++) {
const SFormat *f = &sfile_formats[i];
if (f->magic_off != 0 || f->magic_len == 0) continue;
cnt[(uint8_t)f->magic[0]]++;
}
for (int b = 0; b < 256; b++) {
idx[b] = malloc(sizeof(*idx[b]) * (cnt[b] + 1));
if (!idx[b]) { fprintf(stderr, "%s: out of memory\n", prog); exit(2); }
nidx[b] = 0;
}
for (int i = 0; i < sfile_nformats; i++) {
const SFormat *f = &sfile_formats[i];
if (f->magic_off != 0 || f->magic_len == 0) continue;
int b = (uint8_t)f->magic[0];
idx[b][nidx[b]++] = f;
}
}
/* Best format whose magic matches at p: longest magic wins; on a tie a
format scar knows how to size wins over one it can only bound. */
static const SFormat *match_at(const uint8_t *p, uint64_t avail)
{
const SFormat *best = NULL;
for (int i = 0; i < nidx[p[0]]; i++) {
const SFormat *f = idx[p[0]][i];
if (f->magic_len > avail) continue;
if (memcmp(p, f->magic, f->magic_len) != 0) continue;
if (!best || f->magic_len > best->magic_len ||
(f->magic_len == best->magic_len &&
sizer_for(f) != SZ_NONE && sizer_for(best) == SZ_NONE))
best = f;
}
return best;
}
/* A header is worth carving on if scar can size it exactly (any magic
length — gzip's magic is only 2 bytes, but inflate validates it) or
its magic is at least 3 bytes long (a 2-byte magic in random data is
a false positive every ~64 KiB; 3 bytes is ~1 in 16M). */
static int plausible_header(const SFormat *f)
{
return f && (f->magic_len >= 3 || sizer_for(f) != SZ_NONE);
}
/* ---- structure walkers (one per format with a computable end) ---- */
/* PNG: walk chunks (length + type + data + CRC) until IEND.
First chunk must be IHDR. */
static int64_t png_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 8 + 12 + 13 || memcmp(p + 12, "IHDR", 4) != 0) return -1;
uint64_t pos = 8;
while (pos + 12 <= avail) {
uint32_t len = rd32be(p + pos);
if (len > avail - pos - 12) {
if (consumed) *consumed = pos; /* chunk data runs past EOF */
return -2;
}
int is_iend = memcmp(p + pos + 4, "IEND", 4) == 0;
pos += 12 + (uint64_t)len;
if (is_iend) return (int64_t)pos;
}
if (consumed) *consumed = pos; /* ran out mid-chunk-table */
return -2;
}
/* JPEG: walk markers. Standalone markers (RSTn, TEM) have no length;
every other segment carries a 2-byte big-endian length that includes
itself. SOS scan data is skipped byte-by-byte: 0xFF00 is an escaped
literal, 0xFFD0-0xFFD7 are restart markers, anything else after 0xFF
starts the next marker. */
static int64_t jpeg_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 4 || p[0] != 0xFF || p[1] != 0xD8 || p[2] != 0xFF) return -1;
uint64_t pos = 2;
while (pos + 1 < avail) {
if (p[pos] != 0xFF) return -1; /* expected a marker prefix */
uint64_t m = pos + 1;
while (m < avail && p[m] == 0xFF) m++; /* fill bytes */
if (m >= avail) {
if (consumed) *consumed = pos;
return -2;
}
uint8_t marker = p[m];
if (marker == 0xD9) return (int64_t)(m + 1); /* EOI */
if (marker == 0x01 || (marker >= 0xD0 && marker <= 0xD8)) {
pos = m + 1; /* standalone marker */
continue;
}
if (m + 2 >= avail) {
if (consumed) *consumed = m;
return -2;
}
uint32_t seglen = rd16be(p + m + 1);
if (seglen < 2) return -1;
if (marker == 0xDA) { /* SOS: skip entropy-coded scan data */
uint64_t s = m + 1 + seglen;
if (s >= avail) {
if (consumed) *consumed = avail; /* rest is scan data */
return -2;
}
uint64_t i = s;
int found = 0;
while (i + 1 < avail) {
if (p[i] != 0xFF) { i++; continue; }
uint8_t n = p[i + 1];
if (n == 0x00) { i += 2; continue; } /* escaped FF */
if (n >= 0xD0 && n <= 0xD7) { i += 2; continue; } /* restart */
if (n == 0xFF) { i += 1; continue; } /* fill */
pos = i; found = 1; break; /* next marker */
}
if (!found) {
if (consumed) *consumed = s; /* scan data runs to EOF */
return -2;
}
continue;
}
pos = m + 1 + seglen;
}
if (consumed) *consumed = pos;
return -2;
}
/* GIF: skip sub-blocks (size byte, data, 0 terminates). */
static int gif_skip_subblocks(const uint8_t *p, uint64_t avail, uint64_t *pos)
{
while (*pos < avail) {
uint8_t n = p[*pos];
if (n == 0) { (*pos)++; return 1; }
if (n > avail - *pos - 1) return 0;
*pos += 1 + n;
}
return 0;
}
static int64_t gif_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 13) return -2;
if (memcmp(p, "GIF87a", 6) != 0 && memcmp(p, "GIF89a", 6) != 0) return -1;
uint64_t pos = 13; /* header 6 + logical screen descriptor 7 */
uint8_t packed = p[10];
if (packed & 0x80) {
uint64_t gct = 3ull * (1u << ((packed & 0x07) + 1));
if (gct > avail - pos) {
if (consumed) *consumed = 13;
return -2;
}
pos += gct;
}
while (pos < avail) {
uint64_t block_start = pos;
uint8_t b = p[pos];
if (b == 0x3B) return (int64_t)(pos + 1); /* trailer */
if (b == 0x2C) { /* image descriptor */
if (pos + 10 > avail) {
if (consumed) *consumed = block_start;
return -2;
}
uint8_t ipacked = p[pos + 9];
pos += 10;
if (ipacked & 0x80) {
uint64_t lct = 3ull * (1u << ((ipacked & 0x07) + 1));
if (lct > avail - pos) {
if (consumed) *consumed = block_start;
return -2;
}
pos += lct;
}
if (pos >= avail) {
if (consumed) *consumed = block_start;
return -2;
}
pos += 1; /* LZW minimum code size */
if (!gif_skip_subblocks(p, avail, &pos)) {
if (consumed) *consumed = block_start;
return -2;
}
} else if (b == 0x21) { /* extension */
if (pos + 2 > avail) {
if (consumed) *consumed = block_start;
return -2;
}
pos += 2;
if (!gif_skip_subblocks(p, avail, &pos)) {
if (consumed) *consumed = block_start;
return -2;
}
} else {
return -1; /* unknown block type: not a GIF */
}
}
if (consumed) *consumed = pos;
return -2;
}
/* ZIP: validate one EOCD candidate — central directory offset + size
must land exactly on the EOCD itself, and the comment must fit. */
static int64_t zip_eocd_end(const uint8_t *p, uint64_t avail, uint64_t from)
{
int64_t e;
while ((e = scar_find_bytes(p, avail, FOOT_ZIP_EOCD, 4, from)) >= 0) {
if ((uint64_t)e + 22 > avail) return -2;
uint32_t cd_size = rd32le(p + e + 12);
uint32_t cd_off = rd32le(p + e + 16);
uint16_t comment = rd16le(p + e + 20);
uint64_t end = (uint64_t)e + 22 + comment;
if ((uint64_t)cd_off + cd_size == (uint64_t)e && end <= avail)
return (int64_t)end;
from = (uint64_t)e + 1; /* stray PK\x05\x06 in file data: keep looking */
}
return -1;
}
/* ZIP: walk local file headers, then expect the central directory and
EOCD. Entries with the data-descriptor flag (bit 3) carry no sizes in
the header, so the data is skipped by scanning for the next PK
signature. Returns the EOCD end, -1 if invalid, -2 if truncated. */
static int64_t zip_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 30) return -2;
if (rd16le(p + 4) > 63) return -1; /* version needed */
uint16_t method = rd16le(p + 8);
if (method > 99) return -1; /* unknown method */
uint64_t pos = 0;
int entries = 0;
while (1) {
uint64_t entry_start = pos;
if (pos + 30 > avail) {
if (consumed) *consumed = pos;
return entries ? -2 : -1;
}
if (memcmp(p + pos, "PK\x03\x04", 4) != 0) break;
uint16_t flags = rd16le(p + pos + 6);
uint32_t csize = rd32le(p + pos + 18);
uint16_t fnlen = rd16le(p + pos + 26);
uint16_t extralen = rd16le(p + pos + 28);
pos += 30 + fnlen + extralen;
if (pos > avail) {
if (consumed) *consumed = entry_start;
return -2;
}
entries++;
if (flags & 0x08) {
/* sizes unknown: scan for the next local header, central
directory or EOCD signature (data descriptors in between
are skipped over, they sit just before the signature). */
int64_t nx = -1;
uint64_t s = pos;
while (s + 4 <= avail) {
if (memcmp(p + s, "PK\x03\x04", 4) == 0 ||
memcmp(p + s, "PK\x01\x02", 4) == 0 ||
memcmp(p + s, "PK\x05\x06", 4) == 0) { nx = (int64_t)s; break; }
s++;
}
if (nx < 0) {
if (consumed) *consumed = pos;
return -2;
}
pos = (uint64_t)nx;
continue;
}
if (csize > avail - pos) {
if (consumed) *consumed = pos; /* compressed data truncated */
return -2;
}
pos += csize;
}
if (!entries) return -1;
int64_t eocd = zip_eocd_end(p, avail, pos);
if (eocd >= 0) return eocd;
if (consumed) *consumed = pos; /* headers walked, EOCD beyond EOF */
return -2;
}
/* PDF: header "%PDF-M.m", end at "%%EOF" plus trailing newline. */
static int64_t pdf_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 8 || memcmp(p, "%PDF-", 5) != 0) return -1;
if (!isdigit(p[5]) || p[6] != '.' || !isdigit(p[7])) return -1;
int64_t e = scar_find_bytes(p, avail, FOOT_PDF_EOF, 5, 5);
if (e < 0) {
if (consumed) *consumed = 8; /* header only; body is PDF data */
return -2;
}
uint64_t end = (uint64_t)e + 5;
while (end < avail && (p[end] == '\r' || p[end] == '\n')) end++;
return (int64_t)end;
}
/* gzip: no fixed trailer — inflate the stream (windowBits 31 = gzip
wrapper) and stop at Z_STREAM_END; total_in is the member length.
Concatenated members are followed. Inflate error = not gzip (-1);
running out of input first = truncated (-2). */
static int64_t gzip_end(const uint8_t *p, uint64_t avail, uint64_t *consumed)
{
if (avail < 10 || p[2] != 8 || (p[3] & 0xE0)) return -1;
uint64_t pos = 0;
uint8_t out[8192];
for (;;) {
z_stream zs;
memset(&zs, 0, sizeof zs);
if (inflateInit2(&zs, 31) != Z_OK) return -1;
zs.next_in = (Bytef *)(p + pos);
uint64_t left = avail - pos;
zs.avail_in = (uInt)(left > (1u << 30) ? (1u << 30) : left);
int ret = Z_OK;
while (ret != Z_STREAM_END) {
zs.next_out = out;
zs.avail_out = sizeof out;
ret = inflate(&zs, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
if (consumed) *consumed = pos + zs.total_in;
inflateEnd(&zs);
return ret == Z_BUF_ERROR ? -2 : -1;
}
}
pos += zs.total_in;
inflateEnd(&zs);
/* concatenated member? */
if (pos + 10 <= avail && p[pos] == 0x1F && p[pos + 1] == 0x8B &&
p[pos + 2] == 8 && !(p[pos + 3] & 0xE0))
continue;
return (int64_t)pos;
}
}
/* ---- fallback sizing: next recognised header, else EOF, capped ----
*
* A "next header" is only trusted as a boundary if it is itself a real
* file start: formats scar can size must size plausibly here (exact end,
* or truncated-but-structural), and formats it cannot size need a magic
* of at least 4 bytes. A bare 3-byte magic is not enough — random data
* contains one about every 16M bytes, and JPEG scan data / compressed
* streams are effectively random, so an unvalidated 3-byte match inside
* a file's own data would cut the carve short. (That is exactly what
* happened to a truncated JPEG in the first test run: a 3-byte magic
* 13 bytes into its scan data ended the carve at 13 bytes instead of
* the 200 that were really there.) */
static int64_t fallback_end(const uint8_t *img, uint64_t size, uint64_t off,
uint64_t consumed, const char **method)
{
/* Start after the bytes the structure walk already validated as this
file's own — never inside them (see the consumed note above). */
uint64_t start = off + (consumed ? consumed : 1);
if (start >= size) {
uint64_t rem = size - off;
if (rem > opt_max) { *method = "capped"; return (int64_t)opt_max; }
*method = "eof";
return (int64_t)rem;
}
for (uint64_t m = start; m < size; m++) {
const SFormat *f = match_at(img + m, size - m);
if (!f) continue;
int sz = sizer_for(f);
if (sz != SZ_NONE) {
int64_t e = -1;
switch (sz) {
case SZ_PNG: e = png_end(img + m, size - m, NULL); break;
case SZ_JPEG: e = jpeg_end(img + m, size - m, NULL); break;
case SZ_GIF: e = gif_end(img + m, size - m, NULL); break;
case SZ_ZIP: e = zip_end(img + m, size - m, NULL); break;
case SZ_PDF: e = pdf_end(img + m, size - m, NULL); break;
case SZ_GZIP: e = gzip_end(img + m, size - m, NULL); break;
}
if (e == -1) continue; /* looks like a header, isn't one */
*method = "next-header";
return (int64_t)(m - off);
}
if (f->magic_len >= 4) {
*method = "next-header";
return (int64_t)(m - off);
}
/* 3-byte magic with no structural check: too weak to trust as a
boundary inside another file's data — keep scanning. */
}
uint64_t rem = size - off;
if (rem > opt_max) {
*method = "capped";
return (int64_t)opt_max;
}
*method = "eof";
return (int64_t)rem;
}
typedef struct {
const SFormat *fmt;
uint64_t off;
uint64_t size;
const char *conf; /* high / medium / low */
const char *method; /* how the end was found */
char *file; /* output filename */
} Carve;
static void ext_lower(const char *ext, char *out, size_t n)
{
size_t j = 0;
for (size_t i = 0; ext[i] && j + 1 < n; i++) {
char c = ext[i];
if (c == '.' && i == 0) continue;
out[j++] = (isalnum((unsigned char)c) || c == '.')
? (char)tolower((unsigned char)c) : '_';
}
out[j] = '\0';
if (j == 0) snprintf(out, n, "bin");
}
static int write_file(const char *path, const uint8_t *data, uint64_t len)
{
FILE *fp = fopen(path, "wb");
if (!fp) return -1;
if (len > 0 && fwrite(data, 1, (size_t)len, fp) != (size_t)len) {
fclose(fp);
return -1;
}
if (fclose(fp) != 0) return -1;
return 0;
}
static void usage(void)
{
fprintf(stderr,
"scar " SCAR_VERSION " — file carver built on sfile's format table\n"
"usage: %s [-o outdir] [-m max-bytes] [-q] <image>\n"
" -o dir output directory (default: carved)\n"
" -m size cap per carved file, suffix k/m/g allowed (default: 512m)\n"
" -q quiet: write report.txt only, no stdout table\n",
prog);
}
static uint64_t parse_size(const char *s)
{
char *end;
uint64_t v = strtoull(s, &end, 10);
if (*end == 'k' || *end == 'K') v *= 1024;
else if (*end == 'm' || *end == 'M') v *= 1024 * 1024;
else if (*end == 'g' || *end == 'G') v *= 1024ull * 1024 * 1024;
return v;
}
int main(int argc, char **argv)
{
prog = argv[0];
int ch;
while ((ch = getopt(argc, argv, "o:m:q")) != -1) {
switch (ch) {
case 'o': opt_outdir = optarg; break;
case 'm': opt_max = parse_size(optarg); break;
case 'q': opt_quiet = 1; break;
default: usage(); return 1;
}
}
if (optind >= argc) { usage(); return 1; }
const char *path = argv[optind];
int fd = open(path, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, path, strerror(errno));
return 2;
}
struct stat st;
if (fstat(fd, &st) != 0 || st.st_size == 0) {
fprintf(stderr, "%s: %s is empty or unreadable\n", prog, path);
close(fd);
return 2;
}
uint64_t size = (uint64_t)st.st_size;
const uint8_t *img = mmap(NULL, (size_t)size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (img == MAP_FAILED) {
fprintf(stderr, "%s: cannot map %s: %s\n", prog, path, strerror(errno));
return 2;
}
build_index();
if (mkdir(opt_outdir, 0755) != 0 && errno != EEXIST) {
fprintf(stderr, "%s: cannot create %s: %s\n", prog, opt_outdir, strerror(errno));
return 2;
}
Carve *carves = NULL;
size_t ncarves = 0, cap = 0;
uint64_t pos = 0;
while (pos < size) {
const SFormat *f = match_at(img + pos, size - pos);
if (!plausible_header(f)) { pos++; continue; }
int64_t end = -1;
const char *method = NULL, *conf = NULL;
uint64_t consumed = 0;
switch (sizer_for(f)) {
case SZ_PNG:
end = png_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "png-chunk-walk"; conf = "high"; }
else if (end == -1) { /* damaged chunks: fall back to IEND scan */
int64_t ie = scar_find_bytes(img + pos, size - pos,
FOOT_PNG_IEND, 8, 8);
if (ie >= 0) { end = ie + 8; method = "png-iend-scan"; conf = "medium"; }
}
break;
case SZ_JPEG:
end = jpeg_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "jpeg-marker-walk"; conf = "high"; }
break;
case SZ_GIF:
end = gif_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "gif-block-walk"; conf = "high"; }
break;
case SZ_ZIP:
end = zip_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "zip-local-walk"; conf = "high"; }
else { /* damaged headers: EOCD scan alone still bounds it */
int64_t eocd = zip_eocd_end(img + pos, size - pos, 0);
if (eocd >= 0) { end = eocd; method = "zip-eocd-scan"; conf = "medium"; }
}
break;
case SZ_PDF:
end = pdf_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "pdf-eof-scan"; conf = "high"; }
break;
case SZ_GZIP:
end = gzip_end(img + pos, size - pos, &consumed);
if (end >= 0) { method = "gzip-inflate"; conf = "high"; }
break;
default:
break;
}
if (end == -1) { pos++; continue; } /* invalid header: not a file */
if (end == -2 || end < 0) { /* truncated, or no sizer */
end = fallback_end(img, size, pos, consumed, &method);
conf = "low";
}
if (end <= 0 || (uint64_t)end > size - pos) { pos++; continue; }
/* carve [pos, pos+end) */
char extbuf[32];
ext_lower(f->ext, extbuf, sizeof extbuf);
char fname[64];
snprintf(fname, sizeof fname, "%010llu.%s",
(unsigned long long)pos, extbuf);
char outpath[1024];
snprintf(outpath, sizeof outpath, "%s/%s", opt_outdir, fname);
if (write_file(outpath, img + pos, (uint64_t)end) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n", prog, outpath, strerror(errno));
pos++;
continue;
}
if (ncarves == cap) {
cap = cap ? cap * 2 : 16;
carves = realloc(carves, cap * sizeof(*carves));
if (!carves) { fprintf(stderr, "%s: out of memory\n", prog); return 2; }
}
carves[ncarves].fmt = f;
carves[ncarves].off = pos;
carves[ncarves].size = (uint64_t)end;
carves[ncarves].conf = conf;
carves[ncarves].method = method;
carves[ncarves].file = strdup(fname);
ncarves++;
pos += (uint64_t)end; /* resume after the carved file */
}
/* report: stdout table + <outdir>/report.txt */
char rep_path[1024];
snprintf(rep_path, sizeof rep_path, "%s/report.txt", opt_outdir);
FILE *rep = fopen(rep_path, "w");
if (!rep) fprintf(stderr, "%s: cannot write %s: %s\n", prog, rep_path, strerror(errno));
uint64_t total = 0;
for (size_t i = 0; i < ncarves; i++) total += carves[i].size;
FILE *outs[2] = { rep, opt_quiet ? NULL : stdout };
for (int o = 0; o < 2; o++) {
FILE *fp = outs[o];
if (!fp) continue;
fprintf(fp, "scar " SCAR_VERSION ": %s (%" PRIu64 " bytes) — %zu file%s carved, "
"%" PRIu64 " bytes total\n",
path, size, ncarves, ncarves == 1 ? "" : "s", total);
fprintf(fp, "%-12s %-10s %-28s %-6s %-10s %-17s %s\n",
"offset", "size", "format", "ext", "confidence", "method", "file");
for (size_t i = 0; i < ncarves; i++) {
const Carve *c = &carves[i];
char extbuf[32];
ext_lower(c->fmt->ext, extbuf, sizeof extbuf);
fprintf(fp, "%-12llu %-10llu %-28s %-6s %-10s %-17s %s\n",
(unsigned long long)c->off, (unsigned long long)c->size,
c->fmt->name, extbuf, c->conf, c->method, c->file);
}
}
if (rep) fclose(rep);
munmap((void *)img, (size_t)size);
return ncarves ? 0 : 3;
}
+124 -250
View File
@@ -4,286 +4,160 @@
* filename extension) and prints a detailed decode of the file header:
* field names, offsets, sizes and values, in a uniform table.
*
* The per-format knowledge lives in formats.h, which is GENERATED by
* tools/gen_formats.py from the collected C/C++ reference code
* (tools/all_formats.cpp) plus a curated magic table and hand overrides
* (tools/overrides.json). The engine itself is generic: it contains no
* per-format decode logic, only the table walk, the value formatters and
* the text/XML fallback decoder.
* This file is only the command-line front end. The decode engine lives
* in libsfile (src/sfile_lib.c, public API in src/sfile.h); everything
* printed here comes from sfile_result, so the CLI and the library
* agree by construction. `--json` prints the same result as JSON
* (one object per file, one per line) instead of the human table.
*
* Exit codes: 0 identified, 1 usage error, 2 file unreadable, 3 unknown.
* With several files the worst code wins (unreadable beats unknown).
*
* In text mode, an identified file also gets the "Geotagging:" section
* from decode_geotag() (src/geotag.c), exactly as upstream prints it.
* In --json mode that section is not printed: the same locations come
* from geotag_scan() inside libsfile and are carried in the JSON
* "geotags" array instead.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <sys/stat.h>
#include "formats.h"
#include "sfile.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 */
static const char *prog;
/* ---- value readers (respect per-format endianness) ---- */
static uint16_t rd16(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 rd32(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);
}
static uint64_t rd64(const uint8_t *p, int be) {
uint64_t v = 0;
if (be) { for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; }
else { for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; }
return v;
}
static float rd_f32(const uint8_t *p, int be) {
uint32_t u = rd32(p, be);
float f; memcpy(&f, &u, 4); return f;
}
static double rd_f64(const uint8_t *p, int be) {
uint64_t u = rd64(p, be);
double d; memcpy(&d, &u, 8); return d;
}
static int printable_ascii(const uint8_t *p, size_t n) {
for (size_t i = 0; i < n; i++)
if (!isprint(p[i]) && p[i] != 0) return 0;
return 1;
}
static void print_hex(const uint8_t *p, size_t n) {
for (size_t i = 0; i < n; i++) printf("%02x ", p[i]);
}
/* ---- identification ---- */
static const SFormat *match_magic(const uint8_t *buf, size_t n, const SFormat **cands, int *ncand) {
const SFormat *best = NULL;
*ncand = 0;
for (int i = 0; i < sfile_nformats; i++) {
const SFormat *f = &sfile_formats[i];
if (f->magic_len == 0) continue;
if (f->magic_off + f->magic_len > n) continue;
if (memcmp(buf + f->magic_off, f->magic, f->magic_len) == 0) {
if (*ncand < 64) cands[(*ncand)++] = f;
if (!best || f->magic_len > best->magic_len) best = f;
}
}
return best;
}
static const char *file_ext(const char *path) {
const char *dot = strrchr(path, '.');
const char *slash = strrchr(path, '/');
if (!dot || (slash && dot < slash)) return "";
return dot;
}
/* case-insensitive extension compare (".7z" vs ".7Z") */
static int ext_eq(const char *a, const char *b) {
while (*a && *b) {
if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
a++; b++;
}
return *a == *b;
}
/* ---- text / XML fallback decoder ---- */
static void decode_text(const uint8_t *buf, size_t n) {
/* XML declaration? */
if (n >= 5 && memcmp(buf, "<?xml", 5) == 0) {
printf("Document type: XML\n");
const uint8_t *end = memchr(buf, '>', n);
if (end && (size_t)(end - buf) < 200) {
printf("XML declaration: %.*s>\n", (int)(end - buf), buf);
}
/* root element: first '<' after the declaration that is not a comment/PI */
size_t i = end ? (size_t)(end - buf) + 1 : 5;
while (i < n && isspace(buf[i])) i++;
if (i + 1 < n && buf[i] == '<' && buf[i+1] != '?' && buf[i+1] != '!' && buf[i+1] != '/') {
size_t j = i + 1;
while (j < n && (isalnum(buf[j]) || buf[j] == '_' || buf[j] == '-' || buf[j] == '.' || buf[j] == ':')) j++;
printf("Root element: %.*s\n", (int)(j - i - 1), buf + i + 1);
/* version attribute on the root element */
const uint8_t *v = (const uint8_t *)memmem(buf + i, n - i, "version=\"", 9);
if (v && (size_t)(v - buf) < j + 200) {
const uint8_t *q = memchr(v + 9, '"', n - (size_t)(v - buf) - 9);
if (q) printf("Version attribute: %.*s\n", (int)(q - v - 9), v + 9);
}
}
return;
}
if (n >= 1 && buf[0] == '{') {
printf("Document type: JSON\n");
/* first key, if an object */
const uint8_t *q1 = memchr(buf + 1, '"', n - 1);
const uint8_t *q2 = q1 ? memchr(q1 + 1, '"', n - (size_t)(q1 - buf) - 1) : NULL;
if (q1 && q2 && (size_t)(q2 - q1) < 80)
printf("First key: %.*s\n", (int)(q2 - q1 - 1), q1 + 1);
return;
}
if (n >= 2 && buf[0] == '[') {
/* a JSON array must start with a value; an INI section header
like [PHP] starts with a bare word and must not match */
char c = (char)buf[1];
if (c == '"' || c == '{' || c == '[' || (c >= '0' && c <= '9') ||
c == '-' || c == 't' || c == 'f' || c == 'n') {
printf("Document type: JSON\n");
return;
}
}
/* plain text: first line */
printf("Document type: text\n");
const uint8_t *nl = memchr(buf, '\n', n < 200 ? n : 200);
size_t linelen = nl ? (size_t)(nl - buf) : (n < 200 ? n : 200);
while (linelen > 0 && (buf[linelen-1] == '\r' || buf[linelen-1] == '\n')) linelen--;
printf("First line: %.*s\n", (int)linelen, buf);
}
/* ---- main decode ---- */
static void decode_binary(const SFormat *f, const uint8_t *buf, size_t n, long fsize) {
printf("Header (%s-endian):\n", f->endian ? "big" : "little");
printf(" %-8s %-6s %-28s %s\n", "offset", "size", "field", "value");
for (int i = 0; i < f->nfields; i++) {
const SField *fl = &f->fields[i];
if (fl->offset + fl->size > (uint32_t)n) {
printf(" %-8u %-6u %-28s (beyond header window / EOF)\n",
fl->offset, fl->size, fl->name);
continue;
}
const uint8_t *p = buf + fl->offset;
printf(" %-8u %-6u %-28s ", fl->offset, fl->size, fl->name);
switch (fl->kind) {
case FK_U8: printf("%u\n", p[0]); break;
case FK_U16: printf("%u\n", rd16(p, f->endian)); break;
case FK_U32: printf("%u\n", rd32(p, f->endian)); break;
case FK_U64: printf("%llu\n", (unsigned long long)rd64(p, f->endian)); break;
case FK_I8: printf("%d\n", (int8_t)p[0]); break;
case FK_I16: printf("%d\n", (int16_t)rd16(p, f->endian)); break;
case FK_I32: printf("%d\n", (int32_t)rd32(p, f->endian)); break;
case FK_I64: printf("%lld\n", (long long)(int64_t)rd64(p, f->endian)); break;
case FK_F32: printf("%g\n", (double)rd_f32(p, f->endian)); break;
case FK_F64: printf("%g\n", rd_f64(p, f->endian)); break;
case FK_ASCII:
if (printable_ascii(p, fl->size)) {
/* trim at first NUL */
size_t m = 0;
while (m < fl->size && p[m]) m++;
printf("\"%.*s\"\n", (int)m, p);
} else {
print_hex(p, fl->size); printf("\n");
}
break;
case FK_BYTES:
default:
print_hex(p, fl->size); printf("\n"); break;
}
}
(void)fsize;
}
static void usage(void) {
fprintf(stderr, "Usage: %s <file> [--list]\n", prog);
fprintf(stderr, "Usage: %s <file>... [--json] [--list]\n", prog);
fprintf(stderr, " sfile identifies a file's format and decodes its header.\n");
fprintf(stderr, " --json print machine-readable JSON, one object per file (one per line)\n");
fprintf(stderr, " --list list all known formats (task, extension, name, derivation is in formats.json)\n");
}
static int list_formats(void) {
printf("%-6s %-8s %s\n", "task", "ext", "name");
for (int i = 0; i < sfile_nformats; i++) {
const SFormat *f = &sfile_formats[i];
printf("%-6d %-8s %s\n", f->task, f->ext, f->name);
for (int i = 0; i < sfile_format_count(); i++) {
sfile_format_info info;
if (sfile_get_format_info(i, &info) != 0) continue;
printf("%-6d %-8s %s\n", info.task, info.ext, info.name);
}
printf("%d formats\n", sfile_nformats);
printf("%d formats\n", sfile_format_count());
return 0;
}
/* The human-readable table, byte-identical to the historical output. */
static void print_result_text(const sfile_result *r) {
printf("File: %s (%lld bytes)\n", r->file, (long long)r->size);
if (!r->identified) {
printf("Format: unknown (no magic match, no known extension)\n");
printf("First %d bytes:\n ", HEXDUMP_LEN);
printf("%s%s\n", r->hexdump ? r->hexdump : "",
r->hexdump && *r->hexdump ? " " : "");
return;
}
printf("Format: %s (%s) — task %d\n", r->name, r->ext, r->task);
printf("Identified by: %s\n", r->identified_by);
if (r->has_magic) {
printf("Magic: ");
for (uint32_t i = 0; i < r->magic_len; i++) printf("%02x ", r->magic[i]);
printf("at offset %u\n", r->magic_off);
}
if (r->ncandidates > 0) {
printf("Note: %d formats share this magic; extension disambiguated to %s.\n",
r->ncandidates + 1, r->ext);
printf("Other candidates:");
for (int i = 0; i < r->ncandidates; i++)
printf(" %s (task %d)", r->candidates[i].ext, r->candidates[i].task);
printf("\n");
}
if (r->doc_type != SFILE_DOC_NONE) {
switch (r->doc_type) {
case SFILE_DOC_XML:
printf("Document type: XML\n");
if (r->xml_declaration) printf("XML declaration: %s\n", r->xml_declaration);
if (r->root_element) printf("Root element: %s\n", r->root_element);
if (r->version_attr) printf("Version attribute: %s\n", r->version_attr);
break;
case SFILE_DOC_JSON:
printf("Document type: JSON\n");
if (r->first_key) printf("First key: %s\n", r->first_key);
break;
case SFILE_DOC_TEXT:
default:
printf("Document type: text\n");
printf("First line: %s\n", r->first_line ? r->first_line : "");
break;
}
} else if (r->has_header) {
printf("Header (%s-endian):\n", r->endian ? "big" : "little");
printf(" %-8s %-6s %-28s %s\n", "offset", "size", "field", "value");
for (int i = 0; i < r->nfields; i++) {
const sfile_field *fl = &r->fields[i];
printf(" %-8u %-6u %-28s %s\n", fl->offset, fl->size, fl->name, fl->value);
}
} else {
printf("Header layout: not derived for this format (see formats.json, derivation: %s).\n",
r->format_kind == SFILE_FORMAT_UNKNOWN ? "unknown" : "magic-only");
printf("First %d bytes:\n ", HEXDUMP_LEN);
printf("%s%s\n", r->hexdump ? r->hexdump : "",
r->hexdump && *r->hexdump ? " " : "");
}
}
int main(int argc, char **argv) {
prog = argv[0];
if (argc < 2) { usage(); return 1; }
if (strcmp(argv[1], "--list") == 0) return list_formats();
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { usage(); return 0; }
const char *path = argv[1];
int json = 0, list = 0;
const char *files[argc > 1 ? argc : 1];
int nfiles = 0;
struct stat st;
if (stat(path, &st) != 0) { perror(path); return 2; }
FILE *fp = fopen(path, "rb");
if (!fp) { perror(path); return 2; }
size_t cap = st.st_size < HDR_WIN ? (size_t)st.st_size : HDR_WIN;
uint8_t *buf = malloc(cap ? cap : 1);
if (!buf) { fclose(fp); return 2; }
size_t n = fread(buf, 1, cap, fp);
fclose(fp);
printf("File: %s (%lld bytes)\n", path, (long long)st.st_size);
const SFormat *cands[64];
int ncand = 0;
const SFormat *best = match_magic(buf, n, cands, &ncand);
const SFormat *fmt = best;
const char *how = "magic";
if (!fmt) {
/* extension fallback */
const char *ext = file_ext(path);
if (*ext) {
for (int i = 0; i < sfile_nformats; i++) {
if (ext_eq(sfile_formats[i].ext, ext)) { fmt = &sfile_formats[i]; break; }
}
if (fmt) how = "extension";
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--json") == 0) json = 1;
else if (strcmp(argv[i], "--list") == 0) list = 1;
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
usage();
return 0;
}
} else if (ncand > 1) {
/* several formats share this magic (e.g. PK zip): prefer the one
whose extension matches the filename */
const char *ext = file_ext(path);
if (*ext) {
for (int i = 0; i < ncand; i++) {
if (ext_eq(cands[i]->ext, ext)) { fmt = cands[i]; break; }
}
else if (strcmp(argv[i], "--version") == 0) {
printf("sfile %s\n", SFILE_VERSION);
return 0;
}
else files[nfiles++] = argv[i];
}
if (!fmt) {
printf("Format: unknown (no magic match, no known extension)\n");
printf("First %d bytes:\n ", HEXDUMP_LEN);
print_hex(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
printf("\n");
free(buf);
return 3;
}
if (list) return list_formats();
if (nfiles == 0) { usage(); return 1; }
printf("Format: %s (%s) — task %d\n", fmt->name, fmt->ext, fmt->task);
printf("Identified by: %s\n", how);
if (fmt->magic_len) {
printf("Magic: ");
print_hex((const uint8_t *)fmt->magic, fmt->magic_len);
printf("at offset %u\n", fmt->magic_off);
int rc = 0;
for (int i = 0; i < nfiles; i++) {
sfile_result r;
int st = sfile_decode_file(files[i], &r);
if (st == 2) {
/* same as the old perror(path) on stderr; stdout stays
clean JSON when --json is on */
fprintf(stderr, "%s: %s\n", files[i], r.error ? r.error : "unreadable");
rc = 2;
} else if (st == 3 && rc != 2) {
rc = 3;
}
if (json) {
char *js = sfile_result_to_json(&r);
if (js) {
puts(js);
free(js);
} else {
fprintf(stderr, "%s: failed to serialize JSON\n", files[i]);
if (rc == 0) rc = 2;
}
} else {
if (st != 2) print_result_text(&r);
if (st == 0) decode_geotag(files[i], r.task);
}
sfile_free_result(&r);
}
if (ncand > 1) {
printf("Note: %d formats share this magic; extension disambiguated to %s.\n", ncand, fmt->ext);
printf("Other candidates:");
for (int i = 0; i < ncand; i++)
if (cands[i] != fmt) printf(" %s (task %d)", cands[i]->ext, cands[i]->task);
printf("\n");
}
if (fmt->kind == FMT_TEXT) {
decode_text(buf, n);
} else if (fmt->nfields > 0) {
decode_binary(fmt, buf, n, st.st_size);
} else {
printf("Header layout: not derived for this format (see formats.json, derivation: %s).\n",
fmt->kind == FMT_UNKNOWN ? "unknown" : "magic-only");
printf("First %d bytes:\n ", HEXDUMP_LEN);
print_hex(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
printf("\n");
}
free(buf);
return 0;
return rc;
}
+184
View File
@@ -0,0 +1,184 @@
/* sfile.h — public API for libsfile, the sfile decode engine as a library.
*
* sfile identifies a file's format (by magic bytes, falling back to the
* filename extension) and decodes its header: field names, offsets, sizes
* and values. This header exposes that engine so other tools (stag, sgeo,
* scar, ...) can link it instead of shelling out to the `sfile` binary.
*
* The CLI in src/sfile.c is a thin wrapper over this API: everything it
* prints comes from sfile_result, so library and CLI results agree by
* construction.
*
* Ownership: strings that point into the format table (format name/ext,
* field names, candidate exts) are borrowed — do not free them. Strings
* owned by sfile_result (file, error, field value/raw, hexdump, document
* strings) are freed by sfile_free_result(). sfile_result_to_json()
* returns a malloc'd string the caller frees.
*
* Threading: the format table is static const and the decode itself
* holds no shared state — except the geotag scan, which reuses
* geotag.c's static result buffer. Concurrent sfile_decode_file()
* calls are therefore NOT thread-safe; serialize them, or use
* sfile_decode_mem() (which never scans for geotags).
*/
#ifndef SFILE_H
#define SFILE_H
#include <stddef.h>
#include <stdint.h>
#include "geotag.h"
#define SFILE_VERSION "1.1.0"
/* Max locations geotag_scan() can return for one file (geotag.c holds 8). */
#define SFILE_MAX_GEOTAGS 8
#ifdef __cplusplus
extern "C" {
#endif
/* Field value kinds — same order/values as FK_* in formats.h. */
enum sfile_field_kind {
SFILE_U8 = 0, SFILE_U16, SFILE_U32, SFILE_U64,
SFILE_I8, SFILE_I16, SFILE_I32, SFILE_I64,
SFILE_F32, SFILE_F64, SFILE_ASCII, SFILE_BYTES
};
/* Format kinds — same values as FMT_* in formats.h. */
enum sfile_format_kind {
SFILE_BINARY = 0, SFILE_TEXT, SFILE_FORMAT_UNKNOWN
};
/* What the text fallback decoder found. */
enum sfile_doc_type {
SFILE_DOC_NONE = 0, SFILE_DOC_XML, SFILE_DOC_JSON, SFILE_DOC_TEXT
};
/* One decoded header field. `value` is formatted exactly as the CLI
* prints it (numbers decimal, ASCII quoted, bytes as space-separated hex
* with a trailing space). `raw` is the JSON-friendly form: numbers as
* decimal, ASCII unquoted, bytes as hex without the trailing space;
* NULL when the field runs past the bytes read (beyond_window). */
typedef struct {
uint32_t offset;
uint32_t size;
const char *name; /* borrowed from the format table */
int kind; /* enum sfile_field_kind */
int beyond_window; /* field runs past the header window / EOF */
char *value; /* owned */
char *raw; /* owned, NULL when beyond_window */
int is_number; /* value is a JSON number */
int is_float; /* number came from F32/F64 */
unsigned long long unum;
long long inum;
double fnum;
} sfile_field;
/* Another format sharing the same magic (the chosen format excluded). */
typedef struct {
const char *ext; /* borrowed from the format table */
int task;
} sfile_candidate;
typedef struct {
char *file; /* path as given (owned) */
long size; /* file size in bytes, -1 when unreadable */
int identified; /* 1 = a format was identified */
int status; /* 0 ok, 2 unreadable, 3 unknown — mirrors CLI exit codes */
char *error; /* human-readable reason when status != 0 (owned) */
/* identified format (borrowed strings) */
int task;
const char *ext;
const char *name;
int format_kind; /* enum sfile_format_kind */
int endian; /* 0 little, 1 big */
int nfields_table; /* fields the format declares (0 = no layout) */
const char *identified_by; /* "magic" | "extension" | NULL */
uint8_t magic[32];
uint32_t magic_len;
uint32_t magic_off;
int has_magic;
sfile_candidate candidates[64];
int ncandidates; /* other formats sharing this magic */
/* binary header decode */
int has_header; /* 1 when fields[] holds a decoded header table */
sfile_field *fields;/* owned array, nfields entries */
int nfields;
int has_layout; /* 0 = binary format with no derived layout */
/* text fallback decode */
int doc_type; /* enum sfile_doc_type */
char *xml_declaration; /* "<?xml ...?>" including '>', when present */
char *root_element; /* XML root element name, when found */
char *version_attr; /* version="..." on the root element, when found */
char *first_key; /* first key of a JSON object, when found */
char *first_line; /* first line of a plain-text file */
/* hex dump of the first 64 bytes (owned, space-separated hex, no
* trailing space) — set for unknown files and for binary formats
* with no derived layout */
char *hexdump;
/* geotags, from geotag_scan() (src/geotag.h): EXIF GPS, XMP,
* QuickTime/GeoTIFF/EXR/PSD/CR3 locations. Only sfile_decode_file()
* fills these — it has a path to scan. sfile_decode_mem() never
* touches the filesystem, so its results carry no geotags.
* geotag_status is the geotag_scan() return: -1 no geotagging
* mechanism for this format, 0 mechanism but none found, >0 the
* number of entries in geotags[]. */
GeoResult geotags[SFILE_MAX_GEOTAGS];
int ngeotags;
int geotag_status;
} sfile_result;
/* Decode a file from disk. Returns 0 (identified), 2 (unreadable) or
* 3 (unknown) and fills res either way; call sfile_free_result() when
* done. `res` is zeroed on entry. Also runs geotag_scan() for the
* geotag fields (see above) when the format was identified. */
int sfile_decode_file(const char *path, sfile_result *res);
/* Decode bytes already in memory. display_name is used for the
* extension fallback and reported as `file` (may be NULL). fsize is
* the full file size (may differ from n, the bytes available). Same
* return codes as sfile_decode_file. No geotag scan is done here:
* there is no path to scan (call geotag_scan() yourself if you have
* one). */
int sfile_decode_mem(const uint8_t *buf, size_t n, const char *display_name,
long fsize, sfile_result *res);
/* Release everything sfile_decode_* allocated inside res. */
void sfile_free_result(sfile_result *res);
/* Serialize a decoded result as one compact JSON object (one line, no
* trailing newline). Returns a malloc'd string the caller frees, or
* NULL on allocation failure. See docs/json.md for the schema. */
char *sfile_result_to_json(const sfile_result *res);
/* Format-table introspection (powers `sfile --list`). */
int sfile_format_count(void);
typedef struct {
int task;
const char *ext; /* borrowed from the format table */
const char *name; /* borrowed from the format table */
int kind; /* enum sfile_format_kind */
int endian; /* 0 little, 1 big */
int nfields;
int has_magic;
} sfile_format_info;
/* Fill info for format index (0 .. sfile_format_count()-1).
* Returns 0 on success, -1 when index is out of range. */
int sfile_get_format_info(int index, sfile_format_info *info);
/* "u8" / "u16" / ... / "ascii" / "bytes" for a field kind. */
const char *sfile_field_kind_name(int kind);
#ifdef __cplusplus
}
#endif
#endif /* SFILE_H */
+713
View File
@@ -0,0 +1,713 @@
/* sfile_lib.c — the sfile decode engine, as a linkable library.
*
* This is the engine the `sfile` CLI used to contain inline: value
* readers, magic/extension identification, the text/XML fallback
* decoder, the binary header-table walk, and the JSON serializer.
* It contains no per-format decode logic — the knowledge lives in
* formats.h (generated by tools/gen_formats.py), exactly as before.
*
* The CLI (src/sfile.c) is a thin wrapper: it parses arguments and
* prints sfile_result, either as the human-readable table or as JSON.
* Moving the engine here changes no output: the text printer consumes
* the same strings the old inline code printed.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/stat.h>
#include "sfile.h"
#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 */
#define MAX_CANDIDATES 64
/* Field kinds must stay in step with FK_* in formats.h. */
_Static_assert((int)SFILE_U8 == (int)FK_U8 && (int)SFILE_BYTES == (int)FK_BYTES,
"sfile_field_kind out of step with formats.h FK_*");
_Static_assert((int)SFILE_BINARY == (int)FMT_BINARY &&
(int)SFILE_FORMAT_UNKNOWN == (int)FMT_UNKNOWN,
"sfile_format_kind out of step with formats.h FMT_*");
/* ---- value readers (respect per-format endianness) ---- */
static uint16_t rd16(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 rd32(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);
}
static uint64_t rd64(const uint8_t *p, int be) {
uint64_t v = 0;
if (be) { for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; }
else { for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; }
return v;
}
static float rd_f32(const uint8_t *p, int be) {
uint32_t u = rd32(p, be);
float f; memcpy(&f, &u, 4); return f;
}
static double rd_f64(const uint8_t *p, int be) {
uint64_t u = rd64(p, be);
double d; memcpy(&d, &u, 8); return d;
}
static int printable_ascii(const uint8_t *p, size_t n) {
for (size_t i = 0; i < n; i++)
if (!isprint(p[i]) && p[i] != 0) return 0;
return 1;
}
/* Space-separated lowercase hex, no trailing space. Caller frees. */
static char *hex_string(const uint8_t *p, size_t n) {
char *s = malloc(n * 3 + 1);
if (!s) return NULL;
size_t o = 0;
for (size_t i = 0; i < n; i++) {
if (i) s[o++] = ' ';
o += (size_t)sprintf(s + o, "%02x", p[i]);
}
s[o] = '\0';
return s;
}
/* Same, with a trailing space — exactly what the CLI's old print_hex
* printed before the newline. Caller frees. */
static char *hex_string_trailing(const uint8_t *p, size_t n) {
char *s = malloc(n * 3 + 1);
if (!s) return NULL;
size_t o = 0;
for (size_t i = 0; i < n; i++)
o += (size_t)sprintf(s + o, "%02x ", p[i]);
s[o] = '\0';
return s;
}
static char *xstrdup(const char *s) {
if (!s) return NULL;
size_t n = strlen(s) + 1;
char *d = malloc(n);
if (d) memcpy(d, s, n);
return d;
}
static char *xstrndup(const char *s, size_t n) {
char *d = malloc(n + 1);
if (!d) return NULL;
memcpy(d, s, n);
d[n] = '\0';
return d;
}
/* ---- identification ---- */
static const SFormat *match_magic(const uint8_t *buf, size_t n, const SFormat **cands, int *ncand) {
const SFormat *best = NULL;
*ncand = 0;
for (int i = 0; i < sfile_nformats; i++) {
const SFormat *f = &sfile_formats[i];
if (f->magic_len == 0) continue;
if (f->magic_off + f->magic_len > n) continue;
if (memcmp(buf + f->magic_off, f->magic, f->magic_len) == 0) {
if (*ncand < MAX_CANDIDATES) cands[(*ncand)++] = f;
if (!best || f->magic_len > best->magic_len) best = f;
}
}
return best;
}
static const char *file_ext(const char *path) {
if (!path) return "";
const char *dot = strrchr(path, '.');
const char *slash = strrchr(path, '/');
if (!dot || (slash && dot < slash)) return "";
return dot;
}
/* case-insensitive extension compare (".7z" vs ".7Z") */
static int ext_eq(const char *a, const char *b) {
while (*a && *b) {
if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
a++; b++;
}
return *a == *b;
}
/* ---- field formatting ---- */
static void format_field_value(const SField *fl, const uint8_t *p, int be, sfile_field *out) {
out->offset = fl->offset;
out->size = fl->size;
out->name = fl->name;
out->kind = fl->kind;
out->beyond_window = 0;
char tmp[64];
switch (fl->kind) {
case FK_U8:
out->unum = p[0]; out->is_number = 1;
snprintf(tmp, sizeof tmp, "%u", p[0]); break;
case FK_U16:
out->unum = rd16(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%u", rd16(p, be)); break;
case FK_U32:
out->unum = rd32(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%u", rd32(p, be)); break;
case FK_U64:
out->unum = rd64(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)rd64(p, be)); break;
case FK_I8:
out->inum = (int8_t)p[0]; out->is_number = 1;
snprintf(tmp, sizeof tmp, "%d", (int8_t)p[0]); break;
case FK_I16:
out->inum = (int16_t)rd16(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%d", (int16_t)rd16(p, be)); break;
case FK_I32:
out->inum = (int32_t)rd32(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%d", (int32_t)rd32(p, be)); break;
case FK_I64:
out->inum = (int64_t)rd64(p, be); out->is_number = 1;
snprintf(tmp, sizeof tmp, "%lld", (long long)(int64_t)rd64(p, be)); break;
case FK_F32: {
float f = rd_f32(p, be);
out->fnum = f; out->is_number = 1; out->is_float = 1;
snprintf(tmp, sizeof tmp, "%g", (double)f); break;
}
case FK_F64: {
double d = rd_f64(p, be);
out->fnum = d; out->is_number = 1; out->is_float = 1;
snprintf(tmp, sizeof tmp, "%g", d); break;
}
case FK_ASCII:
if (printable_ascii(p, fl->size)) {
/* trim at first NUL; CLI prints it quoted */
size_t m = 0;
while (m < fl->size && p[m]) m++;
out->raw = xstrndup((const char *)p, m);
out->value = malloc(m + 3);
if (out->value) snprintf(out->value, m + 3, "\"%.*s\"", (int)m, p);
} else {
out->value = hex_string_trailing(p, fl->size);
out->raw = hex_string(p, fl->size);
}
return;
case FK_BYTES:
default:
out->value = hex_string_trailing(p, fl->size);
out->raw = hex_string(p, fl->size);
return;
}
out->value = xstrdup(tmp);
out->raw = xstrdup(tmp);
}
/* ---- text / XML fallback decoder ---- */
static void decode_text_into(const uint8_t *buf, size_t n, sfile_result *res) {
/* XML declaration? */
if (n >= 5 && memcmp(buf, "<?xml", 5) == 0) {
res->doc_type = SFILE_DOC_XML;
const uint8_t *end = memchr(buf, '>', n);
if (end && (size_t)(end - buf) < 200) {
res->xml_declaration = xstrndup((const char *)buf, (size_t)(end - buf) + 1);
}
/* root element: first '<' after the declaration that is not a comment/PI */
size_t i = end ? (size_t)(end - buf) + 1 : 5;
while (i < n && isspace(buf[i])) i++;
if (i + 1 < n && buf[i] == '<' && buf[i+1] != '?' && buf[i+1] != '!' && buf[i+1] != '/') {
size_t j = i + 1;
while (j < n && (isalnum(buf[j]) || buf[j] == '_' || buf[j] == '-' || buf[j] == '.' || buf[j] == ':')) j++;
res->root_element = xstrndup((const char *)buf + i + 1, j - i - 1);
/* version attribute on the root element */
const uint8_t *v = (const uint8_t *)memmem(buf + i, n - i, "version=\"", 9);
if (v && (size_t)(v - buf) < j + 200) {
const uint8_t *q = memchr(v + 9, '"', n - (size_t)(v - buf) - 9);
if (q) res->version_attr = xstrndup((const char *)v + 9, (size_t)(q - v - 9));
}
}
return;
}
if (n >= 1 && buf[0] == '{') {
res->doc_type = SFILE_DOC_JSON;
/* first key, if an object */
const uint8_t *q1 = memchr(buf + 1, '"', n - 1);
const uint8_t *q2 = q1 ? memchr(q1 + 1, '"', n - (size_t)(q1 - buf) - 1) : NULL;
if (q1 && q2 && (size_t)(q2 - q1) < 80)
res->first_key = xstrndup((const char *)q1 + 1, (size_t)(q2 - q1 - 1));
return;
}
if (n >= 2 && buf[0] == '[') {
/* a JSON array must start with a value; an INI section header
like [PHP] starts with a bare word and must not match */
char c = (char)buf[1];
if (c == '"' || c == '{' || c == '[' || (c >= '0' && c <= '9') ||
c == '-' || c == 't' || c == 'f' || c == 'n') {
res->doc_type = SFILE_DOC_JSON;
return;
}
}
/* plain text: first line */
res->doc_type = SFILE_DOC_TEXT;
const uint8_t *nl = memchr(buf, '\n', n < 200 ? n : 200);
size_t linelen = nl ? (size_t)(nl - buf) : (n < 200 ? n : 200);
while (linelen > 0 && (buf[linelen-1] == '\r' || buf[linelen-1] == '\n')) linelen--;
res->first_line = xstrndup((const char *)buf, linelen);
}
/* ---- decode into a result ---- */
static void decode_identified(const SFormat *fmt, const uint8_t *buf, size_t n, sfile_result *res) {
res->task = fmt->task;
res->ext = fmt->ext;
res->name = fmt->name;
res->format_kind = fmt->kind;
res->endian = fmt->endian;
res->nfields_table = fmt->nfields;
res->identified = 1;
res->status = 0;
if (fmt->kind == FMT_TEXT) {
decode_text_into(buf, n, res);
} else if (fmt->nfields > 0) {
res->has_header = 1;
res->has_layout = 1;
res->nfields = fmt->nfields;
res->fields = calloc((size_t)fmt->nfields, sizeof *res->fields);
if (!res->fields) { res->nfields = 0; return; }
for (int i = 0; i < fmt->nfields; i++) {
const SField *fl = &fmt->fields[i];
sfile_field *out = &res->fields[i];
out->offset = fl->offset;
out->size = fl->size;
out->name = fl->name;
out->kind = fl->kind;
if (fl->offset + fl->size > (uint32_t)n) {
out->beyond_window = 1;
out->value = xstrdup("(beyond header window / EOF)");
out->raw = NULL;
continue;
}
format_field_value(fl, buf + fl->offset, fmt->endian, out);
}
/* Geotags are NOT derived from header fields here: the
* dedicated decoders in src/geotag.c (EXIF GPS, XMP,
* QuickTime, GeoTIFF, EXR, PSD, CR3, ...) are the single
* source. sfile_decode_file() runs geotag_scan() for them
* (it has a path to scan); sfile_decode_mem() does not. */
} else {
res->has_layout = 0;
res->hexdump = hex_string(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
}
}
int sfile_decode_mem(const uint8_t *buf, size_t n, const char *display_name,
long fsize, sfile_result *res) {
if (!res) return 2;
memset(res, 0, sizeof *res);
res->file = xstrdup(display_name ? display_name : "");
res->size = fsize;
res->status = 3;
res->geotag_status = -1; /* no scan: decode_mem has no path */
const SFormat *cands[MAX_CANDIDATES];
int ncand = 0;
const SFormat *best = match_magic(buf, n, cands, &ncand);
const SFormat *fmt = best;
const char *how = "magic";
if (!fmt) {
/* extension fallback */
const char *ext = file_ext(display_name);
if (*ext) {
for (int i = 0; i < sfile_nformats; i++) {
if (ext_eq(sfile_formats[i].ext, ext)) { fmt = &sfile_formats[i]; break; }
}
if (fmt) how = "extension";
}
} else if (ncand > 1) {
/* several formats share this magic (e.g. PK zip): prefer the one
whose extension matches the filename */
const char *ext = file_ext(display_name);
if (*ext) {
for (int i = 0; i < ncand; i++) {
if (ext_eq(cands[i]->ext, ext)) { fmt = cands[i]; break; }
}
}
}
if (!fmt) {
res->error = xstrdup("unknown format (no magic match, no known extension)");
res->hexdump = hex_string(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
return 3;
}
res->identified_by = how;
if (fmt->magic_len) {
res->has_magic = 1;
memcpy(res->magic, fmt->magic, fmt->magic_len);
res->magic_len = fmt->magic_len;
res->magic_off = fmt->magic_off;
}
if (ncand > 1) {
for (int i = 0; i < ncand; i++)
if (cands[i] != fmt && res->ncandidates < MAX_CANDIDATES) {
res->candidates[res->ncandidates].ext = cands[i]->ext;
res->candidates[res->ncandidates].task = cands[i]->task;
res->ncandidates++;
}
}
decode_identified(fmt, buf, n, res);
return 0;
}
int sfile_decode_file(const char *path, sfile_result *res) {
if (!res) return 2;
memset(res, 0, sizeof *res);
res->file = xstrdup(path ? path : "");
res->size = -1;
res->status = 2;
res->geotag_status = -1;
struct stat st;
if (stat(path, &st) != 0) {
res->error = xstrdup(strerror(errno));
return 2;
}
FILE *fp = fopen(path, "rb");
if (!fp) {
res->error = xstrdup(strerror(errno));
return 2;
}
size_t cap = st.st_size < HDR_WIN ? (size_t)st.st_size : HDR_WIN;
uint8_t *buf = malloc(cap ? cap : 1);
if (!buf) {
fclose(fp);
res->error = xstrdup("out of memory");
return 2;
}
size_t n = fread(buf, 1, cap, fp);
fclose(fp);
int rc = sfile_decode_mem(buf, n, path, (long)st.st_size, res);
free(buf);
if (rc == 0 && path) {
/* geotags come from the dedicated decoders in src/geotag.c,
* not from the header fields above */
int ngeo = geotag_scan(path, res->task, res->geotags, SFILE_MAX_GEOTAGS);
res->geotag_status = ngeo;
res->ngeotags = ngeo > 0 ? ngeo : 0;
}
return rc;
}
void sfile_free_result(sfile_result *res) {
if (!res) return;
free(res->file);
free(res->error);
if (res->fields) {
for (int i = 0; i < res->nfields; i++) {
free(res->fields[i].value);
free(res->fields[i].raw);
}
free(res->fields);
}
free(res->xml_declaration);
free(res->root_element);
free(res->version_attr);
free(res->first_key);
free(res->first_line);
free(res->hexdump);
memset(res, 0, sizeof *res);
}
/* ---- format-table introspection ---- */
int sfile_format_count(void) {
return sfile_nformats;
}
int sfile_get_format_info(int index, sfile_format_info *info) {
if (!info || index < 0 || index >= sfile_nformats) return -1;
const SFormat *f = &sfile_formats[index];
info->task = f->task;
info->ext = f->ext;
info->name = f->name;
info->kind = f->kind;
info->endian = f->endian;
info->nfields = f->nfields;
info->has_magic = f->magic_len > 0;
return 0;
}
const char *sfile_field_kind_name(int kind) {
switch (kind) {
case SFILE_U8: return "u8";
case SFILE_U16: return "u16";
case SFILE_U32: return "u32";
case SFILE_U64: return "u64";
case SFILE_I8: return "i8";
case SFILE_I16: return "i16";
case SFILE_I32: return "i32";
case SFILE_I64: return "i64";
case SFILE_F32: return "f32";
case SFILE_F64: return "f64";
case SFILE_ASCII: return "ascii";
case SFILE_BYTES: return "bytes";
default: return "unknown";
}
}
/* ---- JSON serialization ---- */
typedef struct {
char *s;
size_t len;
size_t cap;
} jbuf;
static int jb_reserve(jbuf *b, size_t extra) {
if (b->len + extra + 1 <= b->cap) return 0;
size_t ncap = b->cap ? b->cap : 256;
while (ncap < b->len + extra + 1) ncap *= 2;
char *ns = realloc(b->s, ncap);
if (!ns) return -1;
b->s = ns;
b->cap = ncap;
return 0;
}
static int jb_putn(jbuf *b, const char *s, size_t n) {
if (jb_reserve(b, n) != 0) return -1;
memcpy(b->s + b->len, s, n);
b->len += n;
b->s[b->len] = '\0';
return 0;
}
static int jb_puts(jbuf *b, const char *s) {
return jb_putn(b, s, strlen(s));
}
static int jb_printf(jbuf *b, const char *fmt, ...) {
char tmp[512];
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(tmp, sizeof tmp, fmt, ap);
va_end(ap);
if (n < 0) return -1;
if ((size_t)n < sizeof tmp) return jb_putn(b, tmp, (size_t)n);
/* longer than the scratch buffer: allocate exactly */
char *big = malloc((size_t)n + 1);
if (!big) return -1;
va_start(ap, fmt);
vsnprintf(big, (size_t)n + 1, fmt, ap);
va_end(ap);
int rc = jb_putn(b, big, (size_t)n);
free(big);
return rc;
}
/* Append a JSON string literal (with quotes), escaping as needed. */
static int jb_string(jbuf *b, const char *s) {
if (!s) return jb_puts(b, "null");
if (jb_puts(b, "\"") != 0) return -1;
for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
char esc[8];
switch (*p) {
case '"': if (jb_puts(b, "\\\"") != 0) return -1; break;
case '\\': if (jb_puts(b, "\\\\") != 0) return -1; break;
case '\b': if (jb_puts(b, "\\b") != 0) return -1; break;
case '\f': if (jb_puts(b, "\\f") != 0) return -1; break;
case '\n': if (jb_puts(b, "\\n") != 0) return -1; break;
case '\r': if (jb_puts(b, "\\r") != 0) return -1; break;
case '\t': if (jb_puts(b, "\\t") != 0) return -1; break;
default:
if (*p < 0x20) {
snprintf(esc, sizeof esc, "\\u%04x", *p);
if (jb_puts(b, esc) != 0) return -1;
} else {
if (jb_putn(b, (const char *)p, 1) != 0) return -1;
}
}
}
return jb_puts(b, "\"");
}
static const char *format_kind_name(int kind) {
switch (kind) {
case SFILE_BINARY: return "binary";
case SFILE_TEXT: return "text";
default: return "unknown";
}
}
static int jb_field_value(jbuf *b, const sfile_field *fl) {
if (fl->beyond_window) return jb_puts(b, "null");
if (fl->is_number) {
if (fl->is_float) return jb_printf(b, "%.17g", fl->fnum);
if (fl->kind == SFILE_I8 || fl->kind == SFILE_I16 ||
fl->kind == SFILE_I32 || fl->kind == SFILE_I64)
return jb_printf(b, "%lld", fl->inum);
return jb_printf(b, "%llu", fl->unum);
}
return jb_string(b, fl->raw ? fl->raw : "");
}
char *sfile_result_to_json(const sfile_result *res) {
jbuf b = { NULL, 0, 0 };
if (jb_puts(&b, "{") != 0) goto fail;
if (jb_puts(&b, "\"file\":") != 0) goto fail;
if (jb_string(&b, res->file ? res->file : "") != 0) goto fail;
if (jb_printf(&b, ",\"size\":") != 0) goto fail;
if (res->size >= 0) {
if (jb_printf(&b, "%lld", (long long)res->size) != 0) goto fail;
} else if (jb_puts(&b, "null") != 0) goto fail;
if (jb_printf(&b, ",\"identified\":%s", res->identified ? "true" : "false") != 0) goto fail;
if (res->error) {
if (jb_puts(&b, ",\"error\":") != 0) goto fail;
if (jb_string(&b, res->error) != 0) goto fail;
}
if (!res->identified) {
if (res->hexdump) {
if (jb_puts(&b, ",\"hexdump\":") != 0) goto fail;
if (jb_string(&b, res->hexdump) != 0) goto fail;
}
if (jb_puts(&b, "}") != 0) goto fail;
return b.s;
}
/* format */
if (jb_puts(&b, ",\"format\":{\"task\":") != 0) goto fail;
if (jb_printf(&b, "%d,\"ext\":", res->task) != 0) goto fail;
if (jb_string(&b, res->ext) != 0) goto fail;
if (jb_puts(&b, ",\"name\":") != 0) goto fail;
if (jb_string(&b, res->name) != 0) goto fail;
if (jb_puts(&b, ",\"kind\":") != 0) goto fail;
if (jb_string(&b, format_kind_name(res->format_kind)) != 0) goto fail;
if (jb_puts(&b, ",\"endian\":") != 0) goto fail;
if (jb_string(&b, res->endian ? "big" : "little") != 0) goto fail;
if (jb_puts(&b, "}") != 0) goto fail;
if (jb_puts(&b, ",\"identified_by\":") != 0) goto fail;
if (jb_string(&b, res->identified_by ? res->identified_by : "") != 0) goto fail;
if (res->has_magic) {
char *hex = hex_string(res->magic, res->magic_len);
if (!hex) goto fail;
if (jb_puts(&b, ",\"magic\":{\"bytes\":") != 0) { free(hex); goto fail; }
if (jb_string(&b, hex) != 0) { free(hex); goto fail; }
free(hex);
if (jb_printf(&b, ",\"offset\":%u}", res->magic_off) != 0) goto fail;
}
if (res->ncandidates > 0) {
if (jb_puts(&b, ",\"other_candidates\":[") != 0) goto fail;
for (int i = 0; i < res->ncandidates; i++) {
if (i && jb_puts(&b, ",") != 0) goto fail;
if (jb_puts(&b, "{\"ext\":") != 0) goto fail;
if (jb_string(&b, res->candidates[i].ext) != 0) goto fail;
if (jb_printf(&b, ",\"task\":%d}", res->candidates[i].task) != 0) goto fail;
}
if (jb_puts(&b, "]") != 0) goto fail;
}
if (res->doc_type != SFILE_DOC_NONE) {
if (jb_puts(&b, ",\"document\":{") != 0) goto fail;
switch (res->doc_type) {
case SFILE_DOC_XML:
if (jb_puts(&b, "\"type\":\"xml\"") != 0) goto fail;
if (res->xml_declaration) {
if (jb_puts(&b, ",\"declaration\":") != 0) goto fail;
if (jb_string(&b, res->xml_declaration) != 0) goto fail;
}
if (res->root_element) {
if (jb_puts(&b, ",\"root_element\":") != 0) goto fail;
if (jb_string(&b, res->root_element) != 0) goto fail;
}
if (res->version_attr) {
if (jb_puts(&b, ",\"version\":") != 0) goto fail;
if (jb_string(&b, res->version_attr) != 0) goto fail;
}
break;
case SFILE_DOC_JSON:
if (jb_puts(&b, "\"type\":\"json\"") != 0) goto fail;
if (res->first_key) {
if (jb_puts(&b, ",\"first_key\":") != 0) goto fail;
if (jb_string(&b, res->first_key) != 0) goto fail;
}
break;
case SFILE_DOC_TEXT:
default:
if (jb_puts(&b, "\"type\":\"text\",\"first_line\":") != 0) goto fail;
if (jb_string(&b, res->first_line ? res->first_line : "") != 0) goto fail;
break;
}
if (jb_puts(&b, "}") != 0) goto fail;
} else if (res->has_header) {
if (jb_puts(&b, ",\"header\":{\"endian\":") != 0) goto fail;
if (jb_string(&b, res->endian ? "big" : "little") != 0) goto fail;
if (jb_puts(&b, ",\"fields\":[") != 0) goto fail;
for (int i = 0; i < res->nfields; i++) {
const sfile_field *fl = &res->fields[i];
if (i && jb_puts(&b, ",") != 0) goto fail;
if (jb_printf(&b, "{\"offset\":%u,\"size\":%u,\"name\":",
fl->offset, fl->size) != 0) goto fail;
if (jb_string(&b, fl->name) != 0) goto fail;
if (jb_puts(&b, ",\"type\":") != 0) goto fail;
if (jb_string(&b, sfile_field_kind_name(fl->kind)) != 0) goto fail;
if (jb_puts(&b, ",\"value\":") != 0) goto fail;
if (jb_field_value(&b, fl) != 0) goto fail;
if (fl->beyond_window) {
if (jb_puts(&b, ",\"unavailable\":\"beyond header window / EOF\"") != 0) goto fail;
}
if (jb_puts(&b, "}") != 0) goto fail;
}
if (jb_puts(&b, "]}") != 0) goto fail;
} else {
/* binary format with no derived layout */
if (jb_puts(&b, ",\"note\":") != 0) goto fail;
if (jb_string(&b, res->format_kind == SFILE_FORMAT_UNKNOWN
? "no header layout derived (derivation: unknown)"
: "no header layout derived (derivation: magic-only)") != 0) goto fail;
if (res->hexdump) {
if (jb_puts(&b, ",\"hexdump\":") != 0) goto fail;
if (jb_string(&b, res->hexdump) != 0) goto fail;
}
}
/* geotags, from geotag_scan(): emitted whenever the format has a
* geotagging mechanism (empty array when none was found), omitted
* when it has none. Each entry carries the decoder's source
* string plus the optional altitude/datum/datetime. */
if (res->geotag_status >= 0) {
if (jb_puts(&b, ",\"geotags\":[") != 0) goto fail;
for (int i = 0; i < res->ngeotags; i++) {
const GeoResult *g = &res->geotags[i];
if (i && jb_puts(&b, ",") != 0) goto fail;
if (jb_puts(&b, "{\"source\":") != 0) goto fail;
if (jb_string(&b, g->source) != 0) goto fail;
if (jb_printf(&b, ",\"latitude\":%.17g,\"longitude\":%.17g",
g->lat, g->lon) != 0) goto fail;
if (g->has_alt) {
if (jb_printf(&b, ",\"altitude_m\":%.17g", g->alt) != 0) goto fail;
}
if (g->has_datum) {
if (jb_puts(&b, ",\"datum\":") != 0) goto fail;
if (jb_string(&b, g->datum) != 0) goto fail;
}
if (g->has_datetime) {
if (jb_puts(&b, ",\"datetime_utc\":") != 0) goto fail;
if (jb_string(&b, g->datetime) != 0) goto fail;
}
if (jb_puts(&b, "}") != 0) goto fail;
}
if (jb_puts(&b, "]") != 0) goto fail;
}
if (jb_puts(&b, "}") != 0) goto fail;
return b.s;
fail:
free(b.s);
return NULL;
}
+1054
View File
File diff suppressed because it is too large. Load diff
+123
View File
@@ -0,0 +1,123 @@
/* stag.c -- scan a directory of image/video files and tabulate geotags.
*
* Usage: stag [dir] [outfile]
* dir directory to scan, non-recursive (default ".")
* outfile CSV file to write (default "geotags.csv" in the cwd)
*
* Each media file in dir gets one CSV row:
* file,format,latitude,longitude,altitude,datum,timestamp,source
* Coordinates come from running the `sfile` binary on each file and
* parsing its "Geotagging:" section (see src/geotag_client.c and
* docs/geotag-contract.md). Files with no geotag still get a row, with
* the latitude/longitude/altitude/timestamp/source fields empty.
* The sfile binary is located by $SFILE, then PATH, then alongside
* this executable (see find_sfile()).
*/
#define _GNU_SOURCE
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "geotag_client.h"
static void csv_field(FILE *fp, const char *s)
{
int need_quote = 0;
for (const char *p = s; *p; p++) {
if (*p == ',' || *p == '"' || *p == '\n' || *p == '\r') {
need_quote = 1;
break;
}
}
if (!need_quote) {
fputs(s, fp);
return;
}
fputc('"', fp);
for (const char *p = s; *p; p++) {
if (*p == '"') fputc('"', fp);
fputc(*p, fp);
}
fputc('"', fp);
}
static void csv_num(FILE *fp, int present, double v, const char *fmt)
{
if (present) fprintf(fp, fmt, v);
}
int main(int argc, char **argv)
{
const char *dir = ".";
const char *outfile = "geotags.csv";
if (argc > 1) dir = argv[1];
if (argc > 2) outfile = argv[2];
if (argc > 3) {
fprintf(stderr, "usage: stag [dir] [outfile]\n");
return 2;
}
char **names = NULL;
int n = 0;
if (collect_media_files(dir, &names, &n) != 0) {
fprintf(stderr, "stag: cannot open directory '%s': %s\n",
dir, strerror(errno));
return 1;
}
FILE *fp = fopen(outfile, "w");
if (!fp) {
fprintf(stderr, "stag: cannot write '%s': %s\n",
outfile, strerror(errno));
free_media_list(names, n);
return 1;
}
fputs("file,format,latitude,longitude,altitude,datum,timestamp,source\n", fp);
int geotagged = 0;
int rc = 0;
for (int i = 0; i < n; i++) {
char full[PATH_MAX];
if (snprintf(full, sizeof full, "%s/%s", dir, names[i]) >= (int)sizeof full) {
fprintf(stderr, "stag: path too long: '%s/%s'\n", dir, names[i]);
rc = 1;
break;
}
Geotag g;
if (extract_geotag(full, &g) != 0) {
fprintf(stderr, "stag: cannot run sfile on '%s' "
"(set $SFILE or put sfile on PATH)\n", full);
rc = 1;
break;
}
if (g.found) geotagged++;
csv_field(fp, names[i]);
fputc(',', fp);
csv_field(fp, g.format);
fputc(',', fp);
csv_num(fp, g.found, g.latitude, "%.6f");
fputc(',', fp);
csv_num(fp, g.found, g.longitude, "%.6f");
fputc(',', fp);
csv_num(fp, g.found && g.has_altitude, g.altitude, "%.3f");
fputc(',', fp);
if (g.found) csv_field(fp, g.datum);
fputc(',', fp);
if (g.found) csv_field(fp, g.timestamp);
fputc(',', fp);
if (g.found) csv_field(fp, g.source);
fputc('\n', fp);
}
if (fclose(fp) != 0 && rc == 0) {
fprintf(stderr, "stag: cannot finish writing '%s': %s\n",
outfile, strerror(errno));
rc = 1;
}
free_media_list(names, n);
if (rc == 0)
fprintf(stderr, "stag: %d file(s), %d geotagged -> %s\n",
n, geotagged, outfile);
return rc;
}
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Fake `sfile` for the stag/sgeo tests.
Prints canned sfile-style output with known GPS values, dispatched on
the file's basename (case-insensitive). Used by tests/run_tests.sh with
this directory first on PATH, so stag/sgeo exercise the real client
seam (src/geotag_client.c) against deterministic input.
Forms covered:
sf.jpg -- "Geotagging:" section, all fields (EXIF GPS)
paris.jpg -- section form, no altitude / datum / datetime (defaults)
tokyo.jpg -- section form, XMP source, no optional fields
nyc.jpg -- EXIF GPS tag-name fallback form (DMS rationals + refs,
GPSDateStamp/GPSTimeStamp), no "source:" line
anything else -- "none found" (no geotag)
"""
import os
import sys
name = os.path.basename(sys.argv[1])
low = name.lower()
ext = os.path.splitext(low)[1]
fmt = "PNG image" if ext == ".png" else "JPEG image"
def header():
print("Format: %s (%s) -- task 332" % (fmt, ext.lstrip(".")))
def section(source, lat, lon, alt=None, datum=None, dt=None):
header()
print("Geotagging:")
print(" source: %s" % source)
print(" gps_latitude: %.6f" % lat)
print(" gps_longitude: %.6f" % lon)
if alt is not None:
print(" gps_altitude_m: %.3f (above sea level)" % alt)
if datum is not None:
print(" gps_datum: %s" % datum)
if dt is not None:
print(" gps_datetime_utc: %s" % dt)
if low == "sf.jpg":
# Full section form; DMS display in parens is ignored by the parser
# (the decimal before it is authoritative).
header()
print("Geotagging:")
print(" source: EXIF GPS")
print(" gps_latitude: 37.774929 (37\xb046'29.64\"N)")
print(" gps_longitude: -122.419418 (122\xb025'9.90\"W)")
print(" gps_altitude_m: 12.000 (above sea level)")
print(" gps_datum: WGS-84")
print(" gps_datetime_utc: 2024-05-01 12:34:56")
elif low == "paris.jpg":
section("EXIF GPS", 48.856600, 2.352200)
elif low == "tokyo.jpg":
section("XMP", 35.676200, 139.650300)
elif low == "nyc.jpg":
# EXIF tag-name fallback form, as sfile's uniform header table
# would show it: DMS rationals plus hemisphere refs, separate
# date/time tags, no "source:" line (source becomes "unknown").
header()
print("GPSLatitude: 40/1, 42/1, 4608/100")
print("GPSLatitudeRef: N")
print("GPSLongitude: 74/1, 0/1, 2160/100")
print("GPSLongitudeRef: W")
print("GPSAltitude: 10/1")
print("GPSAltitudeRef: 0")
print("GPSDateStamp: 2024:06:15")
print("GPSTimeStamp: 8/1, 30/1, 0/1")
else:
header()
print("Geotagging:")
print(" none found (searched EXIF GPS IFD in JPEG APP1; XMP in JPEG APP1)")
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Check a map.png produced by sgeo (stdlib only, no PIL needed).
Usage: check_map.py map.png <expected-marker-clusters>
Decodes the PNG, finds red marker pixels (r>=200, g<=90, b<=90),
groups them into connected clusters, and requires exactly the
expected number of clusters, each at least 20 pixels (a marker is a
~7px-radius red disc). Also requires the attribution plaque: the
bottom 16 rows must contain both white plaque pixels and dark text
pixels. Prints the image size, cluster count and attribution counts.
"""
import struct
import sys
import zlib
def read_png(path):
with open(path, "rb") as f:
data = f.read()
assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
pos = 8
idat = b""
w = h = None
bit_depth = color_type = None
while pos < len(data):
ln = struct.unpack(">I", data[pos:pos + 4])[0]
typ = data[pos + 4:pos + 8]
body = data[pos + 8:pos + 8 + ln]
if typ == b"IHDR":
w, h, bit_depth, color_type = struct.unpack(">IIBB", body[:10])
elif typ == b"IDAT":
idat += body
elif typ == b"IEND":
break
pos += 12 + ln
assert bit_depth == 8 and color_type in (2, 6), \
"unsupported PNG: depth %s type %s" % (bit_depth, color_type)
ch = 3 if color_type == 2 else 4
raw = zlib.decompress(idat)
stride = w * ch
px = bytearray(w * h * 3)
prev = bytearray(stride)
p = 0
for y in range(h):
filt = raw[p]
p += 1
line = bytearray(raw[p:p + stride])
p += stride
if filt == 1:
for i in range(ch, stride):
line[i] = (line[i] + line[i - ch]) & 0xFF
elif filt == 2:
for i in range(stride):
line[i] = (line[i] + prev[i]) & 0xFF
elif filt == 3:
for i in range(stride):
a = line[i - ch] if i >= ch else 0
line[i] = (line[i] + ((a + prev[i]) >> 1)) & 0xFF
elif filt == 4:
for i in range(stride):
a = line[i - ch] if i >= ch else 0
b = prev[i]
c = prev[i - ch] if i >= ch else 0
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
line[i] = (line[i] + pr) & 0xFF
elif filt != 0:
raise ValueError("unknown PNG filter %d" % filt)
for x in range(w):
o = (y * w + x) * 3
px[o:o + 3] = line[x * ch:x * ch + 3]
prev = line
return w, h, px
def main():
path, expected = sys.argv[1], int(sys.argv[2])
w, h, px = read_png(path)
def rgb(x, y):
o = (y * w + x) * 3
return px[o], px[o + 1], px[o + 2]
red = set()
for y in range(h):
for x in range(w):
r, g, b = rgb(x, y)
if r >= 200 and g <= 90 and b <= 90:
red.add((x, y))
# Cluster red pixels: union neighbours within 2px (a marker disc
# is solid, so 8-connectivity with a 2px reach is plenty).
parent = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
cells = {}
for p in red:
parent[p] = p
cells.setdefault((p[0] // 4, p[1] // 4), []).append(p)
for (x, y) in red:
for cx in (x // 4 - 1, x // 4, x // 4 + 1):
for cy in (y // 4 - 1, y // 4, y // 4 + 1):
for q in cells.get((cx, cy), []):
if q != (x, y) and abs(q[0] - x) <= 2 and abs(q[1] - y) <= 2:
ra, rb = find((x, y)), find(q)
if ra != rb:
parent[ra] = rb
sizes = {}
for p in red:
sizes[find(p)] = sizes.get(find(p), 0) + 1
clusters = sorted((s for s in sizes.values() if s >= 20), reverse=True)
# Attribution plaque: white + dark pixels in the bottom 16 rows.
white = dark = 0
for y in range(max(0, h - 16), h):
for x in range(w):
r, g, b = rgb(x, y)
if r > 240 and g > 240 and b > 240:
white += 1
elif r < 100 and g < 100 and b < 100:
dark += 1
print("map %dx%d clusters=%s (sizes %s) plaque white=%d dark=%d"
% (w, h, len(clusters), clusters, white, dark))
ok = (len(clusters) == expected and white >= 100 and dark >= 10
and w % 256 == 0 and h % 256 == 0)
print("check_map: %s" % ("PASS" if ok else "FAIL"))
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/env python3
"""Check a trip.png produced by `sgeo --trip` (stdlib only).
Usage: check_trip.py trip.csv trip.png
Verifies, against the CSV:
- one red marker cluster per geotagged row, centred on the projected
point (projection mirrors sgeo.c: Web Mercator, zoom from the
bounding box, 64px padding);
- a blue polyline leg between consecutive rows in timestamp order:
blue pixels off the midpoint, so the arrowhead alone cannot pass,
and blue at the midpoint too;
- NO blue line where the CSV file order would have connected points
(the first two wrong-order hops), proving the sort actually
happened rather than the file order being drawn;
- a time-label plaque (white + dark text) by every timestamped
marker, and none by an untimestamped marker.
The attribution plaque is checked by check_map.py in the suite.
"""
import csv
import math
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from check_map import read_png
TILE_PX = 256
MAX_TILES = 100
TARGET_W = 900
TARGET_H = 620
PAD_PX = 64
SINGLE_POINT_ZOOM = 15
MAX_ZOOM = 18
MAX_LAT = 85.05112878
def world_px(z):
return TILE_PX * (1 << z)
def lon_to_px(lon, z):
return (lon + 180.0) / 360.0 * world_px(z)
def lat_to_px(lat, z):
lat = max(-MAX_LAT, min(MAX_LAT, lat))
r = math.radians(lat)
return (1.0 - math.asinh(math.tan(r)) / math.pi) / 2.0 * world_px(z)
def compute_range(xs, ys, zoom):
minx, maxx = min(xs), max(xs)
miny, maxy = min(ys), max(ys)
ntiles = 1 << zoom
tx0 = max(0, math.floor((minx - PAD_PX) / TILE_PX))
tx1 = min(ntiles - 1, math.floor((maxx + PAD_PX) / TILE_PX))
ty0 = max(0, math.floor((miny - PAD_PX) / TILE_PX))
ty1 = min(ntiles - 1, math.floor((maxy + PAD_PX) / TILE_PX))
return zoom, tx0, ty0, tx1, ty1
def pick_zoom(pts):
minlon = min(p[1] for p in pts)
maxlon = max(p[1] for p in pts)
minlat = min(p[0] for p in pts)
maxlat = max(p[0] for p in pts)
lon_span = (maxlon - minlon) / 360.0
y0 = lat_to_px(minlat, 0) / world_px(0)
y1 = lat_to_px(maxlat, 0) / world_px(0)
lat_span = abs(y1 - y0)
if lon_span == 0.0 and lat_span == 0.0:
return SINGLE_POINT_ZOOM
zoom = 0
for z in range(MAX_ZOOM, -1, -1):
if (lon_span * world_px(z) <= TARGET_W
and lat_span * world_px(z) <= TARGET_H):
zoom = z
break
while True:
xs = [lon_to_px(p[1], zoom) for p in pts]
ys = [lat_to_px(p[0], zoom) for p in pts]
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
if (tx1 - tx0 + 1) * (ty1 - ty0 + 1) <= MAX_TILES or zoom == 0:
return zoom
zoom -= 1
def parse_time(s):
"""Mirror sgeo's parse_trip_time: ISO or EXIF-colon, date-only ok.
Returns a dict, or None."""
m = re.match(r"^(\d+)-(\d+)-(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$", s or "")
if not m:
m = re.match(r"^(\d+):(\d+):(\d+)(?: (\d+):(\d+)(?::(\d+))?)?$",
s or "")
if not m:
return None
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
has_clock = m.group(5) is not None
h = int(m.group(4) or 0) if has_clock else 0
mi = int(m.group(5) or 0) if has_clock else 0
sec = int(m.group(6) or 0) if has_clock else 0
if not (1 <= mo <= 12 and 1 <= d <= 31 and 0 <= h <= 23
and 0 <= mi <= 59 and 0 <= sec <= 59):
return None
key = (((((y * 12 + (mo - 1)) * 31 + (d - 1)) * 24 + h) * 60 + mi)
* 60 + sec)
return {"key": key, "has_clock": has_clock, "mo": mo, "dy": d,
"hh": h, "mi": mi}
def label_text(t):
if t["has_clock"]:
return "%02d-%02d %02d:%02d" % (t["mo"], t["dy"], t["hh"], t["mi"])
return "%02d-%02d" % (t["mo"], t["dy"])
def label_rect(mx, my, text, w, h):
"""Mirror sgeo's draw_time_label placement."""
tw = len(text) * 6 - 1
lx, ly = mx + 12, my - 18
if lx + tw + 8 > w:
lx = mx - 12 - (tw + 8)
if lx < 0:
lx = 0
if ly < 0:
ly = my + 12
if ly + 13 > h:
ly = h - 13
if ly < 0:
ly = 0
return lx, ly, tw + 8, 13
def dist_pt_seg(px, py, x0, y0, x1, y1):
dx, dy = x1 - x0, y1 - y0
dd = dx * dx + dy * dy
if dd == 0:
return math.hypot(px - x0, py - y0)
t = max(0.0, min(1.0, ((px - x0) * dx + (py - y0) * dy) / dd))
return math.hypot(px - (x0 + t * dx), py - (y0 + t * dy))
def main():
csv_path, png_path = sys.argv[1], sys.argv[2]
rows = []
with open(csv_path, newline="") as f:
for i, row in enumerate(csv.DictReader(f)):
if not row["latitude"] or not row["longitude"]:
continue
t = parse_time(row["timestamp"])
rows.append({
"file": row["file"],
"lat": float(row["latitude"]),
"lon": float(row["longitude"]),
"order": i,
"time": t,
})
ordered = sorted(rows, key=lambda r: (r["time"] is None,
r["time"]["key"] if r["time"] else 0,
r["order"]))
pts = [(r["lat"], r["lon"]) for r in ordered]
zoom = pick_zoom(pts)
xs = [lon_to_px(p[1], zoom) for p in pts]
ys = [lat_to_px(p[0], zoom) for p in pts]
_, tx0, ty0, tx1, ty1 = compute_range(xs, ys, zoom)
w, h, px = read_png(png_path)
assert w == (tx1 - tx0 + 1) * TILE_PX, "width mismatch: %d" % w
assert h == (ty1 - ty0 + 1) * TILE_PX, "height mismatch: %d" % h
ox, oy = tx0 * TILE_PX, ty0 * TILE_PX
mx = [int(round(x)) - ox for x in xs]
my = [int(round(y)) - oy for y in ys]
def rgb(x, y):
o = (y * w + x) * 3
return px[o], px[o + 1], px[o + 2]
def is_blue(x, y):
r, g, b = rgb(x, y)
return b >= 200 and r <= 90 and g <= 90
def is_red(x, y):
r, g, b = rgb(x, y)
return r >= 200 and g <= 90 and b <= 90
def blue_near(x, y, rad=8):
for dy in range(-rad, rad + 1):
for dx in range(-rad, rad + 1):
if dx * dx + dy * dy > rad * rad:
continue
xx, yy = x + dx, y + dy
if 0 <= xx < w and 0 <= yy < h and is_blue(xx, yy):
return True
return False
fails = []
# 1. Red marker clusters: one per point, centred on the projection.
red = [(x, y) for y in range(h) for x in range(w) if is_red(x, y)]
parent = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
cells = {}
for p in red:
parent[p] = p
cells.setdefault((p[0] // 4, p[1] // 4), []).append(p)
for (x, y) in red:
for cx in (x // 4 - 1, x // 4, x // 4 + 1):
for cy in (y // 4 - 1, y // 4, y // 4 + 1):
for q in cells.get((cx, cy), []):
if q != (x, y) and abs(q[0] - x) <= 2 and abs(q[1] - y) <= 2:
ra, rb = find((x, y)), find(q)
if ra != rb:
parent[ra] = rb
groups = {}
for p in red:
groups.setdefault(find(p), []).append(p)
clusters = [(sum(p[0] for p in ps) / len(ps),
sum(p[1] for p in ps) / len(ps), len(ps))
for ps in groups.values() if len(ps) >= 20]
print("trip: %dx%d zoom=%d markers=%d (sizes %s)"
% (w, h, zoom, len(clusters), sorted(c[2] for c in clusters)))
if len(clusters) != len(pts):
fails.append("marker clusters %d != points %d"
% (len(clusters), len(pts)))
else:
unmatched = list(clusters)
for i, (cx, cy) in enumerate(zip(mx, my)):
best = min(unmatched,
key=lambda c: (c[0] - cx) ** 2 + (c[1] - cy) ** 2)
d = math.hypot(best[0] - cx, best[1] - cy)
if d > 4:
fails.append("marker %d off projection by %.1fpx"
% (i, d))
unmatched.remove(best)
# Label plaque rects (for skipping line samples hidden under them).
plaques = []
for i, r in enumerate(ordered):
if r["time"]:
plaques.append(label_rect(mx[i], my[i], label_text(r["time"]),
w, h))
def in_plaque(x, y):
for (lx, ly, pw, ph) in plaques:
if lx - 2 <= x <= lx + pw + 2 and ly - 2 <= y <= ly + ph + 2:
return True
return False
# 2. Ordered legs: blue off the midpoint, and blue at the midpoint.
for i in range(1, len(ordered)):
x0, y0, x1, y1 = mx[i - 1], my[i - 1], mx[i], my[i]
seg_len = math.hypot(x1 - x0, y1 - y0)
off_mid = False
tried = 0
for t in (0.25, 0.4, 0.6, 0.75):
sx, sy = int(round(x0 + t * (x1 - x0))), int(round(y0 + t * (y1 - y0)))
if math.hypot(sx - x0, sy - y0) < 12:
continue
if math.hypot(sx - x1, sy - y1) < 12:
continue
if in_plaque(sx, sy):
continue
tried += 1
if blue_near(sx, sy):
off_mid = True
break
mid = blue_near((x0 + x1) // 2, (y0 + y1) // 2)
print("leg %d->%d len=%.0fpx off-mid=%s (tried %d) mid=%s"
% (i - 1, i, seg_len, off_mid, tried, mid))
if not off_mid:
fails.append("leg %d->%d: no blue off the midpoint" % (i - 1, i))
if not mid:
fails.append("leg %d->%d: no blue at the midpoint" % (i - 1, i))
# 3. Wrong-order hops (file order) must have NO blue at midpoint.
file_order = sorted(rows, key=lambda r: r["order"])
file_xy = []
for r in file_order:
j = ordered.index(r)
file_xy.append((mx[j], my[j]))
legs = [(mx[i - 1], my[i - 1], mx[i], my[i])
for i in range(1, len(ordered))]
for k in range(min(2, len(file_xy) - 1)):
wx = (file_xy[k][0] + file_xy[k + 1][0]) // 2
wy = (file_xy[k][1] + file_xy[k + 1][1]) // 2
mind = min(dist_pt_seg(wx, wy, *leg) for leg in legs)
print("wrong hop %d midpoint (%d,%d) min-dist-to-real-leg %.1fpx"
% (k, wx, wy, mind))
if mind <= 25:
fails.append("wrong-hop probe %d inconclusive (%.1fpx from a "
"real leg)" % (k, mind))
elif blue_near(wx, wy):
fails.append("wrong hop %d: blue line where file order would "
"connect" % k)
# 4. Time labels: plaque + text by timestamped markers, none by the
# untimestamped one.
for i, r in enumerate(ordered):
lx, ly, pw, ph = label_rect(mx[i], my[i],
label_text(r["time"]) if r["time"]
else "MM-DD HH:MM", w, h)
white = dark = 0
for y in range(max(0, ly), min(h, ly + ph)):
for x in range(max(0, lx), min(w, lx + pw)):
rr, gg, bb = rgb(x, y)
if rr > 245 and gg > 245 and bb > 245:
white += 1
elif rr < 100 and gg < 100 and bb < 100:
dark += 1
if r["time"]:
print("label %s: white=%d dark=%d" % (r["file"], white, dark))
if white < 100 or dark < 5:
fails.append("label %s: plaque/text missing (white=%d "
"dark=%d)" % (r["file"], white, dark))
else:
print("no-label %s: white=%d dark=%d" % (r["file"], white, dark))
if white >= 20:
fails.append("untimestamped %s has a label plaque "
"(white=%d)" % (r["file"], white))
if fails:
print("check_trip: FAIL")
for f in fails:
print(" - " + f)
return 1
print("check_trip: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
file,format,latitude,longitude,altitude,datum,timestamp,source
1 file format latitude longitude altitude datum timestamp source
+6
View File
@@ -0,0 +1,6 @@
file,format,latitude,longitude,altitude,datum,timestamp,source
PARIS.JPG,JPEG image,48.856600,2.352200,,WGS-84,,EXIF GPS
nyc.jpg,JPEG image,40.712800,-74.006000,10.000,WGS-84,2024:06:15 08:30:00,unknown
plain.jpg,JPEG image,,,,,,
sf.jpg,JPEG image,37.774929,-122.419418,12.000,WGS-84,2024-05-01 12:34:56,EXIF GPS
tokyo.jpg,JPEG image,35.676200,139.650300,,WGS-84,,XMP
1 file format latitude longitude altitude datum timestamp source
2 PARIS.JPG JPEG image 48.856600 2.352200 WGS-84 EXIF GPS
3 nyc.jpg JPEG image 40.712800 -74.006000 10.000 WGS-84 2024:06:15 08:30:00 unknown
4 plain.jpg JPEG image
5 sf.jpg JPEG image 37.774929 -122.419418 12.000 WGS-84 2024-05-01 12:34:56 EXIF GPS
6 tokyo.jpg JPEG image 35.676200 139.650300 WGS-84 XMP
+3
View File
@@ -0,0 +1,3 @@
file,format,latitude,longitude,altitude,datum,timestamp,source
nogeo.png,PNG image,,,,,,
plain.jpg,JPEG image,,,,,,
1 file format latitude longitude altitude datum timestamp source
2 nogeo.png PNG image
3 plain.jpg JPEG image
+439
View File
@@ -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('<I', 8) + struct.pack('<HI', 0, 0)
def build_xmp(lat_s, lon_s, alt_s="10/1"):
return (
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>\n'
'<x:xmpmeta xmlns:x="adobe:ns:meta/">\n'
' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n'
' <rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" '
'exif:GPSLatitude="%s" exif:GPSLongitude="%s" exif:GPSAltitude="%s"/>\n'
' </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end="w"?>'
% (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', len(data)) + data
if len(data) % 2:
out += b'\x00'
return out
def build_webp(tiff=None, xmp=None, vp8_payload=b'\x2f\x01\x2e\x00\x00\x00\x00\x00'):
"""Extended WebP: VP8X (flags) + VP8 + EXIF/XMP chunks."""
flags = (0x08 if tiff is not None else 0) | (0x04 if xmp is not None else 0)
vp8x = bytes([flags]) + b'\x00\x00\x00' + b'\x00\x00\x00' + b'\x00\x00\x00'
body = b'WEBP' + riff_chunk(b'VP8X', vp8x) + riff_chunk(b'VP8 ', vp8_payload)
if tiff is not None:
body += riff_chunk(b'EXIF', tiff)
if xmp is not None:
body += riff_chunk(b'XMP ', xmp)
return b'RIFF' + struct.pack('<I', len(body)) + body
def bmff_box(typ, payload):
return 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', 56) + b'\x00' * 56
hdrl = b'LIST' + struct.pack('<I', 4 + len(avih)) + b'hdrl' + avih
body = hdrl
if xmp is not None:
body += b'_PMX' + struct.pack('<I', len(xmp)) + xmp
if len(xmp) % 2:
body += b'\x00'
return b'RIFF' + struct.pack('<I', 4 + len(body)) + b'AVI ' + body
def build_cr3(tiff_direct, xmp):
"""ftyp crx + moov/uuid Canon (CMT4 + CTBO) + mdat + XMP blob.
CTBO offsets are absolute file offsets."""
ftyp = bmff_box(b'ftyp', b'crx \x00\x00\x00\x00crx ')
cmt4 = bmff_box(b'CMT4', tiff_direct)
# layout pass 1: measure with placeholder CTBO (2 records x 20 bytes)
ctbo_body = b'\x00\x00\x00\x02' + b'\x00' * 40
ctbo = bmff_box(b'CTBO', ctbo_body)
uuid_body = b'\x85\xc0\xb6\x87\x82\x0f\x11\xe0\x81\x11\xf4\xce\x46\x2b\x6a\x48'
uuid_inner = cmt4 + ctbo
uuid = bmff_box(b'uuid', uuid_body + uuid_inner)
moov = bmff_box(b'moov', uuid)
mdat = bmff_box(b'mdat', b'\x00' * 64)
xmp_off = len(ftyp) + len(moov) + len(mdat)
mdat_off = len(ftyp) + len(moov) + 8
ctbo_body = (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('<I', 2) # magic 20000630 LE
def attr(name, typ, val):
return name.encode() + b'\x00' + typ.encode() + b'\x00' + \
struct.pack('<I', len(val)) + val
chlist = (b'Y\x00' + struct.pack('<I', 2) + b'\x00\x00\x00\x00' +
struct.pack('<II', 1, 1) + b'\x00')
out += attr('channels', 'chlist', chlist)
out += attr('compression', 'compression', b'\x00')
out += attr('dataWindow', 'box2i', struct.pack('<iiii', 0, 0, 0, 0))
out += attr('displayWindow', 'box2i', struct.pack('<iiii', 0, 0, 0, 0))
out += attr('lineOrder', 'lineOrder', b'\x00')
out += attr('pixelAspectRatio', 'float', struct.pack('<f', 1.0))
out += attr('screenWindowCenter', 'v2f', struct.pack('<ff', 0.0, 0.0))
out += attr('screenWindowWidth', 'float', struct.pack('<f', 1.0))
out += attr('longitude', 'float', struct.pack('<f', lon))
out += attr('latitude', 'float', struct.pack('<f', lat))
out += attr('altitude', 'float', struct.pack('<f', alt))
out += b'\x00' # end of header
out += struct.pack('<Q', len(out) + 8) # chunk offset table (1 chunk)
out += struct.pack('<II', 0, 4) + b'\x00' * 4 # one chunk, 4 bytes
return out
def build_jp2(xmp):
sig = bmff_box(b'jP ', b'\x0d\x0a\x87\x0a')
ftyp = bmff_box(b'ftyp', b'jp2 \x00\x00\x00\x00jp2 ')
uuid = bmff_box(b'uuid', bytes.fromhex('be7acfcb97a942e89c71999491e3afac') + xmp)
return sig + ftyp + uuid
def build_psd(tiff, xmp):
hdr = (b'8BPS' + 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()
+121
View File
@@ -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())
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 B

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 B

+1
View File
@@ -0,0 +1 @@
Eߣ—B†�B÷�B‚ˆmatroskaB‡�S€gÿTÃg«ss¨gÈ¥E£’RECORDING_LOCATIOND‡�San Francisco
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 B

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 B

+7
View File
@@ -0,0 +1,7 @@
Eߣ—B†�B÷�B‚ˆmatroskaB‡�S€gÿA¤iA•a§A‘Fn‡gps.xmpF`“application/rdf+xmlF\Am<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" exif:GPSLatitude="37,46.494N" exif:GPSLongitude="122,25.164W" exif:GPSAltitude="10/1"/>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 331 B

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 304 B

+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""make_fixtures.py — build the small synthetic sample files the
--json and library tests decode. Shared by tests/test_json.py and
tests/test_lib.sh so both test the same bytes.
Every fixture is built from the format table in src/formats.h, so the
expected values below are the table's own ground truth.
"""
import os
import struct
import sys
def build_fixtures(outdir):
os.makedirs(outdir, exist_ok=True)
paths = {}
# PNG (task 564, big-endian): 800x600, 8-bit, colour type 2.
png = (bytes.fromhex("89504e470d0a1a0a") + struct.pack(">I", 13) + b"IHDR"
+ struct.pack(">II", 800, 600) + bytes([8, 2, 0, 0, 0]))
paths["png"] = _write(outdir, "sample.png", png)
# SPS track file (task 678, big-endian, extension-only: no magic).
# latitude 37.7749 / longitude -122.4194 at offsets 27 / 35.
sps = bytearray(161)
sps[0:11] = b"v1.0" + b"\x00" * 7
struct.pack_into(">d", sps, 11, 0.0) # start
struct.pack_into(">d", sps, 19, 3600.0) # end
struct.pack_into(">d", sps, 27, 37.7749) # latitude
struct.pack_into(">d", sps, 35, -122.4194) # longitude
struct.pack_into(">d", sps, 43, 100.0) # chart_max
struct.pack_into(">d", sps, 51, -10.0) # chart_min
struct.pack_into(">h", sps, 59, -8) # timezone
sps[61:72] = b"GPS" + b"\x00" * 8 # source
sps[72:93] = b"sfile-test" + b"\x00" * 11 # author
sps[93:114] = b"geo-fixture" + b"\x00" * 10 # name
sps[114:155] = b"San Francisco" + b"\x00" * 28 # location
struct.pack_into(">h", sps, 155, 2) # channels
struct.pack_into(">i", sps, 157, 0) # note_length
paths["sps"] = _write(outdir, "track.sps", bytes(sps))
# JSON document (task 334, text fallback: first key "name").
paths["json"] = _write(outdir, "doc.json",
b'{"name": "sfile", "version": 1}\n')
# XML document (task 839, text fallback: root <catalog version="2.0">).
paths["xml"] = _write(outdir, "doc.xml",
b'<?xml version="1.0" encoding="UTF-8"?>\n'
b'<catalog version="2.0"><item/></catalog>\n')
# Plain text (task 742).
paths["txt"] = _write(outdir, "note.txt",
b"Hello, sfile.\nSecond line.\n")
# Unknown: no magic match, unknown extension.
paths["unknown"] = _write(outdir, "mystery.zzz", bytes(range(1, 65)))
# Empty PNG: identified by extension, every field beyond the window.
paths["empty_png"] = _write(outdir, "empty.png", b"")
# WEBM (task 805): magic known, FMT_UNKNOWN, no header layout.
paths["webm"] = _write(outdir, "clip.webm",
bytes.fromhex("1a45dfa3") + bytes(60))
# WAB (task 802): magic known, FMT_BINARY, no header layout.
paths["wab"] = _write(outdir, "addr.wab",
bytes.fromhex("9ccbcb8d1375d211915800c04f7956a4")
+ bytes(48))
return paths
def _write(outdir, name, data):
path = os.path.join(outdir, name)
with open(path, "wb") as fh:
fh.write(data)
return path
if __name__ == "__main__":
outdir = sys.argv[1] if len(sys.argv) > 1 else "."
for key, path in build_fixtures(outdir).items():
print(f"{key}: {path}")
+5
View File
@@ -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,
+159
View File
@@ -0,0 +1,159 @@
#!/bin/bash
# stag/sgeo tests. Offline except for the local fake tile server:
# PATH=tests/bin:$PATH (fake `sfile` with canned GPS values)
# SGEO_TILE_BASE=http://127.0.0.1:<port> (tests/tile_server.py)
# Cases: multi-file dir (CSV byte-for-byte + map markers), single
# point, no-geotag dir, empty dir, the default outfiles, and
# sgeo --trip (ordered polyline + time labels from a synthetic CSV,
# single point, and the failure cases).
# Usage: ./tests/run_tests.sh (run from the repo root)
set -u
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TMP="$(mktemp -d /tmp/stag-sgeo-tests.XXXXXX)"
TILE_PID=""
cleanup() { rm -rf "$TMP"; [ -n "$TILE_PID" ] && kill "$TILE_PID" 2>/dev/null; }
trap cleanup EXIT
FAIL=0
pass() { echo "PASS: $1"; }
fail() { echo "FAIL: $1"; FAIL=1; }
cd "$ROOT" || exit 1
make stag sgeo >/dev/null 2>&1 || { echo "FAIL: build stag/sgeo"; exit 1; }
python3 tests/tile_server.py --port-file "$TMP/port" >/dev/null 2>&1 &
TILE_PID=$!
for _ in $(seq 1 50); do [ -s "$TMP/port" ] && break; sleep 0.1; done
[ -s "$TMP/port" ] || { echo "FAIL: tile server did not start"; exit 1; }
export SGEO_TILE_BASE="http://127.0.0.1:$(cat "$TMP/port")"
export PATH="$ROOT/tests/bin:$PATH"
mkdir -p "$TMP/multi/sub" "$TMP/nogeo" "$TMP/empty" "$TMP/single"
touch "$TMP/multi/PARIS.JPG" "$TMP/multi/nyc.jpg" "$TMP/multi/plain.jpg" \
"$TMP/multi/sf.jpg" "$TMP/multi/tokyo.jpg" "$TMP/multi/notes.txt" \
"$TMP/multi/sub/inner.jpg"
touch "$TMP/nogeo/plain.jpg" "$TMP/nogeo/nogeo.png"
touch "$TMP/single/sf.jpg"
# 1. stag, multi-file dir: CSV must match byte-for-byte.
./stag "$TMP/multi" "$TMP/out.csv" 2>"$TMP/stag.log"
if diff -u tests/expected_geotags.csv "$TMP/out.csv" >"$TMP/diff.txt" 2>&1; then
pass "stag multi-file CSV byte-for-byte"
else
fail "stag multi-file CSV byte-for-byte"; cat "$TMP/diff.txt"
fi
# 2. sgeo, multi-file dir: 4 markers (PARIS/nyc/sf/tokyo), plaque on image.
if ./sgeo "$TMP/multi" "$TMP/map.png" 2>"$TMP/sgeo.log"; then
python3 tests/check_map.py "$TMP/map.png" 4 >/tmp/check1.txt 2>&1 \
&& pass "sgeo multi-file map (4 markers + attribution)" \
|| { fail "sgeo multi-file map (4 markers + attribution)"; cat /tmp/check1.txt; }
else
fail "sgeo multi-file exit 0"; cat "$TMP/sgeo.log"
fi
# 3. sgeo, single point: succeeds, exactly 1 marker.
if ./sgeo "$TMP/single" "$TMP/single.png" 2>"$TMP/sgeo1.log"; then
python3 tests/check_map.py "$TMP/single.png" 1 >/tmp/check2.txt 2>&1 \
&& pass "sgeo single-point map (1 marker)" \
|| { fail "sgeo single-point map (1 marker)"; cat /tmp/check2.txt; }
else
fail "sgeo single-point exit 0"; cat "$TMP/sgeo1.log"
fi
# 4. No-geotag dir: stag rows are empty, sgeo fails with no file.
./stag "$TMP/nogeo" "$TMP/nogeo.csv" 2>/dev/null
if diff -q tests/expected_nogeo.csv "$TMP/nogeo.csv" >/dev/null 2>&1; then
pass "stag no-geotag CSV"
else
fail "stag no-geotag CSV"; diff -u tests/expected_nogeo.csv "$TMP/nogeo.csv"
fi
if ./sgeo "$TMP/nogeo" "$TMP/nogeo.png" 2>"$TMP/nogeo.err"; then
fail "sgeo no-geotag exits non-zero"
else
if [ ! -e "$TMP/nogeo.png" ] && grep -q "no geotagged" "$TMP/nogeo.err"; then
pass "sgeo no-geotag: non-zero, message, no file"
else
fail "sgeo no-geotag: message/no-file"; cat "$TMP/nogeo.err"
fi
fi
# 5. Empty dir: stag header only, sgeo fails with no file.
./stag "$TMP/empty" "$TMP/empty.csv" 2>/dev/null
if diff -q tests/expected_empty.csv "$TMP/empty.csv" >/dev/null 2>&1; then
pass "stag empty-dir CSV (header only)"
else
fail "stag empty-dir CSV (header only)"
fi
if ./sgeo "$TMP/empty" "$TMP/empty.png" 2>"$TMP/empty.err"; then
fail "sgeo empty-dir exits non-zero"
elif [ ! -e "$TMP/empty.png" ]; then
pass "sgeo empty-dir: non-zero, no file"
else
fail "sgeo empty-dir: no file expected"
fi
# 6. Default outfiles: stag -> geotags.csv, sgeo -> map.png in the cwd.
mkdir -p "$TMP/cwd" && cp "$TMP/single/sf.jpg" "$TMP/cwd/"
( cd "$TMP/cwd" && "$ROOT/stag" . 2>/dev/null && "$ROOT/sgeo" . 2>/dev/null )
if [ -s "$TMP/cwd/geotags.csv" ] && [ -s "$TMP/cwd/map.png" ]; then
pass "default outfiles geotags.csv / map.png"
else
fail "default outfiles geotags.csv / map.png"
fi
# 7. sgeo --trip: synthetic CSV, rows out of timestamp order.
# b.jpg uses the EXIF-colon timestamp form stag's fallback passes
# through, so the sort must handle mixed ISO/EXIF formats; e.jpg has
# no timestamp and goes last; plain.jpg has no coords and is skipped.
cat > "$TMP/trip.csv" <<'EOF'
file,format,latitude,longitude,altitude,datum,timestamp,source
c.jpg,JPEG image,37.784900,-122.379400,,WGS-84,2024-05-01 10:00:00,EXIF GPS
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
d.jpg,JPEG image,37.754900,-122.439400,,WGS-84,2024-05-01 11:00:00,EXIF GPS
b.jpg,JPEG image,37.804900,-122.409400,,WGS-84,2024:05:01 09:00:00,EXIF GPS
e.jpg,JPEG image,37.794900,-122.439400,,WGS-84,,EXIF GPS
plain.jpg,JPEG image,,,,,,
EOF
if ./sgeo --trip "$TMP/trip.csv" "$TMP/trip.png" 2>"$TMP/trip.log"; then
python3 tests/check_map.py "$TMP/trip.png" 5 >/tmp/check-trip-map.txt 2>&1 \
&& python3 tests/check_trip.py "$TMP/trip.csv" "$TMP/trip.png" >/tmp/check-trip.txt 2>&1 \
&& pass "sgeo --trip ordered polyline + time labels" \
|| { fail "sgeo --trip ordered polyline + time labels"; cat /tmp/check-trip-map.txt /tmp/check-trip.txt "$TMP/trip.log"; }
else
fail "sgeo --trip exit 0"; cat "$TMP/trip.log"
fi
# 8. sgeo --trip: single point (marker + label, no line).
cat > "$TMP/trip-one.csv" <<'EOF'
file,format,latitude,longitude,altitude,datum,timestamp,source
a.jpg,JPEG image,37.774900,-122.419400,,WGS-84,2024-05-01 08:00:00,EXIF GPS
EOF
if ./sgeo --trip "$TMP/trip-one.csv" "$TMP/trip-one.png" 2>/dev/null; then
python3 tests/check_map.py "$TMP/trip-one.png" 1 >/tmp/check-trip1.txt 2>&1 \
&& pass "sgeo --trip single point" \
|| { fail "sgeo --trip single point"; cat /tmp/check-trip1.txt; }
else
fail "sgeo --trip single point exit 0"
fi
# 9. sgeo --trip failures: no geotags, bad header, missing file.
# Each must exit non-zero, print its message, and write no file.
cat > "$TMP/trip-nogeo.csv" <<'EOF'
file,format,latitude,longitude,altitude,datum,timestamp,source
plain.jpg,JPEG image,,,,,,
EOF
printf 'not,a,stag,csv\n1,2,3\n' > "$TMP/trip-bad.csv"
trip_fail=0
./sgeo --trip "$TMP/trip-nogeo.csv" "$TMP/trip-nogeo.png" 2>"$TMP/trip-nogeo.err" && trip_fail=1
[ -e "$TMP/trip-nogeo.png" ] && trip_fail=1
grep -q "no geotagged" "$TMP/trip-nogeo.err" || trip_fail=1
./sgeo --trip "$TMP/trip-bad.csv" "$TMP/trip-bad.png" 2>"$TMP/trip-bad.err" && trip_fail=1
[ -e "$TMP/trip-bad.png" ] && trip_fail=1
grep -q "not a stag CSV" "$TMP/trip-bad.err" || trip_fail=1
./sgeo --trip "$TMP/trip-missing.csv" "$TMP/trip-missing.png" 2>/dev/null && trip_fail=1
[ -e "$TMP/trip-missing.png" ] && trip_fail=1
[ "$trip_fail" = 0 ] && pass "sgeo --trip failures (no geotags, bad header, missing file)" \
|| { fail "sgeo --trip failures"; cat "$TMP/trip-nogeo.err" "$TMP/trip-bad.err"; }
echo "stag/sgeo tests: $([ "$FAIL" = 0 ] && echo ALL PASS || echo FAILURES PRESENT)"
exit "$FAIL"
+306
View File
@@ -0,0 +1,306 @@
#!/usr/bin/env python3
"""test_json.py — verify `sfile --json`.
For every synthetic fixture (tests/make_fixtures.py) this checks:
1. the --json output parses as JSON (one object per line);
2. it carries the same facts as the human-readable output on the
same file (format, identification method, magic, every header
field, document decode, hex dump) — the text table is the
reference, JSON must not disagree with it;
3. exit codes match between modes (0 identified, 2 unreadable,
3 unknown);
4. geotags appear when geotag_scan() finds a location (the
tests/geotag/ fixtures: a JPEG with EXIF GPS, an MP4 with two
QuickTime locations, a JPEG with a mechanism but no location).
Header latitude/longitude FIELDS (e.g. the SPS fixture) are not
geotags — task 678 has no geotagging mechanism, so no key.
Usage:
python3 tests/test_json.py [sfile_binary]
"""
import json
import math
import os
import re
import subprocess
import sys
import tempfile
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from make_fixtures import build_fixtures
SFILE = sys.argv[1] if len(sys.argv) > 1 else "./sfile"
FAILURES = []
def check(name, cond, detail=""):
print(f" {'PASS' if cond else 'FAIL'} {name}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
FAILURES.append(name)
def run(args):
return subprocess.run(args, capture_output=True, text=True)
def parse_text_fields(out):
"""(offset, size, name, value) rows of the header table.
Only lines after the "Header (...-endian):" heading count: the
hex dump of an unknown file (" 01 02 03 ...") would otherwise
match the same shape.
"""
fields = []
in_table = False
for line in out.splitlines():
if line.startswith("Header ("):
in_table = True
continue
if not in_table:
continue
m = re.match(r"^ +(\d+) +(\d+) +(\S+) +(.*)$", line)
if m:
fields.append((int(m.group(1)), int(m.group(2)), m.group(3),
m.group(4).rstrip()))
return fields
def json_display_value(field):
"""Rebuild the CLI's display string for a JSON field value."""
v = field["value"]
if v is None:
return "(beyond header window / EOF)"
t = field["type"]
if t in ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"):
return str(v)
if t in ("f32", "f64"):
return "%g" % v
if t == "ascii":
return '"%s"' % v
return v # bytes: space-separated hex
def check_parity(name, fixture, text, js):
"""The JSON object must say the same thing as the text output."""
m = re.search(r"^Format: (.+?) \((\S+)\) — task (\d+)$", text, re.M)
if js["identified"]:
check(f"{name}: format task", js["format"]["task"] == int(m.group(3)) and
js["format"]["ext"] == m.group(2) and js["format"]["name"] == m.group(1))
m2 = re.search(r"^Identified by: (\w+)$", text, re.M)
check(f"{name}: identified_by", js["identified_by"] == m2.group(1))
else:
check(f"{name}: unidentified", js["identified"] is False)
m3 = re.search(r"^Magic: ([0-9a-f ]+)at offset (\d+)$", text, re.M)
if m3:
check(f"{name}: magic", js["magic"]["bytes"] == m3.group(1).strip() and
js["magic"]["offset"] == int(m3.group(2)))
elif js.get("magic"):
check(f"{name}: magic absent in text", False, "JSON has magic, text does not")
text_fields = parse_text_fields(text)
json_fields = js.get("header", {}).get("fields", [])
check(f"{name}: field count", len(text_fields) == len(json_fields),
f"text={len(text_fields)} json={len(json_fields)}")
for (toff, tsize, tname, tval), jf in zip(text_fields, json_fields):
same = (toff == jf["offset"] and tsize == jf["size"]
and tname == jf["name"])
if jf["type"] in ("f32", "f64") and jf["value"] is not None:
try:
same = same and math.isclose(float(tval), jf["value"], rel_tol=1e-5) # text uses %g (6 sig. digits)
except ValueError:
same = False
else:
same = same and tval == json_display_value(jf)
check(f"{name}: field {tname}", same, f"text={tval!r} json={jf}")
m4 = re.search(r"^Document type: (\w+)$", text, re.M)
if m4:
doc = js.get("document", {})
check(f"{name}: document type", doc.get("type") == m4.group(1).lower())
for key, pat in (("declaration", r"^XML declaration: (.*)$"),
("root_element", r"^Root element: (.*)$"),
("version", r"^Version attribute: (.*)$"),
("first_key", r"^First key: (.*)$"),
("first_line", r"^First line: (.*)$")):
mm = re.search(pat, text, re.M)
if mm:
check(f"{name}: document {key}", doc.get(key) == mm.group(1))
elif key in doc:
check(f"{name}: document {key} absent in text", False)
m5 = re.search(r"^First 64 bytes:\n (.*)$", text, re.M)
if m5:
check(f"{name}: hexdump", js.get("hexdump") == m5.group(1).strip())
# Geotagging section (text) vs "geotags" array (JSON) — both come
# from geotag_scan(), so they must agree.
lats = re.findall(r"^ gps_latitude: (-?[\d.]+)", text, re.M)
lons = re.findall(r"^ gps_longitude: (-?[\d.]+)", text, re.M)
srcs = re.findall(r"^ source: (.*)$", text, re.M)
alts = re.findall(r"^ gps_altitude_m: (-?[\d.]+)", text, re.M)
datums = re.findall(r"^ gps_datum: (.*)$", text, re.M)
whens = re.findall(r"^ gps_datetime_utc: (.*)$", text, re.M)
has_section = "Geotagging:\n" in text
if has_section:
g = js.get("geotags")
check(f"{name}: geotags present", isinstance(g, list))
if isinstance(g, list):
check(f"{name}: geotag count",
len(g) == len(lats) == len(lons) == len(srcs),
f"json={len(g)} text lat/lon/src={len(lats)}/{len(lons)}/{len(srcs)}")
for i, gg in enumerate(g):
if i >= len(lats):
break
check(f"{name}: geotag[{i}] lat/lon",
math.isclose(gg["latitude"], float(lats[i]), abs_tol=1e-6)
and math.isclose(gg["longitude"], float(lons[i]), abs_tol=1e-6))
check(f"{name}: geotag[{i}] source", gg["source"] == srcs[i])
if alts:
check(f"{name}: geotag altitudes",
sorted(float(a) for a in alts)
== sorted(gg.get("altitude_m") for gg in g
if "altitude_m" in gg))
if datums:
check(f"{name}: geotag datums",
sorted(datums) == sorted(gg.get("datum") for gg in g
if "datum" in gg))
if whens:
check(f"{name}: geotag datetimes",
sorted(whens) == sorted(gg.get("datetime_utc") for gg in g
if "datetime_utc" in gg))
if "none found (searched" in text:
check(f"{name}: geotags empty", g == [])
else:
check(f"{name}: no geotags key", "geotags" not in js)
def main():
tmp = tempfile.mkdtemp(prefix="sfile-json-test-")
fx = build_fixtures(tmp)
missing = os.path.join(tmp, "does-not-exist.bin")
print(f"sfile: {SFILE}")
print(f"fixtures: {tmp}")
# --- one file at a time: JSON parses, parity holds, exit codes match
for key in ("png", "sps", "json", "xml", "txt", "unknown",
"empty_png", "webm", "wab"):
path = fx[key]
text = run([SFILE, path])
js_run = run([SFILE, "--json", path])
check(f"{key}: exit code", text.returncode == js_run.returncode,
f"text={text.returncode} json={js_run.returncode}")
lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()]
check(f"{key}: one JSON object", len(lines) == 1,
f"{len(lines)} lines")
if len(lines) != 1:
continue
try:
obj = json.loads(lines[0])
except json.JSONDecodeError as exc:
check(f"{key}: JSON parses", False, str(exc))
continue
check(f"{key}: JSON parses", True)
check(f"{key}: file/size", obj["file"] == path and
obj["size"] == os.path.getsize(path))
check_parity(key, path, text.stdout, obj)
# --- geotags come from geotag_scan(), not from header fields:
# the SPS fixture carries latitude/longitude FIELDS but task 678
# has no geotagging mechanism, so there is no "geotags" key.
obj = json.loads(run([SFILE, "--json", fx["sps"]]).stdout.splitlines()[0])
check("sps: no geotags key (no mechanism)", "geotags" not in obj)
# This PNG has a mechanism (eXIf/XMP) but carries no location.
obj = json.loads(run([SFILE, "--json", fx["png"]]).stdout.splitlines()[0])
check("png: geotags empty (none found)", obj.get("geotags") == [])
# --- real geotags, from tests/geotag/ (EXIF GPS JPEG, two-result
# MP4, JPEG with a mechanism but no location)
geo_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "geotag")
for fname, want in (
("test-gps.jpg", {"n": 1,
"source": "EXIF GPS IFD (JPEG APP1 segment)",
"lat": 37.7749, "lon": -122.4194, "alt": 10.0,
"datum": "WGS-84", "when": "2026-12-01 12:34:56"}),
("test-gps.mp4", {"n": 2, "lat": 37.7749, "lon": -122.4194}),
("test-gps-no-gps.jpg", {"n": 0}),
):
path = os.path.join(geo_dir, fname)
text = run([SFILE, path])
js_run = run([SFILE, "--json", path])
check(f"{fname}: exit code",
text.returncode == js_run.returncode == 0,
f"text={text.returncode} json={js_run.returncode}")
lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()]
check(f"{fname}: one JSON object", len(lines) == 1)
if len(lines) != 1:
continue
obj = json.loads(lines[0])
g = obj.get("geotags")
check(f"{fname}: geotag count",
isinstance(g, list) and len(g) == want["n"], str(g)[:200])
if want["n"] > 0 and isinstance(g, list) and len(g) == want["n"]:
check(f"{fname}: lat/lon",
all(math.isclose(x["latitude"], want["lat"], abs_tol=1e-6)
and math.isclose(x["longitude"], want["lon"], abs_tol=1e-6)
for x in g))
if "source" in want:
check(f"{fname}: source", g[0]["source"] == want["source"],
str(g[0].get("source")))
if "alt" in want:
check(f"{fname}: altitude",
math.isclose(g[0].get("altitude_m", -1), want["alt"],
abs_tol=1e-6))
if "datum" in want:
check(f"{fname}: datum", g[0].get("datum") == want["datum"])
if "when" in want:
check(f"{fname}: datetime",
g[0].get("datetime_utc") == want["when"])
check_parity(fname, path, text.stdout, obj)
# --- shared magic: the XML fixture's JSON lists the other candidates
obj = json.loads(run([SFILE, "--json", fx["xml"]]).stdout.splitlines()[0])
check("xml: other_candidates listed",
len(obj.get("other_candidates", [])) > 0
and all("ext" in c and "task" in c for c in obj["other_candidates"]),
str(obj.get("other_candidates"))[:120])
# --- unreadable file: JSON error object, exit 2, stdout stays JSON
r = run([SFILE, "--json", missing])
check("missing: exit 2", r.returncode == 2, f"got {r.returncode}")
try:
obj = json.loads(r.stdout.splitlines()[0])
check("missing: JSON error object",
obj["identified"] is False and obj["size"] is None
and isinstance(obj.get("error"), str) and obj["error"])
except (IndexError, json.JSONDecodeError) as exc:
check("missing: JSON error object", False, str(exc))
# --- several files: one JSON object per line, worst exit code wins
r = run([SFILE, "--json", fx["png"], fx["sps"], fx["unknown"]])
lines = [ln for ln in r.stdout.splitlines() if ln.strip()]
check("multi: three JSON lines", len(lines) == 3, f"{len(lines)} lines")
check("multi: exit 3 (one unknown)", r.returncode == 3,
f"got {r.returncode}")
try:
objs = [json.loads(ln) for ln in lines]
check("multi: all parse", True)
check("multi: tasks in order",
[o.get("format", {}).get("task") for o in objs] == [564, 678, None])
except json.JSONDecodeError as exc:
check("multi: all parse", False, str(exc))
r = run([SFILE, "--json", fx["png"], missing])
check("multi: exit 2 beats 3", r.returncode == 2, f"got {r.returncode}")
print()
if FAILURES:
print(f"FAILED: {len(FAILURES)} check(s): {', '.join(FAILURES)}")
return 1
print("test_json: all checks passed")
return 0
if __name__ == "__main__":
sys.exit(main())
+109
View File
@@ -0,0 +1,109 @@
#!/bin/sh
# test_lib.sh — build + run the libsfile link test (static and shared).
#
# Compiles tests/test_library.c against libsfile.a and against
# libsfile.so, then checks both against the `sfile` CLI on the same
# fixtures: the field lines must match the CLI's header table exactly,
# the geotag must come through, and the JSON the library emits must
# parse. Usage: ./tests/test_lib.sh (run from the repo root)
set -e
cd "$(dirname "$0")/.."
TMP=$(mktemp -d /tmp/sfile-lib-test-XXXXXX)
trap 'rm -rf "$TMP"' EXIT INT TERM
python3 tests/make_fixtures.py "$TMP" > /dev/null
fail=0
note() { # note <ok|FAIL> <message>
if [ "$1" = ok ]; then echo " PASS $2"; else echo " FAIL $2"; fail=1; fi
}
# CLI field lines in the same "field: name=value" form the C program prints.
cli_fields() {
./sfile "$1" | grep -E '^ [0-9]+ ' \
| sed -E 's/^ +[0-9]+ +[0-9]+ +([^ ]+) +/\1=/' \
| sed 's/[[:space:]]*$//; s/^/field: /'
}
for variant in static shared; do
echo "link variant: $variant"
if [ "$variant" = static ]; then
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o "$TMP/t_$variant" \
tests/test_library.c libsfile.a
else
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o "$TMP/t_$variant" \
tests/test_library.c -L. -lsfile -Wl,-rpath,"$PWD"
fi
for fx in sample.png track.sps; do
if "$TMP/t_$variant" "$TMP/$fx" > "$TMP/out.txt" 2>&1; then
note ok "$variant $fx: exit 0"
else
note FAIL "$variant $fx: exit $?"
fi
# fields printed by the library vs fields printed by the CLI
grep '^field: ' "$TMP/out.txt" | sed 's/[[:space:]]*$//' > "$TMP/lib_fields.txt"
cli_fields "$TMP/$fx" > "$TMP/cli_fields.txt"
if diff -q "$TMP/lib_fields.txt" "$TMP/cli_fields.txt" > /dev/null; then
note ok "$variant $fx: library fields == CLI fields"
else
note FAIL "$variant $fx: library fields != CLI fields"
diff "$TMP/lib_fields.txt" "$TMP/cli_fields.txt" | head -10
fi
# the library's own JSON line must parse
grep '^json: ' "$TMP/out.txt" | sed 's/^json: //' > "$TMP/lib.json"
if python3 -c "import json,sys; json.load(open('$TMP/lib.json'))"; then
note ok "$variant $fx: library JSON parses"
else
note FAIL "$variant $fx: library JSON does not parse"
fi
if [ "$fx" = sample.png ]; then
# PNG has a geotagging mechanism but this fixture has none.
if python3 -c "import json,sys; d=json.load(open('$TMP/lib.json')); sys.exit(0 if d.get('geotags')==[] else 1)"; then
note ok "$variant $fx: library JSON geotags empty (none found)"
else
note FAIL "$variant $fx: library JSON geotags should be []"
fi
fi
if [ "$fx" = track.sps ]; then
# SPS header lat/lon fields are not a geotag: no mechanism.
if python3 -c "import json,sys; d=json.load(open('$TMP/lib.json')); sys.exit(0 if 'geotags' not in d else 1)"; then
note ok "$variant $fx: library JSON has no geotags key (no mechanism)"
else
note FAIL "$variant $fx: library JSON should have no geotags key"
fi
fi
done
# --mem path decodes from a buffer, not from disk
if "$TMP/t_$variant" --mem "$TMP/sample.png" > "$TMP/mem.txt" 2>&1 \
&& grep -q '^field: width=800$' "$TMP/mem.txt"; then
note ok "$variant --mem: decodes PNG from memory (width=800)"
else
note FAIL "$variant --mem: PNG decode from memory"
fi
done
# geotags come through the library (EXIF GPS JPEG: one result).
# Note: test_library decodes from disk here, so sfile_decode_file()
# runs geotag_scan(); --mem mode never scans (no path to scan).
if "$TMP/t_static" tests/geotag/test-gps.jpg | grep -q '^geotag: 37.774900 -122.419400 (EXIF GPS IFD (JPEG APP1 segment))$'; then
note ok "library geotag: 37.774900 -122.419400 (EXIF GPS)"
else
note FAIL "library geotag missing or wrong"
fi
if "$TMP/t_static" tests/geotag/test-gps.jpg > "$TMP/jpg.txt" 2>&1; then
grep '^json: ' "$TMP/jpg.txt" | sed 's/^json: //' > "$TMP/jpg.json"
if python3 -c "import json,sys,math; d=json.load(open('$TMP/jpg.json')); g=d['geotags'][0]; sys.exit(0 if len(d['geotags'])==1 and math.isclose(g['latitude'],37.7749,abs_tol=1e-6) and math.isclose(g['longitude'],-122.4194,abs_tol=1e-6) and g['source']=='EXIF GPS IFD (JPEG APP1 segment)' and g.get('altitude_m')==10.0 and g.get('datum')=='WGS-84' and g.get('datetime_utc')=='2026-12-01 12:34:56' else 1)"; then
note ok "library JSON geotags: EXIF GPS, alt 10.0, WGS-84, 2026-12-01 12:34:56"
else
note FAIL "library JSON geotags wrong"
fi
fi
if [ "$fail" = 0 ]; then
echo "test_lib: all checks passed"
exit 0
else
echo "test_lib: FAILED"
exit 1
fi
+94
View File
@@ -0,0 +1,94 @@
/* test_library.c — link test for libsfile.
*
* Decodes a file through the public API only (no CLI code) and prints
* the result in a canonical form that tests/test_lib.sh diffs against
* the `sfile` CLI's own output on the same file. If the library and
* the CLI disagree, the test fails.
*
* Usage: test_library [--mem] <file>
* --mem decodes from a memory buffer (sfile_decode_mem) instead of
* from disk (sfile_decode_file).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sfile.h"
static uint8_t *slurp(const char *path, long *n_out) {
FILE *fp = fopen(path, "rb");
if (!fp) return NULL;
fseek(fp, 0, SEEK_END);
long n = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t *buf = malloc(n > 0 ? (size_t)n : 1);
if (!buf) { fclose(fp); return NULL; }
size_t got = fread(buf, 1, (size_t)n, fp);
fclose(fp);
*n_out = (long)got;
return buf;
}
int main(int argc, char **argv) {
int use_mem = 0;
const char *path = NULL;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--mem") == 0) use_mem = 1;
else path = argv[i];
}
if (!path) {
fprintf(stderr, "usage: %s [--mem] <file>\n", argv[0]);
return 1;
}
printf("version: %s\n", SFILE_VERSION);
printf("formats: %d\n", sfile_format_count());
sfile_result r;
int st;
if (use_mem) {
long n = 0;
uint8_t *buf = slurp(path, &n);
if (!buf) { fprintf(stderr, "cannot read %s\n", path); return 2; }
st = sfile_decode_mem(buf, (size_t)n, path, n, &r);
free(buf);
} else {
st = sfile_decode_file(path, &r);
}
printf("status: %d\n", st);
if (!r.identified) {
printf("identified: no\n");
if (r.error) printf("error: %s\n", r.error);
sfile_free_result(&r);
return st;
}
printf("format: %s (%s) task %d by %s\n",
r.name, r.ext, r.task, r.identified_by);
for (int i = 0; i < r.nfields; i++)
printf("field: %s=%s\n", r.fields[i].name, r.fields[i].value);
if (r.doc_type == SFILE_DOC_XML) {
printf("doc: xml root=%s\n", r.root_element ? r.root_element : "");
if (r.version_attr) printf("doc: version=%s\n", r.version_attr);
} else if (r.doc_type == SFILE_DOC_JSON) {
printf("doc: json\n");
if (r.first_key) printf("doc: first_key=%s\n", r.first_key);
} else if (r.doc_type == SFILE_DOC_TEXT) {
printf("doc: text first_line=%s\n", r.first_line ? r.first_line : "");
}
if (r.ngeotags > 0) {
for (int i = 0; i < r.ngeotags; i++)
printf("geotag: %.6f %.6f (%s)\n",
r.geotags[i].lat, r.geotags[i].lon, r.geotags[i].source);
} else if (r.geotag_status == 0) {
printf("geotag: none found\n");
}
char *js = sfile_result_to_json(&r);
if (js) {
printf("json: %s\n", js);
free(js);
} else {
printf("json: (null)\n");
}
sfile_free_result(&r);
return st;
}
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Synthetic-image test for scar.
Builds a raw image with known files planted at known offsets (PNG, JPEG,
GIF, ZIP, PDF, gzip, plus a truncated JPEG at the very end), runs
./scar on it, and verifies every planted file is recovered byte-identical
at the right offset with the right size, and that the report lists them.
Usage: python3 tests/test_scar.py [--keep] (run from the repo root)
--keep leaves the image and carved output in /tmp/scar-test/ for inspection.
Exit 0 on success, 1 on any mismatch.
"""
import io
import os
import random
import shutil
import subprocess
import sys
import tempfile
import zipfile
from PIL import Image
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def make_png():
im = Image.new("RGB", (64, 48))
px = im.load()
for y in range(48):
for x in range(64):
px[x, y] = (x * 4 % 256, y * 5 % 256, (x + y) * 2 % 256)
buf = io.BytesIO()
im.save(buf, "PNG")
return buf.getvalue()
def make_jpeg():
im = Image.new("RGB", (80, 60), (200, 30, 90))
px = im.load()
for y in range(60):
for x in range(80):
px[x, y] = ((x * 3) % 256, (y * 4) % 256, 128)
buf = io.BytesIO()
im.save(buf, "JPEG", quality=85)
return buf.getvalue()
def make_gif():
im = Image.new("P", (32, 32))
im.putpalette([i % 256 for i in range(768)])
px = im.load()
for y in range(32):
for x in range(32):
px[x, y] = (x + y) % 256
buf = io.BytesIO()
im.save(buf, "GIF")
return buf.getvalue()
def make_zip():
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("hello.txt", "hello from inside the zip\n" * 20)
zf.writestr("data.bin", bytes(range(256)) * 4)
return buf.getvalue()
def make_pdf():
body = (
b"%PDF-1.4\n"
b"1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n"
b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n"
b"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj\n"
b"xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n"
b"0000000058 00000 n \n0000000115 00000 n \n"
b"trailer << /Size 4 /Root 1 0 R >>\nstartxref\n193\n%%EOF\n"
)
return body
def make_gz():
import gzip
return gzip.compress(b"the quick brown fox jumps over the lazy dog. " * 50)
def main():
keep = "--keep" in sys.argv
work = "/tmp/scar-test" if keep else tempfile.mkdtemp(prefix="scar-test-")
if keep:
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work, exist_ok=True)
rng = random.Random(1234)
# (name, bytes, filler-before) — filler 0 tests back-to-back files.
plan = [
("png", make_png(), 0),
("jpeg", make_jpeg(), 113),
("gif", make_gif(), 4096),
("zip", make_zip(), 0),
("pdf", make_pdf(), 777),
("gz", make_gz(), 2048),
]
jpeg_full = make_jpeg()
truncated = jpeg_full[:200] # truncated file at EOF: low-confidence carve
image = bytearray()
expected = [] # (offset, name, bytes)
for name, data, gap in plan:
image += bytes(rng.randrange(256) for _ in range(gap))
expected.append((len(image), name, data))
image += data
image += bytes(rng.randrange(256) for _ in range(512))
trunc_off = len(image)
image += truncated
img_path = os.path.join(work, "test.img")
with open(img_path, "wb") as f:
f.write(image)
outdir = os.path.join(work, "carved")
scar = os.path.join(REPO, "scar")
proc = subprocess.run([scar, "-o", outdir, img_path],
capture_output=True, text=True)
print(proc.stdout, end="")
if proc.stderr:
print(proc.stderr, end="", file=sys.stderr)
if proc.returncode != 0:
print(f"FAIL: scar exited {proc.returncode}")
return 1
failures = []
extmap = {"png": "png", "jpeg": "jpeg", "gif": "gif",
"zip": "zip", "pdf": "pdf", "gz": "gz"}
for off, name, data in expected:
# output filename: zero-padded offset + lowercase ext from sfile table
fname = f"{off:010d}.{extmap[name]}"
got_path = os.path.join(outdir, fname)
if not os.path.exists(got_path):
failures.append(f"{name} at {off}: missing {fname}")
continue
got = open(got_path, "rb").read()
if got != data:
failures.append(f"{name} at {off}: {len(got)} bytes, "
f"expected {len(data)} (content differs)")
else:
print(f"ok: {name} at offset {off}, {len(data)} bytes, "
f"byte-identical ({fname})")
# truncated JPEG: carved to EOF with low confidence
trunc_name = f"{trunc_off:010d}.jpeg"
trunc_path = os.path.join(outdir, trunc_name)
if not os.path.exists(trunc_path):
failures.append(f"truncated jpeg at {trunc_off}: missing {trunc_name}")
else:
got = open(trunc_path, "rb").read()
if got != truncated:
failures.append(f"truncated jpeg at {trunc_off}: {len(got)} bytes, "
f"expected {len(truncated)}")
else:
print(f"ok: truncated jpeg at offset {trunc_off}, "
f"{len(truncated)} bytes, byte-identical ({trunc_name})")
# report must list every planted offset and the truncated one
report = open(os.path.join(outdir, "report.txt")).read()
for off, name, data in expected + [(trunc_off, "trunc-jpeg", truncated)]:
if str(off) not in report:
failures.append(f"report.txt missing offset {off}")
extmap = {"png": "png", "jpeg": "jpeg", "gif": "gif",
"zip": "zip", "pdf": "pdf", "gz": "gz"}
expected_files = {f"{off:010d}.{extmap[name]}" for off, name, _ in expected}
expected_files.add(trunc_name)
extra = sorted(fn for fn in os.listdir(outdir)
if fn != "report.txt" and fn not in expected_files)
if extra:
failures.append(f"unexpected extra carved files: {extra}")
if failures:
print("FAIL:")
for f in failures:
print(f" - {f}")
return 1
print(f"PASS: {len(expected) + 1} files recovered, image {len(image)} bytes")
if not keep:
shutil.rmtree(work, ignore_errors=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Minimal local tile server for the stag/sgeo tests.
Serves solid-colour 256x256 PNG tiles for any /z/x/y.png, so the
sgeo tests do not depend on the network. sgeo is pointed at it with
$SGEO_TILE_BASE=http://127.0.0.1:<port>.
Usage: tile_server.py --port-file FILE
Binds an ephemeral port, writes the port number to FILE, then serves
forever (the test runner kills it on exit).
"""
import argparse
import binascii
import struct
import zlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def chunk(typ, data):
c = struct.pack(">I", len(data)) + typ + data
return c + struct.pack(">I", binascii.crc32(typ + data) & 0xFFFFFFFF)
def make_tile(x, y):
# Solid fill, shade varies slightly with the tile so stitching is
# visible; plus a 1px darker border.
base = 225 + ((x + y) % 3) * 5
row = b"\x00" + bytes([base, base, base]) * 256
rows = [row] * 256
raw = b"".join(rows)
ihdr = struct.pack(">IIBBBBB", 256, 256, 8, 2, 0, 0, 0)
png = b"\x89PNG\r\n\x1a\n"
png += chunk(b"IHDR", ihdr)
png += chunk(b"IDAT", zlib.compress(raw, 6))
png += chunk(b"IEND", b"")
return png
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
parts = self.path.strip("/").split("/")
try:
z, x, y = int(parts[0]), int(parts[1]), int(parts[2].split(".")[0])
assert 0 <= z <= 22 and 0 <= x < (1 << z) and 0 <= y < (1 << z)
except Exception:
self.send_response(404)
self.end_headers()
return
body = make_tile(x, y)
self.send_response(200)
self.send_header("Content-Type", "image/png")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port-file", required=True)
args = ap.parse_args()
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
with open(args.port_file, "w") as f:
f.write(str(srv.server_address[1]))
srv.serve_forever()
if __name__ == "__main__":
main()
+28
View File
@@ -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"