feat(cameras): booth camera tiles — latest snapshot at rest, live video while a vehicle is in view
Footer camera chips open/close a tile per camera (bottom right, ~15% wide, stacking leftwards); the open set is a per-user preference (users.open_cameras). A tile shows the camera's newest entry/exit snapshot and switches to live video while that camera pushes vehicle events (per-camera activity, same 30 s TTL as lane status). - devices: RTSP MJPEG client + RFC 2435 RTP/JPEG reassembly; Hikvision openLiveStream() on the sub-stream (x02, must be MJPEG — H.264 is refused with that reason) - server: CameraLiveHub (one shared upstream per camera, latest-frame delivery, fps cap, linger, backoff), CameraActivity, /api/cameras/:id/latest-snapshot, WS /api/cameras/:id/live (shared handshake auth with /api/ws + device:read), PUT /api/auth/open-cameras, migration 0033 (open_cameras + snapshot device/time index) - web: CameraDock, footer toggles, binary frames in the platform socket (Tauri too) - .gitattributes: *.jpg / *.bin binary (byte-exact test fixtures) Verified on park-lab cameras end to end and in headless Firefox. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
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<LiveViewer, { lastSent: number }>;
|
||||
source: LiveVideoSource | null;
|
||||
status: LiveStatus;
|
||||
attempt: number;
|
||||
linger: ReturnType<typeof setTimeout> | null;
|
||||
retry: ReturnType<typeof setTimeout> | 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<string, Upstream>();
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user