import type { FastifyBaseLogger } from "fastify"; import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices"; // Live camera video for the booth's camera tiles. ONE upstream session per camera, // shared by every viewer (booth tab, desktop shell) and torn down a few seconds after // the last viewer leaves — never one camera session per tab (a camera has few stream // slots, and the ANPR loop pulls stills from the same unit). // // Frames are complete JPEGs (the driver reassembles RTP/JPEG; nothing is decoded here). // Delivery is LATEST-FRAME-ONLY: a viewer whose socket still holds unsent bytes simply // misses frames, so a slow client can never grow server memory, and a per-viewer frame // cap keeps the desktop shell's IPC light. Advisory viewing only: nothing here touches // the ledger, a gate or a barrier. See wiki/decisions/camera-live-view.md. export type LiveStatus = | { state: "connecting" } | { state: "live" } | { state: "retrying"; reason: string } | { state: "unavailable"; reason: string }; export interface LiveViewer { sendFrame(jpeg: Buffer): void; sendStatus(status: LiveStatus): void; /** True while this viewer's transport still has unsent bytes: skip the frame. */ busy(): boolean; } /** Resolve a camera id to its live-stream capability, or a reason it has none. */ export type LiveResolver = (deviceId: string) => LiveStreamDevice | string; export interface CameraLiveOptions { /** Keep the upstream this long after the last viewer leaves (re-render churn). */ lingerMs?: number; /** Per-viewer frame cap. The cameras send 12.5–20 fps; 10 is plenty to watch a car. */ maxFps?: number; /** Backoff ceiling for reconnects while viewers are present. */ maxRetryMs?: number; /** Retry delay after a non-retryable failure (codec/driver), in case it is fixed. */ unavailableRetryMs?: number; } interface Upstream { readonly deviceId: string; readonly viewers: Map; source: LiveVideoSource | null; status: LiveStatus; attempt: number; linger: ReturnType | null; retry: ReturnType | null; } export function liveMaxFps(): number { const raw = Number(process.env.CAMERA_LIVE_MAX_FPS ?? 10); return Number.isFinite(raw) && raw > 0 ? raw : 10; } export class CameraLiveHub { readonly #resolve: LiveResolver; readonly #logger: FastifyBaseLogger; readonly #lingerMs: number; readonly #minFrameGapMs: number; readonly #maxRetryMs: number; readonly #unavailableRetryMs: number; readonly #upstreams = new Map(); constructor(resolve: LiveResolver, logger: FastifyBaseLogger, opts: CameraLiveOptions = {}) { this.#resolve = resolve; this.#logger = logger; this.#lingerMs = opts.lingerMs ?? 5000; this.#minFrameGapMs = 1000 / (opts.maxFps ?? liveMaxFps()); this.#maxRetryMs = opts.maxRetryMs ?? 30_000; this.#unavailableRetryMs = opts.unavailableRetryMs ?? 60_000; } /** Number of open upstream sessions (diagnostic / tests). */ get upstreamCount(): number { return [...this.#upstreams.values()].filter((u) => u.source !== null).length; } subscribe(deviceId: string, viewer: LiveViewer): () => void { let up = this.#upstreams.get(deviceId); if (!up) { up = { deviceId, viewers: new Map(), source: null, status: { state: "connecting" }, attempt: 0, linger: null, retry: null }; this.#upstreams.set(deviceId, up); } if (up.linger) { clearTimeout(up.linger); up.linger = null; } if (!up.source && !up.retry) { up.status = { state: "connecting" }; this.#start(up); // may settle the status at once (e.g. "unavailable") } // Added after the start so the newcomer gets the CURRENT status exactly once. up.viewers.set(viewer, { lastSent: 0 }); viewer.sendStatus(up.status); const u = up; let done = false; return () => { if (done) return; done = true; u.viewers.delete(viewer); if (u.viewers.size === 0 && !u.linger) { u.linger = setTimeout(() => this.#teardown(u), this.#lingerMs); u.linger.unref?.(); } }; } stopAll(): void { for (const up of [...this.#upstreams.values()]) this.#teardown(up); } #start(up: Upstream): void { const dev = this.#resolve(up.deviceId); if (typeof dev === "string") { this.#setStatus(up, { state: "unavailable", reason: dev }); return; // not a live-capable camera: nothing to retry } let source: LiveVideoSource; try { source = dev.openLiveStream(); } catch (err) { // A driver that cannot even build a session (bad config): report it; the next // subscribe tries again. this.#setStatus(up, { state: "unavailable", reason: (err as Error).message }); return; } up.source = source; let gotFrame = false; source.onFrame((jpeg) => { if (up.source !== source) return; if (!gotFrame) { gotFrame = true; up.attempt = 0; this.#setStatus(up, { state: "live" }); } const now = Date.now(); for (const [viewer, st] of up.viewers) { if (now - st.lastSent < this.#minFrameGapMs || viewer.busy()) continue; st.lastSent = now; try { viewer.sendFrame(jpeg); } catch { /* a broken viewer is removed by its own close handler */ } } }); source.onEnd((err) => this.#onEnded(up, source, err)); source.start().catch(() => undefined); // failures arrive through onEnd } #onEnded(up: Upstream, source: LiveVideoSource | null, err?: Error): void { if (source && up.source !== source) return; // a stale session up.source = null; if (up.viewers.size === 0 || !this.#upstreams.has(up.deviceId)) return; const reason = err?.message ?? "stream ended"; const retryable = (err as { retryable?: boolean } | undefined)?.retryable !== false; let delay: number; if (retryable) { delay = Math.min(this.#maxRetryMs, 1000 * 2 ** up.attempt); up.attempt++; this.#setStatus(up, { state: "retrying", reason }); } else { delay = this.#unavailableRetryMs; this.#setStatus(up, { state: "unavailable", reason }); } // Once, not per retry: a camera that is down for hours must not flood the log. if (up.attempt <= 1) this.#logger.warn(`camera-live ${up.deviceId}: ${reason}`); up.retry = setTimeout(() => { up.retry = null; if (up.viewers.size > 0 && !up.source) this.#start(up); }, delay); up.retry.unref?.(); } #setStatus(up: Upstream, status: LiveStatus): void { up.status = status; for (const viewer of up.viewers.keys()) { try { viewer.sendStatus(status); } catch { /* ignore */ } } } #teardown(up: Upstream): void { if (up.linger) clearTimeout(up.linger); if (up.retry) clearTimeout(up.retry); up.linger = null; up.retry = null; const source = up.source; up.source = null; this.#upstreams.delete(up.deviceId); source?.stop(); } }