How the camera works
The repository is the public site plus the working camera app. The camera, the ONNX models and the plate index all live in the browser. There is no account and no image upload.
The stack
- Astro builds the site.
/appand/demoare the app islands; the homepage has one feature island, the local video check, which loads no model until a clip is chosen. - React renders the camera, the scan dock, the memory, the settings sheet and the video check.
- onnxruntime-web 1.31 runs the ONNX models in a worker on the processor: several WASM threads when the page is cross-origin isolated, one otherwise.
- Tailwind CSS v4 provides the design tokens and utilities.
- Cloudflare Workers static assets serves
dist/; the ONNX models inpublic/modelsand the Vite-emitted runtime in_astroare deployed beside the pages.
The model pair
| Pair | Detector | Reader | Download | Notes |
|---|---|---|---|---|
| Nano | yolo26n_plate_640.onnx (9.8 MB), [1,3,640,640] |
plate_ocr_cct_xs_v2.onnx (3.3 MB) |
about 13 MB | Raw [1,5,8400] anchors; the app applies NMS. |
The detector finds a plate; the OCR reads a tight crop of it. The alphabet is
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_, with _ as the pad character. The output is normalised
and formatted by src/lib/plates.ts — the model is not asked to know UK grouping.
src/lib/vision/models.ts owns the catalogue: file names, input size, download size and the
labels the settings use. The detector input size and output layout come from the config JSON, so
a different graph can be dropped in without hard-coding 640. The Nano graph returns raw anchors
and decodeDetections runs greedy NMS; the end-to-end decoder remains tested for a future model.
Both paths are pure and tested in src/lib/vision/detect.test.ts.
The larger YOLO26s pair was retired after the public benchmarks: it missed a third of the Dutch
plates, was slower on the phone and did not read more plates than Nano. The evidence is on
/benchmarks; the app no longer offers it. The pair is ordinary static assets, with no
object-storage binding.
The frame loop
usePlateScanner owns the camera, the loop and the recorder.
start()requests the rear camera, starts aMediaRecordersegment and loads the models.- A timer loop runs at roughly 10 Hz. It does not run inference blindly on every tick:
- Full-frame search: as soon as the previous pass finishes and the next frame is ready.
Adaptive has no minimum gap; Balanced and Save battery are caps (1.2s and 2s). The loop is
single-flight, so a slow detector skips frames instead of building a backlog. The
viewport — a box the person draws on a frozen frame,
settings.scanAreainsrc/lib/vision/area.ts— is letterboxed to 640×640 and the detector runs. It defaults to the whole picture. It is a precision setting first: the input is a 640×640 square whatever the crop, so a pass costs the same, but sky, windscreen reflections and the car’s own bonnet stop producing detections. It is also the one crop that buys detail — a box smaller than the frame in both directions makes every plate in it larger in the model’s view, while cropping only top and bottom changes nothing on a 16:9 frame, where the width limits the scale. - ROI reuse: between full searches, the app OCRs only the boxes it found last time, at
ocrInterval(220ms). This is the performance trick: detection is the expensive pass, and a plate that has already been located usually moves only a little between frames. - If ROI reads fail, a full search is forced on the next tick.
- Full-frame search: as soon as the previous pass finishes and the next frame is ready.
Adaptive has no minimum gap; Balanced and Save battery are caps (1.2s and 2s). The loop is
single-flight, so a slow detector skips frames instead of building a backlog. The
viewport — a box the person draws on a frozen frame,
- Detections are matched to tracks by IoU. A track keeps its last box and up to eight recent reads.
- Reads are combined by temporal consensus. The last three reads must agree exactly, the result must be a standard UK format, every character must be at least 99% confident, and the weighted per-position support must be at least 90% before the app calls a plate confirmed.
- A weaker track is not discarded. When the track ends, its best consensus is logged as provisional without a toast or vibration. This is how a single 96% read survives even if no more frames arrive.
- A confirmed read stores the plate, time, confidence, region, aliases, a small JPEG crop and the id of the current one-minute recording segment.
The inference session runs in an ORT proxy worker, not on the UI thread. The loop is driven by the
camera: after each pass it waits for the next presented frame, and only one pass is in flight. If a
detector pass takes longer than a frame, the next one starts on the newest frame; no backlog is
queued. Adaptive has no minimum gap between full looks; Balanced and Save battery cap them at 1.2 s
and 2 s. Tracked boxes are re-read every 220 ms, and a full search is forced on start and when a
re-read fails. The report counts looks/s — full-frame searches over two seconds — rather than the
frame rate, because an idle loop must not read as a fast one. COOP/COEP are required for the
multi-threaded path; public/_headers sends them in production, and the dev/preview servers send
the same pair.
The processor
Inference is WebAssembly only. The app runs it in onnxruntime’s proxy worker, with several threads when the page is cross-origin isolated and one otherwise. There is no second execution path.
The first start downloads about 13 MB of Nano weights plus the 15 MB processor runtime that Vite emits with the app. Everything is served from this origin and cached by the browser; the service worker can keep it for offline use after the first run.
Vehicle details
A plate can be looked up with the DVLA for make, colour, fuel, year, engine size and tax/MOT status; an expired or absent MOT, untaxed or SORN is shown as a flag rather than a badge of honour. It is off by default and never runs on its own: the person presses Look up vehicle on one plate in one clip.
The DVLA service cannot be called from a browser — it returns no CORS headers, so the preflight is
rejected and the request never leaves the tab. The lookup therefore needs a server, and this is the
site’s one exception to being static: src/worker.ts serves the assets and answers
POST /api/vehicle. The key is a Worker secret, never in the bundle; astro.config.mjs runs the
same handler as dev middleware so DVLA_API_KEY=... bun run dev works locally.
Rules the handler keeps: one registration per request and nothing else in the body; the
registration is never logged; the reply is reduced to VehicleRecord in src/lib/vehicle.ts;
cache-control: no-store; at most one upstream call a second (the key’s limit). The client
(src/lib/vehicle-client.ts) paces itself the same way. Results are stored with the plate —
plain when no vault exists, sealed inside the vault when one does — and the lookup is hidden on
/demo so invented fixtures never acquire real vehicle details.
Confidence and consensus
decodeOcr reads the ten softmax slots and scores a read from the weakest character, not the
mean. The score is then reduced by:
- a soft UK-format prior — modern, prefix, suffix, Northern Ireland and dateless patterns are
preferred; a six-character
OE56FDis possible as a private plate, but cannot look as strong as a seven-character modern plate; - the probability of the first pad character, which represents uncertainty about where the plate ends;
- the smallest gap between the best and second-best character.
The UI shows that strict score. It is deliberately harsher than the old mean: OE56FDD with a
96% final D is 96%, OE56FD is pulled down by its non-standard length, and a clean OE56FDO is
the only one that can reach a confirmation.
src/lib/vision/consensus.ts votes over the reads in one track. It chooses the most plausible
length, votes per character position (including each read’s alternatives), and keeps every
different reading as an alias. OE56FDO can therefore have OE56FDD and OE56FD attached
without creating three plate memories. Search matches aliases too.
A track commits at most one sighting, and a 60-second exact-text cooldown stops the same plate being written repeatedly. Fuzzy merging is deliberately not applied across different tracks: two real registrations can differ by one character.
Recording
MediaRecorder records the same MediaStream that the camera displays. It prefers H.264/MP4,
then VP8 WebM, and uses VP9 last: some Android encoders advertise VP9 and then produce black
segments. With sound on it asks for H.264 and AAC in the same MP4 and only falls back to
WebM/Opus, because VP8 is a software encoder on almost every Android phone and a 1080p software
encode starves the camera — one report of “1 fps and the whole app is laggy while recording”
was exactly that. The camera is asked for 1280×720 at 30 fps: the detector input is 640×640, so
a 1080p preview only added scaling work to every pass and load to the encoder. The camera waits for its first decoded frame before recording starts, and pausing waits
for the recorder’s final stop event before stopping the camera tracks.
The camera is asked for a quality preset (640×360 / 720p / 1080p / as high as the device
goes) as ideal constraints, and the recorder’s bitrate follows the same preset. Every value is
a hint: the sheet reports what the camera actually delivered, and Developer details repeats it.
Segments are one minute long. When a segment ends, its chunks are combined into a Blob and
written to IndexedDB by src/lib/clips.ts. If a folder handle was chosen (File System Access API,
Chrome/Edge), the same blob is also written into that folder by src/lib/folder.ts; the handle is
persisted in IndexedDB and permission is re-requested on the next recording start. The last MAX_CLIP_SEGMENTS (12) are kept. A sighting
keeps the segment id, so Play clip can fetch and play it without a server. The player shows
the clip’s MIME type, size and duration, and offers a download if the browser cannot decode it.
A segment is not playable until it is closed. A sighting made during the current minute will see “the segment is still being written” until the next minute; that is expected and honest.
The video check
The homepage’s Try your own clip card is the one client island outside /app and /demo.
src/components/home/VideoAnalyzer.tsx loads no model until a file is chosen or Scan this
clip is pressed; the reading pair is then created with the same PlateReader the camera uses.
The file is decoded by the browser from a local object URL (or the bundled example path). Two modes are offered:
- Live (default) plays the clip at normal speed and starts a pass as soon as the previous one finishes, so a one-minute video takes about a minute and produces as many reads as the model can manage in real time. Each pass draws the current video frame into a snapshot canvas and gives the detector and the OCR that same snapshot, so a box and its characters belong to the same frame even though playback has moved on while the model answers.
- Quick pauses the clip and samples up to 120 moments (
sampleTimesinsrc/lib/vision/video-scan.ts) as fast as it can. A short clip is read about once a second; a longer one is spread over its whole length so a ten-minute file does not become a ten-minute wait.
Detections are read in a batch, and the reads are grouped by registration with the strongest read
driving the card (groupVideoReads). Selecting a plate seeks the video to its best moment and
draws the box.
The check is a preview, not a library: it writes no sighting, no clip and no preference, and it does not need the vault or the camera. It uses the Nano pair.
Where things live
The storage keys, field types, limits and folder filenames are catalogued in What is saved.
| Path | What it is |
|---|---|
src/pages/ |
Routes: home, how it works, pricing, camera app, docs, legal, 404 |
src/components/app/ |
Camera, scan dock, clip search, timeline, settings, setup wizard |
src/components/home/VideoAnalyzer.tsx |
The homepage video check: file, sampling, results |
src/components/app/usePlateScanner.ts |
Camera, inference loop, tracking, confirmation, recording |
src/lib/vision/alpr.ts |
ONNX preprocessing, both detector layouts, NMS, OCR decode |
src/lib/vision/models.ts |
The Nano catalogue, the retired-tier fallback, sizes and URLs — pure and tested |
src/lib/vision/scan-plan.ts |
Frame-driven cadence: full look and region read due, single-flight policy — pure and tested |
src/lib/vision/video-scan.ts |
Sampling, grouping and time labels for the video check — pure |
src/lib/vision/types.ts |
Boxes, detections, reads and model config |
src/lib/plates.ts |
Normalising, formatting and matching a registration |
src/lib/sightings.ts |
Grouping reads into memories, ranges and labels |
src/lib/clips.ts |
IndexedDB clip store, clip index and retention limits |
src/lib/checksum.ts |
SHA-256 for media, sha256:<64 hex> |
src/lib/journey.ts |
Journey manifest, legs, media refs, telemetry and tags — pure |
src/lib/journey-store.ts |
IndexedDB journey manifest store, sealed when a vault exists |
src/lib/vault.ts |
RSA/AES envelopes, password-wrapped private key |
src/lib/vault-store.ts |
Vault keys and sealed small records |
src/components/app/vault-context.tsx |
Lock/unlock state and in-memory private key |
src/lib/clip-search.ts |
Clip summaries, plate/road/time search and clip statistics |
src/lib/trips.ts |
GPS distance, point dedupe and average speed |
src/lib/movement.ts |
Credible movement and standstill for the eight-minute journey boundary |
src/lib/route.ts |
Route colour bands, per-pair speed/braking/cornering, pure |
src/lib/geocode.ts |
Nominatim reverse geocoding (opt-in), cached and throttled |
src/lib/motion.ts |
Gyroscope and accelerometer summary, pure and tested |
src/components/app/useTripRecorder.ts |
Session, journey and parked records, movement boundary, motion samples and local persistence |
src/components/app/useJourneys.ts |
Builds and merges manifests when journeys and parked records close |
src/components/app/TimelineMap.tsx |
Leaflet/OpenStreetMap route and plate markers |
src/lib/preferences.ts |
Setup record, road naming and clip limits in local storage |
src/lib/permissions.ts |
Camera, microphone and location probes |
src/lib/demo.ts |
The seven example drives, routes, stills, motion and demo clip |
public/models/ |
The Nano pair, the benchmark reader, config and attribution |
Real app and demo
/app is the real app and /demo is the demo. Both render PlateApp; the demo page passes
demo as a prop and nothing can switch mode inside the app. A fresh install is empty:
useAppIndex returns only the reads in sighted.live.v1, and the camera, clips and vault work as
they do in a normal session.
On /demo, useAppIndex returns only createDemoData() fixtures. The demo does not load the
clip index or journey store, does not open the camera, and keeps stars and location toggles in
memory. Its Dashcam tab is DemoStage; the timeline and clip search are the product tour. The
Demo pill opens a confirmation to /app. createDemoData is pure, so the demo routes, stills
and clip can be tested without a browser.
The homepage video check is separate from both: it has no PlateApp state, no storage and no
demo fixtures. Its Use the example clip button plays the same drawn /demo/drive.mp4 that the
demo uses, and the card says it is drawn.
Setup, clips and limits
OnboardingWizard is a sequence of optional steps: camera, microphone, AI reading, location,
motion, encryption and storage. The reading step asks whether to run AI on the video; the download
is what happens if the answer is yes. The encryption step offers the vault where the security
story belongs, using the same VaultCreateForm as Settings, so a new installation can be
protected before the first drive rather than after. Each permission is asked from a button, so the
browser sees a user gesture;
src/lib/permissions.ts opens the device only long enough to get the answer and then releases it.
The choices are stored as a small record in sighted.setup.v1 so setup does not reappear.
A clip result shows a still captured with one of its reads, and the search field takes focus from On a phone the Timeline draws up to 20 journeys at once (pale blue), fits them all, and keeps the rail as a dialog sheet behind Journeys · n. Tapping a route selects that drive and zooms to it; no panel covers the map by default.
Encryption
The vault is a hybrid scheme. An RSA-OAEP-2048 key pair is generated once; the public key is kept
in the clear so usePlateScanner and useJourneys can seal new media and manifests without a
password. The PKCS#8 private key is encrypted with an AES-256-GCM key derived from the password
with PBKDF2-SHA-256 (600,000 iterations) and stored only as ciphertext. Each segment gets a fresh
AES-256-GCM key, wrapped with the public key; the same envelope structure carries manifests.
VaultProvider holds the public key always and the private key only while unlocked. Locking drops
it, clears decrypted history from the hooks, and leaves recording running. The Clips and Timeline
tabs render LockedPanel while locked. Setup deletes unprotected data by design; folder files
written before setup are outside the app’s reach and remain plaintext.
Journey manifests
A drive is more than a pile of clips. When it closes, useJourneys writes a manifest to
sighted-journeys: one leg per segment with its media reference (name, size, format, SHA-256),
per-fix telemetry, plate tags and road arrays. The manifest is merged, never rewritten from
scratch, so a segment that arrives late is added and a segment pruned later still leaves its leg
and metadata behind.
The Clips screen joins three sources: stored clips (blob present), manifests (history) and demo
fixtures. A manifest leg whose clipId is no longer in sighted-clips becomes a record-only row
with No video; time, roads, speed, G-force, tags and checksum remain. Stored clips are enriched
from their manifest so the plate list is the same whether or not the live-read cache still holds
those sightings.
ClipsPanel is the library and the search at once. src/lib/clip-search.ts joins the clip index,
the sightings with that clipId and the trip telemetry for the clip’s window into a ClipSummary
(roads, plates, average and peak speed, peak G-force and cornering). Searching is just a filter
over those summaries, so a plate, a road and a time all return playable clips. Retention is a pure
function, clipsOutsideLimits, applied by pruneClips after every saved segment: files, days and
megabytes, whichever comes first. The newest segment is never removed for size, so a loop cannot
prune itself to an empty index; a single clip larger than the whole megabyte budget is kept and
the budget is exceeded. The chosen folder is never pruned by the app.
The open tab and the open clip live in the address bar (?tab=clips&clip=…). PlateApp pushes a
history entry on navigation and restores state on popstate. TimelineMap is mounted on the first
Timeline visit and then hidden rather than unmounted, so Back returns to the same Leaflet view.
Location, motion and journeys
useTripRecorder opens a session when the camera or screen share becomes active. The session is
the continuous recording; inside it, one or more journeys are grouped by movement. With
Record GPS on, it uses navigator.geolocation.watchPosition with high accuracy and keeps a
point after two metres of movement or five seconds.
A journey ends at the last credible movement before eight minutes of continuous standstill.
src/lib/movement.ts decides what counts as movement from recent, accurate fixes: a reported speed
of at least 5 km/h, or about 30 metres of sustained displacement. A drifting parked phone, a tunnel
with no fixes, or a single poor-accuracy fix is not evidence either way. The eight-minute decision
is made from lastMovementAt, not from when the app notices the stop. The interval between journeys
is a parked record: it keeps its clips and plate tags, but no route.
Without location — or with no usable fixes — the session is one journey, and the user’s Start/Pause
is the boundary. Clips carry a sessionId, and journey membership is resolved from that session
and the journey’s time window; this is what lets a clip written during the eight minutes before a
split move to the parked record without rewriting its video. sighted.trips.v1 is only the map’s
route cache. The durable record is the journey manifest.
Motion is a separate opt-in in Settings, off by default. When it is on, useTripRecorder
listens to devicemotion, keeps one sample per 100 ms and folds each one into a running summary
for the current journey: peak turn about the screen-normal axis, mean turn rate, peak rotation on
any axis and peak jolt in g. Time spent parked is not added to a journey. The summary is written
when the journey closes, so a two-hour drive costs a few hundred bytes instead of a sensor log. The
raw stream is discarded. iOS asks for motion access separately and only inside a user gesture, which
is why the request happens on the Settings toggle rather than on page load. src/lib/motion.ts is
pure; the browser event shape never reaches the rest of the app.
Each point carries optional speedKmh, turnDeg and joltG samples taken while driving.
src/lib/route.ts turns those into coloured runs: speed from distance and time, G-force from the
recorded jolt (falling back to the change in reported speed), cornering from the turn rate. routeRuns merges adjacent
fixes of the same band into one polyline, so a long drive stays a handful of layers. The legend
names every band, so colour is never the only signal.
TimelineMap uses Leaflet with OpenStreetMap raster tiles. The tile layer is the only
third-party request while Timeline is open. The route and plate markers are drawn from local
data; a marker popup shows the stored vehicle snapshot and plate, and its buttons open the clip
modal or the plate’s search page.
Naming journeys
Journeys start as Drive at HH:MM; parked records as Parked at HH:MM. If the user turns on
naming, PlateApp walks the unnamed journeys with at least two fixes (at most six at a time) and
calls nameDrive from src/lib/geocode.ts. Nominatim requests are queued to one per second, cached
by rounded coordinate, and made only for the start, middle and end fixes. The start, middle and end
are sampled, so each leg’s roads array has names in order. The result replaces the journey name; a
failure leaves the default name in place. Demo journeys carry road names from src/lib/demo.ts and
never call Nominatim.
Search stays pure
The plate functions and the index functions do not import React. That is why the tests can describe the product rather than a component, and why the same rules would work in a native capture app.
What is deliberately absent
- An evidence-export writer. Export this sighting set explains the proposed pack but does not write a file.
- Cloud sync, accounts and a server. The local browser is the source of truth.
- A native store app. The camera app is installable as a web app.
- A formal accuracy benchmark for the bundled models on UK roads.
Those omissions are the honest boundary of the prototype. The camera, the local models, ROI tracking, the index and the local clips are implemented and tested.