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:
2026-11-17 12:48:50 +01:00
parent b6f7ea65a4
commit 39fb5fb7c2
36 changed files with 2067 additions and 45 deletions
+2
View File
@@ -6,3 +6,5 @@
# raw sources are kept byte-for-byte as dropped in # raw sources are kept byte-for-byte as dropped in
wiki/raw/** -text wiki/raw/** -text
*.jpg binary
*.bin binary
+52
View File
@@ -0,0 +1,52 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FastifyBaseLogger } from "fastify";
import { CameraActivity } from "./camera-activity.js";
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
// Per-camera activity drives the booth tiles' snapshot→live switch: one "active" edge
// per run of pushes, re-armed by each push, one "idle" edge TTL after the last push.
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() } as unknown as FastifyBaseLogger;
let seen: CameraActivityEvent[];
let off: () => void;
beforeEach(() => {
vi.useFakeTimers();
seen = [];
off = deviceEvents.onCameraActivity((e) => seen.push(e));
});
afterEach(() => {
off();
vi.useRealTimers();
});
describe("CameraActivity", () => {
it("emits active once, re-arms on each push, idles after the TTL", () => {
const a = new CameraActivity(logger, 30_000);
a.vehicleDetected("cam1");
vi.advanceTimersByTime(20_000);
a.vehicleDetected("cam1"); // re-arm
expect(seen).toEqual([{ deviceId: "cam1", active: true }]);
expect(a.snapshot()).toEqual(["cam1"]);
vi.advanceTimersByTime(29_000);
expect(seen).toHaveLength(1);
vi.advanceTimersByTime(1_000);
expect(seen).toEqual([
{ deviceId: "cam1", active: true },
{ deviceId: "cam1", active: false },
]);
expect(a.snapshot()).toEqual([]);
});
it("tracks cameras independently", () => {
const a = new CameraActivity(logger, 1_000);
a.vehicleDetected("entry");
vi.advanceTimersByTime(600);
a.vehicleDetected("exit");
vi.advanceTimersByTime(400);
expect(a.snapshot()).toEqual(["exit"]);
a.stop();
vi.advanceTimersByTime(5_000);
expect(seen.filter((e) => !e.active)).toEqual([{ deviceId: "entry", active: false }]);
});
});
+50
View File
@@ -0,0 +1,50 @@
import type { FastifyBaseLogger } from "fastify";
import { deviceEvents, type CameraActivityEvent } from "./device-events.js";
import { busyTtlMs } from "./lane-status.js";
// Per-CAMERA "a vehicle is in view" state, for the booth camera tiles: a tile shows the
// camera's latest snapshot and switches to live video while its camera is active. Same
// signal and TTL as LaneStatus (vehicle `active` pushes, no leave event, 30 s after the
// last push) but keyed by camera, not lane: on a shared lane (park-lab: an entry and an
// exit camera on one physical lane) only the camera that saw the car goes live.
// ADVISORY ONLY — it gates nothing. See wiki/decisions/camera-live-view.md.
export type { CameraActivityEvent };
export class CameraActivity {
readonly #logger: FastifyBaseLogger;
readonly #ttlMs: number;
readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
constructor(logger: FastifyBaseLogger, ttlMs = busyTtlMs()) {
this.#logger = logger;
this.#ttlMs = ttlMs;
}
/** Camera ids currently active (for the WS hello). */
snapshot(): string[] {
return [...this.#timers.keys()];
}
/** A vehicle push from `deviceId`: mark it active and (re)arm its clear. */
vehicleDetected(deviceId: string): void {
const existing = this.#timers.get(deviceId);
if (existing) clearTimeout(existing);
const timer = setTimeout(() => {
this.#timers.delete(deviceId);
this.#logger.debug(`camera-activity: ${deviceId} -> idle`);
deviceEvents.emitCameraActivity({ deviceId, active: false });
}, this.#ttlMs);
timer.unref?.();
this.#timers.set(deviceId, timer);
if (!existing) {
this.#logger.debug(`camera-activity: ${deviceId} -> active`);
deviceEvents.emitCameraActivity({ deviceId, active: true });
}
}
stop(): void {
for (const t of this.#timers.values()) clearTimeout(t);
this.#timers.clear();
}
}
+149
View File
@@ -0,0 +1,149 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FastifyBaseLogger } from "fastify";
import type { LiveStreamDevice, LiveVideoSource } from "@parking/devices";
import { CameraLiveHub, type LiveStatus, type LiveViewer } from "./camera-live.js";
// The hub's contract: one upstream per camera however many viewers, latest-frame-only
// delivery (a busy viewer misses frames, never queues them), teardown after the last
// viewer leaves (with a linger), reconnect with backoff while viewers remain, and a
// non-retryable failure (codec) reported as "unavailable".
const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as unknown as FastifyBaseLogger;
class FakeSource implements LiveVideoSource {
frameCbs: Array<(f: Buffer) => void> = [];
endCbs: Array<(e?: Error) => void> = [];
stopped = false;
constructor(private readonly fail?: Error) {}
async start() {
if (this.fail) {
queueMicrotask(() => this.end(this.fail));
throw this.fail;
}
}
stop() {
this.stopped = true;
this.end();
}
onFrame(cb: (f: Buffer) => void) {
this.frameCbs.push(cb);
}
onEnd(cb: (e?: Error) => void) {
this.endCbs.push(cb);
}
frame(b = Buffer.from([0xff, 0xd8])) {
for (const cb of this.frameCbs) cb(b);
}
end(err?: Error) {
for (const cb of this.endCbs.splice(0)) cb(err);
}
}
function viewer(busy = false) {
const frames: Buffer[] = [];
const statuses: LiveStatus[] = [];
const v: LiveViewer & { frames: Buffer[]; statuses: LiveStatus[]; isBusy: boolean } = {
frames,
statuses,
isBusy: busy,
sendFrame: (f) => frames.push(f),
sendStatus: (s) => statuses.push(s),
busy: () => v.isBusy,
};
return v;
}
let sources: FakeSource[];
let nextFail: Error | undefined;
const device: LiveStreamDevice = {
openLiveStream: () => {
const s = new FakeSource(nextFail);
sources.push(s);
return s;
},
};
beforeEach(() => {
vi.useFakeTimers();
sources = [];
nextFail = undefined;
});
afterEach(() => vi.useRealTimers());
describe("CameraLiveHub", () => {
it("shares one upstream between viewers and tears it down after the last leaves", async () => {
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000, maxFps: 1000 });
const a = viewer();
const b = viewer();
const offA = hub.subscribe("cam1", a);
const offB = hub.subscribe("cam1", b);
expect(sources).toHaveLength(1);
sources[0]!.frame();
expect(a.frames).toHaveLength(1);
expect(b.frames).toHaveLength(1);
expect(a.statuses.at(-1)).toEqual({ state: "live" });
offA();
offB();
expect(sources[0]!.stopped).toBe(false); // lingering
vi.advanceTimersByTime(1000);
expect(sources[0]!.stopped).toBe(true);
expect(hub.upstreamCount).toBe(0);
});
it("a viewer returning within the linger reuses the session", () => {
const hub = new CameraLiveHub(() => device, logger, { lingerMs: 1000 });
const off = hub.subscribe("cam1", viewer());
off();
vi.advanceTimersByTime(500);
hub.subscribe("cam1", viewer());
vi.advanceTimersByTime(5000);
expect(sources).toHaveLength(1);
expect(sources[0]!.stopped).toBe(false);
});
it("skips frames for a busy viewer and caps the frame rate", () => {
const hub = new CameraLiveHub(() => device, logger, { maxFps: 10 });
const slow = viewer(true);
const fast = viewer();
hub.subscribe("cam1", slow);
hub.subscribe("cam1", fast);
for (let i = 0; i < 5; i++) sources[0]!.frame(); // same instant: only the first passes the cap
expect(fast.frames).toHaveLength(1);
expect(slow.frames).toHaveLength(0);
vi.advanceTimersByTime(100);
slow.isBusy = false;
sources[0]!.frame();
expect(fast.frames).toHaveLength(2);
expect(slow.frames).toHaveLength(1);
});
it("reconnects with backoff while viewers remain", async () => {
const hub = new CameraLiveHub(() => device, logger);
const v = viewer();
hub.subscribe("cam1", v);
sources[0]!.end(new Error("RTSP connection closed"));
expect(v.statuses.at(-1)).toEqual({ state: "retrying", reason: "RTSP connection closed" });
vi.advanceTimersByTime(1000);
expect(sources).toHaveLength(2);
});
it("reports a non-retryable failure as unavailable", async () => {
const hub = new CameraLiveHub(() => device, logger, { unavailableRetryMs: 60_000 });
nextFail = Object.assign(new Error("camera stream is H264, not MJPEG"), { retryable: false });
const v = viewer();
hub.subscribe("cam1", v);
await vi.advanceTimersByTimeAsync(0);
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "camera stream is H264, not MJPEG" });
vi.advanceTimersByTime(59_000);
expect(sources).toHaveLength(1);
});
it("a camera without live support is unavailable and opens nothing", () => {
const hub = new CameraLiveHub(() => "live view not supported by this camera driver", logger);
const v = viewer();
hub.subscribe("cam1", v);
expect(v.statuses.at(-1)).toEqual({ state: "unavailable", reason: "live view not supported by this camera driver" });
expect(hub.upstreamCount).toBe(0);
});
});
+199
View File
@@ -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();
}
}
+16
View File
@@ -89,6 +89,13 @@ export interface DeviceStatusEvent {
* gate (it never blocks a ticket or opens a barrier). "busy" is set by a vehicle * gate (it never blocks a ticket or opens a barrier). "busy" is set by a vehicle
* `active` event; it auto-clears to "free" after a timeout (this camera class sends * `active` event; it auto-clears to "free" after a timeout (this camera class sends
* no leave/`inactive` signal — see wiki/entities/lpr-camera.md). */ * no leave/`inactive` signal — see wiki/entities/lpr-camera.md). */
/** A camera started/stopped seeing a vehicle (per camera, TTL-cleared). Drives the
* booth camera tiles' snapshot→live switch. Advisory only. See camera-activity.ts. */
export interface CameraActivityEvent {
readonly deviceId: string;
readonly active: boolean;
}
export interface LaneStatusEvent { export interface LaneStatusEvent {
readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity) readonly entry: boolean; // true = busy (a vehicle is at the entry vicinity)
readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity) readonly exit: boolean; // true = busy (a vehicle is at the exit vicinity)
@@ -193,6 +200,15 @@ class DeviceEventBus extends EventEmitter {
return () => this.off("lane-status", cb); return () => this.off("lane-status", cb);
} }
/** Emitted when a camera's vehicle activity flips (camera-activity.ts). Advisory. */
emitCameraActivity(event: CameraActivityEvent): void {
this.emit("camera-activity", event);
}
onCameraActivity(cb: (event: CameraActivityEvent) => void): () => void {
this.on("camera-activity", cb);
return () => this.off("camera-activity", cb);
}
/** Emitted whenever a lane's RADAR presence CHANGES (a presence input shorted/cleared /** Emitted whenever a lane's RADAR presence CHANGES (a presence input shorted/cleared
* at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */ * at an entry/exit barrier). Drives the booth barrier light's blink. Advisory only. */
emitLanePresence(event: LanePresenceEvent): void { emitLanePresence(event: LanePresenceEvent): void {
+47
View File
@@ -37,6 +37,24 @@ interface FontScaleBody {
fontScale: number; fontScale: number;
} }
// Booth camera tiles the user left open (camera device ids, in opening order). Bounded:
// a booth has a handful of cameras; the cap stops a client from storing junk.
const OPEN_CAMERAS_MAX = 8;
const DEVICE_ID_MAX = 64;
interface OpenCamerasBody {
openCameras: string[];
}
/** users.open_cameras (JSON text) → string[]; anything malformed reads as none open. */
function parseOpenCameras(raw: string | null | undefined): string[] {
try {
const v: unknown = JSON.parse(raw ?? "[]");
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, OPEN_CAMERAS_MAX) : [];
} catch {
return [];
}
}
// Self-service profile: a signed-in user edits their OWN display name + email. This is // Self-service profile: a signed-in user edits their OWN display name + email. This is
// NOT the admin user-management path (routes/users.ts) — it only ever touches the caller // NOT the admin user-management path (routes/users.ts) — it only ever touches the caller
// (req.user.sub), needs no `user:*` permission, and can't change username, role, or any // (req.user.sub), needs no `user:*` permission, and can't change username, role, or any
@@ -90,6 +108,7 @@ function sessionView(
language: string; language: string;
theme: string; theme: string;
fontScale: number; fontScale: number;
openCameras?: string | null;
fullName?: string | null; fullName?: string | null;
email?: string | null; email?: string | null;
}, },
@@ -106,6 +125,7 @@ function sessionView(
language: user.language, language: user.language,
theme: user.theme, theme: user.theme,
fontScale: user.fontScale, fontScale: user.fontScale,
openCameras: parseOpenCameras(user.openCameras),
fullName: user.fullName ?? null, fullName: user.fullName ?? null,
email: user.email ?? null, email: user.email ?? null,
// Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes // Effective venue modules (entitled ∩ activated) so the SPA can hide nav/routes
@@ -219,6 +239,33 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
}, },
); );
// Which booth camera tiles I left open (any signed-in user; only touches the caller).
// Persisted like `theme`, restored on the next login from any booth. Ids are not
// checked against `devices`: a removed camera's tile is simply not rendered.
app.put<{ Body: OpenCamerasBody }>(
"/api/auth/open-cameras",
{ preHandler: requireAuth },
async (req, reply) => {
const raw = req.body?.openCameras;
if (
!Array.isArray(raw) ||
raw.length > OPEN_CAMERAS_MAX ||
!raw.every((x) => typeof x === "string" && x.length > 0 && x.length <= DEVICE_ID_MAX)
) {
return reply
.code(400)
.send({ error: `openCameras must be up to ${OPEN_CAMERAS_MAX} device ids` });
}
const openCameras = [...new Set(raw as string[])];
await db
.update(users)
.set({ openCameras: JSON.stringify(openCameras) })
.where(eq(users.id, req.user.sub))
.run();
return { openCameras };
},
);
// Edit MY own display name / email (any signed-in user; no permission needed — it only // Edit MY own display name / email (any signed-in user; no permission needed — it only
// touches the caller). Cannot change username or role — those stay admin-only (users.ts). // touches the caller). Cannot change username or role — those stay admin-only (users.ts).
app.put<{ Body: ProfileBody }>( app.put<{ Body: ProfileBody }>(
+137
View File
@@ -0,0 +1,137 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { devices, snapshots, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { login, seedUser } from "../test-helpers.js";
// Booth camera tiles: latest-snapshot lookup (session:read), the live socket's auth gate
// (same handshake as /api/ws, then device:read), and the per-user open-tiles preference.
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
// A Dahua camera: no live-view capability, so the socket answers without any network.
db.insert(devices)
.values({ id: "cam-dahua", category: "camera", driverId: "dahua", config: { host: "192.0.2.1" } })
.run();
db.insert(devices).values({ id: "relay-1", category: "access", driverId: "stub-access", config: {} }).run();
});
afterEach(async () => {
await app.close();
close();
});
function shot(id: string, deviceId: string, capturedAt: string) {
db.insert(snapshots)
.values({ id, direction: "entry", deviceId, identity: "x", contentType: "image/jpeg", bytes: Buffer.from([1]), capturedAt })
.run();
}
describe("GET /api/cameras/:id/latest-snapshot", () => {
it("returns the camera's newest snapshot", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
shot("s1", "cam-dahua", "2026-11-17T10:00:00.000Z");
shot("s2", "cam-dahua", "2026-11-17T11:00:00.000Z");
shot("s3", "other", "2026-11-17T12:00:00.000Z");
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: auth.cookie } });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ id: "s2", direction: "entry" });
});
it("404s when the camera has none, 403s without session:read", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const admin = await login(app, "admin", "pw");
const none = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: admin.cookie } });
expect(none.statusCode).toBe(404);
await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] });
const dev = await login(app, "dev", "pw");
const res = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie: dev.cookie } });
expect(res.statusCode).toBe(403);
});
});
describe("WS /api/cameras/:id/live", () => {
const origin = "http://booth.local:8080";
it("rejects a cross-origin handshake", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
await expect(
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin: "http://evil.example", host: "booth.local:8080" } }),
).rejects.toThrow(/403/);
});
it("rejects a role without device:read", async () => {
await seedUser(db, { username: "cash", password: "pw", roleId: "cashier2", permissions: ["session:read"] });
const auth = await login(app, "cash", "pw");
await expect(
app.injectWS("/api/cameras/cam-dahua/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
).rejects.toThrow(/403/);
});
it("404s a device that is not a camera", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
await expect(
app.injectWS("/api/cameras/relay-1/live", { headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } }),
).rejects.toThrow(/404/);
});
it("tells the viewer when the camera has no live view", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
let resolveMsg!: (m: string) => void;
const first = new Promise<string>((r) => (resolveMsg = r));
const ws = await app.injectWS(
"/api/cameras/cam-dahua/live",
{ headers: { cookie: auth.cookie, origin, host: "booth.local:8080" } },
{ onInit: (sock) => sock.once("message", (d) => resolveMsg(String(d))) },
);
const msg = await first;
expect(JSON.parse(msg)).toEqual({
kind: "status",
state: "unavailable",
reason: "live view not supported by this camera driver",
});
ws.terminate();
});
});
describe("PUT /api/auth/open-cameras", () => {
it("persists the open tiles and returns them on /me", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
const put = await app.inject({
method: "PUT",
url: "/api/auth/open-cameras",
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
payload: { openCameras: ["cam-b", "cam-a", "cam-b"] },
});
expect(put.statusCode).toBe(200);
expect(put.json()).toEqual({ openCameras: ["cam-b", "cam-a"] });
const me = await app.inject({ url: "/api/auth/me", headers: { cookie: auth.cookie } });
expect(me.json().openCameras).toEqual(["cam-b", "cam-a"]);
});
it("rejects a malformed list", async () => {
await seedUser(db, { username: "admin", password: "pw" });
const auth = await login(app, "admin", "pw");
const res = await app.inject({
method: "PUT",
url: "/api/auth/open-cameras",
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
payload: { openCameras: Array.from({ length: 9 }, (_, i) => `c${i}`) },
});
expect(res.statusCode).toBe(400);
});
});
+83
View File
@@ -0,0 +1,83 @@
import type { FastifyInstance } from "fastify";
import { desc, devices, eq, snapshots, type Db } from "@parking/db";
import { isLiveStreamDevice } from "@parking/devices";
import { requirePermission, roleHasPermissions } from "../auth.js";
import { buildCamera } from "../snapshot.js";
import type { CameraLiveHub, LiveResolver, LiveStatus } from "../camera-live.js";
import { authenticateWsHandshake } from "./ws.js";
// The booth's camera tiles (wiki/decisions/camera-live-view.md):
// - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest
// entry/exit evidence still this camera captured (metadata; bytes stay at
// /api/snapshots/:id). Evidence → `session:read`, like every snapshot read.
// - WS /api/cameras/:deviceId/live — live video while the camera sees a vehicle.
// Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie),
// then `device:read` (the footer's permission). Server → client: text JSON
// `{kind:"status", ...LiveStatus}` and binary messages, each one complete JPEG.
// Advisory viewing only: no route here writes anything.
/** Bytes a viewer's socket may hold unsent before frames are skipped for it. */
const MAX_BUFFERED_BYTES = 256 * 1024;
/** Resolve a camera id to its live capability, or the reason it has none. */
export function liveResolverFor(db: Db): LiveResolver {
return (deviceId) => {
const row = db.select().from(devices).where(eq(devices.id, deviceId)).get();
if (!row || row.category !== "camera") return "unknown camera";
if (!row.enabled) return "camera disabled";
const camera = buildCamera(row);
if (!camera) return "camera driver unavailable";
if (!isLiveStreamDevice(camera)) return "live view not supported by this camera driver";
return camera;
};
}
export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLiveHub): Promise<void> {
app.get<{ Params: { deviceId: string } }>(
"/api/cameras/:deviceId/latest-snapshot",
{ preHandler: requirePermission("session:read") },
async (req, reply) => {
// Uses snapshots_device_time_idx (migration 0033): one index seek, not a scan.
const row = db
.select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt })
.from(snapshots)
.where(eq(snapshots.deviceId, req.params.deviceId))
.orderBy(desc(snapshots.capturedAt))
.limit(1)
.get();
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
return row;
},
);
app.get<{ Params: { deviceId: string } }>(
"/api/cameras/:deviceId/live",
{
websocket: true,
preHandler: async (req) => {
const roleId = await authenticateWsHandshake(req);
if (!roleHasPermissions(roleId, ["device:read"])) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
const row = db.select({ category: devices.category }).from(devices).where(eq(devices.id, req.params.deviceId)).get();
if (!row || row.category !== "camera") {
throw Object.assign(new Error("unknown camera"), { statusCode: 404 });
}
},
},
(socket, req) => {
const open = () => socket.readyState === 1;
const unsubscribe = hub.subscribe(req.params.deviceId, {
sendFrame: (jpeg) => {
if (open()) socket.send(jpeg, { binary: true });
},
sendStatus: (status: LiveStatus) => {
if (open()) socket.send(JSON.stringify({ kind: "status", ...status }));
},
busy: () => !open() || socket.bufferedAmount > MAX_BUFFERED_BYTES,
});
socket.on("close", unsubscribe);
socket.on("error", unsubscribe);
},
);
}
+11 -1
View File
@@ -6,6 +6,7 @@ import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js"; import { buildServer } from "../server.js";
import { hikvisionAlarmRoutes } from "./hikvision-alarm.js"; import { hikvisionAlarmRoutes } from "./hikvision-alarm.js";
import type { AnprBridge } from "../anpr-entry.js"; import type { AnprBridge } from "../anpr-entry.js";
import type { CameraActivity } from "../camera-activity.js";
import { seedUser, login } from "../test-helpers.js"; import { seedUser, login } from "../test-helpers.js";
// Hikvision Alarm Server push ingress. Verifies the discovery endpoint: a vehicle- // Hikvision Alarm Server push ingress. Verifies the discovery endpoint: a vehicle-
@@ -235,6 +236,7 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
let rawDb: Db; let rawDb: Db;
let rawClose: () => void; let rawClose: () => void;
let onVehicleDetected: ReturnType<typeof vi.fn>; let onVehicleDetected: ReturnType<typeof vi.fn>;
let cameraSaw: ReturnType<typeof vi.fn>;
beforeEach(async () => { beforeEach(async () => {
const t = createTestDb(); const t = createTestDb();
@@ -243,7 +245,9 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
onVehicleDetected = vi.fn(async () => {}); onVehicleDetected = vi.fn(async () => {});
const bridge = { onVehicleDetected } as unknown as AnprBridge; const bridge = { onVehicleDetected } as unknown as AnprBridge;
rawApp = Fastify(); rawApp = Fastify();
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge); cameraSaw = vi.fn();
const activity = { vehicleDetected: cameraSaw } as unknown as CameraActivity;
await hikvisionAlarmRoutes(rawApp, rawDb, undefined, bridge, activity);
await rawApp.ready(); await rawApp.ready();
rawDb.insert(devices).values({ rawDb.insert(devices).values({
id: CAM_ID, id: CAM_ID,
@@ -275,10 +279,16 @@ describe("Hikvision Alarm Server → ANPR bridge wiring", () => {
expect(onVehicleDetected).toHaveBeenCalledWith(CAM_ID); expect(onVehicleDetected).toHaveBeenCalledWith(CAM_ID);
}); });
it("marks THIS camera active for the booth camera tile", async () => {
await post(VEHICLE_XML);
expect(cameraSaw).toHaveBeenCalledWith(CAM_ID);
});
it("does NOT call the bridge for a human target", async () => { it("does NOT call the bridge for a human target", async () => {
const human = VEHICLE_XML.replace("vehicle", "human"); const human = VEHICLE_XML.replace("vehicle", "human");
await post(human); await post(human);
expect(onVehicleDetected).not.toHaveBeenCalled(); expect(onVehicleDetected).not.toHaveBeenCalled();
expect(cameraSaw).not.toHaveBeenCalled();
}); });
it("does NOT call the bridge on an `inactive` (leave) vehicle event", async () => { it("does NOT call the bridge on an `inactive` (leave) vehicle event", async () => {
@@ -6,6 +6,7 @@ import { requirePermission } from "../auth.js";
import { verifyDigest } from "../digest-auth.js"; import { verifyDigest } from "../digest-auth.js";
import type { LaneStatus } from "../lane-status.js"; import type { LaneStatus } from "../lane-status.js";
import type { AnprBridge } from "../anpr-entry.js"; import type { AnprBridge } from "../anpr-entry.js";
import type { CameraActivity } from "../camera-activity.js";
// Hikvision "Alarm Server" event PUSH ingress. The newer-firmware cameras (Event → // Hikvision "Alarm Server" event PUSH ingress. The newer-firmware cameras (Event →
// Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm // Smart/VCA with "Detection Target: Human/Vehicle", Notify Surveillance Center, Alarm
@@ -101,6 +102,7 @@ export async function hikvisionAlarmRoutes(
db: Db, db: Db,
laneStatus?: LaneStatus, laneStatus?: LaneStatus,
anprBridge?: AnprBridge, anprBridge?: AnprBridge,
cameraActivity?: CameraActivity,
): Promise<void> { ): Promise<void> {
// Accept ANY content-type as a raw Buffer (the camera may POST application/xml, // Accept ANY content-type as a raw Buffer (the camera may POST application/xml,
// multipart/form-data with a JPEG, or text). Fastify's default JSON parser would 415 // multipart/form-data with a JPEG, or text). Fastify's default JSON parser would 415
@@ -213,6 +215,10 @@ export async function hikvisionAlarmRoutes(
if (laneStatus && isVehicleActive) { if (laneStatus && isVehicleActive) {
laneStatus.vehicleDetected(deviceId); laneStatus.vehicleDetected(deviceId);
} }
// The same signal per camera: the booth's tile for THIS camera switches to live video.
if (cameraActivity && isVehicleActive) {
cameraActivity.vehicleDetected(deviceId);
}
// ANPR BRIDGE: on a vehicle detection, if this camera opts into ANPR (config.anpr), // ANPR BRIDGE: on a vehicle detection, if this camera opts into ANPR (config.anpr),
// pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read // pull a snapshot → read the plate → if it matches a SUBSCRIBER, emit a plate read
+40 -20
View File
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto"; import { randomBytes } from "node:crypto";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance, FastifyRequest } from "fastify";
import type { Db } from "@parking/db"; import type { Db } from "@parking/db";
import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared"; import { feedPermissionFor, watchPermissions, type LedgerEvent, type Permission } from "@parking/shared";
import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js"; import { currentRoleId, requireAuth, roleHasPermissions } from "../auth.js";
@@ -9,7 +9,9 @@ import {
type LaneStatusEvent, type LaneStatusEvent,
type LanePresenceEvent, type LanePresenceEvent,
type PlateRecognizedEvent, type PlateRecognizedEvent,
type CameraActivityEvent,
} from "../device-events.js"; } from "../device-events.js";
import type { CameraActivity } from "../camera-activity.js";
import { enrichEvent } from "../event-enrich.js"; import { enrichEvent } from "../event-enrich.js";
import type { DeviceMonitor } from "../device-monitor.js"; import type { DeviceMonitor } from "../device-monitor.js";
import type { LaneStatus } from "../lane-status.js"; import type { LaneStatus } from "../lane-status.js";
@@ -111,6 +113,32 @@ function isAllowedOrigin(origin: string | undefined, host: string | undefined):
return allow.includes(origin); return allow.includes(origin);
} }
/**
* Authenticate a WebSocket handshake and return the caller's role id: Origin allowlist
* FIRST (anti-CSWSH), then a desktop ticket (x-ws-ticket) or the JWT cookie. Shared by
* every socket route (/api/ws, /api/cameras/:id/live) so they cannot drift apart.
* Permission checks stay with each route.
*/
export async function authenticateWsHandshake(req: FastifyRequest): Promise<string> {
if (!isAllowedOrigin(req.headers.origin, req.headers.host)) {
throw Object.assign(new Error("forbidden origin"), { statusCode: 403 });
}
const rawTicket = req.headers[WS_TICKET_HEADER];
const ticket = Array.isArray(rawTicket) ? rawTicket[0] : rawTicket;
if (ticket !== undefined) {
const t = consumeWsTicket(ticket);
if (!t) {
throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 });
}
return t.roleId;
}
await req.jwtVerify(); // reads the HttpOnly cookie (browser path)
if (!req.user) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
return currentRoleId(req.user.sub) ?? "";
}
type OutMsg = type OutMsg =
| { | {
kind: "hello"; kind: "hello";
@@ -118,12 +146,15 @@ type OutMsg =
devices: unknown; devices: unknown;
lanes: LaneStatusEvent | null; lanes: LaneStatusEvent | null;
radar: LanePresenceEvent | null; radar: LanePresenceEvent | null;
/** Camera ids currently seeing a vehicle (camera tiles go live). */
cameras: string[] | null;
} }
| { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> | null } | { kind: "ledger"; event: unknown; occupancy: ReturnType<typeof getOccupancy> | null }
| { kind: "printer-status"; event: unknown } | { kind: "printer-status"; event: unknown }
| { kind: "device-status"; event: unknown } | { kind: "device-status"; event: unknown }
| { kind: "lane-status"; lanes: LaneStatusEvent } | { kind: "lane-status"; lanes: LaneStatusEvent }
| { kind: "lane-presence"; radar: LanePresenceEvent } | { kind: "lane-presence"; radar: LanePresenceEvent }
| { kind: "camera-activity"; camera: CameraActivityEvent }
| { kind: "plate-recognized"; plate: PlateRecognizedEvent }; | { kind: "plate-recognized"; plate: PlateRecognizedEvent };
declare module "fastify" { declare module "fastify" {
@@ -139,6 +170,7 @@ export async function wsRoutes(
deviceMonitor: DeviceMonitor, deviceMonitor: DeviceMonitor,
laneStatus: LaneStatus, laneStatus: LaneStatus,
lanePresence: LanePresence, lanePresence: LanePresence,
cameraActivity: CameraActivity,
): Promise<void> { ): Promise<void> {
// Desktop-only: mint a WS ticket for the signed-in session (see file header). // Desktop-only: mint a WS ticket for the signed-in session (see file header).
// Ordinary cookie + CSRF auth — the desktop client CAN do that over HTTP (via // Ordinary cookie + CSRF auth — the desktop client CAN do that over HTTP (via
@@ -157,25 +189,7 @@ export async function wsRoutes(
// cross/absent origin before touching either credential, so a hijack // cross/absent origin before touching either credential, so a hijack
// attempt never reaches an authenticated socket. // attempt never reaches an authenticated socket.
preHandler: async (req) => { preHandler: async (req) => {
if (!isAllowedOrigin(req.headers.origin, req.headers.host)) { const roleId = await authenticateWsHandshake(req);
throw Object.assign(new Error("forbidden origin"), { statusCode: 403 });
}
const rawTicket = req.headers[WS_TICKET_HEADER];
const ticket = Array.isArray(rawTicket) ? rawTicket[0] : rawTicket;
let roleId: string;
if (ticket !== undefined) {
const t = consumeWsTicket(ticket);
if (!t) {
throw Object.assign(new Error("invalid or expired ws ticket"), { statusCode: 401 });
}
roleId = t.roleId;
} else {
await req.jwtVerify(); // reads the HttpOnly cookie (browser path)
if (!req.user) {
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
}
roleId = currentRoleId(req.user.sub) ?? "";
}
const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p])); const may = watchPermissions(effectiveModulesFor(db)).some((p) => roleHasPermissions(roleId, [p]));
if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 }); if (!may) throw Object.assign(new Error("forbidden"), { statusCode: 403 });
req.wsRoleId = roleId; req.wsRoleId = roleId;
@@ -206,6 +220,7 @@ export async function wsRoutes(
devices: seesDevices ? deviceMonitor.snapshot() : null, devices: seesDevices ? deviceMonitor.snapshot() : null,
lanes: seesDevices ? laneStatus.snapshot() : null, lanes: seesDevices ? laneStatus.snapshot() : null,
radar: seesDevices ? lanePresence.snapshot() : null, radar: seesDevices ? lanePresence.snapshot() : null,
cameras: seesDevices ? cameraActivity.snapshot() : null,
}); });
// Subscribe to the live buses. Each handler recomputes occupancy from the // Subscribe to the live buses. Each handler recomputes occupancy from the
@@ -233,6 +248,10 @@ export async function wsRoutes(
const offPresence = deviceEvents.onLanePresence((radar) => { const offPresence = deviceEvents.onLanePresence((radar) => {
if (seesDevices) send({ kind: "lane-presence", radar }); if (seesDevices) send({ kind: "lane-presence", radar });
}); });
// A camera started/stopped seeing a vehicle → its booth tile switches live/snapshot.
const offCamera = deviceEvents.onCameraActivity((camera) => {
if (seesDevices) send({ kind: "camera-activity", camera });
});
// A late async plate recognition → backfill the badge on the matching feed row. Advisory. // A late async plate recognition → backfill the badge on the matching feed row. Advisory.
const offPlate = deviceEvents.onPlateRecognized((plate) => { const offPlate = deviceEvents.onPlateRecognized((plate) => {
if (seesOccupancy) send({ kind: "plate-recognized", plate }); if (seesOccupancy) send({ kind: "plate-recognized", plate });
@@ -245,6 +264,7 @@ export async function wsRoutes(
offLane(); offLane();
offPresence(); offPresence();
offPlate(); offPlate();
offCamera();
}); });
}, },
); );
+14 -2
View File
@@ -47,6 +47,9 @@ import { entryRoutes } from "./routes/entry.js";
import { siteRoutes } from "./routes/site.js"; import { siteRoutes } from "./routes/site.js";
import { registerModules } from "./modules/index.js"; import { registerModules } from "./modules/index.js";
import { snapshotRoutes } from "./routes/snapshots.js"; import { snapshotRoutes } from "./routes/snapshots.js";
import { cameraRoutes, liveResolverFor } from "./routes/cameras.js";
import { CameraActivity } from "./camera-activity.js";
import { CameraLiveHub } from "./camera-live.js";
import { tariffRoutes } from "./routes/tariffs.js"; import { tariffRoutes } from "./routes/tariffs.js";
import { printerRoutes } from "./routes/printers.js"; import { printerRoutes } from "./routes/printers.js";
import { setupRoutes } from "./routes/setup.js"; import { setupRoutes } from "./routes/setup.js";
@@ -176,6 +179,14 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
const laneStatus = new LaneStatus(db, app.log); const laneStatus = new LaneStatus(db, app.log);
app.addHook("onClose", async () => laneStatus.stop()); app.addHook("onClose", async () => laneStatus.stop());
// Per-CAMERA vehicle activity (same pushes, keyed by camera) + the live-video hub for
// the booth camera tiles: a tile goes live while its camera sees a vehicle. Advisory
// viewing only. See camera-live.ts, wiki/decisions/camera-live-view.md.
const cameraActivity = new CameraActivity(app.log);
app.addHook("onClose", async () => cameraActivity.stop());
const cameraLive = new CameraLiveHub(liveResolverFor(db), app.log);
app.addHook("onClose", async () => cameraLive.stopAll());
// Per-lane RADAR presence (presence-input edges → barrier-light blink). Mirrors the // Per-lane RADAR presence (presence-input edges → barrier-light blink). Mirrors the
// physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI. // physical button lamp (relay 3): the SAME presence signal, surfaced to the booth UI.
const lanePresence = new LanePresence(db, app.log); const lanePresence = new LanePresence(db, app.log);
@@ -216,10 +227,11 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// Live booth feed: server-pushed ledger + occupancy + printer-status over a // Live booth feed: server-pushed ledger + occupancy + printer-status over a
// single authenticated WebSocket (/api/ws). See routes/ws.ts. // single authenticated WebSocket (/api/ws). See routes/ws.ts.
await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence); await wsRoutes(app, db, deviceMonitor, laneStatus, lanePresence, cameraActivity);
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts. // Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
await snapshotRoutes(app, db); await snapshotRoutes(app, db);
await cameraRoutes(app, db, cameraLive);
// Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen. // Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen.
// Subscribes to the SAME input bus as the telemetry writer below; the two are // Subscribes to the SAME input bus as the telemetry writer below; the two are
@@ -270,7 +282,7 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
// each detected target (vehicle). Source-IP guarded + optional Digest; records the raw // each detected target (vehicle). Source-IP guarded + optional Digest; records the raw
// payload as a `kind:"alarm"` device_event, drives lane busy/free, AND hands a vehicle // payload as a `kind:"alarm"` device_event, drives lane busy/free, AND hands a vehicle
// detection to the ANPR bridge above. See routes/hikvision-alarm.ts. // detection to the ANPR bridge above. See routes/hikvision-alarm.ts.
await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge); await hikvisionAlarmRoutes(app, db, laneStatus, anprBridge, cameraActivity);
// Credential capture ("enroll a card"): lets the operator present an RFID card to a // Credential capture ("enroll a card"): lets the operator present an RFID card to a
// CHOSEN reader to populate a subscription credential, without blocking the other // CHOSEN reader to populate a subscription credential, without blocking the other
+33
View File
@@ -94,6 +94,8 @@ export interface SessionUser {
theme: Theme; theme: Theme;
/** Preferred UI font scale, percent of base (100 = base; clamped 80–160). */ /** Preferred UI font scale, percent of base (100 = base; clamped 80–160). */
fontScale: number; fontScale: number;
/** Booth camera tiles left open (camera device ids, opening order). */
openCameras: string[];
/** Optional display name (profile metadata); null if unset. */ /** Optional display name (profile metadata); null if unset. */
fullName: string | null; fullName: string | null;
/** Optional contact email (profile metadata); null if unset. */ /** Optional contact email (profile metadata); null if unset. */
@@ -156,6 +158,37 @@ export function setFontScalePref(fontScale: number): Promise<{ fontScale: number
return apiFetch("/api/auth/font-scale", { method: "PUT", body: JSON.stringify({ fontScale }) }); return apiFetch("/api/auth/font-scale", { method: "PUT", body: JSON.stringify({ fontScale }) });
} }
/** Persist which booth camera tiles are open (restored on next login). */
export function setOpenCamerasPref(openCameras: string[]): Promise<{ openCameras: string[] }> {
return apiFetch("/api/auth/open-cameras", { method: "PUT", body: JSON.stringify({ openCameras }) });
}
/** The newest entry/exit snapshot a camera captured (a camera tile's resting picture). */
export interface CameraSnapshotMeta {
id: string;
direction: "entry" | "exit";
capturedAt: string;
}
/** Latest snapshot metadata for a camera, or null when it has none yet. */
export async function fetchLatestCameraSnapshot(deviceId: string): Promise<CameraSnapshotMeta | null> {
try {
return await apiFetch<CameraSnapshotMeta>(`/api/cameras/${encodeURIComponent(deviceId)}/latest-snapshot`);
} catch (err) {
if (err instanceof ApiError && err.status === 404) return null;
throw err;
}
}
/** Snapshot bytes as an object URL. Fetched (not an <img src>) so it works in the
* desktop shell too, whose webview does not carry the session cookie. The caller
* revokes the URL. */
export async function fetchSnapshotObjectUrl(id: string): Promise<string> {
const res = await platformFetch(apiUrl(`/api/snapshots/${encodeURIComponent(id)}`), { credentials: "include" });
if (!res.ok) throw new ApiError(`/api/snapshots/${id}: ${res.status}`, res.status);
return URL.createObjectURL(await res.blob());
}
/** Edit MY own profile (display name / email). Returns the refreshed session. /** Edit MY own profile (display name / email). Returns the refreshed session.
* Self-service — touches only the signed-in user; no `user:*` permission needed. */ * Self-service — touches only the signed-in user; no `user:*` permission needed. */
export function updateMyProfile(patch: { export function updateMyProfile(patch: {
+10
View File
@@ -269,6 +269,16 @@ export const en: Catalog = {
clickForIssues: "Click for details", clickForIssues: "Click for details",
checkedAt: "checked {{time}}", checkedAt: "checked {{time}}",
}, },
camera: {
live: "Live",
showTile: "Show this camera",
hideTile: "Hide this camera",
noSnapshot: "No snapshot yet",
idle: "Live view starts when a vehicle arrives",
connecting: "Connecting to live video…",
liveUnavailable: "Live video unavailable",
vehicleInView: "Vehicle in view",
},
booth: { booth: {
processTicket: "Process ticket", processTicket: "Process ticket",
scanPlaceholder: "Scan or type ticket number…", scanPlaceholder: "Scan or type ticket number…",
+10
View File
@@ -271,6 +271,16 @@ export const sq = {
clickForIssues: "Kliko për detajet", clickForIssues: "Kliko për detajet",
checkedAt: "kontrolluar {{time}}", checkedAt: "kontrolluar {{time}}",
}, },
camera: {
live: "Live",
showTile: "Shfaq këtë kamerë",
hideTile: "Fshih këtë kamerë",
noSnapshot: "Ende pa foto",
idle: "Videoja live nis kur vjen një automjet",
connecting: "Po lidhet videoja live…",
liveUnavailable: "Videoja live nuk është e disponueshme",
vehicleInView: "Automjet në pamje",
},
booth: { booth: {
processTicket: "Proceso biletën", processTicket: "Proceso biletën",
scanPlaceholder: "Skano ose shkruaj numrin e biletës…", scanPlaceholder: "Skano ose shkruaj numrin e biletës…",
+16 -1
View File
@@ -41,6 +41,8 @@ interface LiveState {
lanes: LaneStatus | null; lanes: LaneStatus | null;
/** Per-lane radar presence (advisory blink). Null until the first WS hello. */ /** Per-lane radar presence (advisory blink). Null until the first WS hello. */
radar: LanePresence | null; radar: LanePresence | null;
/** Camera ids currently seeing a vehicle — their booth tiles show live video. */
activeCameras: Record<string, true>;
setStatus: (s: WsStatus) => void; setStatus: (s: WsStatus) => void;
setOccupancy: (o: Occupancy) => void; setOccupancy: (o: Occupancy) => void;
pushEvent: (e: LedgerEvent) => void; pushEvent: (e: LedgerEvent) => void;
@@ -52,6 +54,10 @@ interface LiveState {
setLanes: (l: LaneStatus) => void; setLanes: (l: LaneStatus) => void;
/** Set lane radar presence (WS hello + each lane-presence push). */ /** Set lane radar presence (WS hello + each lane-presence push). */
setRadar: (r: LanePresence) => void; setRadar: (r: LanePresence) => void;
/** Replace the active-camera set (WS hello). */
setActiveCameras: (ids: string[]) => void;
/** One camera started/stopped seeing a vehicle (WS camera-activity push). */
setCameraActive: (id: string, active: boolean) => void;
/** Backfill the enriched plate on every feed event matching `identity` (a late async /** Backfill the enriched plate on every feed event matching `identity` (a late async
* recognition that landed after the event's own push). No-op if no row matches. */ * recognition that landed after the event's own push). No-op if no row matches. */
patchPlate: (identity: string, plate: string) => void; patchPlate: (identity: string, plate: string) => void;
@@ -70,6 +76,7 @@ export const useLiveStore = create<LiveState>((set) => ({
occupancy: null, occupancy: null,
feed: [], feed: [],
devices: {}, devices: {},
activeCameras: {},
lanes: null, lanes: null,
radar: null, radar: null,
setStatus: (status) => set({ status }), setStatus: (status) => set({ status }),
@@ -83,10 +90,18 @@ export const useLiveStore = create<LiveState>((set) => ({
upsertDevice: (d) => set((s) => ({ devices: { ...s.devices, [d.deviceId]: d } })), upsertDevice: (d) => set((s) => ({ devices: { ...s.devices, [d.deviceId]: d } })),
setLanes: (lanes) => set({ lanes }), setLanes: (lanes) => set({ lanes }),
setRadar: (radar) => set({ radar }), setRadar: (radar) => set({ radar }),
setActiveCameras: (ids) => set({ activeCameras: Object.fromEntries(ids.map((id) => [id, true as const])) }),
setCameraActive: (id, active) =>
set((st) => {
const next = { ...st.activeCameras };
if (active) next[id] = true;
else delete next[id];
return { activeCameras: next };
}),
patchPlate: (identity, plate) => patchPlate: (identity, plate) =>
set((s) => { set((s) => {
if (!s.feed.some((e) => e.identity === identity && !e.plate)) return s; // nothing to fill if (!s.feed.some((e) => e.identity === identity && !e.plate)) return s; // nothing to fill
return { feed: s.feed.map((e) => (e.identity === identity && !e.plate ? { ...e, plate } : e)) }; return { feed: s.feed.map((e) => (e.identity === identity && !e.plate ? { ...e, plate } : e)) };
}), }),
reset: () => set({ status: "connecting", occupancy: null, feed: [], devices: {}, lanes: null, radar: null }), reset: () => set({ status: "connecting", occupancy: null, feed: [], devices: {}, lanes: null, radar: null, activeCameras: {} }),
})); }));
+13 -6
View File
@@ -27,9 +27,12 @@ import { inTauri } from "./tauri-env.js";
const CONNECT_FAIL_LOG_INTERVAL_MS = 60_000; const CONNECT_FAIL_LOG_INTERVAL_MS = 60_000;
let lastConnectFailLogAt = 0; let lastConnectFailLogAt = 0;
/** A text frame arrives as a string, a binary frame (camera JPEG) as an ArrayBuffer. */
export type PlatformMessage = { data: string | ArrayBuffer };
export interface PlatformSocket { export interface PlatformSocket {
onopen: (() => void) | null; onopen: (() => void) | null;
onmessage: ((ev: { data: string }) => void) | null; onmessage: ((ev: PlatformMessage) => void) | null;
onclose: (() => void) | null; onclose: (() => void) | null;
onerror: (() => void) | null; onerror: (() => void) | null;
close(): void; close(): void;
@@ -37,15 +40,16 @@ export interface PlatformSocket {
class NativeSocketAdapter implements PlatformSocket { class NativeSocketAdapter implements PlatformSocket {
onopen: (() => void) | null = null; onopen: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null; onmessage: ((ev: PlatformMessage) => void) | null = null;
onclose: (() => void) | null = null; onclose: (() => void) | null = null;
onerror: (() => void) | null = null; onerror: (() => void) | null = null;
#sock: WebSocket; #sock: WebSocket;
constructor(url: string) { constructor(url: string) {
this.#sock = new WebSocket(url); this.#sock = new WebSocket(url);
this.#sock.binaryType = "arraybuffer";
this.#sock.onopen = () => this.onopen?.(); this.#sock.onopen = () => this.onopen?.();
this.#sock.onmessage = (ev) => this.onmessage?.({ data: ev.data as string }); this.#sock.onmessage = (ev) => this.onmessage?.({ data: ev.data as string | ArrayBuffer });
this.#sock.onclose = () => this.onclose?.(); this.#sock.onclose = () => this.onclose?.();
this.#sock.onerror = () => this.onerror?.(); this.#sock.onerror = () => this.onerror?.();
} }
@@ -57,7 +61,7 @@ class NativeSocketAdapter implements PlatformSocket {
class TauriSocketAdapter implements PlatformSocket { class TauriSocketAdapter implements PlatformSocket {
onopen: (() => void) | null = null; onopen: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null; onmessage: ((ev: PlatformMessage) => void) | null = null;
onclose: (() => void) | null = null; onclose: (() => void) | null = null;
onerror: (() => void) | null = null; onerror: (() => void) | null = null;
#closed = false; #closed = false;
@@ -95,11 +99,14 @@ class TauriSocketAdapter implements PlatformSocket {
conn.addListener((msg: { type: string; data: unknown }) => { conn.addListener((msg: { type: string; data: unknown }) => {
if (msg.type === "Text") { if (msg.type === "Text") {
this.onmessage?.({ data: msg.data as string }); this.onmessage?.({ data: msg.data as string });
} else if (msg.type === "Binary") {
// Camera live view (routes/cameras.ts): one JPEG per binary message. The
// plugin hands bytes over IPC as a number array.
this.onmessage?.({ data: new Uint8Array(msg.data as number[]).buffer });
} else if (msg.type === "Close") { } else if (msg.type === "Close") {
this.onclose?.(); this.onclose?.();
} }
// Binary/Ping/Pong: the server protocol here is text-JSON only (see // Ping/Pong: nothing to do.
// routes/ws.ts) — nothing else is expected.
}); });
this.onopen?.(); this.onopen?.();
} catch (err) { } catch (err) {
+30 -3
View File
@@ -16,12 +16,13 @@ import { createPlatformSocket, type PlatformSocket } from "./platform-ws.js";
/** Server → client message shapes (mirror routes/ws.ts OutMsg). */ /** Server → client message shapes (mirror routes/ws.ts OutMsg). */
type WsMessage = type WsMessage =
// Parts a role may not see arrive as null (the server filters per role — ws.ts). // Parts a role may not see arrive as null (the server filters per role — ws.ts).
| { kind: "hello"; occupancy: Occupancy | null; devices: DeviceStatus[] | null; lanes: LaneStatus | null; radar: LanePresence | null } | { kind: "hello"; occupancy: Occupancy | null; devices: DeviceStatus[] | null; lanes: LaneStatus | null; radar: LanePresence | null; cameras: string[] | null }
| { kind: "ledger"; event: LedgerEvent; occupancy: Occupancy | null } | { kind: "ledger"; event: LedgerEvent; occupancy: Occupancy | null }
| { kind: "printer-status"; event: unknown } | { kind: "printer-status"; event: unknown }
| { kind: "device-status"; event: DeviceStatus } | { kind: "device-status"; event: DeviceStatus }
| { kind: "lane-status"; lanes: LaneStatus } | { kind: "lane-status"; lanes: LaneStatus }
| { kind: "lane-presence"; radar: LanePresence } | { kind: "lane-presence"; radar: LanePresence }
| { kind: "camera-activity"; camera: { deviceId: string; active: boolean } }
| { kind: "plate-recognized"; plate: { identity: string; plate: string; direction: "entry" | "exit" } }; | { kind: "plate-recognized"; plate: { identity: string; plate: string; direction: "entry" | "exit" } };
@@ -34,8 +35,18 @@ type WsMessage =
*/ */
export function useLiveFeed(enabled: boolean = true): void { export function useLiveFeed(enabled: boolean = true): void {
const qc = useQueryClient(); const qc = useQueryClient();
const { setStatus, setOccupancy, pushEvent, setDevices, upsertDevice, setLanes, setRadar, patchPlate } = const {
useLiveStore(); setStatus,
setOccupancy,
pushEvent,
setDevices,
upsertDevice,
setLanes,
setRadar,
patchPlate,
setActiveCameras,
setCameraActive,
} = useLiveStore();
// Hold the socket + reconnect timer across renders; guard against StrictMode // Hold the socket + reconnect timer across renders; guard against StrictMode
// double-invoke and unmount. // double-invoke and unmount.
const sockRef = useRef<PlatformSocket | null>(null); const sockRef = useRef<PlatformSocket | null>(null);
@@ -73,6 +84,12 @@ export function useLiveFeed(enabled: boolean = true): void {
if (Array.isArray(msg.devices)) setDevices(msg.devices); if (Array.isArray(msg.devices)) setDevices(msg.devices);
if (msg.lanes) setLanes(msg.lanes); if (msg.lanes) setLanes(msg.lanes);
if (msg.radar) setRadar(msg.radar); if (msg.radar) setRadar(msg.radar);
if (Array.isArray(msg.cameras)) setActiveCameras(msg.cameras);
} else if (msg.kind === "camera-activity") {
setCameraActive(msg.camera.deviceId, msg.camera.active);
// Live ended → the tile falls back to the newest snapshot, which this car
// may just have produced.
if (!msg.camera.active) void qc.invalidateQueries({ queryKey: ["camera-latest", msg.camera.deviceId] });
} else if (msg.kind === "device-status") { } else if (msg.kind === "device-status") {
upsertDevice(msg.event); upsertDevice(msg.event);
} else if (msg.kind === "lane-status") { } else if (msg.kind === "lane-status") {
@@ -93,6 +110,12 @@ export function useLiveFeed(enabled: boolean = true): void {
void qc.invalidateQueries({ queryKey: qk.events }); void qc.invalidateQueries({ queryKey: qk.events });
void qc.invalidateQueries({ queryKey: qk.occupancy }); void qc.invalidateQueries({ queryKey: qk.occupancy });
void qc.invalidateQueries({ queryKey: qk.activeSessions }); void qc.invalidateQueries({ queryKey: qk.activeSessions });
// An entry/exit is followed by a fresh camera snapshot → the camera tiles'
// picture. The snapshot is stored AFTER the signed event (entry-flow.ts), so
// refetch a moment later; the idle edge (camera-activity) refetches again.
if (msg.event.type === "vehicle_entry" || msg.event.type === "vehicle_exit") {
window.setTimeout(() => void qc.invalidateQueries({ queryKey: ["camera-latest"] }), 4000);
}
// A shift open/close (or a drawer movement) changes the header control // A shift open/close (or a drawer movement) changes the header control
// state and the per-shift log window — refresh the shift status too. // state and the per-shift log window — refresh the shift status too.
if ( if (
@@ -113,6 +136,10 @@ export function useLiveFeed(enabled: boolean = true): void {
const scheduleReconnect = () => { const scheduleReconnect = () => {
if (closedRef.current) return; if (closedRef.current) return;
setStatus("closed"); setStatus("closed");
// Camera activity is only known while the feed is up: without this a tile would
// stay "live" and re-dial its camera for the whole outage. The hello on reconnect
// restores the real set.
setActiveCameras([]);
// Capped exponential backoff: 0.5s, 1s, 2s, … up to 10s. // Capped exponential backoff: 0.5s, 1s, 2s, … up to 10s.
const delay = Math.min(500 * 2 ** retryRef.current, 10_000); const delay = Math.min(500 * 2 ** retryRef.current, 10_000);
retryRef.current += 1; retryRef.current += 1;
+19 -1
View File
@@ -17,6 +17,7 @@ import {
setLanguagePref, setLanguagePref,
setThemePref, setThemePref,
setFontScalePref, setFontScalePref,
setOpenCamerasPref,
FONT_SCALE_MIN, FONT_SCALE_MIN,
FONT_SCALE_MAX, FONT_SCALE_MAX,
FONT_SCALE_STEP, FONT_SCALE_STEP,
@@ -384,6 +385,17 @@ function RootLayout() {
const canWatch = canWatchFeed(user); const canWatch = canWatchFeed(user);
useLiveFeed(canWatch); useLiveFeed(canWatch);
// Booth camera tiles: a footer camera chip opens/closes its tile. The open set is a
// per-user preference (users.open_cameras), restored on login from any booth; saved
// optimistically — a failed save only means it is not remembered next time.
const toggleCamera = (deviceId: string) => {
if (!user) return;
const current: string[] = user.openCameras ?? [];
const next = current.includes(deviceId) ? current.filter((id) => id !== deviceId) : [...current, deviceId];
setUser({ ...user, openCameras: next });
void setOpenCamerasPref(next).catch(() => undefined);
};
return ( return (
<div className="flex h-screen flex-col bg-term-bg text-term-text"> <div className="flex h-screen flex-col bg-term-bg text-term-text">
<header className="flex items-center gap-4 border-b border-term-border bg-term-panel px-4 py-2"> <header className="flex items-center gap-4 border-b border-term-border bg-term-panel px-4 py-2">
@@ -459,7 +471,13 @@ function RootLayout() {
{/* Fixed device-status footer — relays, readers, cameras, printers. Its REST {/* Fixed device-status footer — relays, readers, cameras, printers. Its REST
seed needs device:read (and its live updates ride the report:read WS), so seed needs device:read (and its live updates ride the report:read WS), so
it's hidden for roles without device visibility (e.g. merchant validators). */} it's hidden for roles without device visibility (e.g. merchant validators). */}
{user && show("device:read") && <DeviceFooter />} {user && show("device:read") && (
<DeviceFooter
openCameras={user.openCameras ?? []}
onToggleCamera={toggleCamera}
canSeeSnapshots={show("session:read")}
/>
)}
</div> </div>
); );
} }
+230
View File
@@ -0,0 +1,230 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { fetchLatestCameraSnapshot, fetchSnapshotObjectUrl, type DeviceStatus } from "../api.js";
import { formatClock } from "../lib/format.js";
import { useLiveStore } from "../lib/live-store.js";
import { wsUrl } from "../lib/origin.js";
import { createPlatformSocket } from "../lib/platform-ws.js";
// Booth camera tiles (wiki/decisions/camera-live-view.md). Opened from the camera
// chips in the device footer; docked bottom-right, the first opened rightmost and each
// next one to its left. A tile rests on the camera's newest entry/exit snapshot and
// switches to live video while that camera is seeing a vehicle (the server's per-camera
// activity, pushed over /api/ws). Live frames come over their own socket as JPEG
// binaries; only the newest frame is shown. Advisory viewing — nothing here gates
// anything.
type LiveState =
| { state: "connecting" }
| { state: "live" }
| { state: "retrying"; reason: string }
| { state: "unavailable"; reason: string };
/** Delay before re-opening a live socket that dropped while the camera is still active. */
const RECONNECT_MS = 2000;
export function CameraDock({
openIds,
cameras,
label,
canSeeSnapshots,
onClose,
}: {
openIds: string[];
/** Configured cameras (for labels, and to skip a tile whose camera was removed). */
cameras: DeviceStatus[];
label: (d: DeviceStatus) => string;
canSeeSnapshots: boolean;
onClose: (deviceId: string) => void;
}) {
const byId = new Map(cameras.map((c) => [c.deviceId, c]));
const shown = openIds.filter((id) => byId.has(id));
if (shown.length === 0) return null;
return (
// Above the footer; first opened rightmost (row-reverse), the next to its left.
<div className="pointer-events-none fixed bottom-9 right-2 z-40 flex flex-row-reverse items-end gap-2">
{shown.map((id) => (
<CameraTile
key={id}
deviceId={id}
title={label(byId.get(id)!)}
canSeeSnapshots={canSeeSnapshots}
onClose={() => onClose(id)}
/>
))}
</div>
);
}
function CameraTile({
deviceId,
title,
canSeeSnapshots,
onClose,
}: {
deviceId: string;
title: string;
canSeeSnapshots: boolean;
onClose: () => void;
}) {
const { t } = useTranslation();
const active = useLiveStore((s) => s.activeCameras[deviceId] === true);
const live = useLiveFrames(deviceId, active);
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
const showLive = active && live.hasFrame;
return (
<div className="pointer-events-auto flex w-[15vw] min-w-[200px] flex-col overflow-hidden rounded-term border border-term-border bg-term-panel shadow-2xl">
<div className="flex items-center gap-2 border-b border-term-border bg-term-panel-2 px-2 py-1 text-[0.6875rem]">
{showLive ? (
<span className="flex items-center gap-1 font-semibold uppercase tracking-wider text-term-red">
<span className="inline-block h-2 w-2 animate-pulse rounded-full bg-term-red" />
{t("camera.live")}
</span>
) : null}
<span className="min-w-0 flex-1 truncate font-semibold text-term-text">{title}</span>
<button
type="button"
onClick={onClose}
className="shrink-0 text-term-muted hover:text-term-text"
aria-label={t("common.close")}
title={t("common.close")}
>
✕
</button>
</div>
<div className="relative aspect-video bg-black">
{/* Live frames are painted straight into this <img> (no re-render per frame). */}
<img
ref={live.imgRef}
alt=""
className={`absolute inset-0 h-full w-full object-contain ${showLive ? "" : "hidden"}`}
/>
{!showLive && snapshot.url && (
<img src={snapshot.url} alt="" className="absolute inset-0 h-full w-full object-contain" />
)}
{!showLive && !snapshot.url && (
<div className="absolute inset-0 flex items-center justify-center px-2 text-center text-[0.6875rem] text-term-muted">
{canSeeSnapshots ? t("camera.noSnapshot") : t("camera.idle")}
</div>
)}
<div className="absolute bottom-0 left-0 right-0 truncate bg-black/60 px-1.5 py-0.5 text-[0.625rem] text-term-muted">
{active && !showLive
? live.status.state === "unavailable" || live.status.state === "retrying"
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
: t("camera.connecting")
: !showLive && snapshot.meta
? `${snapshot.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.meta.capturedAt)}`
: showLive
? t("camera.vehicleInView")
: ""}
</div>
</div>
</div>
);
}
/** Newest snapshot for the tile's resting picture, as an object URL (revoked on change). */
function useLatestSnapshot(deviceId: string, enabled: boolean) {
const meta = useQuery({
queryKey: ["camera-latest", deviceId],
queryFn: () => fetchLatestCameraSnapshot(deviceId),
enabled,
staleTime: 60_000,
});
const id = meta.data?.id ?? null;
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
if (!id) {
setUrl(null);
return;
}
let cancelled = false;
let made: string | null = null;
fetchSnapshotObjectUrl(id)
.then((u) => {
if (cancelled) URL.revokeObjectURL(u);
else {
made = u;
setUrl(u);
}
})
.catch(() => !cancelled && setUrl(null));
return () => {
cancelled = true;
if (made) URL.revokeObjectURL(made);
};
}, [id]);
return { meta: meta.data ?? null, url };
}
/**
* While `active`, hold a live socket to the camera and paint each JPEG into `imgRef`.
* Closed (and the last frame dropped) as soon as the camera goes idle or the tile
* unmounts; reconnects after a drop while still active. The server shares one camera
* session between every viewer and skips frames for a slow one.
*/
function useLiveFrames(deviceId: string, active: boolean) {
const imgRef = useRef<HTMLImageElement>(null);
const [status, setStatus] = useState<LiveState>({ state: "connecting" });
const [hasFrame, setHasFrame] = useState(false);
useEffect(() => {
if (!active) {
setHasFrame(false);
setStatus({ state: "connecting" });
return;
}
let closed = false;
let currentUrl: string | null = null;
let retry: number | undefined;
let sock: ReturnType<typeof createPlatformSocket> | null = null;
const paint = (buf: ArrayBuffer) => {
const img = imgRef.current;
if (closed || !img) return; // a frame landing after cleanup must not resurrect the view
const next = URL.createObjectURL(new Blob([buf], { type: "image/jpeg" }));
const prev = currentUrl;
currentUrl = next;
img.src = next;
if (prev) URL.revokeObjectURL(prev);
setHasFrame(true);
};
const connect = () => {
if (closed) return;
setStatus({ state: "connecting" });
sock = createPlatformSocket(wsUrl(`/api/cameras/${encodeURIComponent(deviceId)}/live`));
sock.onmessage = (ev) => {
if (closed) return;
if (typeof ev.data === "string") {
try {
const msg = JSON.parse(ev.data) as { kind: string } & LiveState;
if (msg.kind === "status") setStatus(msg);
} catch {
/* ignore */
}
} else {
paint(ev.data);
}
};
sock.onclose = () => {
if (closed) return;
retry = window.setTimeout(connect, RECONNECT_MS);
};
sock.onerror = () => sock?.close();
};
connect();
return () => {
closed = true;
if (retry) window.clearTimeout(retry);
sock?.close();
if (currentUrl) URL.revokeObjectURL(currentUrl);
if (imgRef.current) imgRef.current.removeAttribute("src");
};
}, [deviceId, active]);
return { imgRef, status, hasFrame };
}
+45 -8
View File
@@ -5,6 +5,7 @@ import { fetchDeviceStatus, type DeviceStatus } from "../api.js";
import { formatClock } from "../lib/format.js"; import { formatClock } from "../lib/format.js";
import { qk } from "../lib/query.js"; import { qk } from "../lib/query.js";
import { useLiveStore } from "../lib/live-store.js"; import { useLiveStore } from "../lib/live-store.js";
import { CameraDock } from "./CameraDock.js";
// Fixed device-status footer for the booth chrome. One compact chip per configured // Fixed device-status footer for the booth chrome. One compact chip per configured
// device — relays, readers, cameras, printers — labelled by ROLE, never vendor // device — relays, readers, cameras, printers — labelled by ROLE, never vendor
@@ -66,7 +67,18 @@ function sortDevices(list: DeviceStatus[]): DeviceStatus[] {
); );
} }
export function DeviceFooter() { export function DeviceFooter({
openCameras,
onToggleCamera,
canSeeSnapshots,
}: {
/** Camera tiles open (device ids, opening order) — the user's saved preference. */
openCameras: string[];
/** Open/close a camera's tile (a camera chip click). */
onToggleCamera: (deviceId: string) => void;
/** May the user see evidence snapshots (session:read) — the tiles' resting picture. */
canSeeSnapshots: boolean;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const label = useLabel(); const label = useLabel();
// Seed/fallback from REST; the WS keeps the live store authoritative thereafter. // Seed/fallback from REST; the WS keeps the live store authoritative thereafter.
@@ -111,17 +123,33 @@ export function DeviceFooter() {
) : ( ) : (
devices.map((d) => { devices.map((d) => {
const isProblem = d.state !== "ready"; const isProblem = d.state !== "ready";
// A CAMERA chip opens/closes that camera's tile (its issues stay reachable
// from the roll-up on the right); any other chip is interactive only when
// it has a problem (opens the issues panel).
const isCamera = d.category === "camera";
const isOpen = isCamera && openCameras.includes(d.deviceId);
const onClick = isCamera
? () => onToggleCamera(d.deviceId)
: isProblem
? () => setOpen((v) => !v)
: undefined;
return ( return (
<button <button
key={d.deviceId} key={d.deviceId}
type="button" type="button"
// Only a problem chip is interactive (opens the issues panel). onClick={onClick}
onClick={isProblem ? () => setOpen((v) => !v) : undefined} aria-disabled={!onClick}
aria-disabled={!isProblem} aria-pressed={isCamera ? isOpen : undefined}
title={isProblem ? t("devices.clickForIssues") : undefined} title={
className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-term border border-term-border bg-term-panel-2 px-2 py-0.5 ${ isCamera
isProblem ? "cursor-pointer hover:border-term-amber" : "cursor-default" ? t(isOpen ? "camera.hideTile" : "camera.showTile")
}`} : isProblem
? t("devices.clickForIssues")
: undefined
}
className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-term border bg-term-panel-2 px-2 py-0.5 ${
isOpen ? "border-term-amber" : "border-term-border"
} ${onClick ? "cursor-pointer hover:border-term-amber" : "cursor-default"}`}
> >
<span <span
className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT[d.state]} ${ className={`inline-block h-2 w-2 shrink-0 rounded-full ${DOT[d.state]} ${
@@ -153,6 +181,15 @@ export function DeviceFooter() {
)} )}
</button> </button>
{/* Camera tiles, docked bottom-right above this footer. */}
<CameraDock
openIds={openCameras}
cameras={devices.filter((d) => d.category === "camera")}
label={label}
canSeeSnapshots={canSeeSnapshots}
onClose={onToggleCamera}
/>
{/* Issues panel — anchored above the footer, lists only problem devices. */} {/* Issues panel — anchored above the footer, lists only problem devices. */}
{open && problems.length > 0 && ( {open && problems.length > 0 && (
<div className="absolute bottom-full right-2 z-50 mb-1 w-[360px] max-w-[95vw] rounded-term border border-term-border bg-term-panel shadow-2xl"> <div className="absolute bottom-full right-2 z-50 mb-1 w-[360px] max-w-[95vw] rounded-term border border-term-border bg-term-panel shadow-2xl">
@@ -0,0 +1,9 @@
-- Booth camera tiles (wiki/decisions/camera-live-view.md). Two additive changes:
-- * users.open_cameras: the camera tiles a user left open (JSON array of device ids),
-- restored on the next login from any booth, like language/theme/font_scale.
-- * an index for "the latest snapshot this camera took" — the tile's default picture.
-- Without it the lookup scans every stored image row (the bounded-request-cost rule,
-- park-2 2026-10-24). The previous image ignores both on rollback.
ALTER TABLE `users` ADD `open_cameras` text DEFAULT '[]' NOT NULL;
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS `snapshots_device_time_idx` ON `snapshots` (`device_id`,`captured_at`);
+7
View File
@@ -232,6 +232,13 @@
"when": 1788720000000, "when": 1788720000000,
"tag": "0032_hot_path_indexes", "tag": "0032_hot_path_indexes",
"breakpoints": true "breakpoints": true
},
{
"idx": 33,
"version": "6",
"when": 1788730000000,
"tag": "0033_camera_live_view",
"breakpoints": true
} }
] ]
} }
+4
View File
@@ -96,6 +96,10 @@ export const users = sqliteTable("users", {
// avoids float drift; the client clamps to 80–160 in steps of 10. Printed tickets are // avoids float drift; the client clamps to 80–160 in steps of 10. Printed tickets are
// unaffected (server-rendered). // unaffected (server-rendered).
fontScale: integer("font_scale").notNull().default(100), fontScale: integer("font_scale").notNull().default(100),
// Camera tiles this user left open on the booth screen (JSON array of camera device
// ids, in the order opened). Persisted like `theme`; restored on login from any booth.
// See wiki/decisions/camera-live-view.md.
openCameras: text("open_cameras").notNull().default("[]"),
// Optional operator profile metadata — display name + contact details. All // Optional operator profile metadata — display name + contact details. All
// nullable; only username/password/role are required to create a user. fullName // nullable; only username/password/role are required to create a user. fullName
// (when set) is the human label for audit/Z-report display. // (when set) is the human label for audit/Z-report display.
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+35 -1
View File
@@ -1,5 +1,7 @@
import type { import type {
CameraDevice, CameraDevice,
LiveStreamDevice,
LiveVideoSource,
ClockSyncResult, ClockSyncResult,
DeviceHealth, DeviceHealth,
Snapshot, Snapshot,
@@ -14,6 +16,7 @@ import {
stubLog, stubLog,
} from "./common.js"; } from "./common.js";
import { digestGet, digestRequest } from "./http-digest.js"; import { digestGet, digestRequest } from "./http-digest.js";
import { RtspMjpegStream } from "./rtsp-mjpeg.js";
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over // Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
// HTTP when an event fires; the bytes are stored and referenced from the signed // HTTP when an event fires; the bytes are stored and referenced from the signed
@@ -74,6 +77,8 @@ class HttpCamera implements CameraDevice {
// Source outbound from the device-facing NIC on a multi-homed host (the // Source outbound from the device-facing NIC on a multi-homed host (the
// multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md). // multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md).
readonly #localAddress: string | undefined; readonly #localAddress: string | undefined;
/** RTSP port for the live view (not a Setup field: 554 everywhere so far). */
readonly #rtspPort: number;
constructor( constructor(
readonly driverId: string, readonly driverId: string,
@@ -92,6 +97,7 @@ class HttpCamera implements CameraDevice {
this.#localAddress = config.localAddress this.#localAddress = config.localAddress
? String(config.localAddress) ? String(config.localAddress)
: undefined; : undefined;
this.#rtspPort = Number(config.rtspPort ?? 554);
} }
async connect(): Promise<void> {} async connect(): Promise<void> {}
@@ -165,6 +171,23 @@ class HttpCamera implements CameraDevice {
}); });
} }
/** An RTSP MJPEG session on `path` with this camera's address + credentials. */
protected rtspStream(path: string): LiveVideoSource {
return new RtspMjpegStream({
host: this.#host,
port: this.#rtspPort,
path,
user: this.#user,
password: this.#password,
timeoutMs: this.#timeout,
...(this.#localAddress ? { localAddress: this.#localAddress } : {}),
});
}
protected get channel(): number {
return this.#channel;
}
/** Digest request against an arbitrary device path (ISAPI / CGI config reads+writes). */ /** Digest request against an arbitrary device path (ISAPI / CGI config reads+writes). */
protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) { protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) {
return digestRequest({ return digestRequest({
@@ -216,7 +239,18 @@ export function hikvisionFixedZone(localIso: string): string {
return `CST${sign}${hours}:${minutes}:00`; return `CST${sign}${hours}:${minutes}:00`;
} }
class HikvisionCamera extends HttpCamera { class HikvisionCamera extends HttpCamera implements LiveStreamDevice {
/**
* Live view for the booth's camera tiles: the channel's SUB-stream (x02) over RTSP,
* which must be set to MJPEG on the camera (H.264 is refused with that reason).
* The ANPR/evidence stills keep coming from /picture on the configured stream —
* the codec of the sub-stream does not change them (measured on park-lab
* 2026-11-17: no extra 503s with a stream open). See wiki/decisions/camera-live-view.md.
*/
openLiveStream(): LiveVideoSource {
return this.rtspStream(`/Streaming/Channels/${this.channel}02`);
}
/** /**
* Read the camera clock + zone. Rewrite the zone when it is not the site's current * Read the camera clock + zone. Rewrite the zone when it is not the site's current
* fixed offset (see above); otherwise set the clock only when it drifts more than * fixed offset (see above); otherwise set the clock only when it drifts more than
+2 -2
View File
@@ -12,7 +12,7 @@ import type { IncomingMessage } from "node:http";
const md5 = (s: string) => createHash("md5").update(s).digest("hex"); const md5 = (s: string) => createHash("md5").update(s).digest("hex");
/** Parse a `WWW-Authenticate: Digest …` header into its k=v fields. */ /** Parse a `WWW-Authenticate: Digest …` header into its k=v fields. */
function parseChallenge(header: string): Record<string, string> { export function parseChallenge(header: string): Record<string, string> {
const out: Record<string, string> = {}; const out: Record<string, string> = {};
const re = /(\w+)=(?:"([^"]*)"|([^,]*))/g; const re = /(\w+)=(?:"([^"]*)"|([^,]*))/g;
let m: RegExpExecArray | null; let m: RegExpExecArray | null;
@@ -21,7 +21,7 @@ function parseChallenge(header: string): Record<string, string> {
} }
/** Build the `Authorization: Digest …` response value for a challenge. */ /** Build the `Authorization: Digest …` response value for a challenge. */
function buildAuthHeader( export function buildAuthHeader(
c: Record<string, string>, c: Record<string, string>,
user: string, user: string,
password: string, password: string,
@@ -0,0 +1,100 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { JpegDepacketizer, MAX_FRAME_BYTES, rtpPayload, tablesForQ } from "./rfc2435.js";
// Fixture: two frames of RTP/JPEG captured from a park-lab Hikvision DS-2CD1043G2-LIU
// (sub-stream 102 set to MJPEG, 640×360, type 1, Q 48, last packet of a frame padded),
// stored as [u16 length][packet]... The expected JPEGs were rebuilt independently and
// verified to decode with Pillow (2026-11-17).
const dir = fileURLToPath(new URL("./__fixtures__/", import.meta.url));
const capture = readFileSync(`${dir}rtp-jpeg-2frames.bin`);
const expected = [readFileSync(`${dir}rtp-jpeg-frame0.jpg`), readFileSync(`${dir}rtp-jpeg-frame1.jpg`)];
function packets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
for (let i = 0; i < buf.length; ) {
const len = buf.readUInt16BE(i);
out.push(buf.subarray(i + 2, i + 2 + len));
i += 2 + len;
}
return out;
}
describe("JpegDepacketizer", () => {
it("rebuilds the camera's frames byte-for-byte", () => {
const d = new JpegDepacketizer();
const frames = packets(capture)
.map((p) => d.push(p))
.filter((f): f is Buffer => f !== null);
expect(frames).toHaveLength(2);
expect(frames[0]!.equals(expected[0]!)).toBe(true);
expect(frames[1]!.equals(expected[1]!)).toBe(true);
expect(d.dropped).toBe(0);
});
it("drops a frame with a missing packet and recovers on the next one", () => {
const d = new JpegDepacketizer();
const all = packets(capture);
// Remove the 3rd packet of frame 0.
const lossy = [...all.slice(0, 2), ...all.slice(3)];
const frames = lossy.map((p) => d.push(p)).filter((f): f is Buffer => f !== null);
expect(frames).toHaveLength(1);
expect(frames[0]!.equals(expected[1]!)).toBe(true);
expect(d.dropped).toBe(1);
});
it("ignores packets until a frame start when joining mid-frame", () => {
const d = new JpegDepacketizer();
const all = packets(capture);
const firstEnd = all.findIndex((p) => (p[1]! & 0x80) !== 0);
const frames = all
.slice(2) // join inside frame 0
.map((p) => d.push(p))
.filter((f): f is Buffer => f !== null);
expect(firstEnd).toBeGreaterThan(2);
expect(frames).toHaveLength(1);
expect(frames[0]!.equals(expected[1]!)).toBe(true);
});
it("bounds a runaway frame", () => {
const d = new JpegDepacketizer();
const big = 60_000;
let seq = 1;
let offset = 0;
let out: Buffer | null = null;
while (offset <= MAX_FRAME_BYTES + big) {
const pkt = Buffer.alloc(12 + 8 + big);
pkt[0] = 0x80;
pkt[1] = 26;
pkt.writeUInt16BE(seq++ & 0xffff, 2);
pkt.writeUIntBE(offset, 13, 3);
pkt[16] = 1; // type
pkt[17] = 50; // Q
pkt[18] = 80; // 640/8
pkt[19] = 45; // 360/8
out = d.push(pkt) ?? out;
offset += big;
}
expect(out).toBeNull();
expect(d.dropped).toBe(1);
});
});
describe("rtpPayload", () => {
it("strips RTP padding", () => {
const pkt = Buffer.from([0xa0, 0x9a, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0xaa, 0xbb, 0, 0, 3]);
const r = rtpPayload(pkt)!;
expect(r.marker).toBe(true);
expect([...r.payload]).toEqual([0xaa, 0xbb]);
});
});
describe("tablesForQ", () => {
it("Q 50 is the unscaled standard table", () => {
const t = tablesForQ(50);
expect(t.length).toBe(128);
expect(t[0]).toBe(16);
expect(t[64]).toBe(17);
});
});
+190
View File
@@ -0,0 +1,190 @@
// RTP/JPEG depacketizer (RFC 2435). A camera that streams MJPEG over RTSP sends each
// frame as RTP packets carrying the JPEG *scan data* only, plus an 8-byte JPEG header
// (type, Q, width/8, height/8) and, for Q >= 128, the quantization tables in-band.
// The receiver rebuilds the JFIF headers (SOI, DQT, DRI, SOF0, standard DHT, SOS) in
// front of the reassembled scan data. No decode, no re-encode: we only reframe bytes.
//
// MEASURED on park-lab (2026-11-17, Hikvision DS-2CD1043G2-LIU fw V5.8.10 and
// DS-2CD1083G2-LIU fw V5.8.4, sub-stream 102 set to MJPEG 640×360): type 1 (4:2:0),
// Q 48 / 63 (tables derived from Q, none in-band), no restart markers, the last packet
// of every frame carries RTP padding. Frames rebuilt here decode cleanly.
// See wiki/decisions/camera-live-view.md.
/** Hard cap on one reassembled frame. A 640×360 MJPEG frame is ~15–30 KB; a frame
* growing past this is a broken stream, not a big picture — drop it. */
export const MAX_FRAME_BYTES = 2 * 1024 * 1024;
// Standard JPEG luma/chroma quantizers (ITU T.81 Annex K), in ZIGZAG order — which is
// the order a DQT segment carries. RFC 2435 Appendix A scales these by Q.
const LUMA_Q = [
16, 11, 12, 14, 12, 10, 16, 14, 13, 14, 18, 17, 16, 19, 24, 40, 26, 24, 22, 22, 24, 49, 35, 37, 29, 40, 58, 51, 61,
60, 57, 51, 56, 55, 64, 72, 92, 78, 64, 68, 87, 69, 55, 56, 80, 109, 81, 87, 95, 98, 103, 104, 103, 62, 77, 113,
121, 112, 100, 120, 92, 101, 103, 99,
];
const CHROMA_Q = [
17, 18, 18, 24, 21, 24, 47, 26, 26, 47, 99, 66, 56, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99,
];
/** RFC 2435 Appendix A MakeTables: Q 1..99 → luma+chroma tables (128 bytes, zigzag). */
export function tablesForQ(q: number): Buffer {
const qq = Math.min(99, Math.max(1, q));
const factor = qq < 50 ? Math.floor(5000 / qq) : 200 - qq * 2;
const scale = (v: number) => Math.min(255, Math.max(1, Math.floor((v * factor + 50) / 100)));
return Buffer.from([...LUMA_Q.map(scale), ...CHROMA_Q.map(scale)]);
}
// Standard Huffman tables (ITU T.81 K.3), the ones RFC 2435 mandates.
const DC_LUMA_BITS = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
const DC_CHROMA_BITS = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
const DC_VALS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const AC_LUMA_BITS = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
const AC_LUMA_VALS = Buffer.from(
"01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9fa",
"hex",
);
const AC_CHROMA_BITS = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
const AC_CHROMA_VALS = Buffer.from(
"000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9fa",
"hex",
);
function dht(tableClass: number, id: number, bits: number[], vals: ArrayLike<number>): Buffer {
const len = 3 + bits.length + vals.length;
return Buffer.from([0xff, 0xc4, len >> 8, len & 0xff, (tableClass << 4) | id, ...bits, ...Array.from(vals)]);
}
const HUFFMAN = Buffer.concat([
dht(0, 0, DC_LUMA_BITS, DC_VALS),
dht(1, 0, AC_LUMA_BITS, AC_LUMA_VALS),
dht(0, 1, DC_CHROMA_BITS, DC_VALS),
dht(1, 1, AC_CHROMA_BITS, AC_CHROMA_VALS),
]);
/** Build the JFIF headers that precede the scan data (RFC 2435 Appendix B). */
export function jpegHeader(type: number, width: number, height: number, qtables: Buffer, dri: number): Buffer {
const parts: Buffer[] = [Buffer.from([0xff, 0xd8])];
const tableCount = Math.floor(qtables.length / 64);
for (let i = 0; i < tableCount; i++) {
parts.push(Buffer.from([0xff, 0xdb, 0, 67, i]), qtables.subarray(i * 64, i * 64 + 64));
}
if (dri) parts.push(Buffer.from([0xff, 0xdd, 0, 4, dri >> 8, dri & 0xff]));
// Type 0 = 4:2:2 (luma 2×1), type 1 = 4:2:0 (luma 2×2); types 64/65 = same + restart markers.
const lumaSampling = (type & 0x3f) === 0 ? 0x21 : 0x22;
const chromaTable = tableCount > 1 ? 1 : 0;
parts.push(
Buffer.from([
0xff, 0xc0, 0, 17, 8, height >> 8, height & 0xff, width >> 8, width & 0xff, 3,
1, lumaSampling, 0,
2, 0x11, chromaTable,
3, 0x11, chromaTable,
]),
);
parts.push(HUFFMAN);
parts.push(Buffer.from([0xff, 0xda, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]));
return Buffer.concat(parts);
}
/** The RTP fixed header + CSRCs + optional extension; returns the payload (padding stripped). */
export function rtpPayload(packet: Buffer): { payload: Buffer; marker: boolean; seq: number } | null {
if (packet.length < 12 || packet[0]! >> 6 !== 2) return null;
const csrc = packet[0]! & 0x0f;
let offset = 12 + csrc * 4;
if (packet[0]! & 0x10) {
if (packet.length < offset + 4) return null;
offset += 4 + packet.readUInt16BE(offset + 2) * 4;
}
let end = packet.length;
if (packet[0]! & 0x20) end -= packet[packet.length - 1]!;
if (end < offset) return null;
return { payload: packet.subarray(offset, end), marker: (packet[1]! & 0x80) !== 0, seq: packet.readUInt16BE(2) };
}
/**
* Reassembles RTP/JPEG packets into complete JPEG frames. Feed every RTP packet of the
* video track to `push`; it returns a finished frame on the packet carrying the marker
* bit, else null. A lost packet (sequence gap or fragment offset mismatch) drops the
* frame in progress — the next frame starts clean. Memory is bounded by MAX_FRAME_BYTES.
*/
export class JpegDepacketizer {
#chunks: Buffer[] = [];
#size = 0;
#expectOffset = 0;
#lastSeq: number | null = null;
#header: Buffer | null = null;
/** Q-derived tables are the same every frame; cache the last Q's. */
#qCache: { q: number; tables: Buffer } | null = null;
/** Frames dropped for loss/overflow (diagnostic). */
dropped = 0;
push(packet: Buffer): Buffer | null {
const rtp = rtpPayload(packet);
if (!rtp) return null;
const { payload, marker, seq } = rtp;
const gap = this.#lastSeq !== null && ((this.#lastSeq + 1) & 0xffff) !== seq;
this.#lastSeq = seq;
if (gap) this.#reset(true);
if (payload.length < 8) return null;
const fragOffset = payload.readUIntBE(1, 3);
const type = payload[4]!;
const q = payload[5]!;
const width = payload[6]! * 8;
const height = payload[7]! * 8;
let pos = 8;
let dri = 0;
if (type >= 64 && type <= 127) {
if (payload.length < pos + 4) return null;
dri = payload.readUInt16BE(pos);
pos += 4;
}
if (fragOffset === 0) {
if (this.#chunks.length > 0) this.#reset(true); // previous frame never finished
let tables: Buffer;
if (q >= 128) {
if (payload.length < pos + 4) return null;
const len = payload.readUInt16BE(pos + 2);
pos += 4;
if (len === 0 || payload.length < pos + len) return null; // tables "sent earlier": unsupported
tables = Buffer.from(payload.subarray(pos, pos + len));
pos += len;
} else {
if (this.#qCache?.q !== q) this.#qCache = { q, tables: tablesForQ(q) };
tables = this.#qCache.tables;
}
this.#header = jpegHeader(type, width, height, tables, dri);
this.#expectOffset = 0;
} else if (!this.#header || fragOffset !== this.#expectOffset) {
// Joined mid-frame, or a fragment went missing: wait for the next frame start.
if (this.#header) this.#reset(true);
return null;
}
const data = payload.subarray(pos);
this.#size += data.length;
if (this.#size > MAX_FRAME_BYTES) {
this.#reset(true);
return null;
}
this.#chunks.push(Buffer.from(data));
this.#expectOffset = fragOffset + data.length;
if (!marker) return null;
const body = Buffer.concat(this.#chunks, this.#size);
const header = this.#header!;
this.#reset(false);
const hasEoi = body.length >= 2 && body[body.length - 2] === 0xff && body[body.length - 1] === 0xd9;
return Buffer.concat(hasEoi ? [header, body] : [header, body, Buffer.from([0xff, 0xd9])]);
}
#reset(dropped: boolean): void {
if (dropped && this.#chunks.length > 0) this.dropped++;
this.#chunks = [];
this.#size = 0;
this.#expectOffset = 0;
this.#header = null;
}
}
@@ -0,0 +1,146 @@
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { createServer, type Server, type Socket } from "node:net";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { parseSdpVideo, RtspCodecError, RtspMjpegStream } from "./rtsp-mjpeg.js";
// A fake RTSP camera on localhost: Digest-challenges the first DESCRIBE, answers the
// handshake the way the park-lab Hikvision does (absolute control URLs, Session with
// timeout=60, an extra audio track on the 1043), then replays the captured RTP/JPEG
// fixture interleaved on channel 0.
const dir = fileURLToPath(new URL("./__fixtures__/", import.meta.url));
const capture = readFileSync(`${dir}rtp-jpeg-2frames.bin`);
const expected0 = readFileSync(`${dir}rtp-jpeg-frame0.jpg`);
const USER = "viewer";
const PASS = "test-only";
const REALM = "IP Camera(TEST)";
const NONCE = "abc123";
const md5 = (s: string) => createHash("md5").update(s).digest("hex");
interface FakeOpts {
codec?: "JPEG" | "H264";
onRequest?: (method: string) => void;
}
let server: Server | null = null;
function fakeCamera(opts: FakeOpts = {}): Promise<number> {
let port = 0;
return new Promise((resolve) => {
server = createServer((sock: Socket) => {
let buf = "";
sock.on("data", (chunk) => {
buf += chunk.toString("latin1");
let end: number;
while ((end = buf.indexOf("\r\n\r\n")) >= 0) {
const req = buf.slice(0, end);
buf = buf.slice(end + 4);
const [line, ...hdrs] = req.split("\r\n");
const [method, url] = line!.split(" ");
opts.onRequest?.(method!);
const h = Object.fromEntries(
hdrs.map((l) => [l.slice(0, l.indexOf(":")).toLowerCase(), l.slice(l.indexOf(":") + 1).trim()]),
);
const cseq = h["cseq"];
const auth = h["authorization"] ?? "";
const resp = /response="([^"]+)"/.exec(auth)?.[1];
const good = md5(`${md5(`${USER}:${REALM}:${PASS}`)}:${NONCE}:${md5(`${method}:${url}`)}`);
if (resp !== good) {
sock.write(
`RTSP/1.0 401 Unauthorized\r\nCSeq: ${cseq}\r\nWWW-Authenticate: Digest realm="${REALM}", nonce="${NONCE}", stale="FALSE"\r\n\r\n`,
);
continue;
}
const base = `rtsp://127.0.0.1:${port}/Streaming/Channels/102`;
if (method === "DESCRIBE") {
const pt = opts.codec === "H264" ? "96" : "26";
const map = opts.codec === "H264" ? "a=rtpmap:96 H264/90000" : "a=rtpmap:26 JPEG/90000";
const sdp = [
"v=0",
`a=control:${base}/`,
`m=video 0 RTP/AVP ${pt}`,
`a=control:${base}/trackID=1`,
map,
"m=audio 0 RTP/AVP 0",
`a=control:${base}/trackID=2`,
"a=rtpmap:0 PCMU/8000",
"",
].join("\r\n");
sock.write(`RTSP/1.0 200 OK\r\nCSeq: ${cseq}\r\nContent-Type: application/sdp\r\nContent-Length: ${sdp.length}\r\n\r\n${sdp}`);
} else if (method === "SETUP") {
expect(url).toBe(`${base}/trackID=1`);
sock.write(`RTSP/1.0 200 OK\r\nCSeq: ${cseq}\r\nSession: 1234;timeout=60\r\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n\r\n`);
} else if (method === "PLAY") {
sock.write(`RTSP/1.0 200 OK\r\nCSeq: ${cseq}\r\nSession: 1234\r\n\r\n`);
for (let i = 0; i < capture.length; ) {
const len = capture.readUInt16BE(i);
const head = Buffer.from([0x24, 0, len >> 8, len & 0xff]);
sock.write(Buffer.concat([head, capture.subarray(i + 2, i + 2 + len)]));
i += 2 + len;
}
} else {
sock.write(`RTSP/1.0 200 OK\r\nCSeq: ${cseq}\r\n\r\n`);
}
}
});
sock.on("error", () => undefined);
});
server.listen(0, "127.0.0.1", () => {
port = (server!.address() as { port: number }).port;
resolve(port);
});
});
}
afterEach(async () => {
await new Promise<void>((r) => (server ? server.close(() => r()) : r()));
server = null;
});
describe("RtspMjpegStream", () => {
it("authenticates, plays the video track and emits whole JPEG frames", async () => {
const methods: string[] = [];
const port = await fakeCamera({ onRequest: (m) => methods.push(m) });
const s = new RtspMjpegStream({ host: "127.0.0.1", port, path: "/Streaming/Channels/102", user: USER, password: PASS });
const frames: Buffer[] = [];
const got = new Promise<void>((resolve) =>
s.onFrame((f) => {
frames.push(f);
if (frames.length === 2) resolve();
}),
);
await s.start();
await got;
expect(frames[0]!.equals(expected0)).toBe(true);
const ended = new Promise<Error | undefined>((r) => s.onEnd(r));
s.stop();
expect(await ended).toBeUndefined();
expect(methods.slice(0, 4)).toEqual(["DESCRIBE", "DESCRIBE", "SETUP", "PLAY"]);
});
it("refuses an H.264 stream with a codec error and closes", async () => {
const port = await fakeCamera({ codec: "H264" });
const s = new RtspMjpegStream({ host: "127.0.0.1", port, path: "/Streaming/Channels/102", user: USER, password: PASS });
const ended = new Promise<Error | undefined>((r) => s.onEnd(r));
await expect(s.start()).rejects.toBeInstanceOf(RtspCodecError);
expect(await ended).toBeInstanceOf(RtspCodecError);
});
it("reports a wrong password without looping", async () => {
const methods: string[] = [];
const port = await fakeCamera({ onRequest: (m) => methods.push(m) });
const s = new RtspMjpegStream({ host: "127.0.0.1", port, path: "/Streaming/Channels/102", user: USER, password: "wrong" });
await expect(s.start()).rejects.toThrow(/auth rejected/);
expect(methods).toEqual(["DESCRIBE", "DESCRIBE"]);
});
});
describe("parseSdpVideo", () => {
it("resolves a relative control against the base", () => {
const sdp = "v=0\r\nm=video 0 RTP/AVP 26\r\na=control:trackID=1\r\n";
expect(parseSdpVideo(sdp, "rtsp://h/s/")).toEqual({ control: "rtsp://h/s/trackID=1", codec: "JPEG" });
});
});
+336
View File
@@ -0,0 +1,336 @@
import { connect, type Socket } from "node:net";
import { buildAuthHeader, parseChallenge } from "./http-digest.js";
import { JpegDepacketizer } from "./rfc2435.js";
import type { LiveVideoSource } from "../interfaces.js";
// Minimal RTSP client for an MJPEG video track: DESCRIBE → SETUP (RTP over the RTSP TCP
// connection, "interleaved") → PLAY, then RTP/JPEG packets are reassembled into JPEG
// frames (rfc2435.ts). Digest auth, a keepalive at half the session timeout, a stall
// watchdog, and bounded buffers. It never decodes video: an H.264/H.265 track is
// refused with a clear reason (the operator sets the camera's sub-stream to MJPEG).
//
// Why RTSP and not the camera's HTTP MJPEG preview: the Hikvision G2 line answers
// /ISAPI/Streaming/channels/102/httpPreview with `notSupport` (measured on park-lab,
// 2026-11-17). Why MJPEG and not H.264: every MJPEG frame is a whole picture, so a
// view is live ~150 ms after PLAY; H.264 waits for a keyframe (every 2.5–4 s on these
// cameras), and no H.264 decoder is needed anywhere. See wiki/decisions/camera-live-view.md.
export interface RtspMjpegOptions {
readonly host: string;
readonly port?: number;
/** Path of the stream, e.g. "/Streaming/Channels/102". */
readonly path: string;
readonly user: string;
readonly password: string;
/** Bind outbound to the device-facing NIC on a multi-homed host. */
readonly localAddress?: string;
/** Per-request timeout for the RTSP handshake. */
readonly timeoutMs?: number;
/** No frame for this long after PLAY ends the stream with an error. */
readonly stallMs?: number;
}
/** The stream exists but is not MJPEG (e.g. H.264). Not retryable until reconfigured. */
export class RtspCodecError extends Error {
readonly retryable = false;
}
/** Cap on unparsed bytes held from the socket. One RTP packet is ≤ 64 KB; anything
* beyond this means the stream is garbage or we stopped draining it. */
const MAX_BUFFER_BYTES = 1024 * 1024;
const USER_AGENT = "parking-system";
interface RtspResponse {
status: number;
headers: Record<string, string>;
body: string;
}
interface Pending {
resolve: (r: RtspResponse) => void;
reject: (e: Error) => void;
timer: ReturnType<typeof setTimeout>;
}
/** Pick the video track from an SDP: its control URL and whether it is JPEG. */
export function parseSdpVideo(sdp: string, baseUrl: string): { control: string; codec: string } | null {
const lines = sdp.split(/\r?\n/);
let inVideo = false;
let payloadTypes: string[] = [];
let control: string | null = null;
const rtpmap = new Map<string, string>();
let found: { control: string | null; pts: string[]; map: Map<string, string> } | null = null;
const flush = () => {
if (inVideo && !found) found = { control, pts: payloadTypes, map: new Map(rtpmap) };
};
for (const line of lines) {
if (line.startsWith("m=")) {
flush();
inVideo = line.startsWith("m=video");
payloadTypes = inVideo ? line.split(" ").slice(3) : [];
control = null;
rtpmap.clear();
} else if (inVideo && line.startsWith("a=control:")) {
control = line.slice("a=control:".length).trim();
} else if (inVideo && line.startsWith("a=rtpmap:")) {
const m = /^a=rtpmap:(\d+)\s+([^/\s]+)/.exec(line);
if (m) rtpmap.set(m[1]!, m[2]!.toUpperCase());
}
}
flush();
if (!found) return null;
const f = found as { control: string | null; pts: string[]; map: Map<string, string> };
const pt = f.pts[0] ?? "";
// Static payload type 26 is JPEG by definition (RFC 3551), rtpmap or not.
const codec = f.map.get(pt) ?? (pt === "26" ? "JPEG" : `PT${pt}`);
let url = baseUrl;
if (f.control && f.control !== "*") {
url = /^rtsp:\/\//i.test(f.control) ? f.control : `${baseUrl.replace(/\/$/, "")}/${f.control}`;
}
return { control: url, codec };
}
export class RtspMjpegStream implements LiveVideoSource {
readonly #o: Required<Omit<RtspMjpegOptions, "localAddress">> & { localAddress?: string };
readonly #url: string;
#socket: Socket | null = null;
#buf: Buffer = Buffer.alloc(0);
#cseq = 0;
#pending = new Map<number, Pending>();
#challenge: Record<string, string> | null = null;
#session: string | null = null;
#keepalive: ReturnType<typeof setInterval> | null = null;
#stallTimer: ReturnType<typeof setTimeout> | null = null;
#depack = new JpegDepacketizer();
#frameCbs: Array<(jpeg: Buffer) => void> = [];
#endCbs: Array<(err?: Error) => void> = [];
#ended = false;
#playing = false;
constructor(o: RtspMjpegOptions) {
this.#o = { port: 554, timeoutMs: 8000, stallMs: 10_000, ...o };
this.#url = `rtsp://${o.host}:${this.#o.port}${o.path}`;
}
onFrame(cb: (jpeg: Buffer) => void): void {
this.#frameCbs.push(cb);
}
onEnd(cb: (err?: Error) => void): void {
this.#endCbs.push(cb);
}
async start(): Promise<void> {
try {
await this.#handshake();
} catch (err) {
this.#end(err as Error); // never leave a half-open session holding a camera slot
throw err;
}
}
async #handshake(): Promise<void> {
await this.#open();
const describe = await this.#request("DESCRIBE", this.#url, { Accept: "application/sdp" });
if (describe.status !== 200) throw new Error(`RTSP DESCRIBE ${describe.status}`);
const base = describe.headers["content-base"] ?? this.#url;
const video = parseSdpVideo(describe.body, base);
if (!video) throw new RtspCodecError("RTSP stream has no video track");
if (video.codec !== "JPEG") {
throw new RtspCodecError(`camera stream is ${video.codec}, not MJPEG (set the sub-stream codec to MJPEG)`);
}
const setup = await this.#request("SETUP", video.control, {
Transport: "RTP/AVP/TCP;unicast;interleaved=0-1",
});
if (setup.status !== 200) throw new Error(`RTSP SETUP ${setup.status}`);
const sessionHeader = setup.headers["session"] ?? "";
this.#session = sessionHeader.split(";")[0]!.trim() || null;
if (!this.#session) throw new Error("RTSP SETUP returned no session");
const timeoutSec = Number(/timeout=(\d+)/i.exec(sessionHeader)?.[1] ?? 60);
const play = await this.#request("PLAY", base, { Range: "npt=0.000-" });
if (play.status !== 200) throw new Error(`RTSP PLAY ${play.status}`);
this.#playing = true;
// Keepalive at half the advertised timeout (park-lab cameras: timeout=60 and they
// did not drop a 150 s session without one, but other firmware may).
const every = Math.max(5, Math.floor(timeoutSec / 2)) * 1000;
this.#keepalive = setInterval(() => {
this.#request("GET_PARAMETER", base, {}).catch(() => undefined);
}, every);
this.#keepalive.unref?.();
this.#armStall();
}
stop(): void {
if (this.#ended) return;
if (this.#socket && this.#session && this.#playing) {
// Best-effort TEARDOWN so the camera frees its stream slot now, not at timeout.
try {
this.#socket.write(this.#format("TEARDOWN", this.#url, {}));
} catch {
/* closing anyway */
}
}
this.#end();
}
#open(): Promise<void> {
return new Promise((resolve, reject) => {
const socket = connect({
host: this.#o.host,
port: this.#o.port,
...(this.#o.localAddress ? { localAddress: this.#o.localAddress } : {}),
});
socket.setNoDelay(true);
const timer = setTimeout(() => socket.destroy(new Error("RTSP connect timeout")), this.#o.timeoutMs);
socket.once("connect", () => {
clearTimeout(timer);
resolve();
});
socket.once("error", (err) => {
clearTimeout(timer);
reject(err);
this.#end(err);
});
socket.on("data", (chunk: Buffer) => this.#onData(chunk));
socket.on("close", () => this.#end(this.#ended ? undefined : new Error("RTSP connection closed")));
this.#socket = socket;
});
}
#format(method: string, url: string, headers: Record<string, string>): string {
const cseq = ++this.#cseq;
const lines = [`${method} ${url} RTSP/1.0`, `CSeq: ${cseq}`, `User-Agent: ${USER_AGENT}`];
if (this.#session) lines.push(`Session: ${this.#session}`);
if (this.#challenge) {
lines.push(`Authorization: ${buildAuthHeader(this.#challenge, this.#o.user, this.#o.password, method, url)}`);
}
for (const [k, v] of Object.entries(headers)) lines.push(`${k}: ${v}`);
return lines.join("\r\n") + "\r\n\r\n";
}
async #request(method: string, url: string, headers: Record<string, string>): Promise<RtspResponse> {
let res = await this.#send(method, url, headers);
if (res.status === 401 && res.headers["www-authenticate"] && !this.#challengeFresh) {
this.#challenge = parseChallenge(res.headers["www-authenticate"]);
this.#challengeFresh = true;
res = await this.#send(method, url, headers);
}
if (res.status !== 401) this.#challengeFresh = false;
if (res.status === 401) throw new Error("RTSP auth rejected (check username/password)");
return res;
}
/** True right after a fresh challenge: a second 401 is a wrong password, not a stale nonce. */
#challengeFresh = false;
#send(method: string, url: string, headers: Record<string, string>): Promise<RtspResponse> {
const socket = this.#socket;
if (!socket || this.#ended) return Promise.reject(new Error("RTSP connection closed"));
const text = this.#format(method, url, headers);
const cseq = this.#cseq;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.#pending.delete(cseq);
reject(new Error(`RTSP ${method} timeout`));
}, this.#o.timeoutMs);
this.#pending.set(cseq, { resolve, reject, timer });
socket.write(text);
});
}
#onData(chunk: Buffer): void {
this.#buf = this.#buf.length === 0 ? chunk : Buffer.concat([this.#buf, chunk]);
if (this.#buf.length > MAX_BUFFER_BYTES) {
this.#end(new Error("RTSP receive buffer overflow"));
return;
}
for (;;) {
if (this.#buf.length === 0) return;
if (this.#buf[0] === 0x24) {
// Interleaved binary: '$', channel, 16-bit length, packet.
if (this.#buf.length < 4) return;
const len = this.#buf.readUInt16BE(2);
if (this.#buf.length < 4 + len) return;
const channel = this.#buf[1];
const packet = this.#buf.subarray(4, 4 + len);
this.#buf = this.#buf.subarray(4 + len);
if (channel === 0) this.#onRtp(packet);
continue;
}
if (this.#buf.subarray(0, 5).toString("latin1") === "RTSP/") {
const headEnd = this.#buf.indexOf("\r\n\r\n");
if (headEnd < 0) return;
const head = this.#buf.subarray(0, headEnd).toString("latin1");
const headers: Record<string, string> = {};
for (const line of head.split("\r\n").slice(1)) {
const i = line.indexOf(":");
if (i > 0) headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
}
const bodyLen = Number(headers["content-length"] ?? 0);
if (this.#buf.length < headEnd + 4 + bodyLen) return;
const body = this.#buf.subarray(headEnd + 4, headEnd + 4 + bodyLen).toString("utf8");
this.#buf = this.#buf.subarray(headEnd + 4 + bodyLen);
const status = Number(/^RTSP\/\d\.\d\s+(\d+)/.exec(head)?.[1] ?? 0);
const cseq = Number(headers["cseq"] ?? -1);
const p = this.#pending.get(cseq);
if (p) {
this.#pending.delete(cseq);
clearTimeout(p.timer);
p.resolve({ status, headers, body });
}
continue;
}
// Out of sync: skip to the next plausible start ('$' or "RTSP/").
let next = -1;
for (let i = 1; i < this.#buf.length; i++) {
const b = this.#buf[i];
if (b === 0x24 || (b === 0x52 && this.#buf.subarray(i, i + 5).toString("latin1") === "RTSP/")) {
next = i;
break;
}
}
this.#buf = next < 0 ? Buffer.alloc(0) : this.#buf.subarray(next);
}
}
#onRtp(packet: Buffer): void {
const frame = this.#depack.push(packet);
if (!frame) return;
this.#armStall();
for (const cb of this.#frameCbs) {
try {
cb(frame);
} catch {
/* a subscriber's failure never stops the stream */
}
}
}
#armStall(): void {
if (this.#stallTimer) clearTimeout(this.#stallTimer);
this.#stallTimer = setTimeout(() => this.#end(new Error("RTSP stream stalled (no frames)")), this.#o.stallMs);
this.#stallTimer.unref?.();
}
#end(err?: Error): void {
if (this.#ended) return;
this.#ended = true;
if (this.#keepalive) clearInterval(this.#keepalive);
if (this.#stallTimer) clearTimeout(this.#stallTimer);
for (const p of this.#pending.values()) {
clearTimeout(p.timer);
p.reject(err ?? new Error("RTSP stream stopped"));
}
this.#pending.clear();
this.#buf = Buffer.alloc(0);
this.#socket?.destroy();
this.#socket = null;
for (const cb of this.#endCbs) {
try {
cb(err);
} catch {
/* ignore */
}
}
}
}
+3
View File
@@ -32,3 +32,6 @@ export {
NoPrinterAvailableError, NoPrinterAvailableError,
type PrinterInstance, type PrinterInstance,
} from "./printer-routing.js"; } from "./printer-routing.js";
// Live camera view: RTSP MJPEG client + RTP/JPEG reassembly (wiki/decisions/camera-live-view.md).
export { RtspMjpegStream, RtspCodecError, type RtspMjpegOptions } from "./drivers/rtsp-mjpeg.js";
export { JpegDepacketizer } from "./drivers/rfc2435.js";
+23
View File
@@ -198,6 +198,29 @@ export function isCamera(device: Device): device is Device & CameraDevice {
return typeof (device as Partial<CameraDevice>).captureSnapshot === "function"; return typeof (device as Partial<CameraDevice>).captureSnapshot === "function";
} }
/** One live video session from a camera, delivered as complete JPEG frames. Advisory
* viewing only — nothing in the ledger or the gates depends on it. */
export interface LiveVideoSource {
/** Open the session; resolves once frames are flowing (or about to). Rejects on a
* connect/auth/codec failure, after which the source is ended. */
start(): Promise<void>;
/** End the session and free the camera's stream slot. Idempotent. */
stop(): void;
onFrame(cb: (jpeg: Buffer) => void): void;
/** Called once when the session ends; `err` absent = stopped on purpose. */
onEnd(cb: (err?: Error) => void): void;
}
/** Optional capability: a camera that can stream live video for the booth's camera
* tiles. See wiki/decisions/camera-live-view.md. */
export interface LiveStreamDevice {
openLiveStream(): LiveVideoSource;
}
export function isLiveStreamDevice(device: unknown): device is LiveStreamDevice {
return typeof (device as Partial<LiveStreamDevice> | null)?.openLiveStream === "function";
}
/** Outcome of a camera clock sync attempt (see ClockSyncDevice). */ /** Outcome of a camera clock sync attempt (see ClockSyncDevice). */
export interface ClockSyncResult { export interface ClockSyncResult {
/** Camera-vs-host drift in whole seconds at check time; null = the camera's /** Camera-vs-host drift in whole seconds at check time; null = the camera's