Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge remote-tracking branch 'origin/main' into HEAD

Trygve Hemminghytt6f054408daae
diff --cc .env.example
index 58aa29ac1,6d3ee3f6f..9addca068
--- a/.env.example
+++ b/.env.example
@@@ -214,8 -215,10 +215,11 @@@ AISSTREAM_API_KEY
# CCTV_VEGVESEN_ENABLED=1 # set 0 to disable the Statens vegvesen (Norway) road cameras
# CCTV_VEGVESEN_MAX_SOURCES=900 # cap cameras loaded from Statens vegvesen (default loads all ~850 live; max 1000)
# CCTV_VEGVESEN_VIDEO=1 # set 0 to show stills instead of live HLS for Statens vegvesen video cameras
+# CCTV_VEGVESEN_HEIGHTS=1 # set 0 to skip Kartverket ground heights for Statens vegvesen cameras (flat prior instead)
# CCTV_VEGVESEN_URL= # override the Statens vegvesen catalog URL
+ # CCTV_NYC_ENABLED= # off by default; set 1 only if you hold a NYC DOT data-sharing agreement ([email protected]) for the camera feed
+ # CCTV_NYC_MAX_SOURCES=250 # cap cameras loaded from the NYC TMC catalog (nearest borough cores first)
+ # CCTV_NYC_CAMERAS_URL= # override the NYC TMC catalog URL
# CCTV_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs
# CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry
# CCTV_FORCE_AUSTIN= # force live default sources when a source-pack JSON is configured
diff --cc DATA_SOURCES.md
index b35a2d512,da47a4cc6..464021960
--- a/DATA_SOURCES.md
+++ b/DATA_SOURCES.md
@@@ -56,7 -57,7 +57,8 @@@ How to read this
| **DriveBC** (Government of British Columbia) | CCTV camera catalog + frames, British Columbia highways | [Open Government Licence – British Columbia](https://www2.gov.bc.ca/gov/content/data/open-data/open-government-licence-bc) — attribution REQUIRED | "DriveBC. Contains information licensed under the Open Government Licence – British Columbia" |
| **Open Calgary** (`data.calgary.ca`) | CCTV camera catalog + frames, Calgary | [Open Government Licence – City of Calgary](https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – City of Calgary" |
| **Statens vegvesen** (catalog `ogckart-sn1.atlas.vegvesen.no`, frames `kamera.atlas.vegvesen.no`, HLS `kamera.vegvesen.no`) | CCTV camera catalog + frames + live HLS video, Norway road cameras | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) distributed by Statens vegvesen" |
+| **Kartverket** (`ws.geonorge.no/hoydedata/v1/punkt`) | Terrain heights (NN2000) used as the ground prior for Statens vegvesen cameras | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — attribution REQUIRED | "© Kartverket" |
+ | **NYC DOT Traffic Management Center** (`webcams.nyctmc.org`) | CCTV camera catalog + frames, New York City five boroughs | NYC DOT requires developers to sign a [data-sharing agreement](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) for the camera feed. **Off by default**; enable only under your own agreement | "NYC DOT Traffic Management Center" + NYC DOT's required application disclaimer (in the Data attribution popover) |
| **GBFS (Lyft / BCycle)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` |
| **MBTA / MassDOT** (cdn.mbta.com) | Transit layer live vehicles and up to 15 minutes of recently observed positions, Greater Boston | MBTA / MassDOT open realtime vehicle data, used for the live view and up to fifteen minutes of recently observed positions; published for developer use and not against their use. | Attribution to MBTA / MassDOT (courtesy text) |
| **CapMetro** (data.texas.gov) | Transit layer live vehicles, Austin TX | CapMetro open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to CapMetro (courtesy text) |
@@@ -92,7 -93,7 +94,8 @@@ The optional Local ADS-B layer and the
- **Live Traffic NSW cameras.** The camera list is the keyless public `data.livetraffic.com/cameras/traffic-cam.json` feed (Transport for NSW open data, CC BY 4.0); frames are stills on `webcams.transport.nsw.gov.au`, and only that host is registered. That image host answers non-browser clients with an HTML placeholder, so the proxy identifies as a browser for that one host and as itself everywhere else. Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_NSW_ENABLED=0`.
- **Open Calgary traffic cameras.** Keyless. The camera list is the public Socrata dataset `k7p9-kppz` on `data.calgary.ca`; frames are stills on the city's own `trafficcam.calgary.ca` host, and only that host is registered. Most rows publish an `http://` frame URL and the host redirects those to HTTPS, so URLs are upgraded and pinned to that origin before registration. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `quadrant` field and the quadrant suffix on each camera name are Calgary's address grid, not a bearing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. The licence requires the attribution statement above. Disable with `CCTV_CALGARY_ENABLED=0`.
- **Statens vegvesen road cameras.** Keyless. The camera list is one GeoJSON request to the OGC API Features view of the official DATEX 3.1 CCTV site table (`ogckart-sn1.atlas.vegvesen.no/ogc/features/v1/collections/datex_3_1:CctvSimple/items`), so no DATEX account is needed; frames are stills on `kamera.atlas.vegvesen.no/api/images/<cameraId>`, and only that exact path per camera is registered. Cameras the feed reports as faulty are dropped. About 135 working cameras also publish live HLS (`kamera.vegvesen.no/public/<cameraId>/manifest.m3u8`, MPEG-TS); those play as live video through the bounded in-memory HLS relay, with the still as the snapshot fallback, and only that exact manifest path per camera is registered. `CCTV_VEGVESEN_VIDEO=0` keeps every camera on stills. `orientationDescription` names the place a camera faces, not a bearing, so it goes into the label and headings use the id-hash fallback at low confidence. By default every live camera loads (~850); `CCTV_VEGVESEN_MAX_SOURCES` (8–1000) lowers the cap, keeping the cameras nearest Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Bodø and Tromsø and `CCTV_VEGVESEN_ENABLED=0` turns the pack off. Frames are fetched at request time and never stored or redistributed. The NLOD attribution is registered in the Data attribution popover.
+- **Kartverket ground heights for Statens vegvesen cameras.** The camera feed's points are 2D, so the loader asks Kartverket's keyless point-height API (`ws.geonorge.no/hoydedata/v1/punkt`, CC BY 4.0) for the terrain height at each camera. Requests carry 20 points: the API accepts 50, but above ~20 it answers the extra points from contour lines (`hoydekurver`, metres to ~20 m off) or not at all. Eight requests run at a time, about 36 for the whole country (~6 s). Answers are matched by the coordinates the API echoes and recorded only for points that request asked about. Over water the API returns the sea-floor depth (`dybdekurver` or `Havflate`), which is replaced by 0 m, the water surface; for the ~14 bridge cameras that is below the deck, but much closer than the sea floor or the flat prior. Heights are cached in memory by position for the life of the server, and points with no height (a few ferry quays and bridges) for 6 h, so the 15-minute catalog refresh only asks about new or moved cameras. The first 429, 5xx or network failure stops the lookup, with no retries, and no new lookup starts until the backoff ends (Retry-After when sent, else 10 min; bounded to 1 min–1 h). The lane waits at most 12 s, counted from the start of the loader; a slower lookup keeps filling the cache for the next refresh. Only coordinates are sent, with the same User-Agent as the other CCTV requests. `CCTV_VEGVESEN_HEIGHTS=0` turns the lookup off. The Kartverket credit is shown beside the Statens vegvesen entry in the Data attribution popover.
+ - **NYC DOT Traffic Management Center cameras.** Off by default. NYC DOT's [developer data feeds page](https://www.nyc.gov/html/dot/html/about/datafeeds.shtml) asks developers who want the camera feed to contact `[email protected]` and sign a data-sharing agreement. This project does not hold one that covers downstream installations, so the pack loads only when an operator who holds their own agreement sets `CCTV_NYC_ENABLED=1`; with the flag unset, empty or any other value, the server makes no request to NYC DOT. The endpoint needs no key. The camera list is the public `webcams.nyctmc.org/api/cameras` catalog (~980 cameras across the five boroughs); frames are stills at `webcams.nyctmc.org/api/cameras/<uuid>/image`, synthesized from a validated UUID rather than taken from the payload, and only that host is registered. Cameras the feed reports as offline are dropped. The catalog publishes no camera facing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. Once enabled, the 250 cameras nearest the borough cores load; `CCTV_NYC_MAX_SOURCES` (8–400) changes the cap. Frames are fetched at request time and never stored or redistributed. NYC DOT asks every application that uses its data to carry its disclaimer; it is registered verbatim in the Data attribution popover.
- **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals.
- **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All seven registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth.
- **Radio Browser.** `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and malformed or empty successful payloads are rejected atomically. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply.
diff --cc docs/CURRENT-STATE.md
index ec0ccf0d9,aa1295198..20eb307f7
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -3054,7 -3089,7 +3089,7 @@@ its criteria cannot be silently ignored
| Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s |
| Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min |
| Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache |
- | CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) |
-| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS) + NYC DOT TMC (opt-in) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) |
++| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + NYC DOT TMC (opt-in) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) |
| Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh |
| Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) |
| Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s |
diff --cc server/providers/cctv/constants.js
index 6e9c6cd04,ae80904a5..5243be65b
--- a/server/providers/cctv/constants.js
+++ b/server/providers/cctv/constants.js
@@@ -267,39 -267,36 +267,69 @@@ export const NORWAY_ANCHORS =
{ lat: 69.6492, lon: 18.9553 }, // Tromsø
];
+/** Kartverket's keyless point-height API (CC BY 4.0): terrain height above
+ * sea level (NN2000), used as the Vegvesen cameras' ground prior because the
+ * camera feed's points are 2D. */
+export const KARTVERKET_HEIGHT_URL =
+ 'https://ws.geonorge.no/hoydedata/v1/punkt';
+/** Points per request. The API takes up to 50, but above ~20 it answers the
+ * extra points from contour lines (`hoydekurver`, metres to ~20 m off) or not
+ * at all; at 20 nearly every camera resolves from the 1 m terrain model. */
+export const KARTVERKET_MAX_POINTS = 20;
+/** Requests in flight at once. The whole country is ~36 requests of ~1-2 s,
+ * so a cold lookup takes ~6 s. */
+export const KARTVERKET_CONCURRENCY = 8;
+/** Deadline for one complete lookup, shared by every request. */
+export const KARTVERKET_LOOKUP_TIMEOUT_MS = 30 * 1000;
+/** The Vegvesen lane's budget, measured from the start of the loader (catalog
+ * fetch included), for waiting on heights. Under the 15 s per-provider fetch
+ * timeout so this pack is never the catalog's slowest lane. A lookup still
+ * running after it keeps filling the cache for the next refresh. */
+export const KARTVERKET_CATALOG_WAIT_MS = 12 * 1000;
+/** A point Kartverket has no height for (some ferry quays and bridges) is not
+ * asked about again for this long. */
+export const KARTVERKET_NULL_TTL_MS = 6 * 60 * 60 * 1000;
+/** After a 429, a 5xx or a network failure, no lookup starts for this long,
+ * or for the Retry-After the service sent, bounded to [1 min, 1 h]. */
+export const KARTVERKET_FAILURE_BACKOFF_MS = 10 * 60 * 1000;
+export const KARTVERKET_MAX_BACKOFF_MS = 60 * 60 * 1000;
+export const KARTVERKET_MAX_RESPONSE_BYTES = 256 * 1024;
+/** Plausible Norwegian terrain: below sea level only at the shore, and no road
+ * camera sits above ~1,500 m. Anything outside is treated as no height. */
+export const KARTVERKET_HEIGHT_RANGE_M = Object.freeze({ min: -20, max: 2500 });
+/** Same identity the other CCTV upstream requests send. */
+export const KARTVERKET_USER_AGENT = 'gods-eye-view-cctv-proxy/1.0';
+
+ /** NYC DOT Traffic Management Center cameras: one keyless JSON list for the
+ * five boroughs (~980 cameras). Frames are stills synthesized from each
+ * camera UUID on the city's webcam host — never taken from the payload. */
+ export const NYC_CAMERAS_URL = 'https://webcams.nyctmc.org/api/cameras';
+ /** The only origin NYC camera frames may come from. The catalog's `imageUrl`
+ * is ignored; the registered path is always this origin plus a validated
+ * UUID plus `/image`. */
+ export const NYC_IMAGE_ORIGIN = 'https://webcams.nyctmc.org/api/cameras/';
+ export const NYC_IMAGE_URL = (id) => `${NYC_IMAGE_ORIGIN}${id}/image`;
+ export const NYC_CAMERA_ID_RE =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+ export const DEFAULT_NYC_MAX_SOURCES = 250;
+ /** Hard ceiling on the NYC catalog body. The live list is ~980 rows / ~250 KB;
+ * this only exists so an upstream that streams an unbounded body cannot be
+ * buffered without limit. */
+ export const NYC_MAX_CATALOG_BYTES = 4 * 1024 * 1024;
+ /** Ground-elevation prior in metres. Matches the New York CITY_POIS prior;
+ * the client's one-shot ground snap corrects it wherever 3D tiles load. */
+ export const NYC_GROUND_ELEVATION_M = 10;
+ /** Prioritization anchors: one per borough so a cap keeps citywide coverage
+ * rather than Midtown alone. */
+ export const NYC_ANCHORS = [
+ { lat: 40.758, lon: -73.9855 }, // Manhattan (Times Square)
+ { lat: 40.7128, lon: -74.006 }, // Lower Manhattan
+ { lat: 40.6782, lon: -73.9442 }, // Brooklyn
+ { lat: 40.7282, lon: -73.7949 }, // Queens
+ { lat: 40.8448, lon: -73.8648 }, // Bronx
+ { lat: 40.5795, lon: -74.1502 }, // Staten Island
+ ];
+
/** DelDOT CCTV: one keyless statewide JSON catalog; live video via RTMP-over-HTTP (rtmpt:80). */
export const DELDOT_CCTV_URL = 'https://tmc.deldot.gov/json/videocamera.json';
export const DEFAULT_DELDOT_MAX_SOURCES = 300;
diff --cc server/providers/cctv/sources.js
index 15f6df74b,43ba30994..018800357
--- a/server/providers/cctv/sources.js
+++ b/server/providers/cctv/sources.js
@@@ -65,17 -65,13 +65,24 @@@ import
DEFAULT_VEGVESEN_MAX_SOURCES,
VEGVESEN_MAX_CATALOG_BYTES,
NORWAY_ANCHORS,
+ KARTVERKET_HEIGHT_URL,
+ KARTVERKET_MAX_POINTS,
+ KARTVERKET_CONCURRENCY,
+ KARTVERKET_LOOKUP_TIMEOUT_MS,
+ KARTVERKET_CATALOG_WAIT_MS,
+ KARTVERKET_NULL_TTL_MS,
+ KARTVERKET_FAILURE_BACKOFF_MS,
+ KARTVERKET_MAX_BACKOFF_MS,
+ KARTVERKET_USER_AGENT,
+ KARTVERKET_MAX_RESPONSE_BYTES,
+ KARTVERKET_HEIGHT_RANGE_M,
+ NYC_CAMERAS_URL,
+ NYC_IMAGE_URL,
+ NYC_CAMERA_ID_RE,
+ DEFAULT_NYC_MAX_SOURCES,
+ NYC_MAX_CATALOG_BYTES,
+ NYC_GROUND_ELEVATION_M,
+ NYC_ANCHORS,
} from './constants.js';
import {
toFiniteNumber,
@@@ -93,7 -89,8 +100,8 @@@
isLikelyTexasCoordinate,
isLikelyNswCoordinate,
isLikelyCalgaryCoordinate,
- isLikelyNycCoordinate,
isLikelyNorwayCoordinate,
++ isLikelyNycCoordinate,
cameraDisplayCode,
rowArrayToObject,
prioritizeSources,
@@@ -1879,267 -1872,147 +1887,412 @@@ export async function loadVegvesenSourc
}
}
+/**
+ * Kartverket answers by rounded position: `{z, expires}`, where z is metres or
+ * null for "no height there". Heights never expire (camera positions barely
+ * change); nulls expire after KARTVERKET_NULL_TTL_MS. The 15-minute catalog
+ * refresh therefore only asks about new or moved cameras. Bounded well above
+ * the ~900 cameras the pack can load.
+ */
+const kartverketHeightCache = new Map();
+const KARTVERKET_CACHE_LIMIT = 5000;
+/** The lookup in flight, so overlapping catalog loads never start a second. */
+let kartverketPending = null;
+/** No lookup starts before this time (epoch ms) after a transport failure. */
+let kartverketBackoffUntil = 0;
+
+/** Cache key for one position, at the ~0.1 m precision the request sends. */
+const kartverketKey = (lon, lat) => `${lon.toFixed(6)},${lat.toFixed(6)}`;
+
+/** Forget cached heights, the backoff and any lookup in flight. Tests only. */
+export function clearKartverketHeightCache() {
+ kartverketHeightCache.clear();
+ kartverketPending = null;
+ kartverketBackoffUntil = 0;
+}
+
+/**
+ * How long to back off after a failed request: the Retry-After the service
+ * sent (seconds or an HTTP date), else the default, bounded to [1 min, 1 h].
+ *
+ * @param {?string} retryAfter - The Retry-After header, if any.
+ * @param {number} now - Epoch ms.
+ * @returns {number} Milliseconds.
+ */
+export function kartverketBackoffMs(retryAfter, now = Date.now()) {
+ let ms = KARTVERKET_FAILURE_BACKOFF_MS;
+ const text = String(retryAfter ?? '').trim();
+ if (/^\d+$/.test(text)) ms = Number(text) * 1000;
+ else if (text && Number.isFinite(Date.parse(text))) {
+ ms = Date.parse(text) - now;
+ }
+ return Math.max(60 * 1000, Math.min(KARTVERKET_MAX_BACKOFF_MS, ms));
+}
+
+/**
+ * Terrain heights above sea level (NN2000) from Kartverket's keyless
+ * point-height API, KARTVERKET_MAX_POINTS points per request. Each answer is
+ * matched back by the coordinates the API echoes, and only for points that
+ * request asked about, then reported through `into.set(key, z)` as its
+ * request lands, so a caller that stops waiting keeps what has arrived. `z` is
+ * metres, or null when the API has no usable height there.
+ *
+ * Over water `/punkt` returns the depth of the sea floor (`datakilde:
+ * dybdekurver`, `terreng: Havflate`; −547 m under Nordhordlandsbrua). Either
+ * marker counts as 0 m, the water surface. For the ~14 bridge cameras that is
+ * below the deck, but far closer than the sea floor or a flat prior.
+ *
+ * The first transport failure (a non-200 answer, a network error or the
+ * shared deadline) stops the lookup: no further requests start, and the
+ * failure is returned so the caller can back off. Points in failed requests
+ * are not reported, so they are asked again after the backoff.
+ *
+ * @param {Array<{lon:number, lat:number}>} points
+ * @param {{into?: {set: Function}, timeoutMs?: number}} [options]
+ * @returns {Promise<{heights: Map<string, ?number>, failure: ?{status: ?number, retryAfter: ?string}}>}
+ * `heights` is `into` when it is a Map, else a Map of what was reported.
+ */
+export async function fetchKartverketHeights(
+ points,
+ { into = new Map(), timeoutMs = KARTVERKET_LOOKUP_TIMEOUT_MS } = {},
+) {
+ const heights = into instanceof Map ? into : new Map();
+ const report = (key, z) => {
+ if (heights !== into) heights.set(key, z);
+ into.set(key, z);
+ };
+ const unique = Array.from(
+ new Map(
+ (points || [])
+ .filter((p) => isLikelyNorwayCoordinate(p?.lat, p?.lon))
+ .map((p) => [kartverketKey(p.lon, p.lat), p]),
+ ).values(),
+ );
+ let failure = null;
+ if (!unique.length) return { heights, failure };
+ const batches = [];
+ for (let i = 0; i < unique.length; i += KARTVERKET_MAX_POINTS) {
+ batches.push(unique.slice(i, i + KARTVERKET_MAX_POINTS));
+ }
+ const signal = AbortSignal.timeout(timeoutMs);
+ const fetchBatch = async (batch) => {
+ const asked = new Set(batch.map((p) => kartverketKey(p.lon, p.lat)));
+ const url = new URL(KARTVERKET_HEIGHT_URL);
+ url.searchParams.set(
+ 'punkter',
+ JSON.stringify(
+ batch.map((p) => [Number(p.lon.toFixed(6)), Number(p.lat.toFixed(6))]),
+ ),
+ );
+ url.searchParams.set('koordsys', '4258');
+ const resp = await fetch(url, {
+ headers: {
+ Accept: 'application/json',
+ 'User-Agent': KARTVERKET_USER_AGENT,
+ },
+ redirect: 'error',
+ signal,
+ });
+ if (!resp.ok) {
+ try {
+ await resp.body?.cancel();
+ } catch {
+ /* no-op */
+ }
+ const error = new Error(`HTTP ${resp.status}`);
+ error.status = resp.status;
+ error.retryAfter = resp.headers.get('retry-after');
+ throw error;
+ }
+ const payload = await readResponseJsonCapped(
+ resp,
+ KARTVERKET_MAX_RESPONSE_BYTES,
+ );
+ for (const point of Array.isArray(payload?.punkter)
+ ? payload.punkter
+ : []) {
+ const x = toFiniteNumber(point?.x);
+ const y = toFiniteNumber(point?.y);
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
+ const key = kartverketKey(x, y);
+ // Only the points this request asked about: an odd answer can neither
+ // grow the cache nor overwrite another camera.
+ if (!asked.has(key)) continue;
+ asked.delete(key);
+ // `z: null` means no height there; Number(null) would read 0.
+ const raw = point?.z;
+ let z =
+ raw === null || raw === undefined || raw === ''
+ ? NaN
+ : toFiniteNumber(raw);
+ if (
+ Number.isFinite(z) &&
+ (point?.datakilde === 'dybdekurver' || point?.terreng === 'Havflate')
+ ) {
+ z = 0;
+ }
+ const usable =
+ Number.isFinite(z) &&
+ z >= KARTVERKET_HEIGHT_RANGE_M.min &&
+ z <= KARTVERKET_HEIGHT_RANGE_M.max;
+ report(key, usable ? z : null);
+ }
+ };
+ let next = 0;
+ const worker = async () => {
+ while (next < batches.length && !failure) {
+ const batch = batches[next++];
+ try {
+ await fetchBatch(batch);
+ } catch (error) {
+ if (!failure) {
+ failure = {
+ status: Number.isFinite(error?.status) ? error.status : null,
+ retryAfter: error?.retryAfter ?? null,
+ };
+ console.warn(
+ '[CCTV] Kartverket height lookup failed:',
+ error?.message || error,
+ );
+ }
+ }
+ }
+ };
+ await Promise.all(
+ Array.from(
+ { length: Math.min(KARTVERKET_CONCURRENCY, batches.length) },
+ worker,
+ ),
+ );
+ return { heights, failure };
+}
+
+/**
+ * Give each Vegvesen camera its own terrain height as the ground prior, in
+ * place. Waits at most `waitMs` for positions it has no answer for; a lookup
+ * still running then keeps filling the cache for the next catalog refresh.
+ * Cameras without a height keep the flat prior. After a transport failure no
+ * lookup starts until the backoff ends, so a failing Kartverket costs one
+ * attempt, not one per refresh. Never throws. CCTV_VEGVESEN_HEIGHTS=0 turns it
+ * off.
+ *
+ * @param {Array<object>} cameras - Sources from vegvesenCameraToSource().
+ * @param {{waitMs?: number, now?: () => number}} [options]
+ * @returns {Promise<number>} How many cameras got a terrain height.
+ */
+export async function applyVegvesenGroundHeights(
+ cameras,
+ { waitMs = KARTVERKET_CATALOG_WAIT_MS, now = Date.now } = {},
+) {
+ if (String(process.env.CCTV_VEGVESEN_HEIGHTS || '1').trim() === '0') return 0;
+ const list = Array.isArray(cameras) ? cameras : [];
+ const startedAt = now();
+ const missing = list.filter((c) => {
+ const entry = kartverketHeightCache.get(kartverketKey(c.lon, c.lat));
+ return !entry || entry.expires <= startedAt;
+ });
+ if (
+ missing.length &&
+ !kartverketPending &&
+ startedAt >= kartverketBackoffUntil
+ ) {
+ if (kartverketHeightCache.size + missing.length > KARTVERKET_CACHE_LIMIT) {
+ kartverketHeightCache.clear();
+ }
+ const sink = {
+ set: (key, z) =>
+ kartverketHeightCache.set(key, {
+ z,
+ expires: z === null ? now() + KARTVERKET_NULL_TTL_MS : Infinity,
+ }),
+ };
+ kartverketPending = fetchKartverketHeights(missing, { into: sink })
+ .then(({ failure }) => {
+ if (failure) {
+ kartverketBackoffUntil =
+ now() + kartverketBackoffMs(failure.retryAfter, now());
+ }
+ })
+ .catch((error) => {
+ kartverketBackoffUntil = now() + KARTVERKET_FAILURE_BACKOFF_MS;
+ console.warn(
+ '[CCTV] Kartverket height lookup error:',
+ error?.message || error,
+ );
+ })
+ .finally(() => {
+ kartverketPending = null;
+ });
+ }
+ if (missing.length && kartverketPending && waitMs > 0) {
+ let timer;
+ await Promise.race([
+ kartverketPending,
+ new Promise((resolve) => {
+ timer = setTimeout(resolve, waitMs);
+ timer.unref?.();
+ }),
+ ]);
+ clearTimeout(timer);
+ }
+ let applied = 0;
+ for (const camera of list) {
+ const z = kartverketHeightCache.get(
+ kartverketKey(camera.lon, camera.lat),
+ )?.z;
+ if (!Number.isFinite(z)) continue;
+ camera.groundElevationM = Math.round(z * 10) / 10;
+ applied += 1;
+ }
+ if (list.length) {
+ console.log(
+ `[CCTV] Kartverket ground heights: ${applied}/${list.length} Vegvesen cameras`,
+ );
+ }
+ return applied;
+}
++
+ const NYC_BOROUGHS = new Set([
+ 'Manhattan',
+ 'Brooklyn',
+ 'Queens',
+ 'Bronx',
+ 'Staten Island',
+ ]);
+
+ /** NYC TMC publishes `isOnline` as the strings "true"/"false". */
+ export function nycCameraIsOnline(value) {
+ return (
+ value === true ||
+ String(value ?? '')
+ .trim()
+ .toLowerCase() === 'true'
+ );
+ }
+
+ /**
+ * Label for one NYC camera: the intersection an operator recognises
+ * ("Central Park West @ 86 St"). The catalog's `area` is the borough, not
+ * a facing, and is not part of the name.
+ *
+ * @param {object} record - Raw TMC camera row.
+ * @param {string} cameraId - Derived stable id.
+ * @returns {string}
+ */
+ export function nycCameraName(record, cameraId) {
+ const name = String(record?.name ?? '').trim();
+ if (name) return name;
+ const short = String(cameraId || '')
+ .replace(/^nyc-/, '')
+ .slice(0, 8);
+ return short ? `NYC Camera ${short}` : 'NYC Camera';
+ }
+
+ /**
+ * One NYC DOT TMC camera row -> one catalog source, or null.
+ *
+ * Frame URLs are synthesized from a validated UUID on the pinned TMC image
+ * origin. The payload's `imageUrl` is ignored so a catalog edit cannot steer
+ * the frame proxy off-host. There is no heading in the feed; headings use
+ * the shared id-hash fallback at low confidence, like Calgary and Fintraffic.
+ *
+ * @param {object} record - Raw TMC camera row.
+ * @returns {?object}
+ */
+ export function nycCameraToSource(record) {
+ if (!record || typeof record !== 'object') return null;
+ if (!nycCameraIsOnline(record.isOnline)) return null;
+
+ const lat = toFiniteNumber(record.latitude);
+ const lon = toFiniteNumber(record.longitude);
+ if (!isLikelyNycCoordinate(lat, lon)) return null;
+
+ const uuid = String(record.id ?? '').trim();
+ if (!NYC_CAMERA_ID_RE.test(uuid)) return null;
+ const cameraId = `nyc-${uuid.toLowerCase()}`;
+ const imageUrl = NYC_IMAGE_URL(uuid);
+ const name = nycCameraName(record, cameraId);
+ const area = String(record.area ?? '').trim();
+ const city = NYC_BOROUGHS.has(area) ? area : 'New York';
+
+ return {
+ id: cameraId,
+ name,
+ city,
+ cityId: 'nyc',
+ provider: 'NYC DOT Traffic Management Center',
+ lat,
+ lon,
+ headingDeg: fallbackHeadingFromId(cameraId),
+ headingConfidence: 'low',
+ pitchDeg: -18,
+ fovDeg: 44,
+ rangeM: 145,
+ mountHeightM: 8,
+ groundElevationM: NYC_GROUND_ELEVATION_M,
+ feedType: 'image',
+ url: imageUrl,
+ snapshotUrl: imageUrl,
+ sourceKind: 'nyc-dot-tmc',
+ license: 'Public NYC DOT Traffic Management Center traffic camera',
+ code: cameraDisplayCode(name.toUpperCase()),
+ };
+ }
+
+ /**
+ * Fetch NYC DOT Traffic Management Center cameras from the keyless
+ * `webcams.nyctmc.org` catalog. Frames are stills on that same host,
+ * registered from a validated UUID rather than from the payload URL.
+ *
+ * @returns {Promise<Array<object>>} Normalized camera source objects.
+ */
+ export async function loadNycSourcesFromOpenData() {
+ try {
+ const endpoint = process.env.CCTV_NYC_CAMERAS_URL || NYC_CAMERAS_URL;
+ const resp = await fetch(endpoint, {
+ headers: { Accept: 'application/json' },
+ redirect: 'manual',
+ signal: AbortSignal.timeout(CCTV_SOURCE_FETCH_TIMEOUT_MS),
+ });
+ const discard = async () => {
+ try {
+ await resp.body?.cancel();
+ } catch {
+ /* no-op */
+ }
+ return [];
+ };
+ if (resp.status >= 300 && resp.status < 400) {
+ console.warn('[CCTV] NYC catalog redirected; redirects are not followed');
+ return discard();
+ }
+ if (!resp.ok) {
+ console.warn('[CCTV] NYC camera download failed:', resp.status);
+ return discard();
+ }
+ const rows = await readResponseJsonCapped(resp, NYC_MAX_CATALOG_BYTES);
+ if (!Array.isArray(rows)) return [];
+ const cameras = [];
+ const seen = new Set();
+ for (const record of rows) {
+ const camera = nycCameraToSource(record);
+ if (!camera || seen.has(camera.id)) continue;
+ seen.add(camera.id);
+ cameras.push(camera);
+ }
+ const maxRaw = Number(
+ process.env.CCTV_NYC_MAX_SOURCES || DEFAULT_NYC_MAX_SOURCES,
+ );
+ const maxCount = Number.isFinite(maxRaw)
+ ? Math.max(8, Math.min(400, Math.floor(maxRaw)))
+ : DEFAULT_NYC_MAX_SOURCES;
+ const prioritized = prioritizeSources(cameras, maxCount, NYC_ANCHORS);
+ console.log(
+ `[CCTV] Loaded NYC camera sources: ${cameras.length} (using nearest ${prioritized.length})`,
+ );
+ return prioritized;
+ } catch (error) {
+ console.warn('[CCTV] NYC camera download error:', error?.message || error);
+ return [];
+ }
+ }
diff --cc src/data/dataCredits.js
index aa8e8f489,e68caddb4..dde385bea
--- a/src/data/dataCredits.js
+++ b/src/data/dataCredits.js
@@@ -245,10 -252,15 +252,17 @@@ export const DATA_CREDITS =
html:
'Road cameras (Norway): contains data under the ' +
'<a href="https://data.norge.no/nlod/en/2.0" target="_blank" rel="noopener">Norwegian licence for Open Government data (NLOD)</a> ' +
- 'distributed by Statens vegvesen',
+ 'distributed by Statens vegvesen · camera ground heights © ' +
+ '<a href="https://kartverket.no/en/api-and-data/terrengdata" target="_blank" rel="noopener">Kartverket</a> ' +
+ '(<a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>)',
},
+ {
+ key: 'nyc-cctv',
+ html:
+ 'CCTV cameras &amp; frames (New York City, when enabled): ' +
+ '<a href="https://webcams.nyctmc.org/" target="_blank" rel="noopener">NYC DOT Traffic Management Center</a>. ' +
+ NYC_DOT_DISCLAIMER,
+ },
{
key: 'gbfs',
html: 'Bikeshare availability: GBFS operator feeds (e.g. Austin BCycle)',