feat(cameras): booth camera tiles — latest snapshot at rest, live video while a vehicle is in view
Footer camera chips open/close a tile per camera (bottom right, ~15% wide, stacking leftwards); the open set is a per-user preference (users.open_cameras). A tile shows the camera's newest entry/exit snapshot and switches to live video while that camera pushes vehicle events (per-camera activity, same 30 s TTL as lane status). - devices: RTSP MJPEG client + RFC 2435 RTP/JPEG reassembly; Hikvision openLiveStream() on the sub-stream (x02, must be MJPEG — H.264 is refused with that reason) - server: CameraLiveHub (one shared upstream per camera, latest-frame delivery, fps cap, linger, backoff), CameraActivity, /api/cameras/:id/latest-snapshot, WS /api/cameras/:id/live (shared handshake auth with /api/ws + device:read), PUT /api/auth/open-cameras, migration 0033 (open_cameras + snapshot device/time index) - web: CameraDock, footer toggles, binary frames in the platform socket (Tauri too) - .gitattributes: *.jpg / *.bin binary (byte-exact test fixtures) Verified on park-lab cameras end to end and in headless Firefox. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,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`);
|
||||
@@ -232,6 +232,13 @@
|
||||
"when": 1788720000000,
|
||||
"tag": "0032_hot_path_indexes",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 33,
|
||||
"version": "6",
|
||||
"when": 1788730000000,
|
||||
"tag": "0033_camera_live_view",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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
|
||||
// unaffected (server-rendered).
|
||||
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
|
||||
// nullable; only username/password/role are required to create a user. fullName
|
||||
// (when set) is the human label for audit/Z-report display.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -1,5 +1,7 @@
|
||||
import type {
|
||||
CameraDevice,
|
||||
LiveStreamDevice,
|
||||
LiveVideoSource,
|
||||
ClockSyncResult,
|
||||
DeviceHealth,
|
||||
Snapshot,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
stubLog,
|
||||
} from "./common.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
|
||||
// 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
|
||||
// multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md).
|
||||
readonly #localAddress: string | undefined;
|
||||
/** RTSP port for the live view (not a Setup field: 554 everywhere so far). */
|
||||
readonly #rtspPort: number;
|
||||
|
||||
constructor(
|
||||
readonly driverId: string,
|
||||
@@ -92,6 +97,7 @@ class HttpCamera implements CameraDevice {
|
||||
this.#localAddress = config.localAddress
|
||||
? String(config.localAddress)
|
||||
: undefined;
|
||||
this.#rtspPort = Number(config.rtspPort ?? 554);
|
||||
}
|
||||
|
||||
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). */
|
||||
protected deviceRequest(method: "GET" | "PUT", path: string, body?: string) {
|
||||
return digestRequest({
|
||||
@@ -216,7 +239,18 @@ export function hikvisionFixedZone(localIso: string): string {
|
||||
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
|
||||
* fixed offset (see above); otherwise set the clock only when it drifts more than
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { IncomingMessage } from "node:http";
|
||||
const md5 = (s: string) => createHash("md5").update(s).digest("hex");
|
||||
|
||||
/** 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 re = /(\w+)=(?:"([^"]*)"|([^,]*))/g;
|
||||
let m: RegExpExecArray | null;
|
||||
@@ -21,7 +21,7 @@ function parseChallenge(header: string): Record<string, string> {
|
||||
}
|
||||
|
||||
/** Build the `Authorization: Digest …` response value for a challenge. */
|
||||
function buildAuthHeader(
|
||||
export function buildAuthHeader(
|
||||
c: Record<string, string>,
|
||||
user: 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);
|
||||
});
|
||||
});
|
||||
@@ -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" });
|
||||
});
|
||||
});
|
||||
@@ -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 */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,3 +32,6 @@ export {
|
||||
NoPrinterAvailableError,
|
||||
type PrinterInstance,
|
||||
} 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";
|
||||
|
||||
@@ -198,6 +198,29 @@ export function isCamera(device: Device): device is Device & CameraDevice {
|
||||
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). */
|
||||
export interface ClockSyncResult {
|
||||
/** Camera-vs-host drift in whole seconds at check time; null = the camera's
|
||||
|
||||
Reference in New Issue
Block a user